1 // SPDX-License-Identifier: GPL-2.0
3 * Performance events core code:
5 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
6 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
7 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
8 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
13 #include <linux/cpu.h>
14 #include <linux/smp.h>
15 #include <linux/idr.h>
16 #include <linux/file.h>
17 #include <linux/poll.h>
18 #include <linux/slab.h>
19 #include <linux/hash.h>
20 #include <linux/tick.h>
21 #include <linux/sysfs.h>
22 #include <linux/dcache.h>
23 #include <linux/percpu.h>
24 #include <linux/ptrace.h>
25 #include <linux/reboot.h>
26 #include <linux/vmstat.h>
27 #include <linux/device.h>
28 #include <linux/export.h>
29 #include <linux/vmalloc.h>
30 #include <linux/hardirq.h>
31 #include <linux/hugetlb.h>
32 #include <linux/rculist.h>
33 #include <linux/uaccess.h>
34 #include <linux/syscalls.h>
35 #include <linux/anon_inodes.h>
36 #include <linux/kernel_stat.h>
37 #include <linux/cgroup.h>
38 #include <linux/perf_event.h>
39 #include <linux/trace_events.h>
40 #include <linux/hw_breakpoint.h>
41 #include <linux/mm_types.h>
42 #include <linux/module.h>
43 #include <linux/mman.h>
44 #include <linux/compat.h>
45 #include <linux/bpf.h>
46 #include <linux/filter.h>
47 #include <linux/namei.h>
48 #include <linux/parser.h>
49 #include <linux/sched/clock.h>
50 #include <linux/sched/mm.h>
51 #include <linux/proc_ns.h>
52 #include <linux/mount.h>
53 #include <linux/min_heap.h>
54 #include <linux/highmem.h>
55 #include <linux/pgtable.h>
56 #include <linux/buildid.h>
60 #include <asm/irq_regs.h>
62 typedef int (*remote_function_f)(void *);
64 struct remote_function_call {
65 struct task_struct *p;
66 remote_function_f func;
71 static void remote_function(void *data)
73 struct remote_function_call *tfc = data;
74 struct task_struct *p = tfc->p;
78 if (task_cpu(p) != smp_processor_id())
82 * Now that we're on right CPU with IRQs disabled, we can test
83 * if we hit the right task without races.
86 tfc->ret = -ESRCH; /* No such (running) process */
91 tfc->ret = tfc->func(tfc->info);
95 * task_function_call - call a function on the cpu on which a task runs
96 * @p: the task to evaluate
97 * @func: the function to be called
98 * @info: the function call argument
100 * Calls the function @func when the task is currently running. This might
101 * be on the current CPU, which just calls the function directly. This will
102 * retry due to any failures in smp_call_function_single(), such as if the
103 * task_cpu() goes offline concurrently.
105 * returns @func return value or -ESRCH or -ENXIO when the process isn't running
108 task_function_call(struct task_struct *p, remote_function_f func, void *info)
110 struct remote_function_call data = {
119 ret = smp_call_function_single(task_cpu(p), remote_function,
134 * cpu_function_call - call a function on the cpu
135 * @func: the function to be called
136 * @info: the function call argument
138 * Calls the function @func on the remote cpu.
140 * returns: @func return value or -ENXIO when the cpu is offline
142 static int cpu_function_call(int cpu, remote_function_f func, void *info)
144 struct remote_function_call data = {
148 .ret = -ENXIO, /* No such CPU */
151 smp_call_function_single(cpu, remote_function, &data, 1);
156 static inline struct perf_cpu_context *
157 __get_cpu_context(struct perf_event_context *ctx)
159 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
162 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
163 struct perf_event_context *ctx)
165 raw_spin_lock(&cpuctx->ctx.lock);
167 raw_spin_lock(&ctx->lock);
170 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
171 struct perf_event_context *ctx)
174 raw_spin_unlock(&ctx->lock);
175 raw_spin_unlock(&cpuctx->ctx.lock);
178 #define TASK_TOMBSTONE ((void *)-1L)
180 static bool is_kernel_event(struct perf_event *event)
182 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
186 * On task ctx scheduling...
188 * When !ctx->nr_events a task context will not be scheduled. This means
189 * we can disable the scheduler hooks (for performance) without leaving
190 * pending task ctx state.
192 * This however results in two special cases:
194 * - removing the last event from a task ctx; this is relatively straight
195 * forward and is done in __perf_remove_from_context.
197 * - adding the first event to a task ctx; this is tricky because we cannot
198 * rely on ctx->is_active and therefore cannot use event_function_call().
199 * See perf_install_in_context().
201 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
204 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
205 struct perf_event_context *, void *);
207 struct event_function_struct {
208 struct perf_event *event;
213 static int event_function(void *info)
215 struct event_function_struct *efs = info;
216 struct perf_event *event = efs->event;
217 struct perf_event_context *ctx = event->ctx;
218 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
219 struct perf_event_context *task_ctx = cpuctx->task_ctx;
222 lockdep_assert_irqs_disabled();
224 perf_ctx_lock(cpuctx, task_ctx);
226 * Since we do the IPI call without holding ctx->lock things can have
227 * changed, double check we hit the task we set out to hit.
230 if (ctx->task != current) {
236 * We only use event_function_call() on established contexts,
237 * and event_function() is only ever called when active (or
238 * rather, we'll have bailed in task_function_call() or the
239 * above ctx->task != current test), therefore we must have
240 * ctx->is_active here.
242 WARN_ON_ONCE(!ctx->is_active);
244 * And since we have ctx->is_active, cpuctx->task_ctx must
247 WARN_ON_ONCE(task_ctx != ctx);
249 WARN_ON_ONCE(&cpuctx->ctx != ctx);
252 efs->func(event, cpuctx, ctx, efs->data);
254 perf_ctx_unlock(cpuctx, task_ctx);
259 static void event_function_call(struct perf_event *event, event_f func, void *data)
261 struct perf_event_context *ctx = event->ctx;
262 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
263 struct event_function_struct efs = {
269 if (!event->parent) {
271 * If this is a !child event, we must hold ctx::mutex to
272 * stabilize the event->ctx relation. See
273 * perf_event_ctx_lock().
275 lockdep_assert_held(&ctx->mutex);
279 cpu_function_call(event->cpu, event_function, &efs);
283 if (task == TASK_TOMBSTONE)
287 if (!task_function_call(task, event_function, &efs))
290 raw_spin_lock_irq(&ctx->lock);
292 * Reload the task pointer, it might have been changed by
293 * a concurrent perf_event_context_sched_out().
296 if (task == TASK_TOMBSTONE) {
297 raw_spin_unlock_irq(&ctx->lock);
300 if (ctx->is_active) {
301 raw_spin_unlock_irq(&ctx->lock);
304 func(event, NULL, ctx, data);
305 raw_spin_unlock_irq(&ctx->lock);
309 * Similar to event_function_call() + event_function(), but hard assumes IRQs
310 * are already disabled and we're on the right CPU.
312 static void event_function_local(struct perf_event *event, event_f func, void *data)
314 struct perf_event_context *ctx = event->ctx;
315 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
316 struct task_struct *task = READ_ONCE(ctx->task);
317 struct perf_event_context *task_ctx = NULL;
319 lockdep_assert_irqs_disabled();
322 if (task == TASK_TOMBSTONE)
328 perf_ctx_lock(cpuctx, task_ctx);
331 if (task == TASK_TOMBSTONE)
336 * We must be either inactive or active and the right task,
337 * otherwise we're screwed, since we cannot IPI to somewhere
340 if (ctx->is_active) {
341 if (WARN_ON_ONCE(task != current))
344 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
348 WARN_ON_ONCE(&cpuctx->ctx != ctx);
351 func(event, cpuctx, ctx, data);
353 perf_ctx_unlock(cpuctx, task_ctx);
356 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
357 PERF_FLAG_FD_OUTPUT |\
358 PERF_FLAG_PID_CGROUP |\
359 PERF_FLAG_FD_CLOEXEC)
362 * branch priv levels that need permission checks
364 #define PERF_SAMPLE_BRANCH_PERM_PLM \
365 (PERF_SAMPLE_BRANCH_KERNEL |\
366 PERF_SAMPLE_BRANCH_HV)
369 EVENT_FLEXIBLE = 0x1,
372 /* see ctx_resched() for details */
374 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
378 * perf_sched_events : >0 events exist
379 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
382 static void perf_sched_delayed(struct work_struct *work);
383 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
384 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
385 static DEFINE_MUTEX(perf_sched_mutex);
386 static atomic_t perf_sched_count;
388 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
389 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
390 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
392 static atomic_t nr_mmap_events __read_mostly;
393 static atomic_t nr_comm_events __read_mostly;
394 static atomic_t nr_namespaces_events __read_mostly;
395 static atomic_t nr_task_events __read_mostly;
396 static atomic_t nr_freq_events __read_mostly;
397 static atomic_t nr_switch_events __read_mostly;
398 static atomic_t nr_ksymbol_events __read_mostly;
399 static atomic_t nr_bpf_events __read_mostly;
400 static atomic_t nr_cgroup_events __read_mostly;
401 static atomic_t nr_text_poke_events __read_mostly;
402 static atomic_t nr_build_id_events __read_mostly;
404 static LIST_HEAD(pmus);
405 static DEFINE_MUTEX(pmus_lock);
406 static struct srcu_struct pmus_srcu;
407 static cpumask_var_t perf_online_mask;
410 * perf event paranoia level:
411 * -1 - not paranoid at all
412 * 0 - disallow raw tracepoint access for unpriv
413 * 1 - disallow cpu events for unpriv
414 * 2 - disallow kernel profiling for unpriv
416 int sysctl_perf_event_paranoid __read_mostly = 2;
418 /* Minimum for 512 kiB + 1 user control page */
419 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
422 * max perf event sample rate
424 #define DEFAULT_MAX_SAMPLE_RATE 100000
425 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
426 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
428 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
430 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
431 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
433 static int perf_sample_allowed_ns __read_mostly =
434 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
436 static void update_perf_cpu_limits(void)
438 u64 tmp = perf_sample_period_ns;
440 tmp *= sysctl_perf_cpu_time_max_percent;
441 tmp = div_u64(tmp, 100);
445 WRITE_ONCE(perf_sample_allowed_ns, tmp);
448 static bool perf_rotate_context(struct perf_cpu_context *cpuctx);
450 int perf_proc_update_handler(struct ctl_table *table, int write,
451 void *buffer, size_t *lenp, loff_t *ppos)
454 int perf_cpu = sysctl_perf_cpu_time_max_percent;
456 * If throttling is disabled don't allow the write:
458 if (write && (perf_cpu == 100 || perf_cpu == 0))
461 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
465 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
466 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
467 update_perf_cpu_limits();
472 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
474 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
475 void *buffer, size_t *lenp, loff_t *ppos)
477 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
482 if (sysctl_perf_cpu_time_max_percent == 100 ||
483 sysctl_perf_cpu_time_max_percent == 0) {
485 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
486 WRITE_ONCE(perf_sample_allowed_ns, 0);
488 update_perf_cpu_limits();
495 * perf samples are done in some very critical code paths (NMIs).
496 * If they take too much CPU time, the system can lock up and not
497 * get any real work done. This will drop the sample rate when
498 * we detect that events are taking too long.
500 #define NR_ACCUMULATED_SAMPLES 128
501 static DEFINE_PER_CPU(u64, running_sample_length);
503 static u64 __report_avg;
504 static u64 __report_allowed;
506 static void perf_duration_warn(struct irq_work *w)
508 printk_ratelimited(KERN_INFO
509 "perf: interrupt took too long (%lld > %lld), lowering "
510 "kernel.perf_event_max_sample_rate to %d\n",
511 __report_avg, __report_allowed,
512 sysctl_perf_event_sample_rate);
515 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
517 void perf_sample_event_took(u64 sample_len_ns)
519 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
527 /* Decay the counter by 1 average sample. */
528 running_len = __this_cpu_read(running_sample_length);
529 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
530 running_len += sample_len_ns;
531 __this_cpu_write(running_sample_length, running_len);
534 * Note: this will be biased artifically low until we have
535 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
536 * from having to maintain a count.
538 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
539 if (avg_len <= max_len)
542 __report_avg = avg_len;
543 __report_allowed = max_len;
546 * Compute a throttle threshold 25% below the current duration.
548 avg_len += avg_len / 4;
549 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
555 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
556 WRITE_ONCE(max_samples_per_tick, max);
558 sysctl_perf_event_sample_rate = max * HZ;
559 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
561 if (!irq_work_queue(&perf_duration_work)) {
562 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
563 "kernel.perf_event_max_sample_rate to %d\n",
564 __report_avg, __report_allowed,
565 sysctl_perf_event_sample_rate);
569 static atomic64_t perf_event_id;
571 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
572 enum event_type_t event_type);
574 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
575 enum event_type_t event_type,
576 struct task_struct *task);
578 static void update_context_time(struct perf_event_context *ctx);
579 static u64 perf_event_time(struct perf_event *event);
581 void __weak perf_event_print_debug(void) { }
583 static inline u64 perf_clock(void)
585 return local_clock();
588 static inline u64 perf_event_clock(struct perf_event *event)
590 return event->clock();
594 * State based event timekeeping...
596 * The basic idea is to use event->state to determine which (if any) time
597 * fields to increment with the current delta. This means we only need to
598 * update timestamps when we change state or when they are explicitly requested
601 * Event groups make things a little more complicated, but not terribly so. The
602 * rules for a group are that if the group leader is OFF the entire group is
603 * OFF, irrespecive of what the group member states are. This results in
604 * __perf_effective_state().
606 * A futher ramification is that when a group leader flips between OFF and
607 * !OFF, we need to update all group member times.
610 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
611 * need to make sure the relevant context time is updated before we try and
612 * update our timestamps.
615 static __always_inline enum perf_event_state
616 __perf_effective_state(struct perf_event *event)
618 struct perf_event *leader = event->group_leader;
620 if (leader->state <= PERF_EVENT_STATE_OFF)
621 return leader->state;
626 static __always_inline void
627 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
629 enum perf_event_state state = __perf_effective_state(event);
630 u64 delta = now - event->tstamp;
632 *enabled = event->total_time_enabled;
633 if (state >= PERF_EVENT_STATE_INACTIVE)
636 *running = event->total_time_running;
637 if (state >= PERF_EVENT_STATE_ACTIVE)
641 static void perf_event_update_time(struct perf_event *event)
643 u64 now = perf_event_time(event);
645 __perf_update_times(event, now, &event->total_time_enabled,
646 &event->total_time_running);
650 static void perf_event_update_sibling_time(struct perf_event *leader)
652 struct perf_event *sibling;
654 for_each_sibling_event(sibling, leader)
655 perf_event_update_time(sibling);
659 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
661 if (event->state == state)
664 perf_event_update_time(event);
666 * If a group leader gets enabled/disabled all its siblings
669 if ((event->state < 0) ^ (state < 0))
670 perf_event_update_sibling_time(event);
672 WRITE_ONCE(event->state, state);
675 #ifdef CONFIG_CGROUP_PERF
678 perf_cgroup_match(struct perf_event *event)
680 struct perf_event_context *ctx = event->ctx;
681 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
683 /* @event doesn't care about cgroup */
687 /* wants specific cgroup scope but @cpuctx isn't associated with any */
692 * Cgroup scoping is recursive. An event enabled for a cgroup is
693 * also enabled for all its descendant cgroups. If @cpuctx's
694 * cgroup is a descendant of @event's (the test covers identity
695 * case), it's a match.
697 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
698 event->cgrp->css.cgroup);
701 static inline void perf_detach_cgroup(struct perf_event *event)
703 css_put(&event->cgrp->css);
707 static inline int is_cgroup_event(struct perf_event *event)
709 return event->cgrp != NULL;
712 static inline u64 perf_cgroup_event_time(struct perf_event *event)
714 struct perf_cgroup_info *t;
716 t = per_cpu_ptr(event->cgrp->info, event->cpu);
720 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
722 struct perf_cgroup_info *info;
727 info = this_cpu_ptr(cgrp->info);
729 info->time += now - info->timestamp;
730 info->timestamp = now;
733 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
735 struct perf_cgroup *cgrp = cpuctx->cgrp;
736 struct cgroup_subsys_state *css;
739 for (css = &cgrp->css; css; css = css->parent) {
740 cgrp = container_of(css, struct perf_cgroup, css);
741 __update_cgrp_time(cgrp);
746 static inline void update_cgrp_time_from_event(struct perf_event *event)
748 struct perf_cgroup *cgrp;
751 * ensure we access cgroup data only when needed and
752 * when we know the cgroup is pinned (css_get)
754 if (!is_cgroup_event(event))
757 cgrp = perf_cgroup_from_task(current, event->ctx);
759 * Do not update time when cgroup is not active
761 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
762 __update_cgrp_time(event->cgrp);
766 perf_cgroup_set_timestamp(struct task_struct *task,
767 struct perf_event_context *ctx)
769 struct perf_cgroup *cgrp;
770 struct perf_cgroup_info *info;
771 struct cgroup_subsys_state *css;
774 * ctx->lock held by caller
775 * ensure we do not access cgroup data
776 * unless we have the cgroup pinned (css_get)
778 if (!task || !ctx->nr_cgroups)
781 cgrp = perf_cgroup_from_task(task, ctx);
783 for (css = &cgrp->css; css; css = css->parent) {
784 cgrp = container_of(css, struct perf_cgroup, css);
785 info = this_cpu_ptr(cgrp->info);
786 info->timestamp = ctx->timestamp;
790 static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list);
792 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
793 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
796 * reschedule events based on the cgroup constraint of task.
798 * mode SWOUT : schedule out everything
799 * mode SWIN : schedule in based on cgroup for next
801 static void perf_cgroup_switch(struct task_struct *task, int mode)
803 struct perf_cpu_context *cpuctx;
804 struct list_head *list;
808 * Disable interrupts and preemption to avoid this CPU's
809 * cgrp_cpuctx_entry to change under us.
811 local_irq_save(flags);
813 list = this_cpu_ptr(&cgrp_cpuctx_list);
814 list_for_each_entry(cpuctx, list, cgrp_cpuctx_entry) {
815 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
817 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
818 perf_pmu_disable(cpuctx->ctx.pmu);
820 if (mode & PERF_CGROUP_SWOUT) {
821 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
823 * must not be done before ctxswout due
824 * to event_filter_match() in event_sched_out()
829 if (mode & PERF_CGROUP_SWIN) {
830 WARN_ON_ONCE(cpuctx->cgrp);
832 * set cgrp before ctxsw in to allow
833 * event_filter_match() to not have to pass
835 * we pass the cpuctx->ctx to perf_cgroup_from_task()
836 * because cgorup events are only per-cpu
838 cpuctx->cgrp = perf_cgroup_from_task(task,
840 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
842 perf_pmu_enable(cpuctx->ctx.pmu);
843 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
846 local_irq_restore(flags);
849 static inline void perf_cgroup_sched_out(struct task_struct *task,
850 struct task_struct *next)
852 struct perf_cgroup *cgrp1;
853 struct perf_cgroup *cgrp2 = NULL;
857 * we come here when we know perf_cgroup_events > 0
858 * we do not need to pass the ctx here because we know
859 * we are holding the rcu lock
861 cgrp1 = perf_cgroup_from_task(task, NULL);
862 cgrp2 = perf_cgroup_from_task(next, NULL);
865 * only schedule out current cgroup events if we know
866 * that we are switching to a different cgroup. Otherwise,
867 * do no touch the cgroup events.
870 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
875 static inline void perf_cgroup_sched_in(struct task_struct *prev,
876 struct task_struct *task)
878 struct perf_cgroup *cgrp1;
879 struct perf_cgroup *cgrp2 = NULL;
883 * we come here when we know perf_cgroup_events > 0
884 * we do not need to pass the ctx here because we know
885 * we are holding the rcu lock
887 cgrp1 = perf_cgroup_from_task(task, NULL);
888 cgrp2 = perf_cgroup_from_task(prev, NULL);
891 * only need to schedule in cgroup events if we are changing
892 * cgroup during ctxsw. Cgroup events were not scheduled
893 * out of ctxsw out if that was not the case.
896 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
901 static int perf_cgroup_ensure_storage(struct perf_event *event,
902 struct cgroup_subsys_state *css)
904 struct perf_cpu_context *cpuctx;
905 struct perf_event **storage;
906 int cpu, heap_size, ret = 0;
909 * Allow storage to have sufficent space for an iterator for each
910 * possibly nested cgroup plus an iterator for events with no cgroup.
912 for (heap_size = 1; css; css = css->parent)
915 for_each_possible_cpu(cpu) {
916 cpuctx = per_cpu_ptr(event->pmu->pmu_cpu_context, cpu);
917 if (heap_size <= cpuctx->heap_size)
920 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
921 GFP_KERNEL, cpu_to_node(cpu));
927 raw_spin_lock_irq(&cpuctx->ctx.lock);
928 if (cpuctx->heap_size < heap_size) {
929 swap(cpuctx->heap, storage);
930 if (storage == cpuctx->heap_default)
932 cpuctx->heap_size = heap_size;
934 raw_spin_unlock_irq(&cpuctx->ctx.lock);
942 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
943 struct perf_event_attr *attr,
944 struct perf_event *group_leader)
946 struct perf_cgroup *cgrp;
947 struct cgroup_subsys_state *css;
948 struct fd f = fdget(fd);
954 css = css_tryget_online_from_dir(f.file->f_path.dentry,
955 &perf_event_cgrp_subsys);
961 ret = perf_cgroup_ensure_storage(event, css);
965 cgrp = container_of(css, struct perf_cgroup, css);
969 * all events in a group must monitor
970 * the same cgroup because a task belongs
971 * to only one perf cgroup at a time
973 if (group_leader && group_leader->cgrp != cgrp) {
974 perf_detach_cgroup(event);
983 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
985 struct perf_cgroup_info *t;
986 t = per_cpu_ptr(event->cgrp->info, event->cpu);
987 event->shadow_ctx_time = now - t->timestamp;
991 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
993 struct perf_cpu_context *cpuctx;
995 if (!is_cgroup_event(event))
999 * Because cgroup events are always per-cpu events,
1000 * @ctx == &cpuctx->ctx.
1002 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1005 * Since setting cpuctx->cgrp is conditional on the current @cgrp
1006 * matching the event's cgroup, we must do this for every new event,
1007 * because if the first would mismatch, the second would not try again
1008 * and we would leave cpuctx->cgrp unset.
1010 if (ctx->is_active && !cpuctx->cgrp) {
1011 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
1013 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
1014 cpuctx->cgrp = cgrp;
1017 if (ctx->nr_cgroups++)
1020 list_add(&cpuctx->cgrp_cpuctx_entry,
1021 per_cpu_ptr(&cgrp_cpuctx_list, event->cpu));
1025 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1027 struct perf_cpu_context *cpuctx;
1029 if (!is_cgroup_event(event))
1033 * Because cgroup events are always per-cpu events,
1034 * @ctx == &cpuctx->ctx.
1036 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1038 if (--ctx->nr_cgroups)
1041 if (ctx->is_active && cpuctx->cgrp)
1042 cpuctx->cgrp = NULL;
1044 list_del(&cpuctx->cgrp_cpuctx_entry);
1047 #else /* !CONFIG_CGROUP_PERF */
1050 perf_cgroup_match(struct perf_event *event)
1055 static inline void perf_detach_cgroup(struct perf_event *event)
1058 static inline int is_cgroup_event(struct perf_event *event)
1063 static inline void update_cgrp_time_from_event(struct perf_event *event)
1067 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
1071 static inline void perf_cgroup_sched_out(struct task_struct *task,
1072 struct task_struct *next)
1076 static inline void perf_cgroup_sched_in(struct task_struct *prev,
1077 struct task_struct *task)
1081 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1082 struct perf_event_attr *attr,
1083 struct perf_event *group_leader)
1089 perf_cgroup_set_timestamp(struct task_struct *task,
1090 struct perf_event_context *ctx)
1095 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
1100 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
1104 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1110 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1115 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1121 * set default to be dependent on timer tick just
1122 * like original code
1124 #define PERF_CPU_HRTIMER (1000 / HZ)
1126 * function must be called with interrupts disabled
1128 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1130 struct perf_cpu_context *cpuctx;
1133 lockdep_assert_irqs_disabled();
1135 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
1136 rotations = perf_rotate_context(cpuctx);
1138 raw_spin_lock(&cpuctx->hrtimer_lock);
1140 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
1142 cpuctx->hrtimer_active = 0;
1143 raw_spin_unlock(&cpuctx->hrtimer_lock);
1145 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1148 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
1150 struct hrtimer *timer = &cpuctx->hrtimer;
1151 struct pmu *pmu = cpuctx->ctx.pmu;
1154 /* no multiplexing needed for SW PMU */
1155 if (pmu->task_ctx_nr == perf_sw_context)
1159 * check default is sane, if not set then force to
1160 * default interval (1/tick)
1162 interval = pmu->hrtimer_interval_ms;
1164 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1166 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1168 raw_spin_lock_init(&cpuctx->hrtimer_lock);
1169 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
1170 timer->function = perf_mux_hrtimer_handler;
1173 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1175 struct hrtimer *timer = &cpuctx->hrtimer;
1176 struct pmu *pmu = cpuctx->ctx.pmu;
1177 unsigned long flags;
1179 /* not for SW PMU */
1180 if (pmu->task_ctx_nr == perf_sw_context)
1183 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1184 if (!cpuctx->hrtimer_active) {
1185 cpuctx->hrtimer_active = 1;
1186 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1187 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1189 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1194 void perf_pmu_disable(struct pmu *pmu)
1196 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1198 pmu->pmu_disable(pmu);
1201 void perf_pmu_enable(struct pmu *pmu)
1203 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1205 pmu->pmu_enable(pmu);
1208 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1211 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1212 * perf_event_task_tick() are fully serialized because they're strictly cpu
1213 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1214 * disabled, while perf_event_task_tick is called from IRQ context.
1216 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1218 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1220 lockdep_assert_irqs_disabled();
1222 WARN_ON(!list_empty(&ctx->active_ctx_list));
1224 list_add(&ctx->active_ctx_list, head);
1227 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1229 lockdep_assert_irqs_disabled();
1231 WARN_ON(list_empty(&ctx->active_ctx_list));
1233 list_del_init(&ctx->active_ctx_list);
1236 static void get_ctx(struct perf_event_context *ctx)
1238 refcount_inc(&ctx->refcount);
1241 static void *alloc_task_ctx_data(struct pmu *pmu)
1243 if (pmu->task_ctx_cache)
1244 return kmem_cache_zalloc(pmu->task_ctx_cache, GFP_KERNEL);
1249 static void free_task_ctx_data(struct pmu *pmu, void *task_ctx_data)
1251 if (pmu->task_ctx_cache && task_ctx_data)
1252 kmem_cache_free(pmu->task_ctx_cache, task_ctx_data);
1255 static void free_ctx(struct rcu_head *head)
1257 struct perf_event_context *ctx;
1259 ctx = container_of(head, struct perf_event_context, rcu_head);
1260 free_task_ctx_data(ctx->pmu, ctx->task_ctx_data);
1264 static void put_ctx(struct perf_event_context *ctx)
1266 if (refcount_dec_and_test(&ctx->refcount)) {
1267 if (ctx->parent_ctx)
1268 put_ctx(ctx->parent_ctx);
1269 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1270 put_task_struct(ctx->task);
1271 call_rcu(&ctx->rcu_head, free_ctx);
1276 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1277 * perf_pmu_migrate_context() we need some magic.
1279 * Those places that change perf_event::ctx will hold both
1280 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1282 * Lock ordering is by mutex address. There are two other sites where
1283 * perf_event_context::mutex nests and those are:
1285 * - perf_event_exit_task_context() [ child , 0 ]
1286 * perf_event_exit_event()
1287 * put_event() [ parent, 1 ]
1289 * - perf_event_init_context() [ parent, 0 ]
1290 * inherit_task_group()
1293 * perf_event_alloc()
1295 * perf_try_init_event() [ child , 1 ]
1297 * While it appears there is an obvious deadlock here -- the parent and child
1298 * nesting levels are inverted between the two. This is in fact safe because
1299 * life-time rules separate them. That is an exiting task cannot fork, and a
1300 * spawning task cannot (yet) exit.
1302 * But remember that these are parent<->child context relations, and
1303 * migration does not affect children, therefore these two orderings should not
1306 * The change in perf_event::ctx does not affect children (as claimed above)
1307 * because the sys_perf_event_open() case will install a new event and break
1308 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1309 * concerned with cpuctx and that doesn't have children.
1311 * The places that change perf_event::ctx will issue:
1313 * perf_remove_from_context();
1314 * synchronize_rcu();
1315 * perf_install_in_context();
1317 * to affect the change. The remove_from_context() + synchronize_rcu() should
1318 * quiesce the event, after which we can install it in the new location. This
1319 * means that only external vectors (perf_fops, prctl) can perturb the event
1320 * while in transit. Therefore all such accessors should also acquire
1321 * perf_event_context::mutex to serialize against this.
1323 * However; because event->ctx can change while we're waiting to acquire
1324 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1329 * task_struct::perf_event_mutex
1330 * perf_event_context::mutex
1331 * perf_event::child_mutex;
1332 * perf_event_context::lock
1333 * perf_event::mmap_mutex
1335 * perf_addr_filters_head::lock
1339 * cpuctx->mutex / perf_event_context::mutex
1341 static struct perf_event_context *
1342 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1344 struct perf_event_context *ctx;
1348 ctx = READ_ONCE(event->ctx);
1349 if (!refcount_inc_not_zero(&ctx->refcount)) {
1355 mutex_lock_nested(&ctx->mutex, nesting);
1356 if (event->ctx != ctx) {
1357 mutex_unlock(&ctx->mutex);
1365 static inline struct perf_event_context *
1366 perf_event_ctx_lock(struct perf_event *event)
1368 return perf_event_ctx_lock_nested(event, 0);
1371 static void perf_event_ctx_unlock(struct perf_event *event,
1372 struct perf_event_context *ctx)
1374 mutex_unlock(&ctx->mutex);
1379 * This must be done under the ctx->lock, such as to serialize against
1380 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1381 * calling scheduler related locks and ctx->lock nests inside those.
1383 static __must_check struct perf_event_context *
1384 unclone_ctx(struct perf_event_context *ctx)
1386 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1388 lockdep_assert_held(&ctx->lock);
1391 ctx->parent_ctx = NULL;
1397 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1402 * only top level events have the pid namespace they were created in
1405 event = event->parent;
1407 nr = __task_pid_nr_ns(p, type, event->ns);
1408 /* avoid -1 if it is idle thread or runs in another ns */
1409 if (!nr && !pid_alive(p))
1414 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1416 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1419 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1421 return perf_event_pid_type(event, p, PIDTYPE_PID);
1425 * If we inherit events we want to return the parent event id
1428 static u64 primary_event_id(struct perf_event *event)
1433 id = event->parent->id;
1439 * Get the perf_event_context for a task and lock it.
1441 * This has to cope with the fact that until it is locked,
1442 * the context could get moved to another task.
1444 static struct perf_event_context *
1445 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1447 struct perf_event_context *ctx;
1451 * One of the few rules of preemptible RCU is that one cannot do
1452 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1453 * part of the read side critical section was irqs-enabled -- see
1454 * rcu_read_unlock_special().
1456 * Since ctx->lock nests under rq->lock we must ensure the entire read
1457 * side critical section has interrupts disabled.
1459 local_irq_save(*flags);
1461 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1464 * If this context is a clone of another, it might
1465 * get swapped for another underneath us by
1466 * perf_event_task_sched_out, though the
1467 * rcu_read_lock() protects us from any context
1468 * getting freed. Lock the context and check if it
1469 * got swapped before we could get the lock, and retry
1470 * if so. If we locked the right context, then it
1471 * can't get swapped on us any more.
1473 raw_spin_lock(&ctx->lock);
1474 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1475 raw_spin_unlock(&ctx->lock);
1477 local_irq_restore(*flags);
1481 if (ctx->task == TASK_TOMBSTONE ||
1482 !refcount_inc_not_zero(&ctx->refcount)) {
1483 raw_spin_unlock(&ctx->lock);
1486 WARN_ON_ONCE(ctx->task != task);
1491 local_irq_restore(*flags);
1496 * Get the context for a task and increment its pin_count so it
1497 * can't get swapped to another task. This also increments its
1498 * reference count so that the context can't get freed.
1500 static struct perf_event_context *
1501 perf_pin_task_context(struct task_struct *task, int ctxn)
1503 struct perf_event_context *ctx;
1504 unsigned long flags;
1506 ctx = perf_lock_task_context(task, ctxn, &flags);
1509 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1514 static void perf_unpin_context(struct perf_event_context *ctx)
1516 unsigned long flags;
1518 raw_spin_lock_irqsave(&ctx->lock, flags);
1520 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1524 * Update the record of the current time in a context.
1526 static void update_context_time(struct perf_event_context *ctx)
1528 u64 now = perf_clock();
1530 ctx->time += now - ctx->timestamp;
1531 ctx->timestamp = now;
1534 static u64 perf_event_time(struct perf_event *event)
1536 struct perf_event_context *ctx = event->ctx;
1538 if (is_cgroup_event(event))
1539 return perf_cgroup_event_time(event);
1541 return ctx ? ctx->time : 0;
1544 static enum event_type_t get_event_type(struct perf_event *event)
1546 struct perf_event_context *ctx = event->ctx;
1547 enum event_type_t event_type;
1549 lockdep_assert_held(&ctx->lock);
1552 * It's 'group type', really, because if our group leader is
1553 * pinned, so are we.
1555 if (event->group_leader != event)
1556 event = event->group_leader;
1558 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1560 event_type |= EVENT_CPU;
1566 * Helper function to initialize event group nodes.
1568 static void init_event_group(struct perf_event *event)
1570 RB_CLEAR_NODE(&event->group_node);
1571 event->group_index = 0;
1575 * Extract pinned or flexible groups from the context
1576 * based on event attrs bits.
1578 static struct perf_event_groups *
1579 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1581 if (event->attr.pinned)
1582 return &ctx->pinned_groups;
1584 return &ctx->flexible_groups;
1588 * Helper function to initializes perf_event_group trees.
1590 static void perf_event_groups_init(struct perf_event_groups *groups)
1592 groups->tree = RB_ROOT;
1596 static inline struct cgroup *event_cgroup(const struct perf_event *event)
1598 struct cgroup *cgroup = NULL;
1600 #ifdef CONFIG_CGROUP_PERF
1602 cgroup = event->cgrp->css.cgroup;
1609 * Compare function for event groups;
1611 * Implements complex key that first sorts by CPU and then by virtual index
1612 * which provides ordering when rotating groups for the same CPU.
1614 static __always_inline int
1615 perf_event_groups_cmp(const int left_cpu, const struct cgroup *left_cgroup,
1616 const u64 left_group_index, const struct perf_event *right)
1618 if (left_cpu < right->cpu)
1620 if (left_cpu > right->cpu)
1623 #ifdef CONFIG_CGROUP_PERF
1625 const struct cgroup *right_cgroup = event_cgroup(right);
1627 if (left_cgroup != right_cgroup) {
1630 * Left has no cgroup but right does, no
1631 * cgroups come first.
1635 if (!right_cgroup) {
1637 * Right has no cgroup but left does, no
1638 * cgroups come first.
1642 /* Two dissimilar cgroups, order by id. */
1643 if (cgroup_id(left_cgroup) < cgroup_id(right_cgroup))
1651 if (left_group_index < right->group_index)
1653 if (left_group_index > right->group_index)
1659 #define __node_2_pe(node) \
1660 rb_entry((node), struct perf_event, group_node)
1662 static inline bool __group_less(struct rb_node *a, const struct rb_node *b)
1664 struct perf_event *e = __node_2_pe(a);
1665 return perf_event_groups_cmp(e->cpu, event_cgroup(e), e->group_index,
1666 __node_2_pe(b)) < 0;
1669 struct __group_key {
1671 struct cgroup *cgroup;
1674 static inline int __group_cmp(const void *key, const struct rb_node *node)
1676 const struct __group_key *a = key;
1677 const struct perf_event *b = __node_2_pe(node);
1679 /* partial/subtree match: @cpu, @cgroup; ignore: @group_index */
1680 return perf_event_groups_cmp(a->cpu, a->cgroup, b->group_index, b);
1684 * Insert @event into @groups' tree; using {@event->cpu, ++@groups->index} for
1685 * key (see perf_event_groups_less). This places it last inside the CPU
1689 perf_event_groups_insert(struct perf_event_groups *groups,
1690 struct perf_event *event)
1692 event->group_index = ++groups->index;
1694 rb_add(&event->group_node, &groups->tree, __group_less);
1698 * Helper function to insert event into the pinned or flexible groups.
1701 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1703 struct perf_event_groups *groups;
1705 groups = get_event_groups(event, ctx);
1706 perf_event_groups_insert(groups, event);
1710 * Delete a group from a tree.
1713 perf_event_groups_delete(struct perf_event_groups *groups,
1714 struct perf_event *event)
1716 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1717 RB_EMPTY_ROOT(&groups->tree));
1719 rb_erase(&event->group_node, &groups->tree);
1720 init_event_group(event);
1724 * Helper function to delete event from its groups.
1727 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1729 struct perf_event_groups *groups;
1731 groups = get_event_groups(event, ctx);
1732 perf_event_groups_delete(groups, event);
1736 * Get the leftmost event in the cpu/cgroup subtree.
1738 static struct perf_event *
1739 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1740 struct cgroup *cgrp)
1742 struct __group_key key = {
1746 struct rb_node *node;
1748 node = rb_find_first(&key, &groups->tree, __group_cmp);
1750 return __node_2_pe(node);
1756 * Like rb_entry_next_safe() for the @cpu subtree.
1758 static struct perf_event *
1759 perf_event_groups_next(struct perf_event *event)
1761 struct __group_key key = {
1763 .cgroup = event_cgroup(event),
1765 struct rb_node *next;
1767 next = rb_next_match(&key, &event->group_node, __group_cmp);
1769 return __node_2_pe(next);
1775 * Iterate through the whole groups tree.
1777 #define perf_event_groups_for_each(event, groups) \
1778 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1779 typeof(*event), group_node); event; \
1780 event = rb_entry_safe(rb_next(&event->group_node), \
1781 typeof(*event), group_node))
1784 * Add an event from the lists for its context.
1785 * Must be called with ctx->mutex and ctx->lock held.
1788 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1790 lockdep_assert_held(&ctx->lock);
1792 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1793 event->attach_state |= PERF_ATTACH_CONTEXT;
1795 event->tstamp = perf_event_time(event);
1798 * If we're a stand alone event or group leader, we go to the context
1799 * list, group events are kept attached to the group so that
1800 * perf_group_detach can, at all times, locate all siblings.
1802 if (event->group_leader == event) {
1803 event->group_caps = event->event_caps;
1804 add_event_to_groups(event, ctx);
1807 list_add_rcu(&event->event_entry, &ctx->event_list);
1809 if (event->attr.inherit_stat)
1812 if (event->state > PERF_EVENT_STATE_OFF)
1813 perf_cgroup_event_enable(event, ctx);
1819 * Initialize event state based on the perf_event_attr::disabled.
1821 static inline void perf_event__state_init(struct perf_event *event)
1823 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1824 PERF_EVENT_STATE_INACTIVE;
1827 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1829 int entry = sizeof(u64); /* value */
1833 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1834 size += sizeof(u64);
1836 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1837 size += sizeof(u64);
1839 if (event->attr.read_format & PERF_FORMAT_ID)
1840 entry += sizeof(u64);
1842 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1844 size += sizeof(u64);
1848 event->read_size = size;
1851 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1853 struct perf_sample_data *data;
1856 if (sample_type & PERF_SAMPLE_IP)
1857 size += sizeof(data->ip);
1859 if (sample_type & PERF_SAMPLE_ADDR)
1860 size += sizeof(data->addr);
1862 if (sample_type & PERF_SAMPLE_PERIOD)
1863 size += sizeof(data->period);
1865 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
1866 size += sizeof(data->weight.full);
1868 if (sample_type & PERF_SAMPLE_READ)
1869 size += event->read_size;
1871 if (sample_type & PERF_SAMPLE_DATA_SRC)
1872 size += sizeof(data->data_src.val);
1874 if (sample_type & PERF_SAMPLE_TRANSACTION)
1875 size += sizeof(data->txn);
1877 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1878 size += sizeof(data->phys_addr);
1880 if (sample_type & PERF_SAMPLE_CGROUP)
1881 size += sizeof(data->cgroup);
1883 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
1884 size += sizeof(data->data_page_size);
1886 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
1887 size += sizeof(data->code_page_size);
1889 event->header_size = size;
1893 * Called at perf_event creation and when events are attached/detached from a
1896 static void perf_event__header_size(struct perf_event *event)
1898 __perf_event_read_size(event,
1899 event->group_leader->nr_siblings);
1900 __perf_event_header_size(event, event->attr.sample_type);
1903 static void perf_event__id_header_size(struct perf_event *event)
1905 struct perf_sample_data *data;
1906 u64 sample_type = event->attr.sample_type;
1909 if (sample_type & PERF_SAMPLE_TID)
1910 size += sizeof(data->tid_entry);
1912 if (sample_type & PERF_SAMPLE_TIME)
1913 size += sizeof(data->time);
1915 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1916 size += sizeof(data->id);
1918 if (sample_type & PERF_SAMPLE_ID)
1919 size += sizeof(data->id);
1921 if (sample_type & PERF_SAMPLE_STREAM_ID)
1922 size += sizeof(data->stream_id);
1924 if (sample_type & PERF_SAMPLE_CPU)
1925 size += sizeof(data->cpu_entry);
1927 event->id_header_size = size;
1930 static bool perf_event_validate_size(struct perf_event *event)
1933 * The values computed here will be over-written when we actually
1936 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1937 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1938 perf_event__id_header_size(event);
1941 * Sum the lot; should not exceed the 64k limit we have on records.
1942 * Conservative limit to allow for callchains and other variable fields.
1944 if (event->read_size + event->header_size +
1945 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1951 static void perf_group_attach(struct perf_event *event)
1953 struct perf_event *group_leader = event->group_leader, *pos;
1955 lockdep_assert_held(&event->ctx->lock);
1958 * We can have double attach due to group movement in perf_event_open.
1960 if (event->attach_state & PERF_ATTACH_GROUP)
1963 event->attach_state |= PERF_ATTACH_GROUP;
1965 if (group_leader == event)
1968 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1970 group_leader->group_caps &= event->event_caps;
1972 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
1973 group_leader->nr_siblings++;
1975 perf_event__header_size(group_leader);
1977 for_each_sibling_event(pos, group_leader)
1978 perf_event__header_size(pos);
1982 * Remove an event from the lists for its context.
1983 * Must be called with ctx->mutex and ctx->lock held.
1986 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1988 WARN_ON_ONCE(event->ctx != ctx);
1989 lockdep_assert_held(&ctx->lock);
1992 * We can have double detach due to exit/hot-unplug + close.
1994 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1997 event->attach_state &= ~PERF_ATTACH_CONTEXT;
2000 if (event->attr.inherit_stat)
2003 list_del_rcu(&event->event_entry);
2005 if (event->group_leader == event)
2006 del_event_from_groups(event, ctx);
2009 * If event was in error state, then keep it
2010 * that way, otherwise bogus counts will be
2011 * returned on read(). The only way to get out
2012 * of error state is by explicit re-enabling
2015 if (event->state > PERF_EVENT_STATE_OFF) {
2016 perf_cgroup_event_disable(event, ctx);
2017 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2024 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2026 if (!has_aux(aux_event))
2029 if (!event->pmu->aux_output_match)
2032 return event->pmu->aux_output_match(aux_event);
2035 static void put_event(struct perf_event *event);
2036 static void event_sched_out(struct perf_event *event,
2037 struct perf_cpu_context *cpuctx,
2038 struct perf_event_context *ctx);
2040 static void perf_put_aux_event(struct perf_event *event)
2042 struct perf_event_context *ctx = event->ctx;
2043 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2044 struct perf_event *iter;
2047 * If event uses aux_event tear down the link
2049 if (event->aux_event) {
2050 iter = event->aux_event;
2051 event->aux_event = NULL;
2057 * If the event is an aux_event, tear down all links to
2058 * it from other events.
2060 for_each_sibling_event(iter, event->group_leader) {
2061 if (iter->aux_event != event)
2064 iter->aux_event = NULL;
2068 * If it's ACTIVE, schedule it out and put it into ERROR
2069 * state so that we don't try to schedule it again. Note
2070 * that perf_event_enable() will clear the ERROR status.
2072 event_sched_out(iter, cpuctx, ctx);
2073 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2077 static bool perf_need_aux_event(struct perf_event *event)
2079 return !!event->attr.aux_output || !!event->attr.aux_sample_size;
2082 static int perf_get_aux_event(struct perf_event *event,
2083 struct perf_event *group_leader)
2086 * Our group leader must be an aux event if we want to be
2087 * an aux_output. This way, the aux event will precede its
2088 * aux_output events in the group, and therefore will always
2095 * aux_output and aux_sample_size are mutually exclusive.
2097 if (event->attr.aux_output && event->attr.aux_sample_size)
2100 if (event->attr.aux_output &&
2101 !perf_aux_output_match(event, group_leader))
2104 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2107 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2111 * Link aux_outputs to their aux event; this is undone in
2112 * perf_group_detach() by perf_put_aux_event(). When the
2113 * group in torn down, the aux_output events loose their
2114 * link to the aux_event and can't schedule any more.
2116 event->aux_event = group_leader;
2121 static inline struct list_head *get_event_list(struct perf_event *event)
2123 struct perf_event_context *ctx = event->ctx;
2124 return event->attr.pinned ? &ctx->pinned_active : &ctx->flexible_active;
2128 * Events that have PERF_EV_CAP_SIBLING require being part of a group and
2129 * cannot exist on their own, schedule them out and move them into the ERROR
2130 * state. Also see _perf_event_enable(), it will not be able to recover
2133 static inline void perf_remove_sibling_event(struct perf_event *event)
2135 struct perf_event_context *ctx = event->ctx;
2136 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2138 event_sched_out(event, cpuctx, ctx);
2139 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2142 static void perf_group_detach(struct perf_event *event)
2144 struct perf_event *leader = event->group_leader;
2145 struct perf_event *sibling, *tmp;
2146 struct perf_event_context *ctx = event->ctx;
2148 lockdep_assert_held(&ctx->lock);
2151 * We can have double detach due to exit/hot-unplug + close.
2153 if (!(event->attach_state & PERF_ATTACH_GROUP))
2156 event->attach_state &= ~PERF_ATTACH_GROUP;
2158 perf_put_aux_event(event);
2161 * If this is a sibling, remove it from its group.
2163 if (leader != event) {
2164 list_del_init(&event->sibling_list);
2165 event->group_leader->nr_siblings--;
2170 * If this was a group event with sibling events then
2171 * upgrade the siblings to singleton events by adding them
2172 * to whatever list we are on.
2174 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2176 if (sibling->event_caps & PERF_EV_CAP_SIBLING)
2177 perf_remove_sibling_event(sibling);
2179 sibling->group_leader = sibling;
2180 list_del_init(&sibling->sibling_list);
2182 /* Inherit group flags from the previous leader */
2183 sibling->group_caps = event->group_caps;
2185 if (!RB_EMPTY_NODE(&event->group_node)) {
2186 add_event_to_groups(sibling, event->ctx);
2188 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2189 list_add_tail(&sibling->active_list, get_event_list(sibling));
2192 WARN_ON_ONCE(sibling->ctx != event->ctx);
2196 for_each_sibling_event(tmp, leader)
2197 perf_event__header_size(tmp);
2199 perf_event__header_size(leader);
2202 static bool is_orphaned_event(struct perf_event *event)
2204 return event->state == PERF_EVENT_STATE_DEAD;
2207 static inline int __pmu_filter_match(struct perf_event *event)
2209 struct pmu *pmu = event->pmu;
2210 return pmu->filter_match ? pmu->filter_match(event) : 1;
2214 * Check whether we should attempt to schedule an event group based on
2215 * PMU-specific filtering. An event group can consist of HW and SW events,
2216 * potentially with a SW leader, so we must check all the filters, to
2217 * determine whether a group is schedulable:
2219 static inline int pmu_filter_match(struct perf_event *event)
2221 struct perf_event *sibling;
2223 if (!__pmu_filter_match(event))
2226 for_each_sibling_event(sibling, event) {
2227 if (!__pmu_filter_match(sibling))
2235 event_filter_match(struct perf_event *event)
2237 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2238 perf_cgroup_match(event) && pmu_filter_match(event);
2242 event_sched_out(struct perf_event *event,
2243 struct perf_cpu_context *cpuctx,
2244 struct perf_event_context *ctx)
2246 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2248 WARN_ON_ONCE(event->ctx != ctx);
2249 lockdep_assert_held(&ctx->lock);
2251 if (event->state != PERF_EVENT_STATE_ACTIVE)
2255 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2256 * we can schedule events _OUT_ individually through things like
2257 * __perf_remove_from_context().
2259 list_del_init(&event->active_list);
2261 perf_pmu_disable(event->pmu);
2263 event->pmu->del(event, 0);
2266 if (READ_ONCE(event->pending_disable) >= 0) {
2267 WRITE_ONCE(event->pending_disable, -1);
2268 perf_cgroup_event_disable(event, ctx);
2269 state = PERF_EVENT_STATE_OFF;
2271 perf_event_set_state(event, state);
2273 if (!is_software_event(event))
2274 cpuctx->active_oncpu--;
2275 if (!--ctx->nr_active)
2276 perf_event_ctx_deactivate(ctx);
2277 if (event->attr.freq && event->attr.sample_freq)
2279 if (event->attr.exclusive || !cpuctx->active_oncpu)
2280 cpuctx->exclusive = 0;
2282 perf_pmu_enable(event->pmu);
2286 group_sched_out(struct perf_event *group_event,
2287 struct perf_cpu_context *cpuctx,
2288 struct perf_event_context *ctx)
2290 struct perf_event *event;
2292 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2295 perf_pmu_disable(ctx->pmu);
2297 event_sched_out(group_event, cpuctx, ctx);
2300 * Schedule out siblings (if any):
2302 for_each_sibling_event(event, group_event)
2303 event_sched_out(event, cpuctx, ctx);
2305 perf_pmu_enable(ctx->pmu);
2308 #define DETACH_GROUP 0x01UL
2311 * Cross CPU call to remove a performance event
2313 * We disable the event on the hardware level first. After that we
2314 * remove it from the context list.
2317 __perf_remove_from_context(struct perf_event *event,
2318 struct perf_cpu_context *cpuctx,
2319 struct perf_event_context *ctx,
2322 unsigned long flags = (unsigned long)info;
2324 if (ctx->is_active & EVENT_TIME) {
2325 update_context_time(ctx);
2326 update_cgrp_time_from_cpuctx(cpuctx);
2329 event_sched_out(event, cpuctx, ctx);
2330 if (flags & DETACH_GROUP)
2331 perf_group_detach(event);
2332 list_del_event(event, ctx);
2334 if (!ctx->nr_events && ctx->is_active) {
2336 ctx->rotate_necessary = 0;
2338 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2339 cpuctx->task_ctx = NULL;
2345 * Remove the event from a task's (or a CPU's) list of events.
2347 * If event->ctx is a cloned context, callers must make sure that
2348 * every task struct that event->ctx->task could possibly point to
2349 * remains valid. This is OK when called from perf_release since
2350 * that only calls us on the top-level context, which can't be a clone.
2351 * When called from perf_event_exit_task, it's OK because the
2352 * context has been detached from its task.
2354 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2356 struct perf_event_context *ctx = event->ctx;
2358 lockdep_assert_held(&ctx->mutex);
2360 event_function_call(event, __perf_remove_from_context, (void *)flags);
2363 * The above event_function_call() can NO-OP when it hits
2364 * TASK_TOMBSTONE. In that case we must already have been detached
2365 * from the context (by perf_event_exit_event()) but the grouping
2366 * might still be in-tact.
2368 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
2369 if ((flags & DETACH_GROUP) &&
2370 (event->attach_state & PERF_ATTACH_GROUP)) {
2372 * Since in that case we cannot possibly be scheduled, simply
2375 raw_spin_lock_irq(&ctx->lock);
2376 perf_group_detach(event);
2377 raw_spin_unlock_irq(&ctx->lock);
2382 * Cross CPU call to disable a performance event
2384 static void __perf_event_disable(struct perf_event *event,
2385 struct perf_cpu_context *cpuctx,
2386 struct perf_event_context *ctx,
2389 if (event->state < PERF_EVENT_STATE_INACTIVE)
2392 if (ctx->is_active & EVENT_TIME) {
2393 update_context_time(ctx);
2394 update_cgrp_time_from_event(event);
2397 if (event == event->group_leader)
2398 group_sched_out(event, cpuctx, ctx);
2400 event_sched_out(event, cpuctx, ctx);
2402 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2403 perf_cgroup_event_disable(event, ctx);
2409 * If event->ctx is a cloned context, callers must make sure that
2410 * every task struct that event->ctx->task could possibly point to
2411 * remains valid. This condition is satisfied when called through
2412 * perf_event_for_each_child or perf_event_for_each because they
2413 * hold the top-level event's child_mutex, so any descendant that
2414 * goes to exit will block in perf_event_exit_event().
2416 * When called from perf_pending_event it's OK because event->ctx
2417 * is the current context on this CPU and preemption is disabled,
2418 * hence we can't get into perf_event_task_sched_out for this context.
2420 static void _perf_event_disable(struct perf_event *event)
2422 struct perf_event_context *ctx = event->ctx;
2424 raw_spin_lock_irq(&ctx->lock);
2425 if (event->state <= PERF_EVENT_STATE_OFF) {
2426 raw_spin_unlock_irq(&ctx->lock);
2429 raw_spin_unlock_irq(&ctx->lock);
2431 event_function_call(event, __perf_event_disable, NULL);
2434 void perf_event_disable_local(struct perf_event *event)
2436 event_function_local(event, __perf_event_disable, NULL);
2440 * Strictly speaking kernel users cannot create groups and therefore this
2441 * interface does not need the perf_event_ctx_lock() magic.
2443 void perf_event_disable(struct perf_event *event)
2445 struct perf_event_context *ctx;
2447 ctx = perf_event_ctx_lock(event);
2448 _perf_event_disable(event);
2449 perf_event_ctx_unlock(event, ctx);
2451 EXPORT_SYMBOL_GPL(perf_event_disable);
2453 void perf_event_disable_inatomic(struct perf_event *event)
2455 WRITE_ONCE(event->pending_disable, smp_processor_id());
2456 /* can fail, see perf_pending_event_disable() */
2457 irq_work_queue(&event->pending);
2460 static void perf_set_shadow_time(struct perf_event *event,
2461 struct perf_event_context *ctx)
2464 * use the correct time source for the time snapshot
2466 * We could get by without this by leveraging the
2467 * fact that to get to this function, the caller
2468 * has most likely already called update_context_time()
2469 * and update_cgrp_time_xx() and thus both timestamp
2470 * are identical (or very close). Given that tstamp is,
2471 * already adjusted for cgroup, we could say that:
2472 * tstamp - ctx->timestamp
2474 * tstamp - cgrp->timestamp.
2476 * Then, in perf_output_read(), the calculation would
2477 * work with no changes because:
2478 * - event is guaranteed scheduled in
2479 * - no scheduled out in between
2480 * - thus the timestamp would be the same
2482 * But this is a bit hairy.
2484 * So instead, we have an explicit cgroup call to remain
2485 * within the time source all along. We believe it
2486 * is cleaner and simpler to understand.
2488 if (is_cgroup_event(event))
2489 perf_cgroup_set_shadow_time(event, event->tstamp);
2491 event->shadow_ctx_time = event->tstamp - ctx->timestamp;
2494 #define MAX_INTERRUPTS (~0ULL)
2496 static void perf_log_throttle(struct perf_event *event, int enable);
2497 static void perf_log_itrace_start(struct perf_event *event);
2500 event_sched_in(struct perf_event *event,
2501 struct perf_cpu_context *cpuctx,
2502 struct perf_event_context *ctx)
2506 WARN_ON_ONCE(event->ctx != ctx);
2508 lockdep_assert_held(&ctx->lock);
2510 if (event->state <= PERF_EVENT_STATE_OFF)
2513 WRITE_ONCE(event->oncpu, smp_processor_id());
2515 * Order event::oncpu write to happen before the ACTIVE state is
2516 * visible. This allows perf_event_{stop,read}() to observe the correct
2517 * ->oncpu if it sees ACTIVE.
2520 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2523 * Unthrottle events, since we scheduled we might have missed several
2524 * ticks already, also for a heavily scheduling task there is little
2525 * guarantee it'll get a tick in a timely manner.
2527 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2528 perf_log_throttle(event, 1);
2529 event->hw.interrupts = 0;
2532 perf_pmu_disable(event->pmu);
2534 perf_set_shadow_time(event, ctx);
2536 perf_log_itrace_start(event);
2538 if (event->pmu->add(event, PERF_EF_START)) {
2539 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2545 if (!is_software_event(event))
2546 cpuctx->active_oncpu++;
2547 if (!ctx->nr_active++)
2548 perf_event_ctx_activate(ctx);
2549 if (event->attr.freq && event->attr.sample_freq)
2552 if (event->attr.exclusive)
2553 cpuctx->exclusive = 1;
2556 perf_pmu_enable(event->pmu);
2562 group_sched_in(struct perf_event *group_event,
2563 struct perf_cpu_context *cpuctx,
2564 struct perf_event_context *ctx)
2566 struct perf_event *event, *partial_group = NULL;
2567 struct pmu *pmu = ctx->pmu;
2569 if (group_event->state == PERF_EVENT_STATE_OFF)
2572 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2574 if (event_sched_in(group_event, cpuctx, ctx))
2578 * Schedule in siblings as one group (if any):
2580 for_each_sibling_event(event, group_event) {
2581 if (event_sched_in(event, cpuctx, ctx)) {
2582 partial_group = event;
2587 if (!pmu->commit_txn(pmu))
2592 * Groups can be scheduled in as one unit only, so undo any
2593 * partial group before returning:
2594 * The events up to the failed event are scheduled out normally.
2596 for_each_sibling_event(event, group_event) {
2597 if (event == partial_group)
2600 event_sched_out(event, cpuctx, ctx);
2602 event_sched_out(group_event, cpuctx, ctx);
2605 pmu->cancel_txn(pmu);
2610 * Work out whether we can put this event group on the CPU now.
2612 static int group_can_go_on(struct perf_event *event,
2613 struct perf_cpu_context *cpuctx,
2617 * Groups consisting entirely of software events can always go on.
2619 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2622 * If an exclusive group is already on, no other hardware
2625 if (cpuctx->exclusive)
2628 * If this group is exclusive and there are already
2629 * events on the CPU, it can't go on.
2631 if (event->attr.exclusive && !list_empty(get_event_list(event)))
2634 * Otherwise, try to add it if all previous groups were able
2640 static void add_event_to_ctx(struct perf_event *event,
2641 struct perf_event_context *ctx)
2643 list_add_event(event, ctx);
2644 perf_group_attach(event);
2647 static void ctx_sched_out(struct perf_event_context *ctx,
2648 struct perf_cpu_context *cpuctx,
2649 enum event_type_t event_type);
2651 ctx_sched_in(struct perf_event_context *ctx,
2652 struct perf_cpu_context *cpuctx,
2653 enum event_type_t event_type,
2654 struct task_struct *task);
2656 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2657 struct perf_event_context *ctx,
2658 enum event_type_t event_type)
2660 if (!cpuctx->task_ctx)
2663 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2666 ctx_sched_out(ctx, cpuctx, event_type);
2669 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2670 struct perf_event_context *ctx,
2671 struct task_struct *task)
2673 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2675 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2676 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2678 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2682 * We want to maintain the following priority of scheduling:
2683 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2684 * - task pinned (EVENT_PINNED)
2685 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2686 * - task flexible (EVENT_FLEXIBLE).
2688 * In order to avoid unscheduling and scheduling back in everything every
2689 * time an event is added, only do it for the groups of equal priority and
2692 * This can be called after a batch operation on task events, in which case
2693 * event_type is a bit mask of the types of events involved. For CPU events,
2694 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2696 static void ctx_resched(struct perf_cpu_context *cpuctx,
2697 struct perf_event_context *task_ctx,
2698 enum event_type_t event_type)
2700 enum event_type_t ctx_event_type;
2701 bool cpu_event = !!(event_type & EVENT_CPU);
2704 * If pinned groups are involved, flexible groups also need to be
2707 if (event_type & EVENT_PINNED)
2708 event_type |= EVENT_FLEXIBLE;
2710 ctx_event_type = event_type & EVENT_ALL;
2712 perf_pmu_disable(cpuctx->ctx.pmu);
2714 task_ctx_sched_out(cpuctx, task_ctx, event_type);
2717 * Decide which cpu ctx groups to schedule out based on the types
2718 * of events that caused rescheduling:
2719 * - EVENT_CPU: schedule out corresponding groups;
2720 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2721 * - otherwise, do nothing more.
2724 cpu_ctx_sched_out(cpuctx, ctx_event_type);
2725 else if (ctx_event_type & EVENT_PINNED)
2726 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2728 perf_event_sched_in(cpuctx, task_ctx, current);
2729 perf_pmu_enable(cpuctx->ctx.pmu);
2732 void perf_pmu_resched(struct pmu *pmu)
2734 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2735 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2737 perf_ctx_lock(cpuctx, task_ctx);
2738 ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2739 perf_ctx_unlock(cpuctx, task_ctx);
2743 * Cross CPU call to install and enable a performance event
2745 * Very similar to remote_function() + event_function() but cannot assume that
2746 * things like ctx->is_active and cpuctx->task_ctx are set.
2748 static int __perf_install_in_context(void *info)
2750 struct perf_event *event = info;
2751 struct perf_event_context *ctx = event->ctx;
2752 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2753 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2754 bool reprogram = true;
2757 raw_spin_lock(&cpuctx->ctx.lock);
2759 raw_spin_lock(&ctx->lock);
2762 reprogram = (ctx->task == current);
2765 * If the task is running, it must be running on this CPU,
2766 * otherwise we cannot reprogram things.
2768 * If its not running, we don't care, ctx->lock will
2769 * serialize against it becoming runnable.
2771 if (task_curr(ctx->task) && !reprogram) {
2776 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2777 } else if (task_ctx) {
2778 raw_spin_lock(&task_ctx->lock);
2781 #ifdef CONFIG_CGROUP_PERF
2782 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2784 * If the current cgroup doesn't match the event's
2785 * cgroup, we should not try to schedule it.
2787 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2788 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2789 event->cgrp->css.cgroup);
2794 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2795 add_event_to_ctx(event, ctx);
2796 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2798 add_event_to_ctx(event, ctx);
2802 perf_ctx_unlock(cpuctx, task_ctx);
2807 static bool exclusive_event_installable(struct perf_event *event,
2808 struct perf_event_context *ctx);
2811 * Attach a performance event to a context.
2813 * Very similar to event_function_call, see comment there.
2816 perf_install_in_context(struct perf_event_context *ctx,
2817 struct perf_event *event,
2820 struct task_struct *task = READ_ONCE(ctx->task);
2822 lockdep_assert_held(&ctx->mutex);
2824 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2826 if (event->cpu != -1)
2830 * Ensures that if we can observe event->ctx, both the event and ctx
2831 * will be 'complete'. See perf_iterate_sb_cpu().
2833 smp_store_release(&event->ctx, ctx);
2836 * perf_event_attr::disabled events will not run and can be initialized
2837 * without IPI. Except when this is the first event for the context, in
2838 * that case we need the magic of the IPI to set ctx->is_active.
2840 * The IOC_ENABLE that is sure to follow the creation of a disabled
2841 * event will issue the IPI and reprogram the hardware.
2843 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF && ctx->nr_events) {
2844 raw_spin_lock_irq(&ctx->lock);
2845 if (ctx->task == TASK_TOMBSTONE) {
2846 raw_spin_unlock_irq(&ctx->lock);
2849 add_event_to_ctx(event, ctx);
2850 raw_spin_unlock_irq(&ctx->lock);
2855 cpu_function_call(cpu, __perf_install_in_context, event);
2860 * Should not happen, we validate the ctx is still alive before calling.
2862 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2866 * Installing events is tricky because we cannot rely on ctx->is_active
2867 * to be set in case this is the nr_events 0 -> 1 transition.
2869 * Instead we use task_curr(), which tells us if the task is running.
2870 * However, since we use task_curr() outside of rq::lock, we can race
2871 * against the actual state. This means the result can be wrong.
2873 * If we get a false positive, we retry, this is harmless.
2875 * If we get a false negative, things are complicated. If we are after
2876 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2877 * value must be correct. If we're before, it doesn't matter since
2878 * perf_event_context_sched_in() will program the counter.
2880 * However, this hinges on the remote context switch having observed
2881 * our task->perf_event_ctxp[] store, such that it will in fact take
2882 * ctx::lock in perf_event_context_sched_in().
2884 * We do this by task_function_call(), if the IPI fails to hit the task
2885 * we know any future context switch of task must see the
2886 * perf_event_ctpx[] store.
2890 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2891 * task_cpu() load, such that if the IPI then does not find the task
2892 * running, a future context switch of that task must observe the
2897 if (!task_function_call(task, __perf_install_in_context, event))
2900 raw_spin_lock_irq(&ctx->lock);
2902 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2904 * Cannot happen because we already checked above (which also
2905 * cannot happen), and we hold ctx->mutex, which serializes us
2906 * against perf_event_exit_task_context().
2908 raw_spin_unlock_irq(&ctx->lock);
2912 * If the task is not running, ctx->lock will avoid it becoming so,
2913 * thus we can safely install the event.
2915 if (task_curr(task)) {
2916 raw_spin_unlock_irq(&ctx->lock);
2919 add_event_to_ctx(event, ctx);
2920 raw_spin_unlock_irq(&ctx->lock);
2924 * Cross CPU call to enable a performance event
2926 static void __perf_event_enable(struct perf_event *event,
2927 struct perf_cpu_context *cpuctx,
2928 struct perf_event_context *ctx,
2931 struct perf_event *leader = event->group_leader;
2932 struct perf_event_context *task_ctx;
2934 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2935 event->state <= PERF_EVENT_STATE_ERROR)
2939 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2941 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2942 perf_cgroup_event_enable(event, ctx);
2944 if (!ctx->is_active)
2947 if (!event_filter_match(event)) {
2948 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2953 * If the event is in a group and isn't the group leader,
2954 * then don't put it on unless the group is on.
2956 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2957 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2961 task_ctx = cpuctx->task_ctx;
2963 WARN_ON_ONCE(task_ctx != ctx);
2965 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2971 * If event->ctx is a cloned context, callers must make sure that
2972 * every task struct that event->ctx->task could possibly point to
2973 * remains valid. This condition is satisfied when called through
2974 * perf_event_for_each_child or perf_event_for_each as described
2975 * for perf_event_disable.
2977 static void _perf_event_enable(struct perf_event *event)
2979 struct perf_event_context *ctx = event->ctx;
2981 raw_spin_lock_irq(&ctx->lock);
2982 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2983 event->state < PERF_EVENT_STATE_ERROR) {
2985 raw_spin_unlock_irq(&ctx->lock);
2990 * If the event is in error state, clear that first.
2992 * That way, if we see the event in error state below, we know that it
2993 * has gone back into error state, as distinct from the task having
2994 * been scheduled away before the cross-call arrived.
2996 if (event->state == PERF_EVENT_STATE_ERROR) {
2998 * Detached SIBLING events cannot leave ERROR state.
3000 if (event->event_caps & PERF_EV_CAP_SIBLING &&
3001 event->group_leader == event)
3004 event->state = PERF_EVENT_STATE_OFF;
3006 raw_spin_unlock_irq(&ctx->lock);
3008 event_function_call(event, __perf_event_enable, NULL);
3012 * See perf_event_disable();
3014 void perf_event_enable(struct perf_event *event)
3016 struct perf_event_context *ctx;
3018 ctx = perf_event_ctx_lock(event);
3019 _perf_event_enable(event);
3020 perf_event_ctx_unlock(event, ctx);
3022 EXPORT_SYMBOL_GPL(perf_event_enable);
3024 struct stop_event_data {
3025 struct perf_event *event;
3026 unsigned int restart;
3029 static int __perf_event_stop(void *info)
3031 struct stop_event_data *sd = info;
3032 struct perf_event *event = sd->event;
3034 /* if it's already INACTIVE, do nothing */
3035 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3038 /* matches smp_wmb() in event_sched_in() */
3042 * There is a window with interrupts enabled before we get here,
3043 * so we need to check again lest we try to stop another CPU's event.
3045 if (READ_ONCE(event->oncpu) != smp_processor_id())
3048 event->pmu->stop(event, PERF_EF_UPDATE);
3051 * May race with the actual stop (through perf_pmu_output_stop()),
3052 * but it is only used for events with AUX ring buffer, and such
3053 * events will refuse to restart because of rb::aux_mmap_count==0,
3054 * see comments in perf_aux_output_begin().
3056 * Since this is happening on an event-local CPU, no trace is lost
3060 event->pmu->start(event, 0);
3065 static int perf_event_stop(struct perf_event *event, int restart)
3067 struct stop_event_data sd = {
3074 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3077 /* matches smp_wmb() in event_sched_in() */
3081 * We only want to restart ACTIVE events, so if the event goes
3082 * inactive here (event->oncpu==-1), there's nothing more to do;
3083 * fall through with ret==-ENXIO.
3085 ret = cpu_function_call(READ_ONCE(event->oncpu),
3086 __perf_event_stop, &sd);
3087 } while (ret == -EAGAIN);
3093 * In order to contain the amount of racy and tricky in the address filter
3094 * configuration management, it is a two part process:
3096 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3097 * we update the addresses of corresponding vmas in
3098 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3099 * (p2) when an event is scheduled in (pmu::add), it calls
3100 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3101 * if the generation has changed since the previous call.
3103 * If (p1) happens while the event is active, we restart it to force (p2).
3105 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3106 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3108 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3109 * registered mapping, called for every new mmap(), with mm::mmap_lock down
3111 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3114 void perf_event_addr_filters_sync(struct perf_event *event)
3116 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3118 if (!has_addr_filter(event))
3121 raw_spin_lock(&ifh->lock);
3122 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3123 event->pmu->addr_filters_sync(event);
3124 event->hw.addr_filters_gen = event->addr_filters_gen;
3126 raw_spin_unlock(&ifh->lock);
3128 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3130 static int _perf_event_refresh(struct perf_event *event, int refresh)
3133 * not supported on inherited events
3135 if (event->attr.inherit || !is_sampling_event(event))
3138 atomic_add(refresh, &event->event_limit);
3139 _perf_event_enable(event);
3145 * See perf_event_disable()
3147 int perf_event_refresh(struct perf_event *event, int refresh)
3149 struct perf_event_context *ctx;
3152 ctx = perf_event_ctx_lock(event);
3153 ret = _perf_event_refresh(event, refresh);
3154 perf_event_ctx_unlock(event, ctx);
3158 EXPORT_SYMBOL_GPL(perf_event_refresh);
3160 static int perf_event_modify_breakpoint(struct perf_event *bp,
3161 struct perf_event_attr *attr)
3165 _perf_event_disable(bp);
3167 err = modify_user_hw_breakpoint_check(bp, attr, true);
3169 if (!bp->attr.disabled)
3170 _perf_event_enable(bp);
3175 static int perf_event_modify_attr(struct perf_event *event,
3176 struct perf_event_attr *attr)
3178 if (event->attr.type != attr->type)
3181 switch (event->attr.type) {
3182 case PERF_TYPE_BREAKPOINT:
3183 return perf_event_modify_breakpoint(event, attr);
3185 /* Place holder for future additions. */
3190 static void ctx_sched_out(struct perf_event_context *ctx,
3191 struct perf_cpu_context *cpuctx,
3192 enum event_type_t event_type)
3194 struct perf_event *event, *tmp;
3195 int is_active = ctx->is_active;
3197 lockdep_assert_held(&ctx->lock);
3199 if (likely(!ctx->nr_events)) {
3201 * See __perf_remove_from_context().
3203 WARN_ON_ONCE(ctx->is_active);
3205 WARN_ON_ONCE(cpuctx->task_ctx);
3209 ctx->is_active &= ~event_type;
3210 if (!(ctx->is_active & EVENT_ALL))
3214 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3215 if (!ctx->is_active)
3216 cpuctx->task_ctx = NULL;
3220 * Always update time if it was set; not only when it changes.
3221 * Otherwise we can 'forget' to update time for any but the last
3222 * context we sched out. For example:
3224 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3225 * ctx_sched_out(.event_type = EVENT_PINNED)
3227 * would only update time for the pinned events.
3229 if (is_active & EVENT_TIME) {
3230 /* update (and stop) ctx time */
3231 update_context_time(ctx);
3232 update_cgrp_time_from_cpuctx(cpuctx);
3235 is_active ^= ctx->is_active; /* changed bits */
3237 if (!ctx->nr_active || !(is_active & EVENT_ALL))
3240 perf_pmu_disable(ctx->pmu);
3241 if (is_active & EVENT_PINNED) {
3242 list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list)
3243 group_sched_out(event, cpuctx, ctx);
3246 if (is_active & EVENT_FLEXIBLE) {
3247 list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list)
3248 group_sched_out(event, cpuctx, ctx);
3251 * Since we cleared EVENT_FLEXIBLE, also clear
3252 * rotate_necessary, is will be reset by
3253 * ctx_flexible_sched_in() when needed.
3255 ctx->rotate_necessary = 0;
3257 perf_pmu_enable(ctx->pmu);
3261 * Test whether two contexts are equivalent, i.e. whether they have both been
3262 * cloned from the same version of the same context.
3264 * Equivalence is measured using a generation number in the context that is
3265 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3266 * and list_del_event().
3268 static int context_equiv(struct perf_event_context *ctx1,
3269 struct perf_event_context *ctx2)
3271 lockdep_assert_held(&ctx1->lock);
3272 lockdep_assert_held(&ctx2->lock);
3274 /* Pinning disables the swap optimization */
3275 if (ctx1->pin_count || ctx2->pin_count)
3278 /* If ctx1 is the parent of ctx2 */
3279 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3282 /* If ctx2 is the parent of ctx1 */
3283 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3287 * If ctx1 and ctx2 have the same parent; we flatten the parent
3288 * hierarchy, see perf_event_init_context().
3290 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3291 ctx1->parent_gen == ctx2->parent_gen)
3298 static void __perf_event_sync_stat(struct perf_event *event,
3299 struct perf_event *next_event)
3303 if (!event->attr.inherit_stat)
3307 * Update the event value, we cannot use perf_event_read()
3308 * because we're in the middle of a context switch and have IRQs
3309 * disabled, which upsets smp_call_function_single(), however
3310 * we know the event must be on the current CPU, therefore we
3311 * don't need to use it.
3313 if (event->state == PERF_EVENT_STATE_ACTIVE)
3314 event->pmu->read(event);
3316 perf_event_update_time(event);
3319 * In order to keep per-task stats reliable we need to flip the event
3320 * values when we flip the contexts.
3322 value = local64_read(&next_event->count);
3323 value = local64_xchg(&event->count, value);
3324 local64_set(&next_event->count, value);
3326 swap(event->total_time_enabled, next_event->total_time_enabled);
3327 swap(event->total_time_running, next_event->total_time_running);
3330 * Since we swizzled the values, update the user visible data too.
3332 perf_event_update_userpage(event);
3333 perf_event_update_userpage(next_event);
3336 static void perf_event_sync_stat(struct perf_event_context *ctx,
3337 struct perf_event_context *next_ctx)
3339 struct perf_event *event, *next_event;
3344 update_context_time(ctx);
3346 event = list_first_entry(&ctx->event_list,
3347 struct perf_event, event_entry);
3349 next_event = list_first_entry(&next_ctx->event_list,
3350 struct perf_event, event_entry);
3352 while (&event->event_entry != &ctx->event_list &&
3353 &next_event->event_entry != &next_ctx->event_list) {
3355 __perf_event_sync_stat(event, next_event);
3357 event = list_next_entry(event, event_entry);
3358 next_event = list_next_entry(next_event, event_entry);
3362 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
3363 struct task_struct *next)
3365 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
3366 struct perf_event_context *next_ctx;
3367 struct perf_event_context *parent, *next_parent;
3368 struct perf_cpu_context *cpuctx;
3376 cpuctx = __get_cpu_context(ctx);
3377 if (!cpuctx->task_ctx)
3381 next_ctx = next->perf_event_ctxp[ctxn];
3385 parent = rcu_dereference(ctx->parent_ctx);
3386 next_parent = rcu_dereference(next_ctx->parent_ctx);
3388 /* If neither context have a parent context; they cannot be clones. */
3389 if (!parent && !next_parent)
3392 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3394 * Looks like the two contexts are clones, so we might be
3395 * able to optimize the context switch. We lock both
3396 * contexts and check that they are clones under the
3397 * lock (including re-checking that neither has been
3398 * uncloned in the meantime). It doesn't matter which
3399 * order we take the locks because no other cpu could
3400 * be trying to lock both of these tasks.
3402 raw_spin_lock(&ctx->lock);
3403 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3404 if (context_equiv(ctx, next_ctx)) {
3406 WRITE_ONCE(ctx->task, next);
3407 WRITE_ONCE(next_ctx->task, task);
3409 perf_pmu_disable(pmu);
3411 if (cpuctx->sched_cb_usage && pmu->sched_task)
3412 pmu->sched_task(ctx, false);
3415 * PMU specific parts of task perf context can require
3416 * additional synchronization. As an example of such
3417 * synchronization see implementation details of Intel
3418 * LBR call stack data profiling;
3420 if (pmu->swap_task_ctx)
3421 pmu->swap_task_ctx(ctx, next_ctx);
3423 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
3425 perf_pmu_enable(pmu);
3428 * RCU_INIT_POINTER here is safe because we've not
3429 * modified the ctx and the above modification of
3430 * ctx->task and ctx->task_ctx_data are immaterial
3431 * since those values are always verified under
3432 * ctx->lock which we're now holding.
3434 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
3435 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
3439 perf_event_sync_stat(ctx, next_ctx);
3441 raw_spin_unlock(&next_ctx->lock);
3442 raw_spin_unlock(&ctx->lock);
3448 raw_spin_lock(&ctx->lock);
3449 perf_pmu_disable(pmu);
3451 if (cpuctx->sched_cb_usage && pmu->sched_task)
3452 pmu->sched_task(ctx, false);
3453 task_ctx_sched_out(cpuctx, ctx, EVENT_ALL);
3455 perf_pmu_enable(pmu);
3456 raw_spin_unlock(&ctx->lock);
3460 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3462 void perf_sched_cb_dec(struct pmu *pmu)
3464 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3466 this_cpu_dec(perf_sched_cb_usages);
3468 if (!--cpuctx->sched_cb_usage)
3469 list_del(&cpuctx->sched_cb_entry);
3473 void perf_sched_cb_inc(struct pmu *pmu)
3475 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3477 if (!cpuctx->sched_cb_usage++)
3478 list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3480 this_cpu_inc(perf_sched_cb_usages);
3484 * This function provides the context switch callback to the lower code
3485 * layer. It is invoked ONLY when the context switch callback is enabled.
3487 * This callback is relevant even to per-cpu events; for example multi event
3488 * PEBS requires this to provide PID/TID information. This requires we flush
3489 * all queued PEBS records before we context switch to a new task.
3491 static void __perf_pmu_sched_task(struct perf_cpu_context *cpuctx, bool sched_in)
3495 pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */
3497 if (WARN_ON_ONCE(!pmu->sched_task))
3500 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3501 perf_pmu_disable(pmu);
3503 pmu->sched_task(cpuctx->task_ctx, sched_in);
3505 perf_pmu_enable(pmu);
3506 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3509 static void perf_pmu_sched_task(struct task_struct *prev,
3510 struct task_struct *next,
3513 struct perf_cpu_context *cpuctx;
3518 list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
3519 /* will be handled in perf_event_context_sched_in/out */
3520 if (cpuctx->task_ctx)
3523 __perf_pmu_sched_task(cpuctx, sched_in);
3527 static void perf_event_switch(struct task_struct *task,
3528 struct task_struct *next_prev, bool sched_in);
3530 #define for_each_task_context_nr(ctxn) \
3531 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
3534 * Called from scheduler to remove the events of the current task,
3535 * with interrupts disabled.
3537 * We stop each event and update the event value in event->count.
3539 * This does not protect us against NMI, but disable()
3540 * sets the disabled bit in the control field of event _before_
3541 * accessing the event control register. If a NMI hits, then it will
3542 * not restart the event.
3544 void __perf_event_task_sched_out(struct task_struct *task,
3545 struct task_struct *next)
3549 if (__this_cpu_read(perf_sched_cb_usages))
3550 perf_pmu_sched_task(task, next, false);
3552 if (atomic_read(&nr_switch_events))
3553 perf_event_switch(task, next, false);
3555 for_each_task_context_nr(ctxn)
3556 perf_event_context_sched_out(task, ctxn, next);
3559 * if cgroup events exist on this CPU, then we need
3560 * to check if we have to switch out PMU state.
3561 * cgroup event are system-wide mode only
3563 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3564 perf_cgroup_sched_out(task, next);
3568 * Called with IRQs disabled
3570 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3571 enum event_type_t event_type)
3573 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
3576 static bool perf_less_group_idx(const void *l, const void *r)
3578 const struct perf_event *le = *(const struct perf_event **)l;
3579 const struct perf_event *re = *(const struct perf_event **)r;
3581 return le->group_index < re->group_index;
3584 static void swap_ptr(void *l, void *r)
3586 void **lp = l, **rp = r;
3591 static const struct min_heap_callbacks perf_min_heap = {
3592 .elem_size = sizeof(struct perf_event *),
3593 .less = perf_less_group_idx,
3597 static void __heap_add(struct min_heap *heap, struct perf_event *event)
3599 struct perf_event **itrs = heap->data;
3602 itrs[heap->nr] = event;
3607 static noinline int visit_groups_merge(struct perf_cpu_context *cpuctx,
3608 struct perf_event_groups *groups, int cpu,
3609 int (*func)(struct perf_event *, void *),
3612 #ifdef CONFIG_CGROUP_PERF
3613 struct cgroup_subsys_state *css = NULL;
3615 /* Space for per CPU and/or any CPU event iterators. */
3616 struct perf_event *itrs[2];
3617 struct min_heap event_heap;
3618 struct perf_event **evt;
3622 event_heap = (struct min_heap){
3623 .data = cpuctx->heap,
3625 .size = cpuctx->heap_size,
3628 lockdep_assert_held(&cpuctx->ctx.lock);
3630 #ifdef CONFIG_CGROUP_PERF
3632 css = &cpuctx->cgrp->css;
3635 event_heap = (struct min_heap){
3638 .size = ARRAY_SIZE(itrs),
3640 /* Events not within a CPU context may be on any CPU. */
3641 __heap_add(&event_heap, perf_event_groups_first(groups, -1, NULL));
3643 evt = event_heap.data;
3645 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, NULL));
3647 #ifdef CONFIG_CGROUP_PERF
3648 for (; css; css = css->parent)
3649 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, css->cgroup));
3652 min_heapify_all(&event_heap, &perf_min_heap);
3654 while (event_heap.nr) {
3655 ret = func(*evt, data);
3659 *evt = perf_event_groups_next(*evt);
3661 min_heapify(&event_heap, 0, &perf_min_heap);
3663 min_heap_pop(&event_heap, &perf_min_heap);
3669 static int merge_sched_in(struct perf_event *event, void *data)
3671 struct perf_event_context *ctx = event->ctx;
3672 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3673 int *can_add_hw = data;
3675 if (event->state <= PERF_EVENT_STATE_OFF)
3678 if (!event_filter_match(event))
3681 if (group_can_go_on(event, cpuctx, *can_add_hw)) {
3682 if (!group_sched_in(event, cpuctx, ctx))
3683 list_add_tail(&event->active_list, get_event_list(event));
3686 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3687 if (event->attr.pinned) {
3688 perf_cgroup_event_disable(event, ctx);
3689 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3693 ctx->rotate_necessary = 1;
3694 perf_mux_hrtimer_restart(cpuctx);
3701 ctx_pinned_sched_in(struct perf_event_context *ctx,
3702 struct perf_cpu_context *cpuctx)
3706 if (ctx != &cpuctx->ctx)
3709 visit_groups_merge(cpuctx, &ctx->pinned_groups,
3711 merge_sched_in, &can_add_hw);
3715 ctx_flexible_sched_in(struct perf_event_context *ctx,
3716 struct perf_cpu_context *cpuctx)
3720 if (ctx != &cpuctx->ctx)
3723 visit_groups_merge(cpuctx, &ctx->flexible_groups,
3725 merge_sched_in, &can_add_hw);
3729 ctx_sched_in(struct perf_event_context *ctx,
3730 struct perf_cpu_context *cpuctx,
3731 enum event_type_t event_type,
3732 struct task_struct *task)
3734 int is_active = ctx->is_active;
3737 lockdep_assert_held(&ctx->lock);
3739 if (likely(!ctx->nr_events))
3742 ctx->is_active |= (event_type | EVENT_TIME);
3745 cpuctx->task_ctx = ctx;
3747 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3750 is_active ^= ctx->is_active; /* changed bits */
3752 if (is_active & EVENT_TIME) {
3753 /* start ctx time */
3755 ctx->timestamp = now;
3756 perf_cgroup_set_timestamp(task, ctx);
3760 * First go through the list and put on any pinned groups
3761 * in order to give them the best chance of going on.
3763 if (is_active & EVENT_PINNED)
3764 ctx_pinned_sched_in(ctx, cpuctx);
3766 /* Then walk through the lower prio flexible groups */
3767 if (is_active & EVENT_FLEXIBLE)
3768 ctx_flexible_sched_in(ctx, cpuctx);
3771 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3772 enum event_type_t event_type,
3773 struct task_struct *task)
3775 struct perf_event_context *ctx = &cpuctx->ctx;
3777 ctx_sched_in(ctx, cpuctx, event_type, task);
3780 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3781 struct task_struct *task)
3783 struct perf_cpu_context *cpuctx;
3784 struct pmu *pmu = ctx->pmu;
3786 cpuctx = __get_cpu_context(ctx);
3787 if (cpuctx->task_ctx == ctx) {
3788 if (cpuctx->sched_cb_usage)
3789 __perf_pmu_sched_task(cpuctx, true);
3793 perf_ctx_lock(cpuctx, ctx);
3795 * We must check ctx->nr_events while holding ctx->lock, such
3796 * that we serialize against perf_install_in_context().
3798 if (!ctx->nr_events)
3801 perf_pmu_disable(pmu);
3803 * We want to keep the following priority order:
3804 * cpu pinned (that don't need to move), task pinned,
3805 * cpu flexible, task flexible.
3807 * However, if task's ctx is not carrying any pinned
3808 * events, no need to flip the cpuctx's events around.
3810 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3811 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3812 perf_event_sched_in(cpuctx, ctx, task);
3814 if (cpuctx->sched_cb_usage && pmu->sched_task)
3815 pmu->sched_task(cpuctx->task_ctx, true);
3817 perf_pmu_enable(pmu);
3820 perf_ctx_unlock(cpuctx, ctx);
3824 * Called from scheduler to add the events of the current task
3825 * with interrupts disabled.
3827 * We restore the event value and then enable it.
3829 * This does not protect us against NMI, but enable()
3830 * sets the enabled bit in the control field of event _before_
3831 * accessing the event control register. If a NMI hits, then it will
3832 * keep the event running.
3834 void __perf_event_task_sched_in(struct task_struct *prev,
3835 struct task_struct *task)
3837 struct perf_event_context *ctx;
3841 * If cgroup events exist on this CPU, then we need to check if we have
3842 * to switch in PMU state; cgroup event are system-wide mode only.
3844 * Since cgroup events are CPU events, we must schedule these in before
3845 * we schedule in the task events.
3847 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3848 perf_cgroup_sched_in(prev, task);
3850 for_each_task_context_nr(ctxn) {
3851 ctx = task->perf_event_ctxp[ctxn];
3855 perf_event_context_sched_in(ctx, task);
3858 if (atomic_read(&nr_switch_events))
3859 perf_event_switch(task, prev, true);
3861 if (__this_cpu_read(perf_sched_cb_usages))
3862 perf_pmu_sched_task(prev, task, true);
3865 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3867 u64 frequency = event->attr.sample_freq;
3868 u64 sec = NSEC_PER_SEC;
3869 u64 divisor, dividend;
3871 int count_fls, nsec_fls, frequency_fls, sec_fls;
3873 count_fls = fls64(count);
3874 nsec_fls = fls64(nsec);
3875 frequency_fls = fls64(frequency);
3879 * We got @count in @nsec, with a target of sample_freq HZ
3880 * the target period becomes:
3883 * period = -------------------
3884 * @nsec * sample_freq
3889 * Reduce accuracy by one bit such that @a and @b converge
3890 * to a similar magnitude.
3892 #define REDUCE_FLS(a, b) \
3894 if (a##_fls > b##_fls) { \
3904 * Reduce accuracy until either term fits in a u64, then proceed with
3905 * the other, so that finally we can do a u64/u64 division.
3907 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3908 REDUCE_FLS(nsec, frequency);
3909 REDUCE_FLS(sec, count);
3912 if (count_fls + sec_fls > 64) {
3913 divisor = nsec * frequency;
3915 while (count_fls + sec_fls > 64) {
3916 REDUCE_FLS(count, sec);
3920 dividend = count * sec;
3922 dividend = count * sec;
3924 while (nsec_fls + frequency_fls > 64) {
3925 REDUCE_FLS(nsec, frequency);
3929 divisor = nsec * frequency;
3935 return div64_u64(dividend, divisor);
3938 static DEFINE_PER_CPU(int, perf_throttled_count);
3939 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3941 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3943 struct hw_perf_event *hwc = &event->hw;
3944 s64 period, sample_period;
3947 period = perf_calculate_period(event, nsec, count);
3949 delta = (s64)(period - hwc->sample_period);
3950 delta = (delta + 7) / 8; /* low pass filter */
3952 sample_period = hwc->sample_period + delta;
3957 hwc->sample_period = sample_period;
3959 if (local64_read(&hwc->period_left) > 8*sample_period) {
3961 event->pmu->stop(event, PERF_EF_UPDATE);
3963 local64_set(&hwc->period_left, 0);
3966 event->pmu->start(event, PERF_EF_RELOAD);
3971 * combine freq adjustment with unthrottling to avoid two passes over the
3972 * events. At the same time, make sure, having freq events does not change
3973 * the rate of unthrottling as that would introduce bias.
3975 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3978 struct perf_event *event;
3979 struct hw_perf_event *hwc;
3980 u64 now, period = TICK_NSEC;
3984 * only need to iterate over all events iff:
3985 * - context have events in frequency mode (needs freq adjust)
3986 * - there are events to unthrottle on this cpu
3988 if (!(ctx->nr_freq || needs_unthr))
3991 raw_spin_lock(&ctx->lock);
3992 perf_pmu_disable(ctx->pmu);
3994 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3995 if (event->state != PERF_EVENT_STATE_ACTIVE)
3998 if (!event_filter_match(event))
4001 perf_pmu_disable(event->pmu);
4005 if (hwc->interrupts == MAX_INTERRUPTS) {
4006 hwc->interrupts = 0;
4007 perf_log_throttle(event, 1);
4008 event->pmu->start(event, 0);
4011 if (!event->attr.freq || !event->attr.sample_freq)
4015 * stop the event and update event->count
4017 event->pmu->stop(event, PERF_EF_UPDATE);
4019 now = local64_read(&event->count);
4020 delta = now - hwc->freq_count_stamp;
4021 hwc->freq_count_stamp = now;
4025 * reload only if value has changed
4026 * we have stopped the event so tell that
4027 * to perf_adjust_period() to avoid stopping it
4031 perf_adjust_period(event, period, delta, false);
4033 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
4035 perf_pmu_enable(event->pmu);
4038 perf_pmu_enable(ctx->pmu);
4039 raw_spin_unlock(&ctx->lock);
4043 * Move @event to the tail of the @ctx's elegible events.
4045 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4048 * Rotate the first entry last of non-pinned groups. Rotation might be
4049 * disabled by the inheritance code.
4051 if (ctx->rotate_disable)
4054 perf_event_groups_delete(&ctx->flexible_groups, event);
4055 perf_event_groups_insert(&ctx->flexible_groups, event);
4058 /* pick an event from the flexible_groups to rotate */
4059 static inline struct perf_event *
4060 ctx_event_to_rotate(struct perf_event_context *ctx)
4062 struct perf_event *event;
4064 /* pick the first active flexible event */
4065 event = list_first_entry_or_null(&ctx->flexible_active,
4066 struct perf_event, active_list);
4068 /* if no active flexible event, pick the first event */
4070 event = rb_entry_safe(rb_first(&ctx->flexible_groups.tree),
4071 typeof(*event), group_node);
4075 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4076 * finds there are unschedulable events, it will set it again.
4078 ctx->rotate_necessary = 0;
4083 static bool perf_rotate_context(struct perf_cpu_context *cpuctx)
4085 struct perf_event *cpu_event = NULL, *task_event = NULL;
4086 struct perf_event_context *task_ctx = NULL;
4087 int cpu_rotate, task_rotate;
4090 * Since we run this from IRQ context, nobody can install new
4091 * events, thus the event count values are stable.
4094 cpu_rotate = cpuctx->ctx.rotate_necessary;
4095 task_ctx = cpuctx->task_ctx;
4096 task_rotate = task_ctx ? task_ctx->rotate_necessary : 0;
4098 if (!(cpu_rotate || task_rotate))
4101 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4102 perf_pmu_disable(cpuctx->ctx.pmu);
4105 task_event = ctx_event_to_rotate(task_ctx);
4107 cpu_event = ctx_event_to_rotate(&cpuctx->ctx);
4110 * As per the order given at ctx_resched() first 'pop' task flexible
4111 * and then, if needed CPU flexible.
4113 if (task_event || (task_ctx && cpu_event))
4114 ctx_sched_out(task_ctx, cpuctx, EVENT_FLEXIBLE);
4116 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
4119 rotate_ctx(task_ctx, task_event);
4121 rotate_ctx(&cpuctx->ctx, cpu_event);
4123 perf_event_sched_in(cpuctx, task_ctx, current);
4125 perf_pmu_enable(cpuctx->ctx.pmu);
4126 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4131 void perf_event_task_tick(void)
4133 struct list_head *head = this_cpu_ptr(&active_ctx_list);
4134 struct perf_event_context *ctx, *tmp;
4137 lockdep_assert_irqs_disabled();
4139 __this_cpu_inc(perf_throttled_seq);
4140 throttled = __this_cpu_xchg(perf_throttled_count, 0);
4141 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4143 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
4144 perf_adjust_freq_unthr_context(ctx, throttled);
4147 static int event_enable_on_exec(struct perf_event *event,
4148 struct perf_event_context *ctx)
4150 if (!event->attr.enable_on_exec)
4153 event->attr.enable_on_exec = 0;
4154 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4157 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4163 * Enable all of a task's events that have been marked enable-on-exec.
4164 * This expects task == current.
4166 static void perf_event_enable_on_exec(int ctxn)
4168 struct perf_event_context *ctx, *clone_ctx = NULL;
4169 enum event_type_t event_type = 0;
4170 struct perf_cpu_context *cpuctx;
4171 struct perf_event *event;
4172 unsigned long flags;
4175 local_irq_save(flags);
4176 ctx = current->perf_event_ctxp[ctxn];
4177 if (!ctx || !ctx->nr_events)
4180 cpuctx = __get_cpu_context(ctx);
4181 perf_ctx_lock(cpuctx, ctx);
4182 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
4183 list_for_each_entry(event, &ctx->event_list, event_entry) {
4184 enabled |= event_enable_on_exec(event, ctx);
4185 event_type |= get_event_type(event);
4189 * Unclone and reschedule this context if we enabled any event.
4192 clone_ctx = unclone_ctx(ctx);
4193 ctx_resched(cpuctx, ctx, event_type);
4195 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
4197 perf_ctx_unlock(cpuctx, ctx);
4200 local_irq_restore(flags);
4206 struct perf_read_data {
4207 struct perf_event *event;
4212 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4214 u16 local_pkg, event_pkg;
4216 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4217 int local_cpu = smp_processor_id();
4219 event_pkg = topology_physical_package_id(event_cpu);
4220 local_pkg = topology_physical_package_id(local_cpu);
4222 if (event_pkg == local_pkg)
4230 * Cross CPU call to read the hardware event
4232 static void __perf_event_read(void *info)
4234 struct perf_read_data *data = info;
4235 struct perf_event *sub, *event = data->event;
4236 struct perf_event_context *ctx = event->ctx;
4237 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
4238 struct pmu *pmu = event->pmu;
4241 * If this is a task context, we need to check whether it is
4242 * the current task context of this cpu. If not it has been
4243 * scheduled out before the smp call arrived. In that case
4244 * event->count would have been updated to a recent sample
4245 * when the event was scheduled out.
4247 if (ctx->task && cpuctx->task_ctx != ctx)
4250 raw_spin_lock(&ctx->lock);
4251 if (ctx->is_active & EVENT_TIME) {
4252 update_context_time(ctx);
4253 update_cgrp_time_from_event(event);
4256 perf_event_update_time(event);
4258 perf_event_update_sibling_time(event);
4260 if (event->state != PERF_EVENT_STATE_ACTIVE)
4269 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4273 for_each_sibling_event(sub, event) {
4274 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4276 * Use sibling's PMU rather than @event's since
4277 * sibling could be on different (eg: software) PMU.
4279 sub->pmu->read(sub);
4283 data->ret = pmu->commit_txn(pmu);
4286 raw_spin_unlock(&ctx->lock);
4289 static inline u64 perf_event_count(struct perf_event *event)
4291 return local64_read(&event->count) + atomic64_read(&event->child_count);
4295 * NMI-safe method to read a local event, that is an event that
4297 * - either for the current task, or for this CPU
4298 * - does not have inherit set, for inherited task events
4299 * will not be local and we cannot read them atomically
4300 * - must not have a pmu::count method
4302 int perf_event_read_local(struct perf_event *event, u64 *value,
4303 u64 *enabled, u64 *running)
4305 unsigned long flags;
4309 * Disabling interrupts avoids all counter scheduling (context
4310 * switches, timer based rotation and IPIs).
4312 local_irq_save(flags);
4315 * It must not be an event with inherit set, we cannot read
4316 * all child counters from atomic context.
4318 if (event->attr.inherit) {
4323 /* If this is a per-task event, it must be for current */
4324 if ((event->attach_state & PERF_ATTACH_TASK) &&
4325 event->hw.target != current) {
4330 /* If this is a per-CPU event, it must be for this CPU */
4331 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4332 event->cpu != smp_processor_id()) {
4337 /* If this is a pinned event it must be running on this CPU */
4338 if (event->attr.pinned && event->oncpu != smp_processor_id()) {
4344 * If the event is currently on this CPU, its either a per-task event,
4345 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4348 if (event->oncpu == smp_processor_id())
4349 event->pmu->read(event);
4351 *value = local64_read(&event->count);
4352 if (enabled || running) {
4353 u64 now = event->shadow_ctx_time + perf_clock();
4354 u64 __enabled, __running;
4356 __perf_update_times(event, now, &__enabled, &__running);
4358 *enabled = __enabled;
4360 *running = __running;
4363 local_irq_restore(flags);
4368 static int perf_event_read(struct perf_event *event, bool group)
4370 enum perf_event_state state = READ_ONCE(event->state);
4371 int event_cpu, ret = 0;
4374 * If event is enabled and currently active on a CPU, update the
4375 * value in the event structure:
4378 if (state == PERF_EVENT_STATE_ACTIVE) {
4379 struct perf_read_data data;
4382 * Orders the ->state and ->oncpu loads such that if we see
4383 * ACTIVE we must also see the right ->oncpu.
4385 * Matches the smp_wmb() from event_sched_in().
4389 event_cpu = READ_ONCE(event->oncpu);
4390 if ((unsigned)event_cpu >= nr_cpu_ids)
4393 data = (struct perf_read_data){
4400 event_cpu = __perf_event_read_cpu(event, event_cpu);
4403 * Purposely ignore the smp_call_function_single() return
4406 * If event_cpu isn't a valid CPU it means the event got
4407 * scheduled out and that will have updated the event count.
4409 * Therefore, either way, we'll have an up-to-date event count
4412 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4416 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4417 struct perf_event_context *ctx = event->ctx;
4418 unsigned long flags;
4420 raw_spin_lock_irqsave(&ctx->lock, flags);
4421 state = event->state;
4422 if (state != PERF_EVENT_STATE_INACTIVE) {
4423 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4428 * May read while context is not active (e.g., thread is
4429 * blocked), in that case we cannot update context time
4431 if (ctx->is_active & EVENT_TIME) {
4432 update_context_time(ctx);
4433 update_cgrp_time_from_event(event);
4436 perf_event_update_time(event);
4438 perf_event_update_sibling_time(event);
4439 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4446 * Initialize the perf_event context in a task_struct:
4448 static void __perf_event_init_context(struct perf_event_context *ctx)
4450 raw_spin_lock_init(&ctx->lock);
4451 mutex_init(&ctx->mutex);
4452 INIT_LIST_HEAD(&ctx->active_ctx_list);
4453 perf_event_groups_init(&ctx->pinned_groups);
4454 perf_event_groups_init(&ctx->flexible_groups);
4455 INIT_LIST_HEAD(&ctx->event_list);
4456 INIT_LIST_HEAD(&ctx->pinned_active);
4457 INIT_LIST_HEAD(&ctx->flexible_active);
4458 refcount_set(&ctx->refcount, 1);
4461 static struct perf_event_context *
4462 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
4464 struct perf_event_context *ctx;
4466 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4470 __perf_event_init_context(ctx);
4472 ctx->task = get_task_struct(task);
4478 static struct task_struct *
4479 find_lively_task_by_vpid(pid_t vpid)
4481 struct task_struct *task;
4487 task = find_task_by_vpid(vpid);
4489 get_task_struct(task);
4493 return ERR_PTR(-ESRCH);
4499 * Returns a matching context with refcount and pincount.
4501 static struct perf_event_context *
4502 find_get_context(struct pmu *pmu, struct task_struct *task,
4503 struct perf_event *event)
4505 struct perf_event_context *ctx, *clone_ctx = NULL;
4506 struct perf_cpu_context *cpuctx;
4507 void *task_ctx_data = NULL;
4508 unsigned long flags;
4510 int cpu = event->cpu;
4513 /* Must be root to operate on a CPU event: */
4514 err = perf_allow_cpu(&event->attr);
4516 return ERR_PTR(err);
4518 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
4527 ctxn = pmu->task_ctx_nr;
4531 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4532 task_ctx_data = alloc_task_ctx_data(pmu);
4533 if (!task_ctx_data) {
4540 ctx = perf_lock_task_context(task, ctxn, &flags);
4542 clone_ctx = unclone_ctx(ctx);
4545 if (task_ctx_data && !ctx->task_ctx_data) {
4546 ctx->task_ctx_data = task_ctx_data;
4547 task_ctx_data = NULL;
4549 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4554 ctx = alloc_perf_context(pmu, task);
4559 if (task_ctx_data) {
4560 ctx->task_ctx_data = task_ctx_data;
4561 task_ctx_data = NULL;
4565 mutex_lock(&task->perf_event_mutex);
4567 * If it has already passed perf_event_exit_task().
4568 * we must see PF_EXITING, it takes this mutex too.
4570 if (task->flags & PF_EXITING)
4572 else if (task->perf_event_ctxp[ctxn])
4577 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
4579 mutex_unlock(&task->perf_event_mutex);
4581 if (unlikely(err)) {
4590 free_task_ctx_data(pmu, task_ctx_data);
4594 free_task_ctx_data(pmu, task_ctx_data);
4595 return ERR_PTR(err);
4598 static void perf_event_free_filter(struct perf_event *event);
4599 static void perf_event_free_bpf_prog(struct perf_event *event);
4601 static void free_event_rcu(struct rcu_head *head)
4603 struct perf_event *event;
4605 event = container_of(head, struct perf_event, rcu_head);
4607 put_pid_ns(event->ns);
4608 perf_event_free_filter(event);
4612 static void ring_buffer_attach(struct perf_event *event,
4613 struct perf_buffer *rb);
4615 static void detach_sb_event(struct perf_event *event)
4617 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4619 raw_spin_lock(&pel->lock);
4620 list_del_rcu(&event->sb_list);
4621 raw_spin_unlock(&pel->lock);
4624 static bool is_sb_event(struct perf_event *event)
4626 struct perf_event_attr *attr = &event->attr;
4631 if (event->attach_state & PERF_ATTACH_TASK)
4634 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4635 attr->comm || attr->comm_exec ||
4636 attr->task || attr->ksymbol ||
4637 attr->context_switch || attr->text_poke ||
4643 static void unaccount_pmu_sb_event(struct perf_event *event)
4645 if (is_sb_event(event))
4646 detach_sb_event(event);
4649 static void unaccount_event_cpu(struct perf_event *event, int cpu)
4654 if (is_cgroup_event(event))
4655 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
4658 #ifdef CONFIG_NO_HZ_FULL
4659 static DEFINE_SPINLOCK(nr_freq_lock);
4662 static void unaccount_freq_event_nohz(void)
4664 #ifdef CONFIG_NO_HZ_FULL
4665 spin_lock(&nr_freq_lock);
4666 if (atomic_dec_and_test(&nr_freq_events))
4667 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4668 spin_unlock(&nr_freq_lock);
4672 static void unaccount_freq_event(void)
4674 if (tick_nohz_full_enabled())
4675 unaccount_freq_event_nohz();
4677 atomic_dec(&nr_freq_events);
4680 static void unaccount_event(struct perf_event *event)
4687 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
4689 if (event->attr.mmap || event->attr.mmap_data)
4690 atomic_dec(&nr_mmap_events);
4691 if (event->attr.build_id)
4692 atomic_dec(&nr_build_id_events);
4693 if (event->attr.comm)
4694 atomic_dec(&nr_comm_events);
4695 if (event->attr.namespaces)
4696 atomic_dec(&nr_namespaces_events);
4697 if (event->attr.cgroup)
4698 atomic_dec(&nr_cgroup_events);
4699 if (event->attr.task)
4700 atomic_dec(&nr_task_events);
4701 if (event->attr.freq)
4702 unaccount_freq_event();
4703 if (event->attr.context_switch) {
4705 atomic_dec(&nr_switch_events);
4707 if (is_cgroup_event(event))
4709 if (has_branch_stack(event))
4711 if (event->attr.ksymbol)
4712 atomic_dec(&nr_ksymbol_events);
4713 if (event->attr.bpf_event)
4714 atomic_dec(&nr_bpf_events);
4715 if (event->attr.text_poke)
4716 atomic_dec(&nr_text_poke_events);
4719 if (!atomic_add_unless(&perf_sched_count, -1, 1))
4720 schedule_delayed_work(&perf_sched_work, HZ);
4723 unaccount_event_cpu(event, event->cpu);
4725 unaccount_pmu_sb_event(event);
4728 static void perf_sched_delayed(struct work_struct *work)
4730 mutex_lock(&perf_sched_mutex);
4731 if (atomic_dec_and_test(&perf_sched_count))
4732 static_branch_disable(&perf_sched_events);
4733 mutex_unlock(&perf_sched_mutex);
4737 * The following implement mutual exclusion of events on "exclusive" pmus
4738 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
4739 * at a time, so we disallow creating events that might conflict, namely:
4741 * 1) cpu-wide events in the presence of per-task events,
4742 * 2) per-task events in the presence of cpu-wide events,
4743 * 3) two matching events on the same context.
4745 * The former two cases are handled in the allocation path (perf_event_alloc(),
4746 * _free_event()), the latter -- before the first perf_install_in_context().
4748 static int exclusive_event_init(struct perf_event *event)
4750 struct pmu *pmu = event->pmu;
4752 if (!is_exclusive_pmu(pmu))
4756 * Prevent co-existence of per-task and cpu-wide events on the
4757 * same exclusive pmu.
4759 * Negative pmu::exclusive_cnt means there are cpu-wide
4760 * events on this "exclusive" pmu, positive means there are
4763 * Since this is called in perf_event_alloc() path, event::ctx
4764 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4765 * to mean "per-task event", because unlike other attach states it
4766 * never gets cleared.
4768 if (event->attach_state & PERF_ATTACH_TASK) {
4769 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4772 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4779 static void exclusive_event_destroy(struct perf_event *event)
4781 struct pmu *pmu = event->pmu;
4783 if (!is_exclusive_pmu(pmu))
4786 /* see comment in exclusive_event_init() */
4787 if (event->attach_state & PERF_ATTACH_TASK)
4788 atomic_dec(&pmu->exclusive_cnt);
4790 atomic_inc(&pmu->exclusive_cnt);
4793 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4795 if ((e1->pmu == e2->pmu) &&
4796 (e1->cpu == e2->cpu ||
4803 static bool exclusive_event_installable(struct perf_event *event,
4804 struct perf_event_context *ctx)
4806 struct perf_event *iter_event;
4807 struct pmu *pmu = event->pmu;
4809 lockdep_assert_held(&ctx->mutex);
4811 if (!is_exclusive_pmu(pmu))
4814 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4815 if (exclusive_event_match(iter_event, event))
4822 static void perf_addr_filters_splice(struct perf_event *event,
4823 struct list_head *head);
4825 static void _free_event(struct perf_event *event)
4827 irq_work_sync(&event->pending);
4829 unaccount_event(event);
4831 security_perf_event_free(event);
4835 * Can happen when we close an event with re-directed output.
4837 * Since we have a 0 refcount, perf_mmap_close() will skip
4838 * over us; possibly making our ring_buffer_put() the last.
4840 mutex_lock(&event->mmap_mutex);
4841 ring_buffer_attach(event, NULL);
4842 mutex_unlock(&event->mmap_mutex);
4845 if (is_cgroup_event(event))
4846 perf_detach_cgroup(event);
4848 if (!event->parent) {
4849 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4850 put_callchain_buffers();
4853 perf_event_free_bpf_prog(event);
4854 perf_addr_filters_splice(event, NULL);
4855 kfree(event->addr_filter_ranges);
4858 event->destroy(event);
4861 * Must be after ->destroy(), due to uprobe_perf_close() using
4864 if (event->hw.target)
4865 put_task_struct(event->hw.target);
4868 * perf_event_free_task() relies on put_ctx() being 'last', in particular
4869 * all task references must be cleaned up.
4872 put_ctx(event->ctx);
4874 exclusive_event_destroy(event);
4875 module_put(event->pmu->module);
4877 call_rcu(&event->rcu_head, free_event_rcu);
4881 * Used to free events which have a known refcount of 1, such as in error paths
4882 * where the event isn't exposed yet and inherited events.
4884 static void free_event(struct perf_event *event)
4886 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
4887 "unexpected event refcount: %ld; ptr=%p\n",
4888 atomic_long_read(&event->refcount), event)) {
4889 /* leak to avoid use-after-free */
4897 * Remove user event from the owner task.
4899 static void perf_remove_from_owner(struct perf_event *event)
4901 struct task_struct *owner;
4905 * Matches the smp_store_release() in perf_event_exit_task(). If we
4906 * observe !owner it means the list deletion is complete and we can
4907 * indeed free this event, otherwise we need to serialize on
4908 * owner->perf_event_mutex.
4910 owner = READ_ONCE(event->owner);
4913 * Since delayed_put_task_struct() also drops the last
4914 * task reference we can safely take a new reference
4915 * while holding the rcu_read_lock().
4917 get_task_struct(owner);
4923 * If we're here through perf_event_exit_task() we're already
4924 * holding ctx->mutex which would be an inversion wrt. the
4925 * normal lock order.
4927 * However we can safely take this lock because its the child
4930 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
4933 * We have to re-check the event->owner field, if it is cleared
4934 * we raced with perf_event_exit_task(), acquiring the mutex
4935 * ensured they're done, and we can proceed with freeing the
4939 list_del_init(&event->owner_entry);
4940 smp_store_release(&event->owner, NULL);
4942 mutex_unlock(&owner->perf_event_mutex);
4943 put_task_struct(owner);
4947 static void put_event(struct perf_event *event)
4949 if (!atomic_long_dec_and_test(&event->refcount))
4956 * Kill an event dead; while event:refcount will preserve the event
4957 * object, it will not preserve its functionality. Once the last 'user'
4958 * gives up the object, we'll destroy the thing.
4960 int perf_event_release_kernel(struct perf_event *event)
4962 struct perf_event_context *ctx = event->ctx;
4963 struct perf_event *child, *tmp;
4964 LIST_HEAD(free_list);
4967 * If we got here through err_file: fput(event_file); we will not have
4968 * attached to a context yet.
4971 WARN_ON_ONCE(event->attach_state &
4972 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
4976 if (!is_kernel_event(event))
4977 perf_remove_from_owner(event);
4979 ctx = perf_event_ctx_lock(event);
4980 WARN_ON_ONCE(ctx->parent_ctx);
4981 perf_remove_from_context(event, DETACH_GROUP);
4983 raw_spin_lock_irq(&ctx->lock);
4985 * Mark this event as STATE_DEAD, there is no external reference to it
4988 * Anybody acquiring event->child_mutex after the below loop _must_
4989 * also see this, most importantly inherit_event() which will avoid
4990 * placing more children on the list.
4992 * Thus this guarantees that we will in fact observe and kill _ALL_
4995 event->state = PERF_EVENT_STATE_DEAD;
4996 raw_spin_unlock_irq(&ctx->lock);
4998 perf_event_ctx_unlock(event, ctx);
5001 mutex_lock(&event->child_mutex);
5002 list_for_each_entry(child, &event->child_list, child_list) {
5005 * Cannot change, child events are not migrated, see the
5006 * comment with perf_event_ctx_lock_nested().
5008 ctx = READ_ONCE(child->ctx);
5010 * Since child_mutex nests inside ctx::mutex, we must jump
5011 * through hoops. We start by grabbing a reference on the ctx.
5013 * Since the event cannot get freed while we hold the
5014 * child_mutex, the context must also exist and have a !0
5020 * Now that we have a ctx ref, we can drop child_mutex, and
5021 * acquire ctx::mutex without fear of it going away. Then we
5022 * can re-acquire child_mutex.
5024 mutex_unlock(&event->child_mutex);
5025 mutex_lock(&ctx->mutex);
5026 mutex_lock(&event->child_mutex);
5029 * Now that we hold ctx::mutex and child_mutex, revalidate our
5030 * state, if child is still the first entry, it didn't get freed
5031 * and we can continue doing so.
5033 tmp = list_first_entry_or_null(&event->child_list,
5034 struct perf_event, child_list);
5036 perf_remove_from_context(child, DETACH_GROUP);
5037 list_move(&child->child_list, &free_list);
5039 * This matches the refcount bump in inherit_event();
5040 * this can't be the last reference.
5045 mutex_unlock(&event->child_mutex);
5046 mutex_unlock(&ctx->mutex);
5050 mutex_unlock(&event->child_mutex);
5052 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
5053 void *var = &child->ctx->refcount;
5055 list_del(&child->child_list);
5059 * Wake any perf_event_free_task() waiting for this event to be
5062 smp_mb(); /* pairs with wait_var_event() */
5067 put_event(event); /* Must be the 'last' reference */
5070 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5073 * Called when the last reference to the file is gone.
5075 static int perf_release(struct inode *inode, struct file *file)
5077 perf_event_release_kernel(file->private_data);
5081 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5083 struct perf_event *child;
5089 mutex_lock(&event->child_mutex);
5091 (void)perf_event_read(event, false);
5092 total += perf_event_count(event);
5094 *enabled += event->total_time_enabled +
5095 atomic64_read(&event->child_total_time_enabled);
5096 *running += event->total_time_running +
5097 atomic64_read(&event->child_total_time_running);
5099 list_for_each_entry(child, &event->child_list, child_list) {
5100 (void)perf_event_read(child, false);
5101 total += perf_event_count(child);
5102 *enabled += child->total_time_enabled;
5103 *running += child->total_time_running;
5105 mutex_unlock(&event->child_mutex);
5110 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5112 struct perf_event_context *ctx;
5115 ctx = perf_event_ctx_lock(event);
5116 count = __perf_event_read_value(event, enabled, running);
5117 perf_event_ctx_unlock(event, ctx);
5121 EXPORT_SYMBOL_GPL(perf_event_read_value);
5123 static int __perf_read_group_add(struct perf_event *leader,
5124 u64 read_format, u64 *values)
5126 struct perf_event_context *ctx = leader->ctx;
5127 struct perf_event *sub;
5128 unsigned long flags;
5129 int n = 1; /* skip @nr */
5132 ret = perf_event_read(leader, true);
5136 raw_spin_lock_irqsave(&ctx->lock, flags);
5139 * Since we co-schedule groups, {enabled,running} times of siblings
5140 * will be identical to those of the leader, so we only publish one
5143 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5144 values[n++] += leader->total_time_enabled +
5145 atomic64_read(&leader->child_total_time_enabled);
5148 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5149 values[n++] += leader->total_time_running +
5150 atomic64_read(&leader->child_total_time_running);
5154 * Write {count,id} tuples for every sibling.
5156 values[n++] += perf_event_count(leader);
5157 if (read_format & PERF_FORMAT_ID)
5158 values[n++] = primary_event_id(leader);
5160 for_each_sibling_event(sub, leader) {
5161 values[n++] += perf_event_count(sub);
5162 if (read_format & PERF_FORMAT_ID)
5163 values[n++] = primary_event_id(sub);
5166 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5170 static int perf_read_group(struct perf_event *event,
5171 u64 read_format, char __user *buf)
5173 struct perf_event *leader = event->group_leader, *child;
5174 struct perf_event_context *ctx = leader->ctx;
5178 lockdep_assert_held(&ctx->mutex);
5180 values = kzalloc(event->read_size, GFP_KERNEL);
5184 values[0] = 1 + leader->nr_siblings;
5187 * By locking the child_mutex of the leader we effectively
5188 * lock the child list of all siblings.. XXX explain how.
5190 mutex_lock(&leader->child_mutex);
5192 ret = __perf_read_group_add(leader, read_format, values);
5196 list_for_each_entry(child, &leader->child_list, child_list) {
5197 ret = __perf_read_group_add(child, read_format, values);
5202 mutex_unlock(&leader->child_mutex);
5204 ret = event->read_size;
5205 if (copy_to_user(buf, values, event->read_size))
5210 mutex_unlock(&leader->child_mutex);
5216 static int perf_read_one(struct perf_event *event,
5217 u64 read_format, char __user *buf)
5219 u64 enabled, running;
5223 values[n++] = __perf_event_read_value(event, &enabled, &running);
5224 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5225 values[n++] = enabled;
5226 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5227 values[n++] = running;
5228 if (read_format & PERF_FORMAT_ID)
5229 values[n++] = primary_event_id(event);
5231 if (copy_to_user(buf, values, n * sizeof(u64)))
5234 return n * sizeof(u64);
5237 static bool is_event_hup(struct perf_event *event)
5241 if (event->state > PERF_EVENT_STATE_EXIT)
5244 mutex_lock(&event->child_mutex);
5245 no_children = list_empty(&event->child_list);
5246 mutex_unlock(&event->child_mutex);
5251 * Read the performance event - simple non blocking version for now
5254 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5256 u64 read_format = event->attr.read_format;
5260 * Return end-of-file for a read on an event that is in
5261 * error state (i.e. because it was pinned but it couldn't be
5262 * scheduled on to the CPU at some point).
5264 if (event->state == PERF_EVENT_STATE_ERROR)
5267 if (count < event->read_size)
5270 WARN_ON_ONCE(event->ctx->parent_ctx);
5271 if (read_format & PERF_FORMAT_GROUP)
5272 ret = perf_read_group(event, read_format, buf);
5274 ret = perf_read_one(event, read_format, buf);
5280 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5282 struct perf_event *event = file->private_data;
5283 struct perf_event_context *ctx;
5286 ret = security_perf_event_read(event);
5290 ctx = perf_event_ctx_lock(event);
5291 ret = __perf_read(event, buf, count);
5292 perf_event_ctx_unlock(event, ctx);
5297 static __poll_t perf_poll(struct file *file, poll_table *wait)
5299 struct perf_event *event = file->private_data;
5300 struct perf_buffer *rb;
5301 __poll_t events = EPOLLHUP;
5303 poll_wait(file, &event->waitq, wait);
5305 if (is_event_hup(event))
5309 * Pin the event->rb by taking event->mmap_mutex; otherwise
5310 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5312 mutex_lock(&event->mmap_mutex);
5315 events = atomic_xchg(&rb->poll, 0);
5316 mutex_unlock(&event->mmap_mutex);
5320 static void _perf_event_reset(struct perf_event *event)
5322 (void)perf_event_read(event, false);
5323 local64_set(&event->count, 0);
5324 perf_event_update_userpage(event);
5327 /* Assume it's not an event with inherit set. */
5328 u64 perf_event_pause(struct perf_event *event, bool reset)
5330 struct perf_event_context *ctx;
5333 ctx = perf_event_ctx_lock(event);
5334 WARN_ON_ONCE(event->attr.inherit);
5335 _perf_event_disable(event);
5336 count = local64_read(&event->count);
5338 local64_set(&event->count, 0);
5339 perf_event_ctx_unlock(event, ctx);
5343 EXPORT_SYMBOL_GPL(perf_event_pause);
5346 * Holding the top-level event's child_mutex means that any
5347 * descendant process that has inherited this event will block
5348 * in perf_event_exit_event() if it goes to exit, thus satisfying the
5349 * task existence requirements of perf_event_enable/disable.
5351 static void perf_event_for_each_child(struct perf_event *event,
5352 void (*func)(struct perf_event *))
5354 struct perf_event *child;
5356 WARN_ON_ONCE(event->ctx->parent_ctx);
5358 mutex_lock(&event->child_mutex);
5360 list_for_each_entry(child, &event->child_list, child_list)
5362 mutex_unlock(&event->child_mutex);
5365 static void perf_event_for_each(struct perf_event *event,
5366 void (*func)(struct perf_event *))
5368 struct perf_event_context *ctx = event->ctx;
5369 struct perf_event *sibling;
5371 lockdep_assert_held(&ctx->mutex);
5373 event = event->group_leader;
5375 perf_event_for_each_child(event, func);
5376 for_each_sibling_event(sibling, event)
5377 perf_event_for_each_child(sibling, func);
5380 static void __perf_event_period(struct perf_event *event,
5381 struct perf_cpu_context *cpuctx,
5382 struct perf_event_context *ctx,
5385 u64 value = *((u64 *)info);
5388 if (event->attr.freq) {
5389 event->attr.sample_freq = value;
5391 event->attr.sample_period = value;
5392 event->hw.sample_period = value;
5395 active = (event->state == PERF_EVENT_STATE_ACTIVE);
5397 perf_pmu_disable(ctx->pmu);
5399 * We could be throttled; unthrottle now to avoid the tick
5400 * trying to unthrottle while we already re-started the event.
5402 if (event->hw.interrupts == MAX_INTERRUPTS) {
5403 event->hw.interrupts = 0;
5404 perf_log_throttle(event, 1);
5406 event->pmu->stop(event, PERF_EF_UPDATE);
5409 local64_set(&event->hw.period_left, 0);
5412 event->pmu->start(event, PERF_EF_RELOAD);
5413 perf_pmu_enable(ctx->pmu);
5417 static int perf_event_check_period(struct perf_event *event, u64 value)
5419 return event->pmu->check_period(event, value);
5422 static int _perf_event_period(struct perf_event *event, u64 value)
5424 if (!is_sampling_event(event))
5430 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5433 if (perf_event_check_period(event, value))
5436 if (!event->attr.freq && (value & (1ULL << 63)))
5439 event_function_call(event, __perf_event_period, &value);
5444 int perf_event_period(struct perf_event *event, u64 value)
5446 struct perf_event_context *ctx;
5449 ctx = perf_event_ctx_lock(event);
5450 ret = _perf_event_period(event, value);
5451 perf_event_ctx_unlock(event, ctx);
5455 EXPORT_SYMBOL_GPL(perf_event_period);
5457 static const struct file_operations perf_fops;
5459 static inline int perf_fget_light(int fd, struct fd *p)
5461 struct fd f = fdget(fd);
5465 if (f.file->f_op != &perf_fops) {
5473 static int perf_event_set_output(struct perf_event *event,
5474 struct perf_event *output_event);
5475 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5476 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
5477 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5478 struct perf_event_attr *attr);
5480 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5482 void (*func)(struct perf_event *);
5486 case PERF_EVENT_IOC_ENABLE:
5487 func = _perf_event_enable;
5489 case PERF_EVENT_IOC_DISABLE:
5490 func = _perf_event_disable;
5492 case PERF_EVENT_IOC_RESET:
5493 func = _perf_event_reset;
5496 case PERF_EVENT_IOC_REFRESH:
5497 return _perf_event_refresh(event, arg);
5499 case PERF_EVENT_IOC_PERIOD:
5503 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
5506 return _perf_event_period(event, value);
5508 case PERF_EVENT_IOC_ID:
5510 u64 id = primary_event_id(event);
5512 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5517 case PERF_EVENT_IOC_SET_OUTPUT:
5521 struct perf_event *output_event;
5523 ret = perf_fget_light(arg, &output);
5526 output_event = output.file->private_data;
5527 ret = perf_event_set_output(event, output_event);
5530 ret = perf_event_set_output(event, NULL);
5535 case PERF_EVENT_IOC_SET_FILTER:
5536 return perf_event_set_filter(event, (void __user *)arg);
5538 case PERF_EVENT_IOC_SET_BPF:
5539 return perf_event_set_bpf_prog(event, arg);
5541 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5542 struct perf_buffer *rb;
5545 rb = rcu_dereference(event->rb);
5546 if (!rb || !rb->nr_pages) {
5550 rb_toggle_paused(rb, !!arg);
5555 case PERF_EVENT_IOC_QUERY_BPF:
5556 return perf_event_query_prog_array(event, (void __user *)arg);
5558 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5559 struct perf_event_attr new_attr;
5560 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5566 return perf_event_modify_attr(event, &new_attr);
5572 if (flags & PERF_IOC_FLAG_GROUP)
5573 perf_event_for_each(event, func);
5575 perf_event_for_each_child(event, func);
5580 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5582 struct perf_event *event = file->private_data;
5583 struct perf_event_context *ctx;
5586 /* Treat ioctl like writes as it is likely a mutating operation. */
5587 ret = security_perf_event_write(event);
5591 ctx = perf_event_ctx_lock(event);
5592 ret = _perf_ioctl(event, cmd, arg);
5593 perf_event_ctx_unlock(event, ctx);
5598 #ifdef CONFIG_COMPAT
5599 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5602 switch (_IOC_NR(cmd)) {
5603 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5604 case _IOC_NR(PERF_EVENT_IOC_ID):
5605 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5606 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
5607 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5608 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5609 cmd &= ~IOCSIZE_MASK;
5610 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5614 return perf_ioctl(file, cmd, arg);
5617 # define perf_compat_ioctl NULL
5620 int perf_event_task_enable(void)
5622 struct perf_event_context *ctx;
5623 struct perf_event *event;
5625 mutex_lock(¤t->perf_event_mutex);
5626 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5627 ctx = perf_event_ctx_lock(event);
5628 perf_event_for_each_child(event, _perf_event_enable);
5629 perf_event_ctx_unlock(event, ctx);
5631 mutex_unlock(¤t->perf_event_mutex);
5636 int perf_event_task_disable(void)
5638 struct perf_event_context *ctx;
5639 struct perf_event *event;
5641 mutex_lock(¤t->perf_event_mutex);
5642 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5643 ctx = perf_event_ctx_lock(event);
5644 perf_event_for_each_child(event, _perf_event_disable);
5645 perf_event_ctx_unlock(event, ctx);
5647 mutex_unlock(¤t->perf_event_mutex);
5652 static int perf_event_index(struct perf_event *event)
5654 if (event->hw.state & PERF_HES_STOPPED)
5657 if (event->state != PERF_EVENT_STATE_ACTIVE)
5660 return event->pmu->event_idx(event);
5663 static void calc_timer_values(struct perf_event *event,
5670 *now = perf_clock();
5671 ctx_time = event->shadow_ctx_time + *now;
5672 __perf_update_times(event, ctx_time, enabled, running);
5675 static void perf_event_init_userpage(struct perf_event *event)
5677 struct perf_event_mmap_page *userpg;
5678 struct perf_buffer *rb;
5681 rb = rcu_dereference(event->rb);
5685 userpg = rb->user_page;
5687 /* Allow new userspace to detect that bit 0 is deprecated */
5688 userpg->cap_bit0_is_deprecated = 1;
5689 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
5690 userpg->data_offset = PAGE_SIZE;
5691 userpg->data_size = perf_data_size(rb);
5697 void __weak arch_perf_update_userpage(
5698 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
5703 * Callers need to ensure there can be no nesting of this function, otherwise
5704 * the seqlock logic goes bad. We can not serialize this because the arch
5705 * code calls this from NMI context.
5707 void perf_event_update_userpage(struct perf_event *event)
5709 struct perf_event_mmap_page *userpg;
5710 struct perf_buffer *rb;
5711 u64 enabled, running, now;
5714 rb = rcu_dereference(event->rb);
5719 * compute total_time_enabled, total_time_running
5720 * based on snapshot values taken when the event
5721 * was last scheduled in.
5723 * we cannot simply called update_context_time()
5724 * because of locking issue as we can be called in
5727 calc_timer_values(event, &now, &enabled, &running);
5729 userpg = rb->user_page;
5731 * Disable preemption to guarantee consistent time stamps are stored to
5737 userpg->index = perf_event_index(event);
5738 userpg->offset = perf_event_count(event);
5740 userpg->offset -= local64_read(&event->hw.prev_count);
5742 userpg->time_enabled = enabled +
5743 atomic64_read(&event->child_total_time_enabled);
5745 userpg->time_running = running +
5746 atomic64_read(&event->child_total_time_running);
5748 arch_perf_update_userpage(event, userpg, now);
5756 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
5758 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
5760 struct perf_event *event = vmf->vma->vm_file->private_data;
5761 struct perf_buffer *rb;
5762 vm_fault_t ret = VM_FAULT_SIGBUS;
5764 if (vmf->flags & FAULT_FLAG_MKWRITE) {
5765 if (vmf->pgoff == 0)
5771 rb = rcu_dereference(event->rb);
5775 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
5778 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
5782 get_page(vmf->page);
5783 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
5784 vmf->page->index = vmf->pgoff;
5793 static void ring_buffer_attach(struct perf_event *event,
5794 struct perf_buffer *rb)
5796 struct perf_buffer *old_rb = NULL;
5797 unsigned long flags;
5801 * Should be impossible, we set this when removing
5802 * event->rb_entry and wait/clear when adding event->rb_entry.
5804 WARN_ON_ONCE(event->rcu_pending);
5807 spin_lock_irqsave(&old_rb->event_lock, flags);
5808 list_del_rcu(&event->rb_entry);
5809 spin_unlock_irqrestore(&old_rb->event_lock, flags);
5811 event->rcu_batches = get_state_synchronize_rcu();
5812 event->rcu_pending = 1;
5816 if (event->rcu_pending) {
5817 cond_synchronize_rcu(event->rcu_batches);
5818 event->rcu_pending = 0;
5821 spin_lock_irqsave(&rb->event_lock, flags);
5822 list_add_rcu(&event->rb_entry, &rb->event_list);
5823 spin_unlock_irqrestore(&rb->event_lock, flags);
5827 * Avoid racing with perf_mmap_close(AUX): stop the event
5828 * before swizzling the event::rb pointer; if it's getting
5829 * unmapped, its aux_mmap_count will be 0 and it won't
5830 * restart. See the comment in __perf_pmu_output_stop().
5832 * Data will inevitably be lost when set_output is done in
5833 * mid-air, but then again, whoever does it like this is
5834 * not in for the data anyway.
5837 perf_event_stop(event, 0);
5839 rcu_assign_pointer(event->rb, rb);
5842 ring_buffer_put(old_rb);
5844 * Since we detached before setting the new rb, so that we
5845 * could attach the new rb, we could have missed a wakeup.
5848 wake_up_all(&event->waitq);
5852 static void ring_buffer_wakeup(struct perf_event *event)
5854 struct perf_buffer *rb;
5857 rb = rcu_dereference(event->rb);
5859 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
5860 wake_up_all(&event->waitq);
5865 struct perf_buffer *ring_buffer_get(struct perf_event *event)
5867 struct perf_buffer *rb;
5870 rb = rcu_dereference(event->rb);
5872 if (!refcount_inc_not_zero(&rb->refcount))
5880 void ring_buffer_put(struct perf_buffer *rb)
5882 if (!refcount_dec_and_test(&rb->refcount))
5885 WARN_ON_ONCE(!list_empty(&rb->event_list));
5887 call_rcu(&rb->rcu_head, rb_free_rcu);
5890 static void perf_mmap_open(struct vm_area_struct *vma)
5892 struct perf_event *event = vma->vm_file->private_data;
5894 atomic_inc(&event->mmap_count);
5895 atomic_inc(&event->rb->mmap_count);
5898 atomic_inc(&event->rb->aux_mmap_count);
5900 if (event->pmu->event_mapped)
5901 event->pmu->event_mapped(event, vma->vm_mm);
5904 static void perf_pmu_output_stop(struct perf_event *event);
5907 * A buffer can be mmap()ed multiple times; either directly through the same
5908 * event, or through other events by use of perf_event_set_output().
5910 * In order to undo the VM accounting done by perf_mmap() we need to destroy
5911 * the buffer here, where we still have a VM context. This means we need
5912 * to detach all events redirecting to us.
5914 static void perf_mmap_close(struct vm_area_struct *vma)
5916 struct perf_event *event = vma->vm_file->private_data;
5917 struct perf_buffer *rb = ring_buffer_get(event);
5918 struct user_struct *mmap_user = rb->mmap_user;
5919 int mmap_locked = rb->mmap_locked;
5920 unsigned long size = perf_data_size(rb);
5921 bool detach_rest = false;
5923 if (event->pmu->event_unmapped)
5924 event->pmu->event_unmapped(event, vma->vm_mm);
5927 * rb->aux_mmap_count will always drop before rb->mmap_count and
5928 * event->mmap_count, so it is ok to use event->mmap_mutex to
5929 * serialize with perf_mmap here.
5931 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
5932 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
5934 * Stop all AUX events that are writing to this buffer,
5935 * so that we can free its AUX pages and corresponding PMU
5936 * data. Note that after rb::aux_mmap_count dropped to zero,
5937 * they won't start any more (see perf_aux_output_begin()).
5939 perf_pmu_output_stop(event);
5941 /* now it's safe to free the pages */
5942 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
5943 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
5945 /* this has to be the last one */
5947 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
5949 mutex_unlock(&event->mmap_mutex);
5952 if (atomic_dec_and_test(&rb->mmap_count))
5955 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
5958 ring_buffer_attach(event, NULL);
5959 mutex_unlock(&event->mmap_mutex);
5961 /* If there's still other mmap()s of this buffer, we're done. */
5966 * No other mmap()s, detach from all other events that might redirect
5967 * into the now unreachable buffer. Somewhat complicated by the
5968 * fact that rb::event_lock otherwise nests inside mmap_mutex.
5972 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
5973 if (!atomic_long_inc_not_zero(&event->refcount)) {
5975 * This event is en-route to free_event() which will
5976 * detach it and remove it from the list.
5982 mutex_lock(&event->mmap_mutex);
5984 * Check we didn't race with perf_event_set_output() which can
5985 * swizzle the rb from under us while we were waiting to
5986 * acquire mmap_mutex.
5988 * If we find a different rb; ignore this event, a next
5989 * iteration will no longer find it on the list. We have to
5990 * still restart the iteration to make sure we're not now
5991 * iterating the wrong list.
5993 if (event->rb == rb)
5994 ring_buffer_attach(event, NULL);
5996 mutex_unlock(&event->mmap_mutex);
6000 * Restart the iteration; either we're on the wrong list or
6001 * destroyed its integrity by doing a deletion.
6008 * It could be there's still a few 0-ref events on the list; they'll
6009 * get cleaned up by free_event() -- they'll also still have their
6010 * ref on the rb and will free it whenever they are done with it.
6012 * Aside from that, this buffer is 'fully' detached and unmapped,
6013 * undo the VM accounting.
6016 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
6017 &mmap_user->locked_vm);
6018 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
6019 free_uid(mmap_user);
6022 ring_buffer_put(rb); /* could be last */
6025 static const struct vm_operations_struct perf_mmap_vmops = {
6026 .open = perf_mmap_open,
6027 .close = perf_mmap_close, /* non mergeable */
6028 .fault = perf_mmap_fault,
6029 .page_mkwrite = perf_mmap_fault,
6032 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
6034 struct perf_event *event = file->private_data;
6035 unsigned long user_locked, user_lock_limit;
6036 struct user_struct *user = current_user();
6037 struct perf_buffer *rb = NULL;
6038 unsigned long locked, lock_limit;
6039 unsigned long vma_size;
6040 unsigned long nr_pages;
6041 long user_extra = 0, extra = 0;
6042 int ret = 0, flags = 0;
6045 * Don't allow mmap() of inherited per-task counters. This would
6046 * create a performance issue due to all children writing to the
6049 if (event->cpu == -1 && event->attr.inherit)
6052 if (!(vma->vm_flags & VM_SHARED))
6055 ret = security_perf_event_read(event);
6059 vma_size = vma->vm_end - vma->vm_start;
6061 if (vma->vm_pgoff == 0) {
6062 nr_pages = (vma_size / PAGE_SIZE) - 1;
6065 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
6066 * mapped, all subsequent mappings should have the same size
6067 * and offset. Must be above the normal perf buffer.
6069 u64 aux_offset, aux_size;
6074 nr_pages = vma_size / PAGE_SIZE;
6076 mutex_lock(&event->mmap_mutex);
6083 aux_offset = READ_ONCE(rb->user_page->aux_offset);
6084 aux_size = READ_ONCE(rb->user_page->aux_size);
6086 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6089 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6092 /* already mapped with a different offset */
6093 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6096 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6099 /* already mapped with a different size */
6100 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6103 if (!is_power_of_2(nr_pages))
6106 if (!atomic_inc_not_zero(&rb->mmap_count))
6109 if (rb_has_aux(rb)) {
6110 atomic_inc(&rb->aux_mmap_count);
6115 atomic_set(&rb->aux_mmap_count, 1);
6116 user_extra = nr_pages;
6122 * If we have rb pages ensure they're a power-of-two number, so we
6123 * can do bitmasks instead of modulo.
6125 if (nr_pages != 0 && !is_power_of_2(nr_pages))
6128 if (vma_size != PAGE_SIZE * (1 + nr_pages))
6131 WARN_ON_ONCE(event->ctx->parent_ctx);
6133 mutex_lock(&event->mmap_mutex);
6135 if (event->rb->nr_pages != nr_pages) {
6140 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6142 * Raced against perf_mmap_close() through
6143 * perf_event_set_output(). Try again, hope for better
6146 mutex_unlock(&event->mmap_mutex);
6153 user_extra = nr_pages + 1;
6156 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6159 * Increase the limit linearly with more CPUs:
6161 user_lock_limit *= num_online_cpus();
6163 user_locked = atomic_long_read(&user->locked_vm);
6166 * sysctl_perf_event_mlock may have changed, so that
6167 * user->locked_vm > user_lock_limit
6169 if (user_locked > user_lock_limit)
6170 user_locked = user_lock_limit;
6171 user_locked += user_extra;
6173 if (user_locked > user_lock_limit) {
6175 * charge locked_vm until it hits user_lock_limit;
6176 * charge the rest from pinned_vm
6178 extra = user_locked - user_lock_limit;
6179 user_extra -= extra;
6182 lock_limit = rlimit(RLIMIT_MEMLOCK);
6183 lock_limit >>= PAGE_SHIFT;
6184 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
6186 if ((locked > lock_limit) && perf_is_paranoid() &&
6187 !capable(CAP_IPC_LOCK)) {
6192 WARN_ON(!rb && event->rb);
6194 if (vma->vm_flags & VM_WRITE)
6195 flags |= RING_BUFFER_WRITABLE;
6198 rb = rb_alloc(nr_pages,
6199 event->attr.watermark ? event->attr.wakeup_watermark : 0,
6207 atomic_set(&rb->mmap_count, 1);
6208 rb->mmap_user = get_current_user();
6209 rb->mmap_locked = extra;
6211 ring_buffer_attach(event, rb);
6213 perf_event_init_userpage(event);
6214 perf_event_update_userpage(event);
6216 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6217 event->attr.aux_watermark, flags);
6219 rb->aux_mmap_locked = extra;
6224 atomic_long_add(user_extra, &user->locked_vm);
6225 atomic64_add(extra, &vma->vm_mm->pinned_vm);
6227 atomic_inc(&event->mmap_count);
6229 atomic_dec(&rb->mmap_count);
6232 mutex_unlock(&event->mmap_mutex);
6235 * Since pinned accounting is per vm we cannot allow fork() to copy our
6238 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
6239 vma->vm_ops = &perf_mmap_vmops;
6241 if (event->pmu->event_mapped)
6242 event->pmu->event_mapped(event, vma->vm_mm);
6247 static int perf_fasync(int fd, struct file *filp, int on)
6249 struct inode *inode = file_inode(filp);
6250 struct perf_event *event = filp->private_data;
6254 retval = fasync_helper(fd, filp, on, &event->fasync);
6255 inode_unlock(inode);
6263 static const struct file_operations perf_fops = {
6264 .llseek = no_llseek,
6265 .release = perf_release,
6268 .unlocked_ioctl = perf_ioctl,
6269 .compat_ioctl = perf_compat_ioctl,
6271 .fasync = perf_fasync,
6277 * If there's data, ensure we set the poll() state and publish everything
6278 * to user-space before waking everybody up.
6281 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
6283 /* only the parent has fasync state */
6285 event = event->parent;
6286 return &event->fasync;
6289 void perf_event_wakeup(struct perf_event *event)
6291 ring_buffer_wakeup(event);
6293 if (event->pending_kill) {
6294 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6295 event->pending_kill = 0;
6299 static void perf_pending_event_disable(struct perf_event *event)
6301 int cpu = READ_ONCE(event->pending_disable);
6306 if (cpu == smp_processor_id()) {
6307 WRITE_ONCE(event->pending_disable, -1);
6308 perf_event_disable_local(event);
6315 * perf_event_disable_inatomic()
6316 * @pending_disable = CPU-A;
6320 * @pending_disable = -1;
6323 * perf_event_disable_inatomic()
6324 * @pending_disable = CPU-B;
6325 * irq_work_queue(); // FAILS
6328 * perf_pending_event()
6330 * But the event runs on CPU-B and wants disabling there.
6332 irq_work_queue_on(&event->pending, cpu);
6335 static void perf_pending_event(struct irq_work *entry)
6337 struct perf_event *event = container_of(entry, struct perf_event, pending);
6340 rctx = perf_swevent_get_recursion_context();
6342 * If we 'fail' here, that's OK, it means recursion is already disabled
6343 * and we won't recurse 'further'.
6346 perf_pending_event_disable(event);
6348 if (event->pending_wakeup) {
6349 event->pending_wakeup = 0;
6350 perf_event_wakeup(event);
6354 perf_swevent_put_recursion_context(rctx);
6358 * We assume there is only KVM supporting the callbacks.
6359 * Later on, we might change it to a list if there is
6360 * another virtualization implementation supporting the callbacks.
6362 struct perf_guest_info_callbacks *perf_guest_cbs;
6364 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6366 perf_guest_cbs = cbs;
6369 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6371 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6373 perf_guest_cbs = NULL;
6376 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6379 perf_output_sample_regs(struct perf_output_handle *handle,
6380 struct pt_regs *regs, u64 mask)
6383 DECLARE_BITMAP(_mask, 64);
6385 bitmap_from_u64(_mask, mask);
6386 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
6389 val = perf_reg_value(regs, bit);
6390 perf_output_put(handle, val);
6394 static void perf_sample_regs_user(struct perf_regs *regs_user,
6395 struct pt_regs *regs)
6397 if (user_mode(regs)) {
6398 regs_user->abi = perf_reg_abi(current);
6399 regs_user->regs = regs;
6400 } else if (!(current->flags & PF_KTHREAD)) {
6401 perf_get_regs_user(regs_user, regs);
6403 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6404 regs_user->regs = NULL;
6408 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6409 struct pt_regs *regs)
6411 regs_intr->regs = regs;
6412 regs_intr->abi = perf_reg_abi(current);
6417 * Get remaining task size from user stack pointer.
6419 * It'd be better to take stack vma map and limit this more
6420 * precisely, but there's no way to get it safely under interrupt,
6421 * so using TASK_SIZE as limit.
6423 static u64 perf_ustack_task_size(struct pt_regs *regs)
6425 unsigned long addr = perf_user_stack_pointer(regs);
6427 if (!addr || addr >= TASK_SIZE)
6430 return TASK_SIZE - addr;
6434 perf_sample_ustack_size(u16 stack_size, u16 header_size,
6435 struct pt_regs *regs)
6439 /* No regs, no stack pointer, no dump. */
6444 * Check if we fit in with the requested stack size into the:
6446 * If we don't, we limit the size to the TASK_SIZE.
6448 * - remaining sample size
6449 * If we don't, we customize the stack size to
6450 * fit in to the remaining sample size.
6453 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6454 stack_size = min(stack_size, (u16) task_size);
6456 /* Current header size plus static size and dynamic size. */
6457 header_size += 2 * sizeof(u64);
6459 /* Do we fit in with the current stack dump size? */
6460 if ((u16) (header_size + stack_size) < header_size) {
6462 * If we overflow the maximum size for the sample,
6463 * we customize the stack dump size to fit in.
6465 stack_size = USHRT_MAX - header_size - sizeof(u64);
6466 stack_size = round_up(stack_size, sizeof(u64));
6473 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6474 struct pt_regs *regs)
6476 /* Case of a kernel thread, nothing to dump */
6479 perf_output_put(handle, size);
6489 * - the size requested by user or the best one we can fit
6490 * in to the sample max size
6492 * - user stack dump data
6494 * - the actual dumped size
6498 perf_output_put(handle, dump_size);
6501 sp = perf_user_stack_pointer(regs);
6502 fs = force_uaccess_begin();
6503 rem = __output_copy_user(handle, (void *) sp, dump_size);
6504 force_uaccess_end(fs);
6505 dyn_size = dump_size - rem;
6507 perf_output_skip(handle, rem);
6510 perf_output_put(handle, dyn_size);
6514 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
6515 struct perf_sample_data *data,
6518 struct perf_event *sampler = event->aux_event;
6519 struct perf_buffer *rb;
6526 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
6529 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
6532 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6537 * If this is an NMI hit inside sampling code, don't take
6538 * the sample. See also perf_aux_sample_output().
6540 if (READ_ONCE(rb->aux_in_sampling)) {
6543 size = min_t(size_t, size, perf_aux_size(rb));
6544 data->aux_size = ALIGN(size, sizeof(u64));
6546 ring_buffer_put(rb);
6549 return data->aux_size;
6552 long perf_pmu_snapshot_aux(struct perf_buffer *rb,
6553 struct perf_event *event,
6554 struct perf_output_handle *handle,
6557 unsigned long flags;
6561 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
6562 * paths. If we start calling them in NMI context, they may race with
6563 * the IRQ ones, that is, for example, re-starting an event that's just
6564 * been stopped, which is why we're using a separate callback that
6565 * doesn't change the event state.
6567 * IRQs need to be disabled to prevent IPIs from racing with us.
6569 local_irq_save(flags);
6571 * Guard against NMI hits inside the critical section;
6572 * see also perf_prepare_sample_aux().
6574 WRITE_ONCE(rb->aux_in_sampling, 1);
6577 ret = event->pmu->snapshot_aux(event, handle, size);
6580 WRITE_ONCE(rb->aux_in_sampling, 0);
6581 local_irq_restore(flags);
6586 static void perf_aux_sample_output(struct perf_event *event,
6587 struct perf_output_handle *handle,
6588 struct perf_sample_data *data)
6590 struct perf_event *sampler = event->aux_event;
6591 struct perf_buffer *rb;
6595 if (WARN_ON_ONCE(!sampler || !data->aux_size))
6598 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6602 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
6605 * An error here means that perf_output_copy() failed (returned a
6606 * non-zero surplus that it didn't copy), which in its current
6607 * enlightened implementation is not possible. If that changes, we'd
6610 if (WARN_ON_ONCE(size < 0))
6614 * The pad comes from ALIGN()ing data->aux_size up to u64 in
6615 * perf_prepare_sample_aux(), so should not be more than that.
6617 pad = data->aux_size - size;
6618 if (WARN_ON_ONCE(pad >= sizeof(u64)))
6623 perf_output_copy(handle, &zero, pad);
6627 ring_buffer_put(rb);
6630 static void __perf_event_header__init_id(struct perf_event_header *header,
6631 struct perf_sample_data *data,
6632 struct perf_event *event)
6634 u64 sample_type = event->attr.sample_type;
6636 data->type = sample_type;
6637 header->size += event->id_header_size;
6639 if (sample_type & PERF_SAMPLE_TID) {
6640 /* namespace issues */
6641 data->tid_entry.pid = perf_event_pid(event, current);
6642 data->tid_entry.tid = perf_event_tid(event, current);
6645 if (sample_type & PERF_SAMPLE_TIME)
6646 data->time = perf_event_clock(event);
6648 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
6649 data->id = primary_event_id(event);
6651 if (sample_type & PERF_SAMPLE_STREAM_ID)
6652 data->stream_id = event->id;
6654 if (sample_type & PERF_SAMPLE_CPU) {
6655 data->cpu_entry.cpu = raw_smp_processor_id();
6656 data->cpu_entry.reserved = 0;
6660 void perf_event_header__init_id(struct perf_event_header *header,
6661 struct perf_sample_data *data,
6662 struct perf_event *event)
6664 if (event->attr.sample_id_all)
6665 __perf_event_header__init_id(header, data, event);
6668 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
6669 struct perf_sample_data *data)
6671 u64 sample_type = data->type;
6673 if (sample_type & PERF_SAMPLE_TID)
6674 perf_output_put(handle, data->tid_entry);
6676 if (sample_type & PERF_SAMPLE_TIME)
6677 perf_output_put(handle, data->time);
6679 if (sample_type & PERF_SAMPLE_ID)
6680 perf_output_put(handle, data->id);
6682 if (sample_type & PERF_SAMPLE_STREAM_ID)
6683 perf_output_put(handle, data->stream_id);
6685 if (sample_type & PERF_SAMPLE_CPU)
6686 perf_output_put(handle, data->cpu_entry);
6688 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6689 perf_output_put(handle, data->id);
6692 void perf_event__output_id_sample(struct perf_event *event,
6693 struct perf_output_handle *handle,
6694 struct perf_sample_data *sample)
6696 if (event->attr.sample_id_all)
6697 __perf_event__output_id_sample(handle, sample);
6700 static void perf_output_read_one(struct perf_output_handle *handle,
6701 struct perf_event *event,
6702 u64 enabled, u64 running)
6704 u64 read_format = event->attr.read_format;
6708 values[n++] = perf_event_count(event);
6709 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
6710 values[n++] = enabled +
6711 atomic64_read(&event->child_total_time_enabled);
6713 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
6714 values[n++] = running +
6715 atomic64_read(&event->child_total_time_running);
6717 if (read_format & PERF_FORMAT_ID)
6718 values[n++] = primary_event_id(event);
6720 __output_copy(handle, values, n * sizeof(u64));
6723 static void perf_output_read_group(struct perf_output_handle *handle,
6724 struct perf_event *event,
6725 u64 enabled, u64 running)
6727 struct perf_event *leader = event->group_leader, *sub;
6728 u64 read_format = event->attr.read_format;
6732 values[n++] = 1 + leader->nr_siblings;
6734 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6735 values[n++] = enabled;
6737 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6738 values[n++] = running;
6740 if ((leader != event) &&
6741 (leader->state == PERF_EVENT_STATE_ACTIVE))
6742 leader->pmu->read(leader);
6744 values[n++] = perf_event_count(leader);
6745 if (read_format & PERF_FORMAT_ID)
6746 values[n++] = primary_event_id(leader);
6748 __output_copy(handle, values, n * sizeof(u64));
6750 for_each_sibling_event(sub, leader) {
6753 if ((sub != event) &&
6754 (sub->state == PERF_EVENT_STATE_ACTIVE))
6755 sub->pmu->read(sub);
6757 values[n++] = perf_event_count(sub);
6758 if (read_format & PERF_FORMAT_ID)
6759 values[n++] = primary_event_id(sub);
6761 __output_copy(handle, values, n * sizeof(u64));
6765 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
6766 PERF_FORMAT_TOTAL_TIME_RUNNING)
6769 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
6771 * The problem is that its both hard and excessively expensive to iterate the
6772 * child list, not to mention that its impossible to IPI the children running
6773 * on another CPU, from interrupt/NMI context.
6775 static void perf_output_read(struct perf_output_handle *handle,
6776 struct perf_event *event)
6778 u64 enabled = 0, running = 0, now;
6779 u64 read_format = event->attr.read_format;
6782 * compute total_time_enabled, total_time_running
6783 * based on snapshot values taken when the event
6784 * was last scheduled in.
6786 * we cannot simply called update_context_time()
6787 * because of locking issue as we are called in
6790 if (read_format & PERF_FORMAT_TOTAL_TIMES)
6791 calc_timer_values(event, &now, &enabled, &running);
6793 if (event->attr.read_format & PERF_FORMAT_GROUP)
6794 perf_output_read_group(handle, event, enabled, running);
6796 perf_output_read_one(handle, event, enabled, running);
6799 static inline bool perf_sample_save_hw_index(struct perf_event *event)
6801 return event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX;
6804 void perf_output_sample(struct perf_output_handle *handle,
6805 struct perf_event_header *header,
6806 struct perf_sample_data *data,
6807 struct perf_event *event)
6809 u64 sample_type = data->type;
6811 perf_output_put(handle, *header);
6813 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6814 perf_output_put(handle, data->id);
6816 if (sample_type & PERF_SAMPLE_IP)
6817 perf_output_put(handle, data->ip);
6819 if (sample_type & PERF_SAMPLE_TID)
6820 perf_output_put(handle, data->tid_entry);
6822 if (sample_type & PERF_SAMPLE_TIME)
6823 perf_output_put(handle, data->time);
6825 if (sample_type & PERF_SAMPLE_ADDR)
6826 perf_output_put(handle, data->addr);
6828 if (sample_type & PERF_SAMPLE_ID)
6829 perf_output_put(handle, data->id);
6831 if (sample_type & PERF_SAMPLE_STREAM_ID)
6832 perf_output_put(handle, data->stream_id);
6834 if (sample_type & PERF_SAMPLE_CPU)
6835 perf_output_put(handle, data->cpu_entry);
6837 if (sample_type & PERF_SAMPLE_PERIOD)
6838 perf_output_put(handle, data->period);
6840 if (sample_type & PERF_SAMPLE_READ)
6841 perf_output_read(handle, event);
6843 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
6846 size += data->callchain->nr;
6847 size *= sizeof(u64);
6848 __output_copy(handle, data->callchain, size);
6851 if (sample_type & PERF_SAMPLE_RAW) {
6852 struct perf_raw_record *raw = data->raw;
6855 struct perf_raw_frag *frag = &raw->frag;
6857 perf_output_put(handle, raw->size);
6860 __output_custom(handle, frag->copy,
6861 frag->data, frag->size);
6863 __output_copy(handle, frag->data,
6866 if (perf_raw_frag_last(frag))
6871 __output_skip(handle, NULL, frag->pad);
6877 .size = sizeof(u32),
6880 perf_output_put(handle, raw);
6884 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
6885 if (data->br_stack) {
6888 size = data->br_stack->nr
6889 * sizeof(struct perf_branch_entry);
6891 perf_output_put(handle, data->br_stack->nr);
6892 if (perf_sample_save_hw_index(event))
6893 perf_output_put(handle, data->br_stack->hw_idx);
6894 perf_output_copy(handle, data->br_stack->entries, size);
6897 * we always store at least the value of nr
6900 perf_output_put(handle, nr);
6904 if (sample_type & PERF_SAMPLE_REGS_USER) {
6905 u64 abi = data->regs_user.abi;
6908 * If there are no regs to dump, notice it through
6909 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6911 perf_output_put(handle, abi);
6914 u64 mask = event->attr.sample_regs_user;
6915 perf_output_sample_regs(handle,
6916 data->regs_user.regs,
6921 if (sample_type & PERF_SAMPLE_STACK_USER) {
6922 perf_output_sample_ustack(handle,
6923 data->stack_user_size,
6924 data->regs_user.regs);
6927 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
6928 perf_output_put(handle, data->weight.full);
6930 if (sample_type & PERF_SAMPLE_DATA_SRC)
6931 perf_output_put(handle, data->data_src.val);
6933 if (sample_type & PERF_SAMPLE_TRANSACTION)
6934 perf_output_put(handle, data->txn);
6936 if (sample_type & PERF_SAMPLE_REGS_INTR) {
6937 u64 abi = data->regs_intr.abi;
6939 * If there are no regs to dump, notice it through
6940 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6942 perf_output_put(handle, abi);
6945 u64 mask = event->attr.sample_regs_intr;
6947 perf_output_sample_regs(handle,
6948 data->regs_intr.regs,
6953 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
6954 perf_output_put(handle, data->phys_addr);
6956 if (sample_type & PERF_SAMPLE_CGROUP)
6957 perf_output_put(handle, data->cgroup);
6959 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
6960 perf_output_put(handle, data->data_page_size);
6962 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
6963 perf_output_put(handle, data->code_page_size);
6965 if (sample_type & PERF_SAMPLE_AUX) {
6966 perf_output_put(handle, data->aux_size);
6969 perf_aux_sample_output(event, handle, data);
6972 if (!event->attr.watermark) {
6973 int wakeup_events = event->attr.wakeup_events;
6975 if (wakeup_events) {
6976 struct perf_buffer *rb = handle->rb;
6977 int events = local_inc_return(&rb->events);
6979 if (events >= wakeup_events) {
6980 local_sub(wakeup_events, &rb->events);
6981 local_inc(&rb->wakeup);
6987 static u64 perf_virt_to_phys(u64 virt)
6990 struct page *p = NULL;
6995 if (virt >= TASK_SIZE) {
6996 /* If it's vmalloc()d memory, leave phys_addr as 0 */
6997 if (virt_addr_valid((void *)(uintptr_t)virt) &&
6998 !(virt >= VMALLOC_START && virt < VMALLOC_END))
6999 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
7002 * Walking the pages tables for user address.
7003 * Interrupts are disabled, so it prevents any tear down
7004 * of the page tables.
7005 * Try IRQ-safe get_user_page_fast_only first.
7006 * If failed, leave phys_addr as 0.
7008 if (current->mm != NULL) {
7009 pagefault_disable();
7010 if (get_user_page_fast_only(virt, 0, &p))
7011 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
7023 * Return the pagetable size of a given virtual address.
7025 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
7029 #ifdef CONFIG_HAVE_FAST_GUP
7036 pgdp = pgd_offset(mm, addr);
7037 pgd = READ_ONCE(*pgdp);
7042 return pgd_leaf_size(pgd);
7044 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
7045 p4d = READ_ONCE(*p4dp);
7046 if (!p4d_present(p4d))
7050 return p4d_leaf_size(p4d);
7052 pudp = pud_offset_lockless(p4dp, p4d, addr);
7053 pud = READ_ONCE(*pudp);
7054 if (!pud_present(pud))
7058 return pud_leaf_size(pud);
7060 pmdp = pmd_offset_lockless(pudp, pud, addr);
7061 pmd = READ_ONCE(*pmdp);
7062 if (!pmd_present(pmd))
7066 return pmd_leaf_size(pmd);
7068 ptep = pte_offset_map(&pmd, addr);
7069 pte = ptep_get_lockless(ptep);
7070 if (pte_present(pte))
7071 size = pte_leaf_size(pte);
7073 #endif /* CONFIG_HAVE_FAST_GUP */
7078 static u64 perf_get_page_size(unsigned long addr)
7080 struct mm_struct *mm;
7081 unsigned long flags;
7088 * Software page-table walkers must disable IRQs,
7089 * which prevents any tear down of the page tables.
7091 local_irq_save(flags);
7096 * For kernel threads and the like, use init_mm so that
7097 * we can find kernel memory.
7102 size = perf_get_pgtable_size(mm, addr);
7104 local_irq_restore(flags);
7109 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
7111 struct perf_callchain_entry *
7112 perf_callchain(struct perf_event *event, struct pt_regs *regs)
7114 bool kernel = !event->attr.exclude_callchain_kernel;
7115 bool user = !event->attr.exclude_callchain_user;
7116 /* Disallow cross-task user callchains. */
7117 bool crosstask = event->ctx->task && event->ctx->task != current;
7118 const u32 max_stack = event->attr.sample_max_stack;
7119 struct perf_callchain_entry *callchain;
7121 if (!kernel && !user)
7122 return &__empty_callchain;
7124 callchain = get_perf_callchain(regs, 0, kernel, user,
7125 max_stack, crosstask, true);
7126 return callchain ?: &__empty_callchain;
7129 void perf_prepare_sample(struct perf_event_header *header,
7130 struct perf_sample_data *data,
7131 struct perf_event *event,
7132 struct pt_regs *regs)
7134 u64 sample_type = event->attr.sample_type;
7136 header->type = PERF_RECORD_SAMPLE;
7137 header->size = sizeof(*header) + event->header_size;
7140 header->misc |= perf_misc_flags(regs);
7142 __perf_event_header__init_id(header, data, event);
7144 if (sample_type & (PERF_SAMPLE_IP | PERF_SAMPLE_CODE_PAGE_SIZE))
7145 data->ip = perf_instruction_pointer(regs);
7147 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7150 if (!(sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
7151 data->callchain = perf_callchain(event, regs);
7153 size += data->callchain->nr;
7155 header->size += size * sizeof(u64);
7158 if (sample_type & PERF_SAMPLE_RAW) {
7159 struct perf_raw_record *raw = data->raw;
7163 struct perf_raw_frag *frag = &raw->frag;
7168 if (perf_raw_frag_last(frag))
7173 size = round_up(sum + sizeof(u32), sizeof(u64));
7174 raw->size = size - sizeof(u32);
7175 frag->pad = raw->size - sum;
7180 header->size += size;
7183 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7184 int size = sizeof(u64); /* nr */
7185 if (data->br_stack) {
7186 if (perf_sample_save_hw_index(event))
7187 size += sizeof(u64);
7189 size += data->br_stack->nr
7190 * sizeof(struct perf_branch_entry);
7192 header->size += size;
7195 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
7196 perf_sample_regs_user(&data->regs_user, regs);
7198 if (sample_type & PERF_SAMPLE_REGS_USER) {
7199 /* regs dump ABI info */
7200 int size = sizeof(u64);
7202 if (data->regs_user.regs) {
7203 u64 mask = event->attr.sample_regs_user;
7204 size += hweight64(mask) * sizeof(u64);
7207 header->size += size;
7210 if (sample_type & PERF_SAMPLE_STACK_USER) {
7212 * Either we need PERF_SAMPLE_STACK_USER bit to be always
7213 * processed as the last one or have additional check added
7214 * in case new sample type is added, because we could eat
7215 * up the rest of the sample size.
7217 u16 stack_size = event->attr.sample_stack_user;
7218 u16 size = sizeof(u64);
7220 stack_size = perf_sample_ustack_size(stack_size, header->size,
7221 data->regs_user.regs);
7224 * If there is something to dump, add space for the dump
7225 * itself and for the field that tells the dynamic size,
7226 * which is how many have been actually dumped.
7229 size += sizeof(u64) + stack_size;
7231 data->stack_user_size = stack_size;
7232 header->size += size;
7235 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7236 /* regs dump ABI info */
7237 int size = sizeof(u64);
7239 perf_sample_regs_intr(&data->regs_intr, regs);
7241 if (data->regs_intr.regs) {
7242 u64 mask = event->attr.sample_regs_intr;
7244 size += hweight64(mask) * sizeof(u64);
7247 header->size += size;
7250 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7251 data->phys_addr = perf_virt_to_phys(data->addr);
7253 #ifdef CONFIG_CGROUP_PERF
7254 if (sample_type & PERF_SAMPLE_CGROUP) {
7255 struct cgroup *cgrp;
7257 /* protected by RCU */
7258 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
7259 data->cgroup = cgroup_id(cgrp);
7264 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't
7265 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr,
7266 * but the value will not dump to the userspace.
7268 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
7269 data->data_page_size = perf_get_page_size(data->addr);
7271 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
7272 data->code_page_size = perf_get_page_size(data->ip);
7274 if (sample_type & PERF_SAMPLE_AUX) {
7277 header->size += sizeof(u64); /* size */
7280 * Given the 16bit nature of header::size, an AUX sample can
7281 * easily overflow it, what with all the preceding sample bits.
7282 * Make sure this doesn't happen by using up to U16_MAX bytes
7283 * per sample in total (rounded down to 8 byte boundary).
7285 size = min_t(size_t, U16_MAX - header->size,
7286 event->attr.aux_sample_size);
7287 size = rounddown(size, 8);
7288 size = perf_prepare_sample_aux(event, data, size);
7290 WARN_ON_ONCE(size + header->size > U16_MAX);
7291 header->size += size;
7294 * If you're adding more sample types here, you likely need to do
7295 * something about the overflowing header::size, like repurpose the
7296 * lowest 3 bits of size, which should be always zero at the moment.
7297 * This raises a more important question, do we really need 512k sized
7298 * samples and why, so good argumentation is in order for whatever you
7301 WARN_ON_ONCE(header->size & 7);
7304 static __always_inline int
7305 __perf_event_output(struct perf_event *event,
7306 struct perf_sample_data *data,
7307 struct pt_regs *regs,
7308 int (*output_begin)(struct perf_output_handle *,
7309 struct perf_sample_data *,
7310 struct perf_event *,
7313 struct perf_output_handle handle;
7314 struct perf_event_header header;
7317 /* protect the callchain buffers */
7320 perf_prepare_sample(&header, data, event, regs);
7322 err = output_begin(&handle, data, event, header.size);
7326 perf_output_sample(&handle, &header, data, event);
7328 perf_output_end(&handle);
7336 perf_event_output_forward(struct perf_event *event,
7337 struct perf_sample_data *data,
7338 struct pt_regs *regs)
7340 __perf_event_output(event, data, regs, perf_output_begin_forward);
7344 perf_event_output_backward(struct perf_event *event,
7345 struct perf_sample_data *data,
7346 struct pt_regs *regs)
7348 __perf_event_output(event, data, regs, perf_output_begin_backward);
7352 perf_event_output(struct perf_event *event,
7353 struct perf_sample_data *data,
7354 struct pt_regs *regs)
7356 return __perf_event_output(event, data, regs, perf_output_begin);
7363 struct perf_read_event {
7364 struct perf_event_header header;
7371 perf_event_read_event(struct perf_event *event,
7372 struct task_struct *task)
7374 struct perf_output_handle handle;
7375 struct perf_sample_data sample;
7376 struct perf_read_event read_event = {
7378 .type = PERF_RECORD_READ,
7380 .size = sizeof(read_event) + event->read_size,
7382 .pid = perf_event_pid(event, task),
7383 .tid = perf_event_tid(event, task),
7387 perf_event_header__init_id(&read_event.header, &sample, event);
7388 ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
7392 perf_output_put(&handle, read_event);
7393 perf_output_read(&handle, event);
7394 perf_event__output_id_sample(event, &handle, &sample);
7396 perf_output_end(&handle);
7399 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
7402 perf_iterate_ctx(struct perf_event_context *ctx,
7403 perf_iterate_f output,
7404 void *data, bool all)
7406 struct perf_event *event;
7408 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7410 if (event->state < PERF_EVENT_STATE_INACTIVE)
7412 if (!event_filter_match(event))
7416 output(event, data);
7420 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
7422 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
7423 struct perf_event *event;
7425 list_for_each_entry_rcu(event, &pel->list, sb_list) {
7427 * Skip events that are not fully formed yet; ensure that
7428 * if we observe event->ctx, both event and ctx will be
7429 * complete enough. See perf_install_in_context().
7431 if (!smp_load_acquire(&event->ctx))
7434 if (event->state < PERF_EVENT_STATE_INACTIVE)
7436 if (!event_filter_match(event))
7438 output(event, data);
7443 * Iterate all events that need to receive side-band events.
7445 * For new callers; ensure that account_pmu_sb_event() includes
7446 * your event, otherwise it might not get delivered.
7449 perf_iterate_sb(perf_iterate_f output, void *data,
7450 struct perf_event_context *task_ctx)
7452 struct perf_event_context *ctx;
7459 * If we have task_ctx != NULL we only notify the task context itself.
7460 * The task_ctx is set only for EXIT events before releasing task
7464 perf_iterate_ctx(task_ctx, output, data, false);
7468 perf_iterate_sb_cpu(output, data);
7470 for_each_task_context_nr(ctxn) {
7471 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7473 perf_iterate_ctx(ctx, output, data, false);
7481 * Clear all file-based filters at exec, they'll have to be
7482 * re-instated when/if these objects are mmapped again.
7484 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
7486 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7487 struct perf_addr_filter *filter;
7488 unsigned int restart = 0, count = 0;
7489 unsigned long flags;
7491 if (!has_addr_filter(event))
7494 raw_spin_lock_irqsave(&ifh->lock, flags);
7495 list_for_each_entry(filter, &ifh->list, entry) {
7496 if (filter->path.dentry) {
7497 event->addr_filter_ranges[count].start = 0;
7498 event->addr_filter_ranges[count].size = 0;
7506 event->addr_filters_gen++;
7507 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7510 perf_event_stop(event, 1);
7513 void perf_event_exec(void)
7515 struct perf_event_context *ctx;
7519 for_each_task_context_nr(ctxn) {
7520 ctx = current->perf_event_ctxp[ctxn];
7524 perf_event_enable_on_exec(ctxn);
7526 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
7532 struct remote_output {
7533 struct perf_buffer *rb;
7537 static void __perf_event_output_stop(struct perf_event *event, void *data)
7539 struct perf_event *parent = event->parent;
7540 struct remote_output *ro = data;
7541 struct perf_buffer *rb = ro->rb;
7542 struct stop_event_data sd = {
7546 if (!has_aux(event))
7553 * In case of inheritance, it will be the parent that links to the
7554 * ring-buffer, but it will be the child that's actually using it.
7556 * We are using event::rb to determine if the event should be stopped,
7557 * however this may race with ring_buffer_attach() (through set_output),
7558 * which will make us skip the event that actually needs to be stopped.
7559 * So ring_buffer_attach() has to stop an aux event before re-assigning
7562 if (rcu_dereference(parent->rb) == rb)
7563 ro->err = __perf_event_stop(&sd);
7566 static int __perf_pmu_output_stop(void *info)
7568 struct perf_event *event = info;
7569 struct pmu *pmu = event->ctx->pmu;
7570 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7571 struct remote_output ro = {
7576 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
7577 if (cpuctx->task_ctx)
7578 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
7585 static void perf_pmu_output_stop(struct perf_event *event)
7587 struct perf_event *iter;
7592 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
7594 * For per-CPU events, we need to make sure that neither they
7595 * nor their children are running; for cpu==-1 events it's
7596 * sufficient to stop the event itself if it's active, since
7597 * it can't have children.
7601 cpu = READ_ONCE(iter->oncpu);
7606 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
7607 if (err == -EAGAIN) {
7616 * task tracking -- fork/exit
7618 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
7621 struct perf_task_event {
7622 struct task_struct *task;
7623 struct perf_event_context *task_ctx;
7626 struct perf_event_header header;
7636 static int perf_event_task_match(struct perf_event *event)
7638 return event->attr.comm || event->attr.mmap ||
7639 event->attr.mmap2 || event->attr.mmap_data ||
7643 static void perf_event_task_output(struct perf_event *event,
7646 struct perf_task_event *task_event = data;
7647 struct perf_output_handle handle;
7648 struct perf_sample_data sample;
7649 struct task_struct *task = task_event->task;
7650 int ret, size = task_event->event_id.header.size;
7652 if (!perf_event_task_match(event))
7655 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
7657 ret = perf_output_begin(&handle, &sample, event,
7658 task_event->event_id.header.size);
7662 task_event->event_id.pid = perf_event_pid(event, task);
7663 task_event->event_id.tid = perf_event_tid(event, task);
7665 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
7666 task_event->event_id.ppid = perf_event_pid(event,
7668 task_event->event_id.ptid = perf_event_pid(event,
7670 } else { /* PERF_RECORD_FORK */
7671 task_event->event_id.ppid = perf_event_pid(event, current);
7672 task_event->event_id.ptid = perf_event_tid(event, current);
7675 task_event->event_id.time = perf_event_clock(event);
7677 perf_output_put(&handle, task_event->event_id);
7679 perf_event__output_id_sample(event, &handle, &sample);
7681 perf_output_end(&handle);
7683 task_event->event_id.header.size = size;
7686 static void perf_event_task(struct task_struct *task,
7687 struct perf_event_context *task_ctx,
7690 struct perf_task_event task_event;
7692 if (!atomic_read(&nr_comm_events) &&
7693 !atomic_read(&nr_mmap_events) &&
7694 !atomic_read(&nr_task_events))
7697 task_event = (struct perf_task_event){
7699 .task_ctx = task_ctx,
7702 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
7704 .size = sizeof(task_event.event_id),
7714 perf_iterate_sb(perf_event_task_output,
7719 void perf_event_fork(struct task_struct *task)
7721 perf_event_task(task, NULL, 1);
7722 perf_event_namespaces(task);
7729 struct perf_comm_event {
7730 struct task_struct *task;
7735 struct perf_event_header header;
7742 static int perf_event_comm_match(struct perf_event *event)
7744 return event->attr.comm;
7747 static void perf_event_comm_output(struct perf_event *event,
7750 struct perf_comm_event *comm_event = data;
7751 struct perf_output_handle handle;
7752 struct perf_sample_data sample;
7753 int size = comm_event->event_id.header.size;
7756 if (!perf_event_comm_match(event))
7759 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
7760 ret = perf_output_begin(&handle, &sample, event,
7761 comm_event->event_id.header.size);
7766 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
7767 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
7769 perf_output_put(&handle, comm_event->event_id);
7770 __output_copy(&handle, comm_event->comm,
7771 comm_event->comm_size);
7773 perf_event__output_id_sample(event, &handle, &sample);
7775 perf_output_end(&handle);
7777 comm_event->event_id.header.size = size;
7780 static void perf_event_comm_event(struct perf_comm_event *comm_event)
7782 char comm[TASK_COMM_LEN];
7785 memset(comm, 0, sizeof(comm));
7786 strlcpy(comm, comm_event->task->comm, sizeof(comm));
7787 size = ALIGN(strlen(comm)+1, sizeof(u64));
7789 comm_event->comm = comm;
7790 comm_event->comm_size = size;
7792 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
7794 perf_iterate_sb(perf_event_comm_output,
7799 void perf_event_comm(struct task_struct *task, bool exec)
7801 struct perf_comm_event comm_event;
7803 if (!atomic_read(&nr_comm_events))
7806 comm_event = (struct perf_comm_event){
7812 .type = PERF_RECORD_COMM,
7813 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
7821 perf_event_comm_event(&comm_event);
7825 * namespaces tracking
7828 struct perf_namespaces_event {
7829 struct task_struct *task;
7832 struct perf_event_header header;
7837 struct perf_ns_link_info link_info[NR_NAMESPACES];
7841 static int perf_event_namespaces_match(struct perf_event *event)
7843 return event->attr.namespaces;
7846 static void perf_event_namespaces_output(struct perf_event *event,
7849 struct perf_namespaces_event *namespaces_event = data;
7850 struct perf_output_handle handle;
7851 struct perf_sample_data sample;
7852 u16 header_size = namespaces_event->event_id.header.size;
7855 if (!perf_event_namespaces_match(event))
7858 perf_event_header__init_id(&namespaces_event->event_id.header,
7860 ret = perf_output_begin(&handle, &sample, event,
7861 namespaces_event->event_id.header.size);
7865 namespaces_event->event_id.pid = perf_event_pid(event,
7866 namespaces_event->task);
7867 namespaces_event->event_id.tid = perf_event_tid(event,
7868 namespaces_event->task);
7870 perf_output_put(&handle, namespaces_event->event_id);
7872 perf_event__output_id_sample(event, &handle, &sample);
7874 perf_output_end(&handle);
7876 namespaces_event->event_id.header.size = header_size;
7879 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
7880 struct task_struct *task,
7881 const struct proc_ns_operations *ns_ops)
7883 struct path ns_path;
7884 struct inode *ns_inode;
7887 error = ns_get_path(&ns_path, task, ns_ops);
7889 ns_inode = ns_path.dentry->d_inode;
7890 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
7891 ns_link_info->ino = ns_inode->i_ino;
7896 void perf_event_namespaces(struct task_struct *task)
7898 struct perf_namespaces_event namespaces_event;
7899 struct perf_ns_link_info *ns_link_info;
7901 if (!atomic_read(&nr_namespaces_events))
7904 namespaces_event = (struct perf_namespaces_event){
7908 .type = PERF_RECORD_NAMESPACES,
7910 .size = sizeof(namespaces_event.event_id),
7914 .nr_namespaces = NR_NAMESPACES,
7915 /* .link_info[NR_NAMESPACES] */
7919 ns_link_info = namespaces_event.event_id.link_info;
7921 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
7922 task, &mntns_operations);
7924 #ifdef CONFIG_USER_NS
7925 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
7926 task, &userns_operations);
7928 #ifdef CONFIG_NET_NS
7929 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
7930 task, &netns_operations);
7932 #ifdef CONFIG_UTS_NS
7933 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
7934 task, &utsns_operations);
7936 #ifdef CONFIG_IPC_NS
7937 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
7938 task, &ipcns_operations);
7940 #ifdef CONFIG_PID_NS
7941 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
7942 task, &pidns_operations);
7944 #ifdef CONFIG_CGROUPS
7945 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
7946 task, &cgroupns_operations);
7949 perf_iterate_sb(perf_event_namespaces_output,
7957 #ifdef CONFIG_CGROUP_PERF
7959 struct perf_cgroup_event {
7963 struct perf_event_header header;
7969 static int perf_event_cgroup_match(struct perf_event *event)
7971 return event->attr.cgroup;
7974 static void perf_event_cgroup_output(struct perf_event *event, void *data)
7976 struct perf_cgroup_event *cgroup_event = data;
7977 struct perf_output_handle handle;
7978 struct perf_sample_data sample;
7979 u16 header_size = cgroup_event->event_id.header.size;
7982 if (!perf_event_cgroup_match(event))
7985 perf_event_header__init_id(&cgroup_event->event_id.header,
7987 ret = perf_output_begin(&handle, &sample, event,
7988 cgroup_event->event_id.header.size);
7992 perf_output_put(&handle, cgroup_event->event_id);
7993 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
7995 perf_event__output_id_sample(event, &handle, &sample);
7997 perf_output_end(&handle);
7999 cgroup_event->event_id.header.size = header_size;
8002 static void perf_event_cgroup(struct cgroup *cgrp)
8004 struct perf_cgroup_event cgroup_event;
8005 char path_enomem[16] = "//enomem";
8009 if (!atomic_read(&nr_cgroup_events))
8012 cgroup_event = (struct perf_cgroup_event){
8015 .type = PERF_RECORD_CGROUP,
8017 .size = sizeof(cgroup_event.event_id),
8019 .id = cgroup_id(cgrp),
8023 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
8024 if (pathname == NULL) {
8025 cgroup_event.path = path_enomem;
8027 /* just to be sure to have enough space for alignment */
8028 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
8029 cgroup_event.path = pathname;
8033 * Since our buffer works in 8 byte units we need to align our string
8034 * size to a multiple of 8. However, we must guarantee the tail end is
8035 * zero'd out to avoid leaking random bits to userspace.
8037 size = strlen(cgroup_event.path) + 1;
8038 while (!IS_ALIGNED(size, sizeof(u64)))
8039 cgroup_event.path[size++] = '\0';
8041 cgroup_event.event_id.header.size += size;
8042 cgroup_event.path_size = size;
8044 perf_iterate_sb(perf_event_cgroup_output,
8057 struct perf_mmap_event {
8058 struct vm_area_struct *vma;
8060 const char *file_name;
8066 u8 build_id[BUILD_ID_SIZE_MAX];
8070 struct perf_event_header header;
8080 static int perf_event_mmap_match(struct perf_event *event,
8083 struct perf_mmap_event *mmap_event = data;
8084 struct vm_area_struct *vma = mmap_event->vma;
8085 int executable = vma->vm_flags & VM_EXEC;
8087 return (!executable && event->attr.mmap_data) ||
8088 (executable && (event->attr.mmap || event->attr.mmap2));
8091 static void perf_event_mmap_output(struct perf_event *event,
8094 struct perf_mmap_event *mmap_event = data;
8095 struct perf_output_handle handle;
8096 struct perf_sample_data sample;
8097 int size = mmap_event->event_id.header.size;
8098 u32 type = mmap_event->event_id.header.type;
8102 if (!perf_event_mmap_match(event, data))
8105 if (event->attr.mmap2) {
8106 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
8107 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
8108 mmap_event->event_id.header.size += sizeof(mmap_event->min);
8109 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
8110 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
8111 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
8112 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
8115 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
8116 ret = perf_output_begin(&handle, &sample, event,
8117 mmap_event->event_id.header.size);
8121 mmap_event->event_id.pid = perf_event_pid(event, current);
8122 mmap_event->event_id.tid = perf_event_tid(event, current);
8124 use_build_id = event->attr.build_id && mmap_event->build_id_size;
8126 if (event->attr.mmap2 && use_build_id)
8127 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
8129 perf_output_put(&handle, mmap_event->event_id);
8131 if (event->attr.mmap2) {
8133 u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 };
8135 __output_copy(&handle, size, 4);
8136 __output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX);
8138 perf_output_put(&handle, mmap_event->maj);
8139 perf_output_put(&handle, mmap_event->min);
8140 perf_output_put(&handle, mmap_event->ino);
8141 perf_output_put(&handle, mmap_event->ino_generation);
8143 perf_output_put(&handle, mmap_event->prot);
8144 perf_output_put(&handle, mmap_event->flags);
8147 __output_copy(&handle, mmap_event->file_name,
8148 mmap_event->file_size);
8150 perf_event__output_id_sample(event, &handle, &sample);
8152 perf_output_end(&handle);
8154 mmap_event->event_id.header.size = size;
8155 mmap_event->event_id.header.type = type;
8158 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
8160 struct vm_area_struct *vma = mmap_event->vma;
8161 struct file *file = vma->vm_file;
8162 int maj = 0, min = 0;
8163 u64 ino = 0, gen = 0;
8164 u32 prot = 0, flags = 0;
8170 if (vma->vm_flags & VM_READ)
8172 if (vma->vm_flags & VM_WRITE)
8174 if (vma->vm_flags & VM_EXEC)
8177 if (vma->vm_flags & VM_MAYSHARE)
8180 flags = MAP_PRIVATE;
8182 if (vma->vm_flags & VM_DENYWRITE)
8183 flags |= MAP_DENYWRITE;
8184 if (vma->vm_flags & VM_MAYEXEC)
8185 flags |= MAP_EXECUTABLE;
8186 if (vma->vm_flags & VM_LOCKED)
8187 flags |= MAP_LOCKED;
8188 if (is_vm_hugetlb_page(vma))
8189 flags |= MAP_HUGETLB;
8192 struct inode *inode;
8195 buf = kmalloc(PATH_MAX, GFP_KERNEL);
8201 * d_path() works from the end of the rb backwards, so we
8202 * need to add enough zero bytes after the string to handle
8203 * the 64bit alignment we do later.
8205 name = file_path(file, buf, PATH_MAX - sizeof(u64));
8210 inode = file_inode(vma->vm_file);
8211 dev = inode->i_sb->s_dev;
8213 gen = inode->i_generation;
8219 if (vma->vm_ops && vma->vm_ops->name) {
8220 name = (char *) vma->vm_ops->name(vma);
8225 name = (char *)arch_vma_name(vma);
8229 if (vma->vm_start <= vma->vm_mm->start_brk &&
8230 vma->vm_end >= vma->vm_mm->brk) {
8234 if (vma->vm_start <= vma->vm_mm->start_stack &&
8235 vma->vm_end >= vma->vm_mm->start_stack) {
8245 strlcpy(tmp, name, sizeof(tmp));
8249 * Since our buffer works in 8 byte units we need to align our string
8250 * size to a multiple of 8. However, we must guarantee the tail end is
8251 * zero'd out to avoid leaking random bits to userspace.
8253 size = strlen(name)+1;
8254 while (!IS_ALIGNED(size, sizeof(u64)))
8255 name[size++] = '\0';
8257 mmap_event->file_name = name;
8258 mmap_event->file_size = size;
8259 mmap_event->maj = maj;
8260 mmap_event->min = min;
8261 mmap_event->ino = ino;
8262 mmap_event->ino_generation = gen;
8263 mmap_event->prot = prot;
8264 mmap_event->flags = flags;
8266 if (!(vma->vm_flags & VM_EXEC))
8267 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
8269 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
8271 if (atomic_read(&nr_build_id_events))
8272 build_id_parse(vma, mmap_event->build_id, &mmap_event->build_id_size);
8274 perf_iterate_sb(perf_event_mmap_output,
8282 * Check whether inode and address range match filter criteria.
8284 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
8285 struct file *file, unsigned long offset,
8288 /* d_inode(NULL) won't be equal to any mapped user-space file */
8289 if (!filter->path.dentry)
8292 if (d_inode(filter->path.dentry) != file_inode(file))
8295 if (filter->offset > offset + size)
8298 if (filter->offset + filter->size < offset)
8304 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
8305 struct vm_area_struct *vma,
8306 struct perf_addr_filter_range *fr)
8308 unsigned long vma_size = vma->vm_end - vma->vm_start;
8309 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8310 struct file *file = vma->vm_file;
8312 if (!perf_addr_filter_match(filter, file, off, vma_size))
8315 if (filter->offset < off) {
8316 fr->start = vma->vm_start;
8317 fr->size = min(vma_size, filter->size - (off - filter->offset));
8319 fr->start = vma->vm_start + filter->offset - off;
8320 fr->size = min(vma->vm_end - fr->start, filter->size);
8326 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
8328 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8329 struct vm_area_struct *vma = data;
8330 struct perf_addr_filter *filter;
8331 unsigned int restart = 0, count = 0;
8332 unsigned long flags;
8334 if (!has_addr_filter(event))
8340 raw_spin_lock_irqsave(&ifh->lock, flags);
8341 list_for_each_entry(filter, &ifh->list, entry) {
8342 if (perf_addr_filter_vma_adjust(filter, vma,
8343 &event->addr_filter_ranges[count]))
8350 event->addr_filters_gen++;
8351 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8354 perf_event_stop(event, 1);
8358 * Adjust all task's events' filters to the new vma
8360 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
8362 struct perf_event_context *ctx;
8366 * Data tracing isn't supported yet and as such there is no need
8367 * to keep track of anything that isn't related to executable code:
8369 if (!(vma->vm_flags & VM_EXEC))
8373 for_each_task_context_nr(ctxn) {
8374 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
8378 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
8383 void perf_event_mmap(struct vm_area_struct *vma)
8385 struct perf_mmap_event mmap_event;
8387 if (!atomic_read(&nr_mmap_events))
8390 mmap_event = (struct perf_mmap_event){
8396 .type = PERF_RECORD_MMAP,
8397 .misc = PERF_RECORD_MISC_USER,
8402 .start = vma->vm_start,
8403 .len = vma->vm_end - vma->vm_start,
8404 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
8406 /* .maj (attr_mmap2 only) */
8407 /* .min (attr_mmap2 only) */
8408 /* .ino (attr_mmap2 only) */
8409 /* .ino_generation (attr_mmap2 only) */
8410 /* .prot (attr_mmap2 only) */
8411 /* .flags (attr_mmap2 only) */
8414 perf_addr_filters_adjust(vma);
8415 perf_event_mmap_event(&mmap_event);
8418 void perf_event_aux_event(struct perf_event *event, unsigned long head,
8419 unsigned long size, u64 flags)
8421 struct perf_output_handle handle;
8422 struct perf_sample_data sample;
8423 struct perf_aux_event {
8424 struct perf_event_header header;
8430 .type = PERF_RECORD_AUX,
8432 .size = sizeof(rec),
8440 perf_event_header__init_id(&rec.header, &sample, event);
8441 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8446 perf_output_put(&handle, rec);
8447 perf_event__output_id_sample(event, &handle, &sample);
8449 perf_output_end(&handle);
8453 * Lost/dropped samples logging
8455 void perf_log_lost_samples(struct perf_event *event, u64 lost)
8457 struct perf_output_handle handle;
8458 struct perf_sample_data sample;
8462 struct perf_event_header header;
8464 } lost_samples_event = {
8466 .type = PERF_RECORD_LOST_SAMPLES,
8468 .size = sizeof(lost_samples_event),
8473 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
8475 ret = perf_output_begin(&handle, &sample, event,
8476 lost_samples_event.header.size);
8480 perf_output_put(&handle, lost_samples_event);
8481 perf_event__output_id_sample(event, &handle, &sample);
8482 perf_output_end(&handle);
8486 * context_switch tracking
8489 struct perf_switch_event {
8490 struct task_struct *task;
8491 struct task_struct *next_prev;
8494 struct perf_event_header header;
8500 static int perf_event_switch_match(struct perf_event *event)
8502 return event->attr.context_switch;
8505 static void perf_event_switch_output(struct perf_event *event, void *data)
8507 struct perf_switch_event *se = data;
8508 struct perf_output_handle handle;
8509 struct perf_sample_data sample;
8512 if (!perf_event_switch_match(event))
8515 /* Only CPU-wide events are allowed to see next/prev pid/tid */
8516 if (event->ctx->task) {
8517 se->event_id.header.type = PERF_RECORD_SWITCH;
8518 se->event_id.header.size = sizeof(se->event_id.header);
8520 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
8521 se->event_id.header.size = sizeof(se->event_id);
8522 se->event_id.next_prev_pid =
8523 perf_event_pid(event, se->next_prev);
8524 se->event_id.next_prev_tid =
8525 perf_event_tid(event, se->next_prev);
8528 perf_event_header__init_id(&se->event_id.header, &sample, event);
8530 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
8534 if (event->ctx->task)
8535 perf_output_put(&handle, se->event_id.header);
8537 perf_output_put(&handle, se->event_id);
8539 perf_event__output_id_sample(event, &handle, &sample);
8541 perf_output_end(&handle);
8544 static void perf_event_switch(struct task_struct *task,
8545 struct task_struct *next_prev, bool sched_in)
8547 struct perf_switch_event switch_event;
8549 /* N.B. caller checks nr_switch_events != 0 */
8551 switch_event = (struct perf_switch_event){
8553 .next_prev = next_prev,
8557 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
8560 /* .next_prev_pid */
8561 /* .next_prev_tid */
8565 if (!sched_in && task->state == TASK_RUNNING)
8566 switch_event.event_id.header.misc |=
8567 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
8569 perf_iterate_sb(perf_event_switch_output,
8575 * IRQ throttle logging
8578 static void perf_log_throttle(struct perf_event *event, int enable)
8580 struct perf_output_handle handle;
8581 struct perf_sample_data sample;
8585 struct perf_event_header header;
8589 } throttle_event = {
8591 .type = PERF_RECORD_THROTTLE,
8593 .size = sizeof(throttle_event),
8595 .time = perf_event_clock(event),
8596 .id = primary_event_id(event),
8597 .stream_id = event->id,
8601 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
8603 perf_event_header__init_id(&throttle_event.header, &sample, event);
8605 ret = perf_output_begin(&handle, &sample, event,
8606 throttle_event.header.size);
8610 perf_output_put(&handle, throttle_event);
8611 perf_event__output_id_sample(event, &handle, &sample);
8612 perf_output_end(&handle);
8616 * ksymbol register/unregister tracking
8619 struct perf_ksymbol_event {
8623 struct perf_event_header header;
8631 static int perf_event_ksymbol_match(struct perf_event *event)
8633 return event->attr.ksymbol;
8636 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
8638 struct perf_ksymbol_event *ksymbol_event = data;
8639 struct perf_output_handle handle;
8640 struct perf_sample_data sample;
8643 if (!perf_event_ksymbol_match(event))
8646 perf_event_header__init_id(&ksymbol_event->event_id.header,
8648 ret = perf_output_begin(&handle, &sample, event,
8649 ksymbol_event->event_id.header.size);
8653 perf_output_put(&handle, ksymbol_event->event_id);
8654 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
8655 perf_event__output_id_sample(event, &handle, &sample);
8657 perf_output_end(&handle);
8660 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
8663 struct perf_ksymbol_event ksymbol_event;
8664 char name[KSYM_NAME_LEN];
8668 if (!atomic_read(&nr_ksymbol_events))
8671 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
8672 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
8675 strlcpy(name, sym, KSYM_NAME_LEN);
8676 name_len = strlen(name) + 1;
8677 while (!IS_ALIGNED(name_len, sizeof(u64)))
8678 name[name_len++] = '\0';
8679 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
8682 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
8684 ksymbol_event = (struct perf_ksymbol_event){
8686 .name_len = name_len,
8689 .type = PERF_RECORD_KSYMBOL,
8690 .size = sizeof(ksymbol_event.event_id) +
8695 .ksym_type = ksym_type,
8700 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
8703 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
8707 * bpf program load/unload tracking
8710 struct perf_bpf_event {
8711 struct bpf_prog *prog;
8713 struct perf_event_header header;
8717 u8 tag[BPF_TAG_SIZE];
8721 static int perf_event_bpf_match(struct perf_event *event)
8723 return event->attr.bpf_event;
8726 static void perf_event_bpf_output(struct perf_event *event, void *data)
8728 struct perf_bpf_event *bpf_event = data;
8729 struct perf_output_handle handle;
8730 struct perf_sample_data sample;
8733 if (!perf_event_bpf_match(event))
8736 perf_event_header__init_id(&bpf_event->event_id.header,
8738 ret = perf_output_begin(&handle, data, event,
8739 bpf_event->event_id.header.size);
8743 perf_output_put(&handle, bpf_event->event_id);
8744 perf_event__output_id_sample(event, &handle, &sample);
8746 perf_output_end(&handle);
8749 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
8750 enum perf_bpf_event_type type)
8752 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
8755 if (prog->aux->func_cnt == 0) {
8756 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
8757 (u64)(unsigned long)prog->bpf_func,
8758 prog->jited_len, unregister,
8759 prog->aux->ksym.name);
8761 for (i = 0; i < prog->aux->func_cnt; i++) {
8762 struct bpf_prog *subprog = prog->aux->func[i];
8765 PERF_RECORD_KSYMBOL_TYPE_BPF,
8766 (u64)(unsigned long)subprog->bpf_func,
8767 subprog->jited_len, unregister,
8768 prog->aux->ksym.name);
8773 void perf_event_bpf_event(struct bpf_prog *prog,
8774 enum perf_bpf_event_type type,
8777 struct perf_bpf_event bpf_event;
8779 if (type <= PERF_BPF_EVENT_UNKNOWN ||
8780 type >= PERF_BPF_EVENT_MAX)
8784 case PERF_BPF_EVENT_PROG_LOAD:
8785 case PERF_BPF_EVENT_PROG_UNLOAD:
8786 if (atomic_read(&nr_ksymbol_events))
8787 perf_event_bpf_emit_ksymbols(prog, type);
8793 if (!atomic_read(&nr_bpf_events))
8796 bpf_event = (struct perf_bpf_event){
8800 .type = PERF_RECORD_BPF_EVENT,
8801 .size = sizeof(bpf_event.event_id),
8805 .id = prog->aux->id,
8809 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
8811 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
8812 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
8815 struct perf_text_poke_event {
8816 const void *old_bytes;
8817 const void *new_bytes;
8823 struct perf_event_header header;
8829 static int perf_event_text_poke_match(struct perf_event *event)
8831 return event->attr.text_poke;
8834 static void perf_event_text_poke_output(struct perf_event *event, void *data)
8836 struct perf_text_poke_event *text_poke_event = data;
8837 struct perf_output_handle handle;
8838 struct perf_sample_data sample;
8842 if (!perf_event_text_poke_match(event))
8845 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
8847 ret = perf_output_begin(&handle, &sample, event,
8848 text_poke_event->event_id.header.size);
8852 perf_output_put(&handle, text_poke_event->event_id);
8853 perf_output_put(&handle, text_poke_event->old_len);
8854 perf_output_put(&handle, text_poke_event->new_len);
8856 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
8857 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
8859 if (text_poke_event->pad)
8860 __output_copy(&handle, &padding, text_poke_event->pad);
8862 perf_event__output_id_sample(event, &handle, &sample);
8864 perf_output_end(&handle);
8867 void perf_event_text_poke(const void *addr, const void *old_bytes,
8868 size_t old_len, const void *new_bytes, size_t new_len)
8870 struct perf_text_poke_event text_poke_event;
8873 if (!atomic_read(&nr_text_poke_events))
8876 tot = sizeof(text_poke_event.old_len) + old_len;
8877 tot += sizeof(text_poke_event.new_len) + new_len;
8878 pad = ALIGN(tot, sizeof(u64)) - tot;
8880 text_poke_event = (struct perf_text_poke_event){
8881 .old_bytes = old_bytes,
8882 .new_bytes = new_bytes,
8888 .type = PERF_RECORD_TEXT_POKE,
8889 .misc = PERF_RECORD_MISC_KERNEL,
8890 .size = sizeof(text_poke_event.event_id) + tot + pad,
8892 .addr = (unsigned long)addr,
8896 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
8899 void perf_event_itrace_started(struct perf_event *event)
8901 event->attach_state |= PERF_ATTACH_ITRACE;
8904 static void perf_log_itrace_start(struct perf_event *event)
8906 struct perf_output_handle handle;
8907 struct perf_sample_data sample;
8908 struct perf_aux_event {
8909 struct perf_event_header header;
8916 event = event->parent;
8918 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
8919 event->attach_state & PERF_ATTACH_ITRACE)
8922 rec.header.type = PERF_RECORD_ITRACE_START;
8923 rec.header.misc = 0;
8924 rec.header.size = sizeof(rec);
8925 rec.pid = perf_event_pid(event, current);
8926 rec.tid = perf_event_tid(event, current);
8928 perf_event_header__init_id(&rec.header, &sample, event);
8929 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8934 perf_output_put(&handle, rec);
8935 perf_event__output_id_sample(event, &handle, &sample);
8937 perf_output_end(&handle);
8941 __perf_event_account_interrupt(struct perf_event *event, int throttle)
8943 struct hw_perf_event *hwc = &event->hw;
8947 seq = __this_cpu_read(perf_throttled_seq);
8948 if (seq != hwc->interrupts_seq) {
8949 hwc->interrupts_seq = seq;
8950 hwc->interrupts = 1;
8953 if (unlikely(throttle
8954 && hwc->interrupts >= max_samples_per_tick)) {
8955 __this_cpu_inc(perf_throttled_count);
8956 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
8957 hwc->interrupts = MAX_INTERRUPTS;
8958 perf_log_throttle(event, 0);
8963 if (event->attr.freq) {
8964 u64 now = perf_clock();
8965 s64 delta = now - hwc->freq_time_stamp;
8967 hwc->freq_time_stamp = now;
8969 if (delta > 0 && delta < 2*TICK_NSEC)
8970 perf_adjust_period(event, delta, hwc->last_period, true);
8976 int perf_event_account_interrupt(struct perf_event *event)
8978 return __perf_event_account_interrupt(event, 1);
8982 * Generic event overflow handling, sampling.
8985 static int __perf_event_overflow(struct perf_event *event,
8986 int throttle, struct perf_sample_data *data,
8987 struct pt_regs *regs)
8989 int events = atomic_read(&event->event_limit);
8993 * Non-sampling counters might still use the PMI to fold short
8994 * hardware counters, ignore those.
8996 if (unlikely(!is_sampling_event(event)))
8999 ret = __perf_event_account_interrupt(event, throttle);
9002 * XXX event_limit might not quite work as expected on inherited
9006 event->pending_kill = POLL_IN;
9007 if (events && atomic_dec_and_test(&event->event_limit)) {
9009 event->pending_kill = POLL_HUP;
9011 perf_event_disable_inatomic(event);
9014 READ_ONCE(event->overflow_handler)(event, data, regs);
9016 if (*perf_event_fasync(event) && event->pending_kill) {
9017 event->pending_wakeup = 1;
9018 irq_work_queue(&event->pending);
9024 int perf_event_overflow(struct perf_event *event,
9025 struct perf_sample_data *data,
9026 struct pt_regs *regs)
9028 return __perf_event_overflow(event, 1, data, regs);
9032 * Generic software event infrastructure
9035 struct swevent_htable {
9036 struct swevent_hlist *swevent_hlist;
9037 struct mutex hlist_mutex;
9040 /* Recursion avoidance in each contexts */
9041 int recursion[PERF_NR_CONTEXTS];
9044 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
9047 * We directly increment event->count and keep a second value in
9048 * event->hw.period_left to count intervals. This period event
9049 * is kept in the range [-sample_period, 0] so that we can use the
9053 u64 perf_swevent_set_period(struct perf_event *event)
9055 struct hw_perf_event *hwc = &event->hw;
9056 u64 period = hwc->last_period;
9060 hwc->last_period = hwc->sample_period;
9063 old = val = local64_read(&hwc->period_left);
9067 nr = div64_u64(period + val, period);
9068 offset = nr * period;
9070 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
9076 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
9077 struct perf_sample_data *data,
9078 struct pt_regs *regs)
9080 struct hw_perf_event *hwc = &event->hw;
9084 overflow = perf_swevent_set_period(event);
9086 if (hwc->interrupts == MAX_INTERRUPTS)
9089 for (; overflow; overflow--) {
9090 if (__perf_event_overflow(event, throttle,
9093 * We inhibit the overflow from happening when
9094 * hwc->interrupts == MAX_INTERRUPTS.
9102 static void perf_swevent_event(struct perf_event *event, u64 nr,
9103 struct perf_sample_data *data,
9104 struct pt_regs *regs)
9106 struct hw_perf_event *hwc = &event->hw;
9108 local64_add(nr, &event->count);
9113 if (!is_sampling_event(event))
9116 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
9118 return perf_swevent_overflow(event, 1, data, regs);
9120 data->period = event->hw.last_period;
9122 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
9123 return perf_swevent_overflow(event, 1, data, regs);
9125 if (local64_add_negative(nr, &hwc->period_left))
9128 perf_swevent_overflow(event, 0, data, regs);
9131 static int perf_exclude_event(struct perf_event *event,
9132 struct pt_regs *regs)
9134 if (event->hw.state & PERF_HES_STOPPED)
9138 if (event->attr.exclude_user && user_mode(regs))
9141 if (event->attr.exclude_kernel && !user_mode(regs))
9148 static int perf_swevent_match(struct perf_event *event,
9149 enum perf_type_id type,
9151 struct perf_sample_data *data,
9152 struct pt_regs *regs)
9154 if (event->attr.type != type)
9157 if (event->attr.config != event_id)
9160 if (perf_exclude_event(event, regs))
9166 static inline u64 swevent_hash(u64 type, u32 event_id)
9168 u64 val = event_id | (type << 32);
9170 return hash_64(val, SWEVENT_HLIST_BITS);
9173 static inline struct hlist_head *
9174 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
9176 u64 hash = swevent_hash(type, event_id);
9178 return &hlist->heads[hash];
9181 /* For the read side: events when they trigger */
9182 static inline struct hlist_head *
9183 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
9185 struct swevent_hlist *hlist;
9187 hlist = rcu_dereference(swhash->swevent_hlist);
9191 return __find_swevent_head(hlist, type, event_id);
9194 /* For the event head insertion and removal in the hlist */
9195 static inline struct hlist_head *
9196 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
9198 struct swevent_hlist *hlist;
9199 u32 event_id = event->attr.config;
9200 u64 type = event->attr.type;
9203 * Event scheduling is always serialized against hlist allocation
9204 * and release. Which makes the protected version suitable here.
9205 * The context lock guarantees that.
9207 hlist = rcu_dereference_protected(swhash->swevent_hlist,
9208 lockdep_is_held(&event->ctx->lock));
9212 return __find_swevent_head(hlist, type, event_id);
9215 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
9217 struct perf_sample_data *data,
9218 struct pt_regs *regs)
9220 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9221 struct perf_event *event;
9222 struct hlist_head *head;
9225 head = find_swevent_head_rcu(swhash, type, event_id);
9229 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9230 if (perf_swevent_match(event, type, event_id, data, regs))
9231 perf_swevent_event(event, nr, data, regs);
9237 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
9239 int perf_swevent_get_recursion_context(void)
9241 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9243 return get_recursion_context(swhash->recursion);
9245 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
9247 void perf_swevent_put_recursion_context(int rctx)
9249 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9251 put_recursion_context(swhash->recursion, rctx);
9254 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9256 struct perf_sample_data data;
9258 if (WARN_ON_ONCE(!regs))
9261 perf_sample_data_init(&data, addr, 0);
9262 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
9265 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9269 preempt_disable_notrace();
9270 rctx = perf_swevent_get_recursion_context();
9271 if (unlikely(rctx < 0))
9274 ___perf_sw_event(event_id, nr, regs, addr);
9276 perf_swevent_put_recursion_context(rctx);
9278 preempt_enable_notrace();
9281 static void perf_swevent_read(struct perf_event *event)
9285 static int perf_swevent_add(struct perf_event *event, int flags)
9287 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9288 struct hw_perf_event *hwc = &event->hw;
9289 struct hlist_head *head;
9291 if (is_sampling_event(event)) {
9292 hwc->last_period = hwc->sample_period;
9293 perf_swevent_set_period(event);
9296 hwc->state = !(flags & PERF_EF_START);
9298 head = find_swevent_head(swhash, event);
9299 if (WARN_ON_ONCE(!head))
9302 hlist_add_head_rcu(&event->hlist_entry, head);
9303 perf_event_update_userpage(event);
9308 static void perf_swevent_del(struct perf_event *event, int flags)
9310 hlist_del_rcu(&event->hlist_entry);
9313 static void perf_swevent_start(struct perf_event *event, int flags)
9315 event->hw.state = 0;
9318 static void perf_swevent_stop(struct perf_event *event, int flags)
9320 event->hw.state = PERF_HES_STOPPED;
9323 /* Deref the hlist from the update side */
9324 static inline struct swevent_hlist *
9325 swevent_hlist_deref(struct swevent_htable *swhash)
9327 return rcu_dereference_protected(swhash->swevent_hlist,
9328 lockdep_is_held(&swhash->hlist_mutex));
9331 static void swevent_hlist_release(struct swevent_htable *swhash)
9333 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
9338 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
9339 kfree_rcu(hlist, rcu_head);
9342 static void swevent_hlist_put_cpu(int cpu)
9344 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9346 mutex_lock(&swhash->hlist_mutex);
9348 if (!--swhash->hlist_refcount)
9349 swevent_hlist_release(swhash);
9351 mutex_unlock(&swhash->hlist_mutex);
9354 static void swevent_hlist_put(void)
9358 for_each_possible_cpu(cpu)
9359 swevent_hlist_put_cpu(cpu);
9362 static int swevent_hlist_get_cpu(int cpu)
9364 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9367 mutex_lock(&swhash->hlist_mutex);
9368 if (!swevent_hlist_deref(swhash) &&
9369 cpumask_test_cpu(cpu, perf_online_mask)) {
9370 struct swevent_hlist *hlist;
9372 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
9377 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9379 swhash->hlist_refcount++;
9381 mutex_unlock(&swhash->hlist_mutex);
9386 static int swevent_hlist_get(void)
9388 int err, cpu, failed_cpu;
9390 mutex_lock(&pmus_lock);
9391 for_each_possible_cpu(cpu) {
9392 err = swevent_hlist_get_cpu(cpu);
9398 mutex_unlock(&pmus_lock);
9401 for_each_possible_cpu(cpu) {
9402 if (cpu == failed_cpu)
9404 swevent_hlist_put_cpu(cpu);
9406 mutex_unlock(&pmus_lock);
9410 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
9412 static void sw_perf_event_destroy(struct perf_event *event)
9414 u64 event_id = event->attr.config;
9416 WARN_ON(event->parent);
9418 static_key_slow_dec(&perf_swevent_enabled[event_id]);
9419 swevent_hlist_put();
9422 static int perf_swevent_init(struct perf_event *event)
9424 u64 event_id = event->attr.config;
9426 if (event->attr.type != PERF_TYPE_SOFTWARE)
9430 * no branch sampling for software events
9432 if (has_branch_stack(event))
9436 case PERF_COUNT_SW_CPU_CLOCK:
9437 case PERF_COUNT_SW_TASK_CLOCK:
9444 if (event_id >= PERF_COUNT_SW_MAX)
9447 if (!event->parent) {
9450 err = swevent_hlist_get();
9454 static_key_slow_inc(&perf_swevent_enabled[event_id]);
9455 event->destroy = sw_perf_event_destroy;
9461 static struct pmu perf_swevent = {
9462 .task_ctx_nr = perf_sw_context,
9464 .capabilities = PERF_PMU_CAP_NO_NMI,
9466 .event_init = perf_swevent_init,
9467 .add = perf_swevent_add,
9468 .del = perf_swevent_del,
9469 .start = perf_swevent_start,
9470 .stop = perf_swevent_stop,
9471 .read = perf_swevent_read,
9474 #ifdef CONFIG_EVENT_TRACING
9476 static int perf_tp_filter_match(struct perf_event *event,
9477 struct perf_sample_data *data)
9479 void *record = data->raw->frag.data;
9481 /* only top level events have filters set */
9483 event = event->parent;
9485 if (likely(!event->filter) || filter_match_preds(event->filter, record))
9490 static int perf_tp_event_match(struct perf_event *event,
9491 struct perf_sample_data *data,
9492 struct pt_regs *regs)
9494 if (event->hw.state & PERF_HES_STOPPED)
9497 * If exclude_kernel, only trace user-space tracepoints (uprobes)
9499 if (event->attr.exclude_kernel && !user_mode(regs))
9502 if (!perf_tp_filter_match(event, data))
9508 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
9509 struct trace_event_call *call, u64 count,
9510 struct pt_regs *regs, struct hlist_head *head,
9511 struct task_struct *task)
9513 if (bpf_prog_array_valid(call)) {
9514 *(struct pt_regs **)raw_data = regs;
9515 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
9516 perf_swevent_put_recursion_context(rctx);
9520 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
9523 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
9525 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
9526 struct pt_regs *regs, struct hlist_head *head, int rctx,
9527 struct task_struct *task)
9529 struct perf_sample_data data;
9530 struct perf_event *event;
9532 struct perf_raw_record raw = {
9539 perf_sample_data_init(&data, 0, 0);
9542 perf_trace_buf_update(record, event_type);
9544 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9545 if (perf_tp_event_match(event, &data, regs))
9546 perf_swevent_event(event, count, &data, regs);
9550 * If we got specified a target task, also iterate its context and
9551 * deliver this event there too.
9553 if (task && task != current) {
9554 struct perf_event_context *ctx;
9555 struct trace_entry *entry = record;
9558 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
9562 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
9563 if (event->cpu != smp_processor_id())
9565 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9567 if (event->attr.config != entry->type)
9569 if (perf_tp_event_match(event, &data, regs))
9570 perf_swevent_event(event, count, &data, regs);
9576 perf_swevent_put_recursion_context(rctx);
9578 EXPORT_SYMBOL_GPL(perf_tp_event);
9580 static void tp_perf_event_destroy(struct perf_event *event)
9582 perf_trace_destroy(event);
9585 static int perf_tp_event_init(struct perf_event *event)
9589 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9593 * no branch sampling for tracepoint events
9595 if (has_branch_stack(event))
9598 err = perf_trace_init(event);
9602 event->destroy = tp_perf_event_destroy;
9607 static struct pmu perf_tracepoint = {
9608 .task_ctx_nr = perf_sw_context,
9610 .event_init = perf_tp_event_init,
9611 .add = perf_trace_add,
9612 .del = perf_trace_del,
9613 .start = perf_swevent_start,
9614 .stop = perf_swevent_stop,
9615 .read = perf_swevent_read,
9618 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
9620 * Flags in config, used by dynamic PMU kprobe and uprobe
9621 * The flags should match following PMU_FORMAT_ATTR().
9623 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
9624 * if not set, create kprobe/uprobe
9626 * The following values specify a reference counter (or semaphore in the
9627 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
9628 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
9630 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
9631 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
9633 enum perf_probe_config {
9634 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
9635 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
9636 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
9639 PMU_FORMAT_ATTR(retprobe, "config:0");
9642 #ifdef CONFIG_KPROBE_EVENTS
9643 static struct attribute *kprobe_attrs[] = {
9644 &format_attr_retprobe.attr,
9648 static struct attribute_group kprobe_format_group = {
9650 .attrs = kprobe_attrs,
9653 static const struct attribute_group *kprobe_attr_groups[] = {
9654 &kprobe_format_group,
9658 static int perf_kprobe_event_init(struct perf_event *event);
9659 static struct pmu perf_kprobe = {
9660 .task_ctx_nr = perf_sw_context,
9661 .event_init = perf_kprobe_event_init,
9662 .add = perf_trace_add,
9663 .del = perf_trace_del,
9664 .start = perf_swevent_start,
9665 .stop = perf_swevent_stop,
9666 .read = perf_swevent_read,
9667 .attr_groups = kprobe_attr_groups,
9670 static int perf_kprobe_event_init(struct perf_event *event)
9675 if (event->attr.type != perf_kprobe.type)
9678 if (!perfmon_capable())
9682 * no branch sampling for probe events
9684 if (has_branch_stack(event))
9687 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9688 err = perf_kprobe_init(event, is_retprobe);
9692 event->destroy = perf_kprobe_destroy;
9696 #endif /* CONFIG_KPROBE_EVENTS */
9698 #ifdef CONFIG_UPROBE_EVENTS
9699 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
9701 static struct attribute *uprobe_attrs[] = {
9702 &format_attr_retprobe.attr,
9703 &format_attr_ref_ctr_offset.attr,
9707 static struct attribute_group uprobe_format_group = {
9709 .attrs = uprobe_attrs,
9712 static const struct attribute_group *uprobe_attr_groups[] = {
9713 &uprobe_format_group,
9717 static int perf_uprobe_event_init(struct perf_event *event);
9718 static struct pmu perf_uprobe = {
9719 .task_ctx_nr = perf_sw_context,
9720 .event_init = perf_uprobe_event_init,
9721 .add = perf_trace_add,
9722 .del = perf_trace_del,
9723 .start = perf_swevent_start,
9724 .stop = perf_swevent_stop,
9725 .read = perf_swevent_read,
9726 .attr_groups = uprobe_attr_groups,
9729 static int perf_uprobe_event_init(struct perf_event *event)
9732 unsigned long ref_ctr_offset;
9735 if (event->attr.type != perf_uprobe.type)
9738 if (!perfmon_capable())
9742 * no branch sampling for probe events
9744 if (has_branch_stack(event))
9747 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9748 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9749 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
9753 event->destroy = perf_uprobe_destroy;
9757 #endif /* CONFIG_UPROBE_EVENTS */
9759 static inline void perf_tp_register(void)
9761 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
9762 #ifdef CONFIG_KPROBE_EVENTS
9763 perf_pmu_register(&perf_kprobe, "kprobe", -1);
9765 #ifdef CONFIG_UPROBE_EVENTS
9766 perf_pmu_register(&perf_uprobe, "uprobe", -1);
9770 static void perf_event_free_filter(struct perf_event *event)
9772 ftrace_profile_free_filter(event);
9775 #ifdef CONFIG_BPF_SYSCALL
9776 static void bpf_overflow_handler(struct perf_event *event,
9777 struct perf_sample_data *data,
9778 struct pt_regs *regs)
9780 struct bpf_perf_event_data_kern ctx = {
9786 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
9787 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
9790 ret = BPF_PROG_RUN(event->prog, &ctx);
9793 __this_cpu_dec(bpf_prog_active);
9797 event->orig_overflow_handler(event, data, regs);
9800 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9802 struct bpf_prog *prog;
9804 if (event->overflow_handler_context)
9805 /* hw breakpoint or kernel counter */
9811 prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
9813 return PTR_ERR(prog);
9815 if (event->attr.precise_ip &&
9816 prog->call_get_stack &&
9817 (!(event->attr.sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY) ||
9818 event->attr.exclude_callchain_kernel ||
9819 event->attr.exclude_callchain_user)) {
9821 * On perf_event with precise_ip, calling bpf_get_stack()
9822 * may trigger unwinder warnings and occasional crashes.
9823 * bpf_get_[stack|stackid] works around this issue by using
9824 * callchain attached to perf_sample_data. If the
9825 * perf_event does not full (kernel and user) callchain
9826 * attached to perf_sample_data, do not allow attaching BPF
9827 * program that calls bpf_get_[stack|stackid].
9834 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
9835 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
9839 static void perf_event_free_bpf_handler(struct perf_event *event)
9841 struct bpf_prog *prog = event->prog;
9846 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
9851 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9855 static void perf_event_free_bpf_handler(struct perf_event *event)
9861 * returns true if the event is a tracepoint, or a kprobe/upprobe created
9862 * with perf_event_open()
9864 static inline bool perf_event_is_tracing(struct perf_event *event)
9866 if (event->pmu == &perf_tracepoint)
9868 #ifdef CONFIG_KPROBE_EVENTS
9869 if (event->pmu == &perf_kprobe)
9872 #ifdef CONFIG_UPROBE_EVENTS
9873 if (event->pmu == &perf_uprobe)
9879 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9881 bool is_kprobe, is_tracepoint, is_syscall_tp;
9882 struct bpf_prog *prog;
9885 if (!perf_event_is_tracing(event))
9886 return perf_event_set_bpf_handler(event, prog_fd);
9888 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
9889 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
9890 is_syscall_tp = is_syscall_trace_event(event->tp_event);
9891 if (!is_kprobe && !is_tracepoint && !is_syscall_tp)
9892 /* bpf programs can only be attached to u/kprobe or tracepoint */
9895 prog = bpf_prog_get(prog_fd);
9897 return PTR_ERR(prog);
9899 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
9900 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
9901 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
9902 /* valid fd, but invalid bpf program type */
9907 /* Kprobe override only works for kprobes, not uprobes. */
9908 if (prog->kprobe_override &&
9909 !(event->tp_event->flags & TRACE_EVENT_FL_KPROBE)) {
9914 if (is_tracepoint || is_syscall_tp) {
9915 int off = trace_event_get_offsets(event->tp_event);
9917 if (prog->aux->max_ctx_offset > off) {
9923 ret = perf_event_attach_bpf_prog(event, prog);
9929 static void perf_event_free_bpf_prog(struct perf_event *event)
9931 if (!perf_event_is_tracing(event)) {
9932 perf_event_free_bpf_handler(event);
9935 perf_event_detach_bpf_prog(event);
9940 static inline void perf_tp_register(void)
9944 static void perf_event_free_filter(struct perf_event *event)
9948 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9953 static void perf_event_free_bpf_prog(struct perf_event *event)
9956 #endif /* CONFIG_EVENT_TRACING */
9958 #ifdef CONFIG_HAVE_HW_BREAKPOINT
9959 void perf_bp_event(struct perf_event *bp, void *data)
9961 struct perf_sample_data sample;
9962 struct pt_regs *regs = data;
9964 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
9966 if (!bp->hw.state && !perf_exclude_event(bp, regs))
9967 perf_swevent_event(bp, 1, &sample, regs);
9972 * Allocate a new address filter
9974 static struct perf_addr_filter *
9975 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
9977 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
9978 struct perf_addr_filter *filter;
9980 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
9984 INIT_LIST_HEAD(&filter->entry);
9985 list_add_tail(&filter->entry, filters);
9990 static void free_filters_list(struct list_head *filters)
9992 struct perf_addr_filter *filter, *iter;
9994 list_for_each_entry_safe(filter, iter, filters, entry) {
9995 path_put(&filter->path);
9996 list_del(&filter->entry);
10002 * Free existing address filters and optionally install new ones
10004 static void perf_addr_filters_splice(struct perf_event *event,
10005 struct list_head *head)
10007 unsigned long flags;
10010 if (!has_addr_filter(event))
10013 /* don't bother with children, they don't have their own filters */
10017 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
10019 list_splice_init(&event->addr_filters.list, &list);
10021 list_splice(head, &event->addr_filters.list);
10023 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
10025 free_filters_list(&list);
10029 * Scan through mm's vmas and see if one of them matches the
10030 * @filter; if so, adjust filter's address range.
10031 * Called with mm::mmap_lock down for reading.
10033 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
10034 struct mm_struct *mm,
10035 struct perf_addr_filter_range *fr)
10037 struct vm_area_struct *vma;
10039 for (vma = mm->mmap; vma; vma = vma->vm_next) {
10043 if (perf_addr_filter_vma_adjust(filter, vma, fr))
10049 * Update event's address range filters based on the
10050 * task's existing mappings, if any.
10052 static void perf_event_addr_filters_apply(struct perf_event *event)
10054 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
10055 struct task_struct *task = READ_ONCE(event->ctx->task);
10056 struct perf_addr_filter *filter;
10057 struct mm_struct *mm = NULL;
10058 unsigned int count = 0;
10059 unsigned long flags;
10062 * We may observe TASK_TOMBSTONE, which means that the event tear-down
10063 * will stop on the parent's child_mutex that our caller is also holding
10065 if (task == TASK_TOMBSTONE)
10068 if (ifh->nr_file_filters) {
10069 mm = get_task_mm(event->ctx->task);
10073 mmap_read_lock(mm);
10076 raw_spin_lock_irqsave(&ifh->lock, flags);
10077 list_for_each_entry(filter, &ifh->list, entry) {
10078 if (filter->path.dentry) {
10080 * Adjust base offset if the filter is associated to a
10081 * binary that needs to be mapped:
10083 event->addr_filter_ranges[count].start = 0;
10084 event->addr_filter_ranges[count].size = 0;
10086 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
10088 event->addr_filter_ranges[count].start = filter->offset;
10089 event->addr_filter_ranges[count].size = filter->size;
10095 event->addr_filters_gen++;
10096 raw_spin_unlock_irqrestore(&ifh->lock, flags);
10098 if (ifh->nr_file_filters) {
10099 mmap_read_unlock(mm);
10105 perf_event_stop(event, 1);
10109 * Address range filtering: limiting the data to certain
10110 * instruction address ranges. Filters are ioctl()ed to us from
10111 * userspace as ascii strings.
10113 * Filter string format:
10115 * ACTION RANGE_SPEC
10116 * where ACTION is one of the
10117 * * "filter": limit the trace to this region
10118 * * "start": start tracing from this address
10119 * * "stop": stop tracing at this address/region;
10121 * * for kernel addresses: <start address>[/<size>]
10122 * * for object files: <start address>[/<size>]@</path/to/object/file>
10124 * if <size> is not specified or is zero, the range is treated as a single
10125 * address; not valid for ACTION=="filter".
10139 IF_STATE_ACTION = 0,
10144 static const match_table_t if_tokens = {
10145 { IF_ACT_FILTER, "filter" },
10146 { IF_ACT_START, "start" },
10147 { IF_ACT_STOP, "stop" },
10148 { IF_SRC_FILE, "%u/%u@%s" },
10149 { IF_SRC_KERNEL, "%u/%u" },
10150 { IF_SRC_FILEADDR, "%u@%s" },
10151 { IF_SRC_KERNELADDR, "%u" },
10152 { IF_ACT_NONE, NULL },
10156 * Address filter string parser
10159 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
10160 struct list_head *filters)
10162 struct perf_addr_filter *filter = NULL;
10163 char *start, *orig, *filename = NULL;
10164 substring_t args[MAX_OPT_ARGS];
10165 int state = IF_STATE_ACTION, token;
10166 unsigned int kernel = 0;
10169 orig = fstr = kstrdup(fstr, GFP_KERNEL);
10173 while ((start = strsep(&fstr, " ,\n")) != NULL) {
10174 static const enum perf_addr_filter_action_t actions[] = {
10175 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
10176 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
10177 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
10184 /* filter definition begins */
10185 if (state == IF_STATE_ACTION) {
10186 filter = perf_addr_filter_new(event, filters);
10191 token = match_token(start, if_tokens, args);
10193 case IF_ACT_FILTER:
10196 if (state != IF_STATE_ACTION)
10199 filter->action = actions[token];
10200 state = IF_STATE_SOURCE;
10203 case IF_SRC_KERNELADDR:
10204 case IF_SRC_KERNEL:
10208 case IF_SRC_FILEADDR:
10210 if (state != IF_STATE_SOURCE)
10214 ret = kstrtoul(args[0].from, 0, &filter->offset);
10218 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
10220 ret = kstrtoul(args[1].from, 0, &filter->size);
10225 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
10226 int fpos = token == IF_SRC_FILE ? 2 : 1;
10229 filename = match_strdup(&args[fpos]);
10236 state = IF_STATE_END;
10244 * Filter definition is fully parsed, validate and install it.
10245 * Make sure that it doesn't contradict itself or the event's
10248 if (state == IF_STATE_END) {
10250 if (kernel && event->attr.exclude_kernel)
10254 * ACTION "filter" must have a non-zero length region
10257 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
10266 * For now, we only support file-based filters
10267 * in per-task events; doing so for CPU-wide
10268 * events requires additional context switching
10269 * trickery, since same object code will be
10270 * mapped at different virtual addresses in
10271 * different processes.
10274 if (!event->ctx->task)
10277 /* look up the path and grab its inode */
10278 ret = kern_path(filename, LOOKUP_FOLLOW,
10284 if (!filter->path.dentry ||
10285 !S_ISREG(d_inode(filter->path.dentry)
10289 event->addr_filters.nr_file_filters++;
10292 /* ready to consume more filters */
10293 state = IF_STATE_ACTION;
10298 if (state != IF_STATE_ACTION)
10308 free_filters_list(filters);
10315 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
10317 LIST_HEAD(filters);
10321 * Since this is called in perf_ioctl() path, we're already holding
10324 lockdep_assert_held(&event->ctx->mutex);
10326 if (WARN_ON_ONCE(event->parent))
10329 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
10331 goto fail_clear_files;
10333 ret = event->pmu->addr_filters_validate(&filters);
10335 goto fail_free_filters;
10337 /* remove existing filters, if any */
10338 perf_addr_filters_splice(event, &filters);
10340 /* install new filters */
10341 perf_event_for_each_child(event, perf_event_addr_filters_apply);
10346 free_filters_list(&filters);
10349 event->addr_filters.nr_file_filters = 0;
10354 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
10359 filter_str = strndup_user(arg, PAGE_SIZE);
10360 if (IS_ERR(filter_str))
10361 return PTR_ERR(filter_str);
10363 #ifdef CONFIG_EVENT_TRACING
10364 if (perf_event_is_tracing(event)) {
10365 struct perf_event_context *ctx = event->ctx;
10368 * Beware, here be dragons!!
10370 * the tracepoint muck will deadlock against ctx->mutex, but
10371 * the tracepoint stuff does not actually need it. So
10372 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
10373 * already have a reference on ctx.
10375 * This can result in event getting moved to a different ctx,
10376 * but that does not affect the tracepoint state.
10378 mutex_unlock(&ctx->mutex);
10379 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
10380 mutex_lock(&ctx->mutex);
10383 if (has_addr_filter(event))
10384 ret = perf_event_set_addr_filter(event, filter_str);
10391 * hrtimer based swevent callback
10394 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
10396 enum hrtimer_restart ret = HRTIMER_RESTART;
10397 struct perf_sample_data data;
10398 struct pt_regs *regs;
10399 struct perf_event *event;
10402 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
10404 if (event->state != PERF_EVENT_STATE_ACTIVE)
10405 return HRTIMER_NORESTART;
10407 event->pmu->read(event);
10409 perf_sample_data_init(&data, 0, event->hw.last_period);
10410 regs = get_irq_regs();
10412 if (regs && !perf_exclude_event(event, regs)) {
10413 if (!(event->attr.exclude_idle && is_idle_task(current)))
10414 if (__perf_event_overflow(event, 1, &data, regs))
10415 ret = HRTIMER_NORESTART;
10418 period = max_t(u64, 10000, event->hw.sample_period);
10419 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
10424 static void perf_swevent_start_hrtimer(struct perf_event *event)
10426 struct hw_perf_event *hwc = &event->hw;
10429 if (!is_sampling_event(event))
10432 period = local64_read(&hwc->period_left);
10437 local64_set(&hwc->period_left, 0);
10439 period = max_t(u64, 10000, hwc->sample_period);
10441 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
10442 HRTIMER_MODE_REL_PINNED_HARD);
10445 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
10447 struct hw_perf_event *hwc = &event->hw;
10449 if (is_sampling_event(event)) {
10450 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
10451 local64_set(&hwc->period_left, ktime_to_ns(remaining));
10453 hrtimer_cancel(&hwc->hrtimer);
10457 static void perf_swevent_init_hrtimer(struct perf_event *event)
10459 struct hw_perf_event *hwc = &event->hw;
10461 if (!is_sampling_event(event))
10464 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
10465 hwc->hrtimer.function = perf_swevent_hrtimer;
10468 * Since hrtimers have a fixed rate, we can do a static freq->period
10469 * mapping and avoid the whole period adjust feedback stuff.
10471 if (event->attr.freq) {
10472 long freq = event->attr.sample_freq;
10474 event->attr.sample_period = NSEC_PER_SEC / freq;
10475 hwc->sample_period = event->attr.sample_period;
10476 local64_set(&hwc->period_left, hwc->sample_period);
10477 hwc->last_period = hwc->sample_period;
10478 event->attr.freq = 0;
10483 * Software event: cpu wall time clock
10486 static void cpu_clock_event_update(struct perf_event *event)
10491 now = local_clock();
10492 prev = local64_xchg(&event->hw.prev_count, now);
10493 local64_add(now - prev, &event->count);
10496 static void cpu_clock_event_start(struct perf_event *event, int flags)
10498 local64_set(&event->hw.prev_count, local_clock());
10499 perf_swevent_start_hrtimer(event);
10502 static void cpu_clock_event_stop(struct perf_event *event, int flags)
10504 perf_swevent_cancel_hrtimer(event);
10505 cpu_clock_event_update(event);
10508 static int cpu_clock_event_add(struct perf_event *event, int flags)
10510 if (flags & PERF_EF_START)
10511 cpu_clock_event_start(event, flags);
10512 perf_event_update_userpage(event);
10517 static void cpu_clock_event_del(struct perf_event *event, int flags)
10519 cpu_clock_event_stop(event, flags);
10522 static void cpu_clock_event_read(struct perf_event *event)
10524 cpu_clock_event_update(event);
10527 static int cpu_clock_event_init(struct perf_event *event)
10529 if (event->attr.type != PERF_TYPE_SOFTWARE)
10532 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
10536 * no branch sampling for software events
10538 if (has_branch_stack(event))
10539 return -EOPNOTSUPP;
10541 perf_swevent_init_hrtimer(event);
10546 static struct pmu perf_cpu_clock = {
10547 .task_ctx_nr = perf_sw_context,
10549 .capabilities = PERF_PMU_CAP_NO_NMI,
10551 .event_init = cpu_clock_event_init,
10552 .add = cpu_clock_event_add,
10553 .del = cpu_clock_event_del,
10554 .start = cpu_clock_event_start,
10555 .stop = cpu_clock_event_stop,
10556 .read = cpu_clock_event_read,
10560 * Software event: task time clock
10563 static void task_clock_event_update(struct perf_event *event, u64 now)
10568 prev = local64_xchg(&event->hw.prev_count, now);
10569 delta = now - prev;
10570 local64_add(delta, &event->count);
10573 static void task_clock_event_start(struct perf_event *event, int flags)
10575 local64_set(&event->hw.prev_count, event->ctx->time);
10576 perf_swevent_start_hrtimer(event);
10579 static void task_clock_event_stop(struct perf_event *event, int flags)
10581 perf_swevent_cancel_hrtimer(event);
10582 task_clock_event_update(event, event->ctx->time);
10585 static int task_clock_event_add(struct perf_event *event, int flags)
10587 if (flags & PERF_EF_START)
10588 task_clock_event_start(event, flags);
10589 perf_event_update_userpage(event);
10594 static void task_clock_event_del(struct perf_event *event, int flags)
10596 task_clock_event_stop(event, PERF_EF_UPDATE);
10599 static void task_clock_event_read(struct perf_event *event)
10601 u64 now = perf_clock();
10602 u64 delta = now - event->ctx->timestamp;
10603 u64 time = event->ctx->time + delta;
10605 task_clock_event_update(event, time);
10608 static int task_clock_event_init(struct perf_event *event)
10610 if (event->attr.type != PERF_TYPE_SOFTWARE)
10613 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
10617 * no branch sampling for software events
10619 if (has_branch_stack(event))
10620 return -EOPNOTSUPP;
10622 perf_swevent_init_hrtimer(event);
10627 static struct pmu perf_task_clock = {
10628 .task_ctx_nr = perf_sw_context,
10630 .capabilities = PERF_PMU_CAP_NO_NMI,
10632 .event_init = task_clock_event_init,
10633 .add = task_clock_event_add,
10634 .del = task_clock_event_del,
10635 .start = task_clock_event_start,
10636 .stop = task_clock_event_stop,
10637 .read = task_clock_event_read,
10640 static void perf_pmu_nop_void(struct pmu *pmu)
10644 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
10648 static int perf_pmu_nop_int(struct pmu *pmu)
10653 static int perf_event_nop_int(struct perf_event *event, u64 value)
10658 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
10660 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
10662 __this_cpu_write(nop_txn_flags, flags);
10664 if (flags & ~PERF_PMU_TXN_ADD)
10667 perf_pmu_disable(pmu);
10670 static int perf_pmu_commit_txn(struct pmu *pmu)
10672 unsigned int flags = __this_cpu_read(nop_txn_flags);
10674 __this_cpu_write(nop_txn_flags, 0);
10676 if (flags & ~PERF_PMU_TXN_ADD)
10679 perf_pmu_enable(pmu);
10683 static void perf_pmu_cancel_txn(struct pmu *pmu)
10685 unsigned int flags = __this_cpu_read(nop_txn_flags);
10687 __this_cpu_write(nop_txn_flags, 0);
10689 if (flags & ~PERF_PMU_TXN_ADD)
10692 perf_pmu_enable(pmu);
10695 static int perf_event_idx_default(struct perf_event *event)
10701 * Ensures all contexts with the same task_ctx_nr have the same
10702 * pmu_cpu_context too.
10704 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
10711 list_for_each_entry(pmu, &pmus, entry) {
10712 if (pmu->task_ctx_nr == ctxn)
10713 return pmu->pmu_cpu_context;
10719 static void free_pmu_context(struct pmu *pmu)
10722 * Static contexts such as perf_sw_context have a global lifetime
10723 * and may be shared between different PMUs. Avoid freeing them
10724 * when a single PMU is going away.
10726 if (pmu->task_ctx_nr > perf_invalid_context)
10729 free_percpu(pmu->pmu_cpu_context);
10733 * Let userspace know that this PMU supports address range filtering:
10735 static ssize_t nr_addr_filters_show(struct device *dev,
10736 struct device_attribute *attr,
10739 struct pmu *pmu = dev_get_drvdata(dev);
10741 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
10743 DEVICE_ATTR_RO(nr_addr_filters);
10745 static struct idr pmu_idr;
10748 type_show(struct device *dev, struct device_attribute *attr, char *page)
10750 struct pmu *pmu = dev_get_drvdata(dev);
10752 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
10754 static DEVICE_ATTR_RO(type);
10757 perf_event_mux_interval_ms_show(struct device *dev,
10758 struct device_attribute *attr,
10761 struct pmu *pmu = dev_get_drvdata(dev);
10763 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
10766 static DEFINE_MUTEX(mux_interval_mutex);
10769 perf_event_mux_interval_ms_store(struct device *dev,
10770 struct device_attribute *attr,
10771 const char *buf, size_t count)
10773 struct pmu *pmu = dev_get_drvdata(dev);
10774 int timer, cpu, ret;
10776 ret = kstrtoint(buf, 0, &timer);
10783 /* same value, noting to do */
10784 if (timer == pmu->hrtimer_interval_ms)
10787 mutex_lock(&mux_interval_mutex);
10788 pmu->hrtimer_interval_ms = timer;
10790 /* update all cpuctx for this PMU */
10792 for_each_online_cpu(cpu) {
10793 struct perf_cpu_context *cpuctx;
10794 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10795 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
10797 cpu_function_call(cpu,
10798 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
10800 cpus_read_unlock();
10801 mutex_unlock(&mux_interval_mutex);
10805 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
10807 static struct attribute *pmu_dev_attrs[] = {
10808 &dev_attr_type.attr,
10809 &dev_attr_perf_event_mux_interval_ms.attr,
10812 ATTRIBUTE_GROUPS(pmu_dev);
10814 static int pmu_bus_running;
10815 static struct bus_type pmu_bus = {
10816 .name = "event_source",
10817 .dev_groups = pmu_dev_groups,
10820 static void pmu_dev_release(struct device *dev)
10825 static int pmu_dev_alloc(struct pmu *pmu)
10829 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
10833 pmu->dev->groups = pmu->attr_groups;
10834 device_initialize(pmu->dev);
10835 ret = dev_set_name(pmu->dev, "%s", pmu->name);
10839 dev_set_drvdata(pmu->dev, pmu);
10840 pmu->dev->bus = &pmu_bus;
10841 pmu->dev->release = pmu_dev_release;
10842 ret = device_add(pmu->dev);
10846 /* For PMUs with address filters, throw in an extra attribute: */
10847 if (pmu->nr_addr_filters)
10848 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
10853 if (pmu->attr_update)
10854 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
10863 device_del(pmu->dev);
10866 put_device(pmu->dev);
10870 static struct lock_class_key cpuctx_mutex;
10871 static struct lock_class_key cpuctx_lock;
10873 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
10875 int cpu, ret, max = PERF_TYPE_MAX;
10877 mutex_lock(&pmus_lock);
10879 pmu->pmu_disable_count = alloc_percpu(int);
10880 if (!pmu->pmu_disable_count)
10888 if (type != PERF_TYPE_SOFTWARE) {
10892 ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL);
10896 WARN_ON(type >= 0 && ret != type);
10902 if (pmu_bus_running) {
10903 ret = pmu_dev_alloc(pmu);
10909 if (pmu->task_ctx_nr == perf_hw_context) {
10910 static int hw_context_taken = 0;
10913 * Other than systems with heterogeneous CPUs, it never makes
10914 * sense for two PMUs to share perf_hw_context. PMUs which are
10915 * uncore must use perf_invalid_context.
10917 if (WARN_ON_ONCE(hw_context_taken &&
10918 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
10919 pmu->task_ctx_nr = perf_invalid_context;
10921 hw_context_taken = 1;
10924 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
10925 if (pmu->pmu_cpu_context)
10926 goto got_cpu_context;
10929 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
10930 if (!pmu->pmu_cpu_context)
10933 for_each_possible_cpu(cpu) {
10934 struct perf_cpu_context *cpuctx;
10936 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10937 __perf_event_init_context(&cpuctx->ctx);
10938 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
10939 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
10940 cpuctx->ctx.pmu = pmu;
10941 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
10943 __perf_mux_hrtimer_init(cpuctx, cpu);
10945 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
10946 cpuctx->heap = cpuctx->heap_default;
10950 if (!pmu->start_txn) {
10951 if (pmu->pmu_enable) {
10953 * If we have pmu_enable/pmu_disable calls, install
10954 * transaction stubs that use that to try and batch
10955 * hardware accesses.
10957 pmu->start_txn = perf_pmu_start_txn;
10958 pmu->commit_txn = perf_pmu_commit_txn;
10959 pmu->cancel_txn = perf_pmu_cancel_txn;
10961 pmu->start_txn = perf_pmu_nop_txn;
10962 pmu->commit_txn = perf_pmu_nop_int;
10963 pmu->cancel_txn = perf_pmu_nop_void;
10967 if (!pmu->pmu_enable) {
10968 pmu->pmu_enable = perf_pmu_nop_void;
10969 pmu->pmu_disable = perf_pmu_nop_void;
10972 if (!pmu->check_period)
10973 pmu->check_period = perf_event_nop_int;
10975 if (!pmu->event_idx)
10976 pmu->event_idx = perf_event_idx_default;
10979 * Ensure the TYPE_SOFTWARE PMUs are at the head of the list,
10980 * since these cannot be in the IDR. This way the linear search
10981 * is fast, provided a valid software event is provided.
10983 if (type == PERF_TYPE_SOFTWARE || !name)
10984 list_add_rcu(&pmu->entry, &pmus);
10986 list_add_tail_rcu(&pmu->entry, &pmus);
10988 atomic_set(&pmu->exclusive_cnt, 0);
10991 mutex_unlock(&pmus_lock);
10996 device_del(pmu->dev);
10997 put_device(pmu->dev);
11000 if (pmu->type != PERF_TYPE_SOFTWARE)
11001 idr_remove(&pmu_idr, pmu->type);
11004 free_percpu(pmu->pmu_disable_count);
11007 EXPORT_SYMBOL_GPL(perf_pmu_register);
11009 void perf_pmu_unregister(struct pmu *pmu)
11011 mutex_lock(&pmus_lock);
11012 list_del_rcu(&pmu->entry);
11015 * We dereference the pmu list under both SRCU and regular RCU, so
11016 * synchronize against both of those.
11018 synchronize_srcu(&pmus_srcu);
11021 free_percpu(pmu->pmu_disable_count);
11022 if (pmu->type != PERF_TYPE_SOFTWARE)
11023 idr_remove(&pmu_idr, pmu->type);
11024 if (pmu_bus_running) {
11025 if (pmu->nr_addr_filters)
11026 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
11027 device_del(pmu->dev);
11028 put_device(pmu->dev);
11030 free_pmu_context(pmu);
11031 mutex_unlock(&pmus_lock);
11033 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
11035 static inline bool has_extended_regs(struct perf_event *event)
11037 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
11038 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
11041 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
11043 struct perf_event_context *ctx = NULL;
11046 if (!try_module_get(pmu->module))
11050 * A number of pmu->event_init() methods iterate the sibling_list to,
11051 * for example, validate if the group fits on the PMU. Therefore,
11052 * if this is a sibling event, acquire the ctx->mutex to protect
11053 * the sibling_list.
11055 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
11057 * This ctx->mutex can nest when we're called through
11058 * inheritance. See the perf_event_ctx_lock_nested() comment.
11060 ctx = perf_event_ctx_lock_nested(event->group_leader,
11061 SINGLE_DEPTH_NESTING);
11066 ret = pmu->event_init(event);
11069 perf_event_ctx_unlock(event->group_leader, ctx);
11072 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
11073 has_extended_regs(event))
11076 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
11077 event_has_any_exclude_flag(event))
11080 if (ret && event->destroy)
11081 event->destroy(event);
11085 module_put(pmu->module);
11090 static struct pmu *perf_init_event(struct perf_event *event)
11092 int idx, type, ret;
11095 idx = srcu_read_lock(&pmus_srcu);
11097 /* Try parent's PMU first: */
11098 if (event->parent && event->parent->pmu) {
11099 pmu = event->parent->pmu;
11100 ret = perf_try_init_event(pmu, event);
11106 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
11107 * are often aliases for PERF_TYPE_RAW.
11109 type = event->attr.type;
11110 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE)
11111 type = PERF_TYPE_RAW;
11115 pmu = idr_find(&pmu_idr, type);
11118 ret = perf_try_init_event(pmu, event);
11119 if (ret == -ENOENT && event->attr.type != type) {
11120 type = event->attr.type;
11125 pmu = ERR_PTR(ret);
11130 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
11131 ret = perf_try_init_event(pmu, event);
11135 if (ret != -ENOENT) {
11136 pmu = ERR_PTR(ret);
11140 pmu = ERR_PTR(-ENOENT);
11142 srcu_read_unlock(&pmus_srcu, idx);
11147 static void attach_sb_event(struct perf_event *event)
11149 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
11151 raw_spin_lock(&pel->lock);
11152 list_add_rcu(&event->sb_list, &pel->list);
11153 raw_spin_unlock(&pel->lock);
11157 * We keep a list of all !task (and therefore per-cpu) events
11158 * that need to receive side-band records.
11160 * This avoids having to scan all the various PMU per-cpu contexts
11161 * looking for them.
11163 static void account_pmu_sb_event(struct perf_event *event)
11165 if (is_sb_event(event))
11166 attach_sb_event(event);
11169 static void account_event_cpu(struct perf_event *event, int cpu)
11174 if (is_cgroup_event(event))
11175 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
11178 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
11179 static void account_freq_event_nohz(void)
11181 #ifdef CONFIG_NO_HZ_FULL
11182 /* Lock so we don't race with concurrent unaccount */
11183 spin_lock(&nr_freq_lock);
11184 if (atomic_inc_return(&nr_freq_events) == 1)
11185 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
11186 spin_unlock(&nr_freq_lock);
11190 static void account_freq_event(void)
11192 if (tick_nohz_full_enabled())
11193 account_freq_event_nohz();
11195 atomic_inc(&nr_freq_events);
11199 static void account_event(struct perf_event *event)
11206 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
11208 if (event->attr.mmap || event->attr.mmap_data)
11209 atomic_inc(&nr_mmap_events);
11210 if (event->attr.build_id)
11211 atomic_inc(&nr_build_id_events);
11212 if (event->attr.comm)
11213 atomic_inc(&nr_comm_events);
11214 if (event->attr.namespaces)
11215 atomic_inc(&nr_namespaces_events);
11216 if (event->attr.cgroup)
11217 atomic_inc(&nr_cgroup_events);
11218 if (event->attr.task)
11219 atomic_inc(&nr_task_events);
11220 if (event->attr.freq)
11221 account_freq_event();
11222 if (event->attr.context_switch) {
11223 atomic_inc(&nr_switch_events);
11226 if (has_branch_stack(event))
11228 if (is_cgroup_event(event))
11230 if (event->attr.ksymbol)
11231 atomic_inc(&nr_ksymbol_events);
11232 if (event->attr.bpf_event)
11233 atomic_inc(&nr_bpf_events);
11234 if (event->attr.text_poke)
11235 atomic_inc(&nr_text_poke_events);
11239 * We need the mutex here because static_branch_enable()
11240 * must complete *before* the perf_sched_count increment
11243 if (atomic_inc_not_zero(&perf_sched_count))
11246 mutex_lock(&perf_sched_mutex);
11247 if (!atomic_read(&perf_sched_count)) {
11248 static_branch_enable(&perf_sched_events);
11250 * Guarantee that all CPUs observe they key change and
11251 * call the perf scheduling hooks before proceeding to
11252 * install events that need them.
11257 * Now that we have waited for the sync_sched(), allow further
11258 * increments to by-pass the mutex.
11260 atomic_inc(&perf_sched_count);
11261 mutex_unlock(&perf_sched_mutex);
11265 account_event_cpu(event, event->cpu);
11267 account_pmu_sb_event(event);
11271 * Allocate and initialize an event structure
11273 static struct perf_event *
11274 perf_event_alloc(struct perf_event_attr *attr, int cpu,
11275 struct task_struct *task,
11276 struct perf_event *group_leader,
11277 struct perf_event *parent_event,
11278 perf_overflow_handler_t overflow_handler,
11279 void *context, int cgroup_fd)
11282 struct perf_event *event;
11283 struct hw_perf_event *hwc;
11284 long err = -EINVAL;
11286 if ((unsigned)cpu >= nr_cpu_ids) {
11287 if (!task || cpu != -1)
11288 return ERR_PTR(-EINVAL);
11291 event = kzalloc(sizeof(*event), GFP_KERNEL);
11293 return ERR_PTR(-ENOMEM);
11296 * Single events are their own group leaders, with an
11297 * empty sibling list:
11300 group_leader = event;
11302 mutex_init(&event->child_mutex);
11303 INIT_LIST_HEAD(&event->child_list);
11305 INIT_LIST_HEAD(&event->event_entry);
11306 INIT_LIST_HEAD(&event->sibling_list);
11307 INIT_LIST_HEAD(&event->active_list);
11308 init_event_group(event);
11309 INIT_LIST_HEAD(&event->rb_entry);
11310 INIT_LIST_HEAD(&event->active_entry);
11311 INIT_LIST_HEAD(&event->addr_filters.list);
11312 INIT_HLIST_NODE(&event->hlist_entry);
11315 init_waitqueue_head(&event->waitq);
11316 event->pending_disable = -1;
11317 init_irq_work(&event->pending, perf_pending_event);
11319 mutex_init(&event->mmap_mutex);
11320 raw_spin_lock_init(&event->addr_filters.lock);
11322 atomic_long_set(&event->refcount, 1);
11324 event->attr = *attr;
11325 event->group_leader = group_leader;
11329 event->parent = parent_event;
11331 event->ns = get_pid_ns(task_active_pid_ns(current));
11332 event->id = atomic64_inc_return(&perf_event_id);
11334 event->state = PERF_EVENT_STATE_INACTIVE;
11337 event->attach_state = PERF_ATTACH_TASK;
11339 * XXX pmu::event_init needs to know what task to account to
11340 * and we cannot use the ctx information because we need the
11341 * pmu before we get a ctx.
11343 event->hw.target = get_task_struct(task);
11346 event->clock = &local_clock;
11348 event->clock = parent_event->clock;
11350 if (!overflow_handler && parent_event) {
11351 overflow_handler = parent_event->overflow_handler;
11352 context = parent_event->overflow_handler_context;
11353 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
11354 if (overflow_handler == bpf_overflow_handler) {
11355 struct bpf_prog *prog = parent_event->prog;
11357 bpf_prog_inc(prog);
11358 event->prog = prog;
11359 event->orig_overflow_handler =
11360 parent_event->orig_overflow_handler;
11365 if (overflow_handler) {
11366 event->overflow_handler = overflow_handler;
11367 event->overflow_handler_context = context;
11368 } else if (is_write_backward(event)){
11369 event->overflow_handler = perf_event_output_backward;
11370 event->overflow_handler_context = NULL;
11372 event->overflow_handler = perf_event_output_forward;
11373 event->overflow_handler_context = NULL;
11376 perf_event__state_init(event);
11381 hwc->sample_period = attr->sample_period;
11382 if (attr->freq && attr->sample_freq)
11383 hwc->sample_period = 1;
11384 hwc->last_period = hwc->sample_period;
11386 local64_set(&hwc->period_left, hwc->sample_period);
11389 * We currently do not support PERF_SAMPLE_READ on inherited events.
11390 * See perf_output_read().
11392 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
11395 if (!has_branch_stack(event))
11396 event->attr.branch_sample_type = 0;
11398 pmu = perf_init_event(event);
11400 err = PTR_ERR(pmu);
11405 * Disallow uncore-cgroup events, they don't make sense as the cgroup will
11406 * be different on other CPUs in the uncore mask.
11408 if (pmu->task_ctx_nr == perf_invalid_context && cgroup_fd != -1) {
11413 if (event->attr.aux_output &&
11414 !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
11419 if (cgroup_fd != -1) {
11420 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
11425 err = exclusive_event_init(event);
11429 if (has_addr_filter(event)) {
11430 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
11431 sizeof(struct perf_addr_filter_range),
11433 if (!event->addr_filter_ranges) {
11439 * Clone the parent's vma offsets: they are valid until exec()
11440 * even if the mm is not shared with the parent.
11442 if (event->parent) {
11443 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11445 raw_spin_lock_irq(&ifh->lock);
11446 memcpy(event->addr_filter_ranges,
11447 event->parent->addr_filter_ranges,
11448 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
11449 raw_spin_unlock_irq(&ifh->lock);
11452 /* force hw sync on the address filters */
11453 event->addr_filters_gen = 1;
11456 if (!event->parent) {
11457 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
11458 err = get_callchain_buffers(attr->sample_max_stack);
11460 goto err_addr_filters;
11464 err = security_perf_event_alloc(event);
11466 goto err_callchain_buffer;
11468 /* symmetric to unaccount_event() in _free_event() */
11469 account_event(event);
11473 err_callchain_buffer:
11474 if (!event->parent) {
11475 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
11476 put_callchain_buffers();
11479 kfree(event->addr_filter_ranges);
11482 exclusive_event_destroy(event);
11485 if (is_cgroup_event(event))
11486 perf_detach_cgroup(event);
11487 if (event->destroy)
11488 event->destroy(event);
11489 module_put(pmu->module);
11492 put_pid_ns(event->ns);
11493 if (event->hw.target)
11494 put_task_struct(event->hw.target);
11497 return ERR_PTR(err);
11500 static int perf_copy_attr(struct perf_event_attr __user *uattr,
11501 struct perf_event_attr *attr)
11506 /* Zero the full structure, so that a short copy will be nice. */
11507 memset(attr, 0, sizeof(*attr));
11509 ret = get_user(size, &uattr->size);
11513 /* ABI compatibility quirk: */
11515 size = PERF_ATTR_SIZE_VER0;
11516 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
11519 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
11528 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
11531 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
11534 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
11537 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
11538 u64 mask = attr->branch_sample_type;
11540 /* only using defined bits */
11541 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
11544 /* at least one branch bit must be set */
11545 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
11548 /* propagate priv level, when not set for branch */
11549 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
11551 /* exclude_kernel checked on syscall entry */
11552 if (!attr->exclude_kernel)
11553 mask |= PERF_SAMPLE_BRANCH_KERNEL;
11555 if (!attr->exclude_user)
11556 mask |= PERF_SAMPLE_BRANCH_USER;
11558 if (!attr->exclude_hv)
11559 mask |= PERF_SAMPLE_BRANCH_HV;
11561 * adjust user setting (for HW filter setup)
11563 attr->branch_sample_type = mask;
11565 /* privileged levels capture (kernel, hv): check permissions */
11566 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
11567 ret = perf_allow_kernel(attr);
11573 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
11574 ret = perf_reg_validate(attr->sample_regs_user);
11579 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
11580 if (!arch_perf_have_user_stack_dump())
11584 * We have __u32 type for the size, but so far
11585 * we can only use __u16 as maximum due to the
11586 * __u16 sample size limit.
11588 if (attr->sample_stack_user >= USHRT_MAX)
11590 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
11594 if (!attr->sample_max_stack)
11595 attr->sample_max_stack = sysctl_perf_event_max_stack;
11597 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
11598 ret = perf_reg_validate(attr->sample_regs_intr);
11600 #ifndef CONFIG_CGROUP_PERF
11601 if (attr->sample_type & PERF_SAMPLE_CGROUP)
11604 if ((attr->sample_type & PERF_SAMPLE_WEIGHT) &&
11605 (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT))
11612 put_user(sizeof(*attr), &uattr->size);
11618 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
11620 struct perf_buffer *rb = NULL;
11626 /* don't allow circular references */
11627 if (event == output_event)
11631 * Don't allow cross-cpu buffers
11633 if (output_event->cpu != event->cpu)
11637 * If its not a per-cpu rb, it must be the same task.
11639 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
11643 * Mixing clocks in the same buffer is trouble you don't need.
11645 if (output_event->clock != event->clock)
11649 * Either writing ring buffer from beginning or from end.
11650 * Mixing is not allowed.
11652 if (is_write_backward(output_event) != is_write_backward(event))
11656 * If both events generate aux data, they must be on the same PMU
11658 if (has_aux(event) && has_aux(output_event) &&
11659 event->pmu != output_event->pmu)
11663 mutex_lock(&event->mmap_mutex);
11664 /* Can't redirect output if we've got an active mmap() */
11665 if (atomic_read(&event->mmap_count))
11668 if (output_event) {
11669 /* get the rb we want to redirect to */
11670 rb = ring_buffer_get(output_event);
11675 ring_buffer_attach(event, rb);
11679 mutex_unlock(&event->mmap_mutex);
11685 static void mutex_lock_double(struct mutex *a, struct mutex *b)
11691 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
11694 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
11696 bool nmi_safe = false;
11699 case CLOCK_MONOTONIC:
11700 event->clock = &ktime_get_mono_fast_ns;
11704 case CLOCK_MONOTONIC_RAW:
11705 event->clock = &ktime_get_raw_fast_ns;
11709 case CLOCK_REALTIME:
11710 event->clock = &ktime_get_real_ns;
11713 case CLOCK_BOOTTIME:
11714 event->clock = &ktime_get_boottime_ns;
11718 event->clock = &ktime_get_clocktai_ns;
11725 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
11732 * Variation on perf_event_ctx_lock_nested(), except we take two context
11735 static struct perf_event_context *
11736 __perf_event_ctx_lock_double(struct perf_event *group_leader,
11737 struct perf_event_context *ctx)
11739 struct perf_event_context *gctx;
11743 gctx = READ_ONCE(group_leader->ctx);
11744 if (!refcount_inc_not_zero(&gctx->refcount)) {
11750 mutex_lock_double(&gctx->mutex, &ctx->mutex);
11752 if (group_leader->ctx != gctx) {
11753 mutex_unlock(&ctx->mutex);
11754 mutex_unlock(&gctx->mutex);
11763 * sys_perf_event_open - open a performance event, associate it to a task/cpu
11765 * @attr_uptr: event_id type attributes for monitoring/sampling
11768 * @group_fd: group leader event fd
11770 SYSCALL_DEFINE5(perf_event_open,
11771 struct perf_event_attr __user *, attr_uptr,
11772 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
11774 struct perf_event *group_leader = NULL, *output_event = NULL;
11775 struct perf_event *event, *sibling;
11776 struct perf_event_attr attr;
11777 struct perf_event_context *ctx, *gctx;
11778 struct file *event_file = NULL;
11779 struct fd group = {NULL, 0};
11780 struct task_struct *task = NULL;
11783 int move_group = 0;
11785 int f_flags = O_RDWR;
11786 int cgroup_fd = -1;
11788 /* for future expandability... */
11789 if (flags & ~PERF_FLAG_ALL)
11792 /* Do we allow access to perf_event_open(2) ? */
11793 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
11797 err = perf_copy_attr(attr_uptr, &attr);
11801 if (!attr.exclude_kernel) {
11802 err = perf_allow_kernel(&attr);
11807 if (attr.namespaces) {
11808 if (!perfmon_capable())
11813 if (attr.sample_freq > sysctl_perf_event_sample_rate)
11816 if (attr.sample_period & (1ULL << 63))
11820 /* Only privileged users can get physical addresses */
11821 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
11822 err = perf_allow_kernel(&attr);
11827 err = security_locked_down(LOCKDOWN_PERF);
11828 if (err && (attr.sample_type & PERF_SAMPLE_REGS_INTR))
11829 /* REGS_INTR can leak data, lockdown must prevent this */
11835 * In cgroup mode, the pid argument is used to pass the fd
11836 * opened to the cgroup directory in cgroupfs. The cpu argument
11837 * designates the cpu on which to monitor threads from that
11840 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
11843 if (flags & PERF_FLAG_FD_CLOEXEC)
11844 f_flags |= O_CLOEXEC;
11846 event_fd = get_unused_fd_flags(f_flags);
11850 if (group_fd != -1) {
11851 err = perf_fget_light(group_fd, &group);
11854 group_leader = group.file->private_data;
11855 if (flags & PERF_FLAG_FD_OUTPUT)
11856 output_event = group_leader;
11857 if (flags & PERF_FLAG_FD_NO_GROUP)
11858 group_leader = NULL;
11861 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
11862 task = find_lively_task_by_vpid(pid);
11863 if (IS_ERR(task)) {
11864 err = PTR_ERR(task);
11869 if (task && group_leader &&
11870 group_leader->attr.inherit != attr.inherit) {
11875 if (flags & PERF_FLAG_PID_CGROUP)
11878 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
11879 NULL, NULL, cgroup_fd);
11880 if (IS_ERR(event)) {
11881 err = PTR_ERR(event);
11885 if (is_sampling_event(event)) {
11886 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
11893 * Special case software events and allow them to be part of
11894 * any hardware group.
11898 if (attr.use_clockid) {
11899 err = perf_event_set_clock(event, attr.clockid);
11904 if (pmu->task_ctx_nr == perf_sw_context)
11905 event->event_caps |= PERF_EV_CAP_SOFTWARE;
11907 if (group_leader) {
11908 if (is_software_event(event) &&
11909 !in_software_context(group_leader)) {
11911 * If the event is a sw event, but the group_leader
11912 * is on hw context.
11914 * Allow the addition of software events to hw
11915 * groups, this is safe because software events
11916 * never fail to schedule.
11918 pmu = group_leader->ctx->pmu;
11919 } else if (!is_software_event(event) &&
11920 is_software_event(group_leader) &&
11921 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11923 * In case the group is a pure software group, and we
11924 * try to add a hardware event, move the whole group to
11925 * the hardware context.
11932 * Get the target context (task or percpu):
11934 ctx = find_get_context(pmu, task, event);
11936 err = PTR_ERR(ctx);
11941 * Look up the group leader (we will attach this event to it):
11943 if (group_leader) {
11947 * Do not allow a recursive hierarchy (this new sibling
11948 * becoming part of another group-sibling):
11950 if (group_leader->group_leader != group_leader)
11953 /* All events in a group should have the same clock */
11954 if (group_leader->clock != event->clock)
11958 * Make sure we're both events for the same CPU;
11959 * grouping events for different CPUs is broken; since
11960 * you can never concurrently schedule them anyhow.
11962 if (group_leader->cpu != event->cpu)
11966 * Make sure we're both on the same task, or both
11969 if (group_leader->ctx->task != ctx->task)
11973 * Do not allow to attach to a group in a different task
11974 * or CPU context. If we're moving SW events, we'll fix
11975 * this up later, so allow that.
11977 if (!move_group && group_leader->ctx != ctx)
11981 * Only a group leader can be exclusive or pinned
11983 if (attr.exclusive || attr.pinned)
11987 if (output_event) {
11988 err = perf_event_set_output(event, output_event);
11993 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
11995 if (IS_ERR(event_file)) {
11996 err = PTR_ERR(event_file);
12002 err = down_read_interruptible(&task->signal->exec_update_lock);
12007 * Preserve ptrace permission check for backwards compatibility.
12009 * We must hold exec_update_lock across this and any potential
12010 * perf_install_in_context() call for this new event to
12011 * serialize against exec() altering our credentials (and the
12012 * perf_event_exit_task() that could imply).
12015 if (!perfmon_capable() && !ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
12020 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
12022 if (gctx->task == TASK_TOMBSTONE) {
12028 * Check if we raced against another sys_perf_event_open() call
12029 * moving the software group underneath us.
12031 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
12033 * If someone moved the group out from under us, check
12034 * if this new event wound up on the same ctx, if so
12035 * its the regular !move_group case, otherwise fail.
12041 perf_event_ctx_unlock(group_leader, gctx);
12047 * Failure to create exclusive events returns -EBUSY.
12050 if (!exclusive_event_installable(group_leader, ctx))
12053 for_each_sibling_event(sibling, group_leader) {
12054 if (!exclusive_event_installable(sibling, ctx))
12058 mutex_lock(&ctx->mutex);
12061 if (ctx->task == TASK_TOMBSTONE) {
12066 if (!perf_event_validate_size(event)) {
12073 * Check if the @cpu we're creating an event for is online.
12075 * We use the perf_cpu_context::ctx::mutex to serialize against
12076 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12078 struct perf_cpu_context *cpuctx =
12079 container_of(ctx, struct perf_cpu_context, ctx);
12081 if (!cpuctx->online) {
12087 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
12093 * Must be under the same ctx::mutex as perf_install_in_context(),
12094 * because we need to serialize with concurrent event creation.
12096 if (!exclusive_event_installable(event, ctx)) {
12101 WARN_ON_ONCE(ctx->parent_ctx);
12104 * This is the point on no return; we cannot fail hereafter. This is
12105 * where we start modifying current state.
12110 * See perf_event_ctx_lock() for comments on the details
12111 * of swizzling perf_event::ctx.
12113 perf_remove_from_context(group_leader, 0);
12116 for_each_sibling_event(sibling, group_leader) {
12117 perf_remove_from_context(sibling, 0);
12122 * Wait for everybody to stop referencing the events through
12123 * the old lists, before installing it on new lists.
12128 * Install the group siblings before the group leader.
12130 * Because a group leader will try and install the entire group
12131 * (through the sibling list, which is still in-tact), we can
12132 * end up with siblings installed in the wrong context.
12134 * By installing siblings first we NO-OP because they're not
12135 * reachable through the group lists.
12137 for_each_sibling_event(sibling, group_leader) {
12138 perf_event__state_init(sibling);
12139 perf_install_in_context(ctx, sibling, sibling->cpu);
12144 * Removing from the context ends up with disabled
12145 * event. What we want here is event in the initial
12146 * startup state, ready to be add into new context.
12148 perf_event__state_init(group_leader);
12149 perf_install_in_context(ctx, group_leader, group_leader->cpu);
12154 * Precalculate sample_data sizes; do while holding ctx::mutex such
12155 * that we're serialized against further additions and before
12156 * perf_install_in_context() which is the point the event is active and
12157 * can use these values.
12159 perf_event__header_size(event);
12160 perf_event__id_header_size(event);
12162 event->owner = current;
12164 perf_install_in_context(ctx, event, event->cpu);
12165 perf_unpin_context(ctx);
12168 perf_event_ctx_unlock(group_leader, gctx);
12169 mutex_unlock(&ctx->mutex);
12172 up_read(&task->signal->exec_update_lock);
12173 put_task_struct(task);
12176 mutex_lock(¤t->perf_event_mutex);
12177 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
12178 mutex_unlock(¤t->perf_event_mutex);
12181 * Drop the reference on the group_event after placing the
12182 * new event on the sibling_list. This ensures destruction
12183 * of the group leader will find the pointer to itself in
12184 * perf_group_detach().
12187 fd_install(event_fd, event_file);
12192 perf_event_ctx_unlock(group_leader, gctx);
12193 mutex_unlock(&ctx->mutex);
12196 up_read(&task->signal->exec_update_lock);
12200 perf_unpin_context(ctx);
12204 * If event_file is set, the fput() above will have called ->release()
12205 * and that will take care of freeing the event.
12211 put_task_struct(task);
12215 put_unused_fd(event_fd);
12220 * perf_event_create_kernel_counter
12222 * @attr: attributes of the counter to create
12223 * @cpu: cpu in which the counter is bound
12224 * @task: task to profile (NULL for percpu)
12226 struct perf_event *
12227 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
12228 struct task_struct *task,
12229 perf_overflow_handler_t overflow_handler,
12232 struct perf_event_context *ctx;
12233 struct perf_event *event;
12237 * Grouping is not supported for kernel events, neither is 'AUX',
12238 * make sure the caller's intentions are adjusted.
12240 if (attr->aux_output)
12241 return ERR_PTR(-EINVAL);
12243 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
12244 overflow_handler, context, -1);
12245 if (IS_ERR(event)) {
12246 err = PTR_ERR(event);
12250 /* Mark owner so we could distinguish it from user events. */
12251 event->owner = TASK_TOMBSTONE;
12254 * Get the target context (task or percpu):
12256 ctx = find_get_context(event->pmu, task, event);
12258 err = PTR_ERR(ctx);
12262 WARN_ON_ONCE(ctx->parent_ctx);
12263 mutex_lock(&ctx->mutex);
12264 if (ctx->task == TASK_TOMBSTONE) {
12271 * Check if the @cpu we're creating an event for is online.
12273 * We use the perf_cpu_context::ctx::mutex to serialize against
12274 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12276 struct perf_cpu_context *cpuctx =
12277 container_of(ctx, struct perf_cpu_context, ctx);
12278 if (!cpuctx->online) {
12284 if (!exclusive_event_installable(event, ctx)) {
12289 perf_install_in_context(ctx, event, event->cpu);
12290 perf_unpin_context(ctx);
12291 mutex_unlock(&ctx->mutex);
12296 mutex_unlock(&ctx->mutex);
12297 perf_unpin_context(ctx);
12302 return ERR_PTR(err);
12304 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
12306 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
12308 struct perf_event_context *src_ctx;
12309 struct perf_event_context *dst_ctx;
12310 struct perf_event *event, *tmp;
12313 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
12314 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
12317 * See perf_event_ctx_lock() for comments on the details
12318 * of swizzling perf_event::ctx.
12320 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
12321 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
12323 perf_remove_from_context(event, 0);
12324 unaccount_event_cpu(event, src_cpu);
12326 list_add(&event->migrate_entry, &events);
12330 * Wait for the events to quiesce before re-instating them.
12335 * Re-instate events in 2 passes.
12337 * Skip over group leaders and only install siblings on this first
12338 * pass, siblings will not get enabled without a leader, however a
12339 * leader will enable its siblings, even if those are still on the old
12342 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12343 if (event->group_leader == event)
12346 list_del(&event->migrate_entry);
12347 if (event->state >= PERF_EVENT_STATE_OFF)
12348 event->state = PERF_EVENT_STATE_INACTIVE;
12349 account_event_cpu(event, dst_cpu);
12350 perf_install_in_context(dst_ctx, event, dst_cpu);
12355 * Once all the siblings are setup properly, install the group leaders
12358 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12359 list_del(&event->migrate_entry);
12360 if (event->state >= PERF_EVENT_STATE_OFF)
12361 event->state = PERF_EVENT_STATE_INACTIVE;
12362 account_event_cpu(event, dst_cpu);
12363 perf_install_in_context(dst_ctx, event, dst_cpu);
12366 mutex_unlock(&dst_ctx->mutex);
12367 mutex_unlock(&src_ctx->mutex);
12369 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
12371 static void sync_child_event(struct perf_event *child_event,
12372 struct task_struct *child)
12374 struct perf_event *parent_event = child_event->parent;
12377 if (child_event->attr.inherit_stat)
12378 perf_event_read_event(child_event, child);
12380 child_val = perf_event_count(child_event);
12383 * Add back the child's count to the parent's count:
12385 atomic64_add(child_val, &parent_event->child_count);
12386 atomic64_add(child_event->total_time_enabled,
12387 &parent_event->child_total_time_enabled);
12388 atomic64_add(child_event->total_time_running,
12389 &parent_event->child_total_time_running);
12393 perf_event_exit_event(struct perf_event *child_event,
12394 struct perf_event_context *child_ctx,
12395 struct task_struct *child)
12397 struct perf_event *parent_event = child_event->parent;
12400 * Do not destroy the 'original' grouping; because of the context
12401 * switch optimization the original events could've ended up in a
12402 * random child task.
12404 * If we were to destroy the original group, all group related
12405 * operations would cease to function properly after this random
12408 * Do destroy all inherited groups, we don't care about those
12409 * and being thorough is better.
12411 raw_spin_lock_irq(&child_ctx->lock);
12412 WARN_ON_ONCE(child_ctx->is_active);
12415 perf_group_detach(child_event);
12416 list_del_event(child_event, child_ctx);
12417 perf_event_set_state(child_event, PERF_EVENT_STATE_EXIT); /* is_event_hup() */
12418 raw_spin_unlock_irq(&child_ctx->lock);
12421 * Parent events are governed by their filedesc, retain them.
12423 if (!parent_event) {
12424 perf_event_wakeup(child_event);
12428 * Child events can be cleaned up.
12431 sync_child_event(child_event, child);
12434 * Remove this event from the parent's list
12436 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
12437 mutex_lock(&parent_event->child_mutex);
12438 list_del_init(&child_event->child_list);
12439 mutex_unlock(&parent_event->child_mutex);
12442 * Kick perf_poll() for is_event_hup().
12444 perf_event_wakeup(parent_event);
12445 free_event(child_event);
12446 put_event(parent_event);
12449 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
12451 struct perf_event_context *child_ctx, *clone_ctx = NULL;
12452 struct perf_event *child_event, *next;
12454 WARN_ON_ONCE(child != current);
12456 child_ctx = perf_pin_task_context(child, ctxn);
12461 * In order to reduce the amount of tricky in ctx tear-down, we hold
12462 * ctx::mutex over the entire thing. This serializes against almost
12463 * everything that wants to access the ctx.
12465 * The exception is sys_perf_event_open() /
12466 * perf_event_create_kernel_count() which does find_get_context()
12467 * without ctx::mutex (it cannot because of the move_group double mutex
12468 * lock thing). See the comments in perf_install_in_context().
12470 mutex_lock(&child_ctx->mutex);
12473 * In a single ctx::lock section, de-schedule the events and detach the
12474 * context from the task such that we cannot ever get it scheduled back
12477 raw_spin_lock_irq(&child_ctx->lock);
12478 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL);
12481 * Now that the context is inactive, destroy the task <-> ctx relation
12482 * and mark the context dead.
12484 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
12485 put_ctx(child_ctx); /* cannot be last */
12486 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
12487 put_task_struct(current); /* cannot be last */
12489 clone_ctx = unclone_ctx(child_ctx);
12490 raw_spin_unlock_irq(&child_ctx->lock);
12493 put_ctx(clone_ctx);
12496 * Report the task dead after unscheduling the events so that we
12497 * won't get any samples after PERF_RECORD_EXIT. We can however still
12498 * get a few PERF_RECORD_READ events.
12500 perf_event_task(child, child_ctx, 0);
12502 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
12503 perf_event_exit_event(child_event, child_ctx, child);
12505 mutex_unlock(&child_ctx->mutex);
12507 put_ctx(child_ctx);
12511 * When a child task exits, feed back event values to parent events.
12513 * Can be called with exec_update_lock held when called from
12514 * setup_new_exec().
12516 void perf_event_exit_task(struct task_struct *child)
12518 struct perf_event *event, *tmp;
12521 mutex_lock(&child->perf_event_mutex);
12522 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
12524 list_del_init(&event->owner_entry);
12527 * Ensure the list deletion is visible before we clear
12528 * the owner, closes a race against perf_release() where
12529 * we need to serialize on the owner->perf_event_mutex.
12531 smp_store_release(&event->owner, NULL);
12533 mutex_unlock(&child->perf_event_mutex);
12535 for_each_task_context_nr(ctxn)
12536 perf_event_exit_task_context(child, ctxn);
12539 * The perf_event_exit_task_context calls perf_event_task
12540 * with child's task_ctx, which generates EXIT events for
12541 * child contexts and sets child->perf_event_ctxp[] to NULL.
12542 * At this point we need to send EXIT events to cpu contexts.
12544 perf_event_task(child, NULL, 0);
12547 static void perf_free_event(struct perf_event *event,
12548 struct perf_event_context *ctx)
12550 struct perf_event *parent = event->parent;
12552 if (WARN_ON_ONCE(!parent))
12555 mutex_lock(&parent->child_mutex);
12556 list_del_init(&event->child_list);
12557 mutex_unlock(&parent->child_mutex);
12561 raw_spin_lock_irq(&ctx->lock);
12562 perf_group_detach(event);
12563 list_del_event(event, ctx);
12564 raw_spin_unlock_irq(&ctx->lock);
12569 * Free a context as created by inheritance by perf_event_init_task() below,
12570 * used by fork() in case of fail.
12572 * Even though the task has never lived, the context and events have been
12573 * exposed through the child_list, so we must take care tearing it all down.
12575 void perf_event_free_task(struct task_struct *task)
12577 struct perf_event_context *ctx;
12578 struct perf_event *event, *tmp;
12581 for_each_task_context_nr(ctxn) {
12582 ctx = task->perf_event_ctxp[ctxn];
12586 mutex_lock(&ctx->mutex);
12587 raw_spin_lock_irq(&ctx->lock);
12589 * Destroy the task <-> ctx relation and mark the context dead.
12591 * This is important because even though the task hasn't been
12592 * exposed yet the context has been (through child_list).
12594 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
12595 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
12596 put_task_struct(task); /* cannot be last */
12597 raw_spin_unlock_irq(&ctx->lock);
12599 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
12600 perf_free_event(event, ctx);
12602 mutex_unlock(&ctx->mutex);
12605 * perf_event_release_kernel() could've stolen some of our
12606 * child events and still have them on its free_list. In that
12607 * case we must wait for these events to have been freed (in
12608 * particular all their references to this task must've been
12611 * Without this copy_process() will unconditionally free this
12612 * task (irrespective of its reference count) and
12613 * _free_event()'s put_task_struct(event->hw.target) will be a
12616 * Wait for all events to drop their context reference.
12618 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
12619 put_ctx(ctx); /* must be last */
12623 void perf_event_delayed_put(struct task_struct *task)
12627 for_each_task_context_nr(ctxn)
12628 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
12631 struct file *perf_event_get(unsigned int fd)
12633 struct file *file = fget(fd);
12635 return ERR_PTR(-EBADF);
12637 if (file->f_op != &perf_fops) {
12639 return ERR_PTR(-EBADF);
12645 const struct perf_event *perf_get_event(struct file *file)
12647 if (file->f_op != &perf_fops)
12648 return ERR_PTR(-EINVAL);
12650 return file->private_data;
12653 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
12656 return ERR_PTR(-EINVAL);
12658 return &event->attr;
12662 * Inherit an event from parent task to child task.
12665 * - valid pointer on success
12666 * - NULL for orphaned events
12667 * - IS_ERR() on error
12669 static struct perf_event *
12670 inherit_event(struct perf_event *parent_event,
12671 struct task_struct *parent,
12672 struct perf_event_context *parent_ctx,
12673 struct task_struct *child,
12674 struct perf_event *group_leader,
12675 struct perf_event_context *child_ctx)
12677 enum perf_event_state parent_state = parent_event->state;
12678 struct perf_event *child_event;
12679 unsigned long flags;
12682 * Instead of creating recursive hierarchies of events,
12683 * we link inherited events back to the original parent,
12684 * which has a filp for sure, which we use as the reference
12687 if (parent_event->parent)
12688 parent_event = parent_event->parent;
12690 child_event = perf_event_alloc(&parent_event->attr,
12693 group_leader, parent_event,
12695 if (IS_ERR(child_event))
12696 return child_event;
12699 if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) &&
12700 !child_ctx->task_ctx_data) {
12701 struct pmu *pmu = child_event->pmu;
12703 child_ctx->task_ctx_data = alloc_task_ctx_data(pmu);
12704 if (!child_ctx->task_ctx_data) {
12705 free_event(child_event);
12706 return ERR_PTR(-ENOMEM);
12711 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
12712 * must be under the same lock in order to serialize against
12713 * perf_event_release_kernel(), such that either we must observe
12714 * is_orphaned_event() or they will observe us on the child_list.
12716 mutex_lock(&parent_event->child_mutex);
12717 if (is_orphaned_event(parent_event) ||
12718 !atomic_long_inc_not_zero(&parent_event->refcount)) {
12719 mutex_unlock(&parent_event->child_mutex);
12720 /* task_ctx_data is freed with child_ctx */
12721 free_event(child_event);
12725 get_ctx(child_ctx);
12728 * Make the child state follow the state of the parent event,
12729 * not its attr.disabled bit. We hold the parent's mutex,
12730 * so we won't race with perf_event_{en, dis}able_family.
12732 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
12733 child_event->state = PERF_EVENT_STATE_INACTIVE;
12735 child_event->state = PERF_EVENT_STATE_OFF;
12737 if (parent_event->attr.freq) {
12738 u64 sample_period = parent_event->hw.sample_period;
12739 struct hw_perf_event *hwc = &child_event->hw;
12741 hwc->sample_period = sample_period;
12742 hwc->last_period = sample_period;
12744 local64_set(&hwc->period_left, sample_period);
12747 child_event->ctx = child_ctx;
12748 child_event->overflow_handler = parent_event->overflow_handler;
12749 child_event->overflow_handler_context
12750 = parent_event->overflow_handler_context;
12753 * Precalculate sample_data sizes
12755 perf_event__header_size(child_event);
12756 perf_event__id_header_size(child_event);
12759 * Link it up in the child's context:
12761 raw_spin_lock_irqsave(&child_ctx->lock, flags);
12762 add_event_to_ctx(child_event, child_ctx);
12763 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
12766 * Link this into the parent event's child list
12768 list_add_tail(&child_event->child_list, &parent_event->child_list);
12769 mutex_unlock(&parent_event->child_mutex);
12771 return child_event;
12775 * Inherits an event group.
12777 * This will quietly suppress orphaned events; !inherit_event() is not an error.
12778 * This matches with perf_event_release_kernel() removing all child events.
12784 static int inherit_group(struct perf_event *parent_event,
12785 struct task_struct *parent,
12786 struct perf_event_context *parent_ctx,
12787 struct task_struct *child,
12788 struct perf_event_context *child_ctx)
12790 struct perf_event *leader;
12791 struct perf_event *sub;
12792 struct perf_event *child_ctr;
12794 leader = inherit_event(parent_event, parent, parent_ctx,
12795 child, NULL, child_ctx);
12796 if (IS_ERR(leader))
12797 return PTR_ERR(leader);
12799 * @leader can be NULL here because of is_orphaned_event(). In this
12800 * case inherit_event() will create individual events, similar to what
12801 * perf_group_detach() would do anyway.
12803 for_each_sibling_event(sub, parent_event) {
12804 child_ctr = inherit_event(sub, parent, parent_ctx,
12805 child, leader, child_ctx);
12806 if (IS_ERR(child_ctr))
12807 return PTR_ERR(child_ctr);
12809 if (sub->aux_event == parent_event && child_ctr &&
12810 !perf_get_aux_event(child_ctr, leader))
12817 * Creates the child task context and tries to inherit the event-group.
12819 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
12820 * inherited_all set when we 'fail' to inherit an orphaned event; this is
12821 * consistent with perf_event_release_kernel() removing all child events.
12828 inherit_task_group(struct perf_event *event, struct task_struct *parent,
12829 struct perf_event_context *parent_ctx,
12830 struct task_struct *child, int ctxn,
12831 int *inherited_all)
12834 struct perf_event_context *child_ctx;
12836 if (!event->attr.inherit) {
12837 *inherited_all = 0;
12841 child_ctx = child->perf_event_ctxp[ctxn];
12844 * This is executed from the parent task context, so
12845 * inherit events that have been marked for cloning.
12846 * First allocate and initialize a context for the
12849 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
12853 child->perf_event_ctxp[ctxn] = child_ctx;
12856 ret = inherit_group(event, parent, parent_ctx,
12860 *inherited_all = 0;
12866 * Initialize the perf_event context in task_struct
12868 static int perf_event_init_context(struct task_struct *child, int ctxn)
12870 struct perf_event_context *child_ctx, *parent_ctx;
12871 struct perf_event_context *cloned_ctx;
12872 struct perf_event *event;
12873 struct task_struct *parent = current;
12874 int inherited_all = 1;
12875 unsigned long flags;
12878 if (likely(!parent->perf_event_ctxp[ctxn]))
12882 * If the parent's context is a clone, pin it so it won't get
12883 * swapped under us.
12885 parent_ctx = perf_pin_task_context(parent, ctxn);
12890 * No need to check if parent_ctx != NULL here; since we saw
12891 * it non-NULL earlier, the only reason for it to become NULL
12892 * is if we exit, and since we're currently in the middle of
12893 * a fork we can't be exiting at the same time.
12897 * Lock the parent list. No need to lock the child - not PID
12898 * hashed yet and not running, so nobody can access it.
12900 mutex_lock(&parent_ctx->mutex);
12903 * We dont have to disable NMIs - we are only looking at
12904 * the list, not manipulating it:
12906 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
12907 ret = inherit_task_group(event, parent, parent_ctx,
12908 child, ctxn, &inherited_all);
12914 * We can't hold ctx->lock when iterating the ->flexible_group list due
12915 * to allocations, but we need to prevent rotation because
12916 * rotate_ctx() will change the list from interrupt context.
12918 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12919 parent_ctx->rotate_disable = 1;
12920 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12922 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
12923 ret = inherit_task_group(event, parent, parent_ctx,
12924 child, ctxn, &inherited_all);
12929 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12930 parent_ctx->rotate_disable = 0;
12932 child_ctx = child->perf_event_ctxp[ctxn];
12934 if (child_ctx && inherited_all) {
12936 * Mark the child context as a clone of the parent
12937 * context, or of whatever the parent is a clone of.
12939 * Note that if the parent is a clone, the holding of
12940 * parent_ctx->lock avoids it from being uncloned.
12942 cloned_ctx = parent_ctx->parent_ctx;
12944 child_ctx->parent_ctx = cloned_ctx;
12945 child_ctx->parent_gen = parent_ctx->parent_gen;
12947 child_ctx->parent_ctx = parent_ctx;
12948 child_ctx->parent_gen = parent_ctx->generation;
12950 get_ctx(child_ctx->parent_ctx);
12953 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12955 mutex_unlock(&parent_ctx->mutex);
12957 perf_unpin_context(parent_ctx);
12958 put_ctx(parent_ctx);
12964 * Initialize the perf_event context in task_struct
12966 int perf_event_init_task(struct task_struct *child)
12970 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
12971 mutex_init(&child->perf_event_mutex);
12972 INIT_LIST_HEAD(&child->perf_event_list);
12974 for_each_task_context_nr(ctxn) {
12975 ret = perf_event_init_context(child, ctxn);
12977 perf_event_free_task(child);
12985 static void __init perf_event_init_all_cpus(void)
12987 struct swevent_htable *swhash;
12990 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
12992 for_each_possible_cpu(cpu) {
12993 swhash = &per_cpu(swevent_htable, cpu);
12994 mutex_init(&swhash->hlist_mutex);
12995 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
12997 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
12998 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
13000 #ifdef CONFIG_CGROUP_PERF
13001 INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu));
13003 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
13007 static void perf_swevent_init_cpu(unsigned int cpu)
13009 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
13011 mutex_lock(&swhash->hlist_mutex);
13012 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
13013 struct swevent_hlist *hlist;
13015 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
13017 rcu_assign_pointer(swhash->swevent_hlist, hlist);
13019 mutex_unlock(&swhash->hlist_mutex);
13022 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
13023 static void __perf_event_exit_context(void *__info)
13025 struct perf_event_context *ctx = __info;
13026 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
13027 struct perf_event *event;
13029 raw_spin_lock(&ctx->lock);
13030 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
13031 list_for_each_entry(event, &ctx->event_list, event_entry)
13032 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
13033 raw_spin_unlock(&ctx->lock);
13036 static void perf_event_exit_cpu_context(int cpu)
13038 struct perf_cpu_context *cpuctx;
13039 struct perf_event_context *ctx;
13042 mutex_lock(&pmus_lock);
13043 list_for_each_entry(pmu, &pmus, entry) {
13044 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
13045 ctx = &cpuctx->ctx;
13047 mutex_lock(&ctx->mutex);
13048 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
13049 cpuctx->online = 0;
13050 mutex_unlock(&ctx->mutex);
13052 cpumask_clear_cpu(cpu, perf_online_mask);
13053 mutex_unlock(&pmus_lock);
13057 static void perf_event_exit_cpu_context(int cpu) { }
13061 int perf_event_init_cpu(unsigned int cpu)
13063 struct perf_cpu_context *cpuctx;
13064 struct perf_event_context *ctx;
13067 perf_swevent_init_cpu(cpu);
13069 mutex_lock(&pmus_lock);
13070 cpumask_set_cpu(cpu, perf_online_mask);
13071 list_for_each_entry(pmu, &pmus, entry) {
13072 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
13073 ctx = &cpuctx->ctx;
13075 mutex_lock(&ctx->mutex);
13076 cpuctx->online = 1;
13077 mutex_unlock(&ctx->mutex);
13079 mutex_unlock(&pmus_lock);
13084 int perf_event_exit_cpu(unsigned int cpu)
13086 perf_event_exit_cpu_context(cpu);
13091 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
13095 for_each_online_cpu(cpu)
13096 perf_event_exit_cpu(cpu);
13102 * Run the perf reboot notifier at the very last possible moment so that
13103 * the generic watchdog code runs as long as possible.
13105 static struct notifier_block perf_reboot_notifier = {
13106 .notifier_call = perf_reboot,
13107 .priority = INT_MIN,
13110 void __init perf_event_init(void)
13114 idr_init(&pmu_idr);
13116 perf_event_init_all_cpus();
13117 init_srcu_struct(&pmus_srcu);
13118 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
13119 perf_pmu_register(&perf_cpu_clock, NULL, -1);
13120 perf_pmu_register(&perf_task_clock, NULL, -1);
13121 perf_tp_register();
13122 perf_event_init_cpu(smp_processor_id());
13123 register_reboot_notifier(&perf_reboot_notifier);
13125 ret = init_hw_breakpoint();
13126 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
13129 * Build time assertion that we keep the data_head at the intended
13130 * location. IOW, validation we got the __reserved[] size right.
13132 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
13136 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
13139 struct perf_pmu_events_attr *pmu_attr =
13140 container_of(attr, struct perf_pmu_events_attr, attr);
13142 if (pmu_attr->event_str)
13143 return sprintf(page, "%s\n", pmu_attr->event_str);
13147 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
13149 static int __init perf_event_sysfs_init(void)
13154 mutex_lock(&pmus_lock);
13156 ret = bus_register(&pmu_bus);
13160 list_for_each_entry(pmu, &pmus, entry) {
13161 if (!pmu->name || pmu->type < 0)
13164 ret = pmu_dev_alloc(pmu);
13165 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
13167 pmu_bus_running = 1;
13171 mutex_unlock(&pmus_lock);
13175 device_initcall(perf_event_sysfs_init);
13177 #ifdef CONFIG_CGROUP_PERF
13178 static struct cgroup_subsys_state *
13179 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
13181 struct perf_cgroup *jc;
13183 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
13185 return ERR_PTR(-ENOMEM);
13187 jc->info = alloc_percpu(struct perf_cgroup_info);
13190 return ERR_PTR(-ENOMEM);
13196 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
13198 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
13200 free_percpu(jc->info);
13204 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
13206 perf_event_cgroup(css->cgroup);
13210 static int __perf_cgroup_move(void *info)
13212 struct task_struct *task = info;
13214 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
13219 static void perf_cgroup_attach(struct cgroup_taskset *tset)
13221 struct task_struct *task;
13222 struct cgroup_subsys_state *css;
13224 cgroup_taskset_for_each(task, css, tset)
13225 task_function_call(task, __perf_cgroup_move, task);
13228 struct cgroup_subsys perf_event_cgrp_subsys = {
13229 .css_alloc = perf_cgroup_css_alloc,
13230 .css_free = perf_cgroup_css_free,
13231 .css_online = perf_cgroup_css_online,
13232 .attach = perf_cgroup_attach,
13234 * Implicitly enable on dfl hierarchy so that perf events can
13235 * always be filtered by cgroup2 path as long as perf_event
13236 * controller is not mounted on a legacy hierarchy.
13238 .implicit_on_dfl = true,
13241 #endif /* CONFIG_CGROUP_PERF */