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;
408 static struct kmem_cache *perf_event_cache;
411 * perf event paranoia level:
412 * -1 - not paranoid at all
413 * 0 - disallow raw tracepoint access for unpriv
414 * 1 - disallow cpu events for unpriv
415 * 2 - disallow kernel profiling for unpriv
417 int sysctl_perf_event_paranoid __read_mostly = 2;
419 /* Minimum for 512 kiB + 1 user control page */
420 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
423 * max perf event sample rate
425 #define DEFAULT_MAX_SAMPLE_RATE 100000
426 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
427 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
429 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
431 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
432 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
434 static int perf_sample_allowed_ns __read_mostly =
435 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
437 static void update_perf_cpu_limits(void)
439 u64 tmp = perf_sample_period_ns;
441 tmp *= sysctl_perf_cpu_time_max_percent;
442 tmp = div_u64(tmp, 100);
446 WRITE_ONCE(perf_sample_allowed_ns, tmp);
449 static bool perf_rotate_context(struct perf_cpu_context *cpuctx);
451 int perf_proc_update_handler(struct ctl_table *table, int write,
452 void *buffer, size_t *lenp, loff_t *ppos)
455 int perf_cpu = sysctl_perf_cpu_time_max_percent;
457 * If throttling is disabled don't allow the write:
459 if (write && (perf_cpu == 100 || perf_cpu == 0))
462 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
466 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
467 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
468 update_perf_cpu_limits();
473 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
475 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
476 void *buffer, size_t *lenp, loff_t *ppos)
478 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
483 if (sysctl_perf_cpu_time_max_percent == 100 ||
484 sysctl_perf_cpu_time_max_percent == 0) {
486 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
487 WRITE_ONCE(perf_sample_allowed_ns, 0);
489 update_perf_cpu_limits();
496 * perf samples are done in some very critical code paths (NMIs).
497 * If they take too much CPU time, the system can lock up and not
498 * get any real work done. This will drop the sample rate when
499 * we detect that events are taking too long.
501 #define NR_ACCUMULATED_SAMPLES 128
502 static DEFINE_PER_CPU(u64, running_sample_length);
504 static u64 __report_avg;
505 static u64 __report_allowed;
507 static void perf_duration_warn(struct irq_work *w)
509 printk_ratelimited(KERN_INFO
510 "perf: interrupt took too long (%lld > %lld), lowering "
511 "kernel.perf_event_max_sample_rate to %d\n",
512 __report_avg, __report_allowed,
513 sysctl_perf_event_sample_rate);
516 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
518 void perf_sample_event_took(u64 sample_len_ns)
520 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
528 /* Decay the counter by 1 average sample. */
529 running_len = __this_cpu_read(running_sample_length);
530 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
531 running_len += sample_len_ns;
532 __this_cpu_write(running_sample_length, running_len);
535 * Note: this will be biased artifically low until we have
536 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
537 * from having to maintain a count.
539 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
540 if (avg_len <= max_len)
543 __report_avg = avg_len;
544 __report_allowed = max_len;
547 * Compute a throttle threshold 25% below the current duration.
549 avg_len += avg_len / 4;
550 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
556 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
557 WRITE_ONCE(max_samples_per_tick, max);
559 sysctl_perf_event_sample_rate = max * HZ;
560 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
562 if (!irq_work_queue(&perf_duration_work)) {
563 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
564 "kernel.perf_event_max_sample_rate to %d\n",
565 __report_avg, __report_allowed,
566 sysctl_perf_event_sample_rate);
570 static atomic64_t perf_event_id;
572 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
573 enum event_type_t event_type);
575 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
576 enum event_type_t event_type,
577 struct task_struct *task);
579 static void update_context_time(struct perf_event_context *ctx);
580 static u64 perf_event_time(struct perf_event *event);
582 void __weak perf_event_print_debug(void) { }
584 extern __weak const char *perf_pmu_name(void)
589 static inline u64 perf_clock(void)
591 return local_clock();
594 static inline u64 perf_event_clock(struct perf_event *event)
596 return event->clock();
600 * State based event timekeeping...
602 * The basic idea is to use event->state to determine which (if any) time
603 * fields to increment with the current delta. This means we only need to
604 * update timestamps when we change state or when they are explicitly requested
607 * Event groups make things a little more complicated, but not terribly so. The
608 * rules for a group are that if the group leader is OFF the entire group is
609 * OFF, irrespecive of what the group member states are. This results in
610 * __perf_effective_state().
612 * A futher ramification is that when a group leader flips between OFF and
613 * !OFF, we need to update all group member times.
616 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
617 * need to make sure the relevant context time is updated before we try and
618 * update our timestamps.
621 static __always_inline enum perf_event_state
622 __perf_effective_state(struct perf_event *event)
624 struct perf_event *leader = event->group_leader;
626 if (leader->state <= PERF_EVENT_STATE_OFF)
627 return leader->state;
632 static __always_inline void
633 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
635 enum perf_event_state state = __perf_effective_state(event);
636 u64 delta = now - event->tstamp;
638 *enabled = event->total_time_enabled;
639 if (state >= PERF_EVENT_STATE_INACTIVE)
642 *running = event->total_time_running;
643 if (state >= PERF_EVENT_STATE_ACTIVE)
647 static void perf_event_update_time(struct perf_event *event)
649 u64 now = perf_event_time(event);
651 __perf_update_times(event, now, &event->total_time_enabled,
652 &event->total_time_running);
656 static void perf_event_update_sibling_time(struct perf_event *leader)
658 struct perf_event *sibling;
660 for_each_sibling_event(sibling, leader)
661 perf_event_update_time(sibling);
665 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
667 if (event->state == state)
670 perf_event_update_time(event);
672 * If a group leader gets enabled/disabled all its siblings
675 if ((event->state < 0) ^ (state < 0))
676 perf_event_update_sibling_time(event);
678 WRITE_ONCE(event->state, state);
681 #ifdef CONFIG_CGROUP_PERF
684 perf_cgroup_match(struct perf_event *event)
686 struct perf_event_context *ctx = event->ctx;
687 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
689 /* @event doesn't care about cgroup */
693 /* wants specific cgroup scope but @cpuctx isn't associated with any */
698 * Cgroup scoping is recursive. An event enabled for a cgroup is
699 * also enabled for all its descendant cgroups. If @cpuctx's
700 * cgroup is a descendant of @event's (the test covers identity
701 * case), it's a match.
703 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
704 event->cgrp->css.cgroup);
707 static inline void perf_detach_cgroup(struct perf_event *event)
709 css_put(&event->cgrp->css);
713 static inline int is_cgroup_event(struct perf_event *event)
715 return event->cgrp != NULL;
718 static inline u64 perf_cgroup_event_time(struct perf_event *event)
720 struct perf_cgroup_info *t;
722 t = per_cpu_ptr(event->cgrp->info, event->cpu);
726 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
728 struct perf_cgroup_info *info;
733 info = this_cpu_ptr(cgrp->info);
735 info->time += now - info->timestamp;
736 info->timestamp = now;
739 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
741 struct perf_cgroup *cgrp = cpuctx->cgrp;
742 struct cgroup_subsys_state *css;
745 for (css = &cgrp->css; css; css = css->parent) {
746 cgrp = container_of(css, struct perf_cgroup, css);
747 __update_cgrp_time(cgrp);
752 static inline void update_cgrp_time_from_event(struct perf_event *event)
754 struct perf_cgroup *cgrp;
757 * ensure we access cgroup data only when needed and
758 * when we know the cgroup is pinned (css_get)
760 if (!is_cgroup_event(event))
763 cgrp = perf_cgroup_from_task(current, event->ctx);
765 * Do not update time when cgroup is not active
767 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
768 __update_cgrp_time(event->cgrp);
772 perf_cgroup_set_timestamp(struct task_struct *task,
773 struct perf_event_context *ctx)
775 struct perf_cgroup *cgrp;
776 struct perf_cgroup_info *info;
777 struct cgroup_subsys_state *css;
780 * ctx->lock held by caller
781 * ensure we do not access cgroup data
782 * unless we have the cgroup pinned (css_get)
784 if (!task || !ctx->nr_cgroups)
787 cgrp = perf_cgroup_from_task(task, ctx);
789 for (css = &cgrp->css; css; css = css->parent) {
790 cgrp = container_of(css, struct perf_cgroup, css);
791 info = this_cpu_ptr(cgrp->info);
792 info->timestamp = ctx->timestamp;
796 static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list);
798 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
799 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
802 * reschedule events based on the cgroup constraint of task.
804 * mode SWOUT : schedule out everything
805 * mode SWIN : schedule in based on cgroup for next
807 static void perf_cgroup_switch(struct task_struct *task, int mode)
809 struct perf_cpu_context *cpuctx;
810 struct list_head *list;
814 * Disable interrupts and preemption to avoid this CPU's
815 * cgrp_cpuctx_entry to change under us.
817 local_irq_save(flags);
819 list = this_cpu_ptr(&cgrp_cpuctx_list);
820 list_for_each_entry(cpuctx, list, cgrp_cpuctx_entry) {
821 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
823 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
824 perf_pmu_disable(cpuctx->ctx.pmu);
826 if (mode & PERF_CGROUP_SWOUT) {
827 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
829 * must not be done before ctxswout due
830 * to event_filter_match() in event_sched_out()
835 if (mode & PERF_CGROUP_SWIN) {
836 WARN_ON_ONCE(cpuctx->cgrp);
838 * set cgrp before ctxsw in to allow
839 * event_filter_match() to not have to pass
841 * we pass the cpuctx->ctx to perf_cgroup_from_task()
842 * because cgorup events are only per-cpu
844 cpuctx->cgrp = perf_cgroup_from_task(task,
846 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
848 perf_pmu_enable(cpuctx->ctx.pmu);
849 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
852 local_irq_restore(flags);
855 static inline void perf_cgroup_sched_out(struct task_struct *task,
856 struct task_struct *next)
858 struct perf_cgroup *cgrp1;
859 struct perf_cgroup *cgrp2 = NULL;
863 * we come here when we know perf_cgroup_events > 0
864 * we do not need to pass the ctx here because we know
865 * we are holding the rcu lock
867 cgrp1 = perf_cgroup_from_task(task, NULL);
868 cgrp2 = perf_cgroup_from_task(next, NULL);
871 * only schedule out current cgroup events if we know
872 * that we are switching to a different cgroup. Otherwise,
873 * do no touch the cgroup events.
876 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
881 static inline void perf_cgroup_sched_in(struct task_struct *prev,
882 struct task_struct *task)
884 struct perf_cgroup *cgrp1;
885 struct perf_cgroup *cgrp2 = NULL;
889 * we come here when we know perf_cgroup_events > 0
890 * we do not need to pass the ctx here because we know
891 * we are holding the rcu lock
893 cgrp1 = perf_cgroup_from_task(task, NULL);
894 cgrp2 = perf_cgroup_from_task(prev, NULL);
897 * only need to schedule in cgroup events if we are changing
898 * cgroup during ctxsw. Cgroup events were not scheduled
899 * out of ctxsw out if that was not the case.
902 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
907 static int perf_cgroup_ensure_storage(struct perf_event *event,
908 struct cgroup_subsys_state *css)
910 struct perf_cpu_context *cpuctx;
911 struct perf_event **storage;
912 int cpu, heap_size, ret = 0;
915 * Allow storage to have sufficent space for an iterator for each
916 * possibly nested cgroup plus an iterator for events with no cgroup.
918 for (heap_size = 1; css; css = css->parent)
921 for_each_possible_cpu(cpu) {
922 cpuctx = per_cpu_ptr(event->pmu->pmu_cpu_context, cpu);
923 if (heap_size <= cpuctx->heap_size)
926 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
927 GFP_KERNEL, cpu_to_node(cpu));
933 raw_spin_lock_irq(&cpuctx->ctx.lock);
934 if (cpuctx->heap_size < heap_size) {
935 swap(cpuctx->heap, storage);
936 if (storage == cpuctx->heap_default)
938 cpuctx->heap_size = heap_size;
940 raw_spin_unlock_irq(&cpuctx->ctx.lock);
948 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
949 struct perf_event_attr *attr,
950 struct perf_event *group_leader)
952 struct perf_cgroup *cgrp;
953 struct cgroup_subsys_state *css;
954 struct fd f = fdget(fd);
960 css = css_tryget_online_from_dir(f.file->f_path.dentry,
961 &perf_event_cgrp_subsys);
967 ret = perf_cgroup_ensure_storage(event, css);
971 cgrp = container_of(css, struct perf_cgroup, css);
975 * all events in a group must monitor
976 * the same cgroup because a task belongs
977 * to only one perf cgroup at a time
979 if (group_leader && group_leader->cgrp != cgrp) {
980 perf_detach_cgroup(event);
989 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
991 struct perf_cgroup_info *t;
992 t = per_cpu_ptr(event->cgrp->info, event->cpu);
993 event->shadow_ctx_time = now - t->timestamp;
997 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
999 struct perf_cpu_context *cpuctx;
1001 if (!is_cgroup_event(event))
1005 * Because cgroup events are always per-cpu events,
1006 * @ctx == &cpuctx->ctx.
1008 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1011 * Since setting cpuctx->cgrp is conditional on the current @cgrp
1012 * matching the event's cgroup, we must do this for every new event,
1013 * because if the first would mismatch, the second would not try again
1014 * and we would leave cpuctx->cgrp unset.
1016 if (ctx->is_active && !cpuctx->cgrp) {
1017 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
1019 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
1020 cpuctx->cgrp = cgrp;
1023 if (ctx->nr_cgroups++)
1026 list_add(&cpuctx->cgrp_cpuctx_entry,
1027 per_cpu_ptr(&cgrp_cpuctx_list, event->cpu));
1031 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1033 struct perf_cpu_context *cpuctx;
1035 if (!is_cgroup_event(event))
1039 * Because cgroup events are always per-cpu events,
1040 * @ctx == &cpuctx->ctx.
1042 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1044 if (--ctx->nr_cgroups)
1047 if (ctx->is_active && cpuctx->cgrp)
1048 cpuctx->cgrp = NULL;
1050 list_del(&cpuctx->cgrp_cpuctx_entry);
1053 #else /* !CONFIG_CGROUP_PERF */
1056 perf_cgroup_match(struct perf_event *event)
1061 static inline void perf_detach_cgroup(struct perf_event *event)
1064 static inline int is_cgroup_event(struct perf_event *event)
1069 static inline void update_cgrp_time_from_event(struct perf_event *event)
1073 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
1077 static inline void perf_cgroup_sched_out(struct task_struct *task,
1078 struct task_struct *next)
1082 static inline void perf_cgroup_sched_in(struct task_struct *prev,
1083 struct task_struct *task)
1087 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1088 struct perf_event_attr *attr,
1089 struct perf_event *group_leader)
1095 perf_cgroup_set_timestamp(struct task_struct *task,
1096 struct perf_event_context *ctx)
1101 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
1106 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
1110 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1116 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1121 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1127 * set default to be dependent on timer tick just
1128 * like original code
1130 #define PERF_CPU_HRTIMER (1000 / HZ)
1132 * function must be called with interrupts disabled
1134 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1136 struct perf_cpu_context *cpuctx;
1139 lockdep_assert_irqs_disabled();
1141 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
1142 rotations = perf_rotate_context(cpuctx);
1144 raw_spin_lock(&cpuctx->hrtimer_lock);
1146 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
1148 cpuctx->hrtimer_active = 0;
1149 raw_spin_unlock(&cpuctx->hrtimer_lock);
1151 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1154 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
1156 struct hrtimer *timer = &cpuctx->hrtimer;
1157 struct pmu *pmu = cpuctx->ctx.pmu;
1160 /* no multiplexing needed for SW PMU */
1161 if (pmu->task_ctx_nr == perf_sw_context)
1165 * check default is sane, if not set then force to
1166 * default interval (1/tick)
1168 interval = pmu->hrtimer_interval_ms;
1170 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1172 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1174 raw_spin_lock_init(&cpuctx->hrtimer_lock);
1175 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
1176 timer->function = perf_mux_hrtimer_handler;
1179 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1181 struct hrtimer *timer = &cpuctx->hrtimer;
1182 struct pmu *pmu = cpuctx->ctx.pmu;
1183 unsigned long flags;
1185 /* not for SW PMU */
1186 if (pmu->task_ctx_nr == perf_sw_context)
1189 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1190 if (!cpuctx->hrtimer_active) {
1191 cpuctx->hrtimer_active = 1;
1192 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1193 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1195 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1200 void perf_pmu_disable(struct pmu *pmu)
1202 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1204 pmu->pmu_disable(pmu);
1207 void perf_pmu_enable(struct pmu *pmu)
1209 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1211 pmu->pmu_enable(pmu);
1214 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1217 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1218 * perf_event_task_tick() are fully serialized because they're strictly cpu
1219 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1220 * disabled, while perf_event_task_tick is called from IRQ context.
1222 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1224 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1226 lockdep_assert_irqs_disabled();
1228 WARN_ON(!list_empty(&ctx->active_ctx_list));
1230 list_add(&ctx->active_ctx_list, head);
1233 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1235 lockdep_assert_irqs_disabled();
1237 WARN_ON(list_empty(&ctx->active_ctx_list));
1239 list_del_init(&ctx->active_ctx_list);
1242 static void get_ctx(struct perf_event_context *ctx)
1244 refcount_inc(&ctx->refcount);
1247 static void *alloc_task_ctx_data(struct pmu *pmu)
1249 if (pmu->task_ctx_cache)
1250 return kmem_cache_zalloc(pmu->task_ctx_cache, GFP_KERNEL);
1255 static void free_task_ctx_data(struct pmu *pmu, void *task_ctx_data)
1257 if (pmu->task_ctx_cache && task_ctx_data)
1258 kmem_cache_free(pmu->task_ctx_cache, task_ctx_data);
1261 static void free_ctx(struct rcu_head *head)
1263 struct perf_event_context *ctx;
1265 ctx = container_of(head, struct perf_event_context, rcu_head);
1266 free_task_ctx_data(ctx->pmu, ctx->task_ctx_data);
1270 static void put_ctx(struct perf_event_context *ctx)
1272 if (refcount_dec_and_test(&ctx->refcount)) {
1273 if (ctx->parent_ctx)
1274 put_ctx(ctx->parent_ctx);
1275 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1276 put_task_struct(ctx->task);
1277 call_rcu(&ctx->rcu_head, free_ctx);
1282 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1283 * perf_pmu_migrate_context() we need some magic.
1285 * Those places that change perf_event::ctx will hold both
1286 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1288 * Lock ordering is by mutex address. There are two other sites where
1289 * perf_event_context::mutex nests and those are:
1291 * - perf_event_exit_task_context() [ child , 0 ]
1292 * perf_event_exit_event()
1293 * put_event() [ parent, 1 ]
1295 * - perf_event_init_context() [ parent, 0 ]
1296 * inherit_task_group()
1299 * perf_event_alloc()
1301 * perf_try_init_event() [ child , 1 ]
1303 * While it appears there is an obvious deadlock here -- the parent and child
1304 * nesting levels are inverted between the two. This is in fact safe because
1305 * life-time rules separate them. That is an exiting task cannot fork, and a
1306 * spawning task cannot (yet) exit.
1308 * But remember that these are parent<->child context relations, and
1309 * migration does not affect children, therefore these two orderings should not
1312 * The change in perf_event::ctx does not affect children (as claimed above)
1313 * because the sys_perf_event_open() case will install a new event and break
1314 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1315 * concerned with cpuctx and that doesn't have children.
1317 * The places that change perf_event::ctx will issue:
1319 * perf_remove_from_context();
1320 * synchronize_rcu();
1321 * perf_install_in_context();
1323 * to affect the change. The remove_from_context() + synchronize_rcu() should
1324 * quiesce the event, after which we can install it in the new location. This
1325 * means that only external vectors (perf_fops, prctl) can perturb the event
1326 * while in transit. Therefore all such accessors should also acquire
1327 * perf_event_context::mutex to serialize against this.
1329 * However; because event->ctx can change while we're waiting to acquire
1330 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1335 * task_struct::perf_event_mutex
1336 * perf_event_context::mutex
1337 * perf_event::child_mutex;
1338 * perf_event_context::lock
1339 * perf_event::mmap_mutex
1341 * perf_addr_filters_head::lock
1345 * cpuctx->mutex / perf_event_context::mutex
1347 static struct perf_event_context *
1348 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1350 struct perf_event_context *ctx;
1354 ctx = READ_ONCE(event->ctx);
1355 if (!refcount_inc_not_zero(&ctx->refcount)) {
1361 mutex_lock_nested(&ctx->mutex, nesting);
1362 if (event->ctx != ctx) {
1363 mutex_unlock(&ctx->mutex);
1371 static inline struct perf_event_context *
1372 perf_event_ctx_lock(struct perf_event *event)
1374 return perf_event_ctx_lock_nested(event, 0);
1377 static void perf_event_ctx_unlock(struct perf_event *event,
1378 struct perf_event_context *ctx)
1380 mutex_unlock(&ctx->mutex);
1385 * This must be done under the ctx->lock, such as to serialize against
1386 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1387 * calling scheduler related locks and ctx->lock nests inside those.
1389 static __must_check struct perf_event_context *
1390 unclone_ctx(struct perf_event_context *ctx)
1392 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1394 lockdep_assert_held(&ctx->lock);
1397 ctx->parent_ctx = NULL;
1403 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1408 * only top level events have the pid namespace they were created in
1411 event = event->parent;
1413 nr = __task_pid_nr_ns(p, type, event->ns);
1414 /* avoid -1 if it is idle thread or runs in another ns */
1415 if (!nr && !pid_alive(p))
1420 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1422 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1425 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1427 return perf_event_pid_type(event, p, PIDTYPE_PID);
1431 * If we inherit events we want to return the parent event id
1434 static u64 primary_event_id(struct perf_event *event)
1439 id = event->parent->id;
1445 * Get the perf_event_context for a task and lock it.
1447 * This has to cope with the fact that until it is locked,
1448 * the context could get moved to another task.
1450 static struct perf_event_context *
1451 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1453 struct perf_event_context *ctx;
1457 * One of the few rules of preemptible RCU is that one cannot do
1458 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1459 * part of the read side critical section was irqs-enabled -- see
1460 * rcu_read_unlock_special().
1462 * Since ctx->lock nests under rq->lock we must ensure the entire read
1463 * side critical section has interrupts disabled.
1465 local_irq_save(*flags);
1467 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1470 * If this context is a clone of another, it might
1471 * get swapped for another underneath us by
1472 * perf_event_task_sched_out, though the
1473 * rcu_read_lock() protects us from any context
1474 * getting freed. Lock the context and check if it
1475 * got swapped before we could get the lock, and retry
1476 * if so. If we locked the right context, then it
1477 * can't get swapped on us any more.
1479 raw_spin_lock(&ctx->lock);
1480 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1481 raw_spin_unlock(&ctx->lock);
1483 local_irq_restore(*flags);
1487 if (ctx->task == TASK_TOMBSTONE ||
1488 !refcount_inc_not_zero(&ctx->refcount)) {
1489 raw_spin_unlock(&ctx->lock);
1492 WARN_ON_ONCE(ctx->task != task);
1497 local_irq_restore(*flags);
1502 * Get the context for a task and increment its pin_count so it
1503 * can't get swapped to another task. This also increments its
1504 * reference count so that the context can't get freed.
1506 static struct perf_event_context *
1507 perf_pin_task_context(struct task_struct *task, int ctxn)
1509 struct perf_event_context *ctx;
1510 unsigned long flags;
1512 ctx = perf_lock_task_context(task, ctxn, &flags);
1515 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1520 static void perf_unpin_context(struct perf_event_context *ctx)
1522 unsigned long flags;
1524 raw_spin_lock_irqsave(&ctx->lock, flags);
1526 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1530 * Update the record of the current time in a context.
1532 static void update_context_time(struct perf_event_context *ctx)
1534 u64 now = perf_clock();
1536 ctx->time += now - ctx->timestamp;
1537 ctx->timestamp = now;
1540 static u64 perf_event_time(struct perf_event *event)
1542 struct perf_event_context *ctx = event->ctx;
1544 if (is_cgroup_event(event))
1545 return perf_cgroup_event_time(event);
1547 return ctx ? ctx->time : 0;
1550 static enum event_type_t get_event_type(struct perf_event *event)
1552 struct perf_event_context *ctx = event->ctx;
1553 enum event_type_t event_type;
1555 lockdep_assert_held(&ctx->lock);
1558 * It's 'group type', really, because if our group leader is
1559 * pinned, so are we.
1561 if (event->group_leader != event)
1562 event = event->group_leader;
1564 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1566 event_type |= EVENT_CPU;
1572 * Helper function to initialize event group nodes.
1574 static void init_event_group(struct perf_event *event)
1576 RB_CLEAR_NODE(&event->group_node);
1577 event->group_index = 0;
1581 * Extract pinned or flexible groups from the context
1582 * based on event attrs bits.
1584 static struct perf_event_groups *
1585 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1587 if (event->attr.pinned)
1588 return &ctx->pinned_groups;
1590 return &ctx->flexible_groups;
1594 * Helper function to initializes perf_event_group trees.
1596 static void perf_event_groups_init(struct perf_event_groups *groups)
1598 groups->tree = RB_ROOT;
1602 static inline struct cgroup *event_cgroup(const struct perf_event *event)
1604 struct cgroup *cgroup = NULL;
1606 #ifdef CONFIG_CGROUP_PERF
1608 cgroup = event->cgrp->css.cgroup;
1615 * Compare function for event groups;
1617 * Implements complex key that first sorts by CPU and then by virtual index
1618 * which provides ordering when rotating groups for the same CPU.
1620 static __always_inline int
1621 perf_event_groups_cmp(const int left_cpu, const struct cgroup *left_cgroup,
1622 const u64 left_group_index, const struct perf_event *right)
1624 if (left_cpu < right->cpu)
1626 if (left_cpu > right->cpu)
1629 #ifdef CONFIG_CGROUP_PERF
1631 const struct cgroup *right_cgroup = event_cgroup(right);
1633 if (left_cgroup != right_cgroup) {
1636 * Left has no cgroup but right does, no
1637 * cgroups come first.
1641 if (!right_cgroup) {
1643 * Right has no cgroup but left does, no
1644 * cgroups come first.
1648 /* Two dissimilar cgroups, order by id. */
1649 if (cgroup_id(left_cgroup) < cgroup_id(right_cgroup))
1657 if (left_group_index < right->group_index)
1659 if (left_group_index > right->group_index)
1665 #define __node_2_pe(node) \
1666 rb_entry((node), struct perf_event, group_node)
1668 static inline bool __group_less(struct rb_node *a, const struct rb_node *b)
1670 struct perf_event *e = __node_2_pe(a);
1671 return perf_event_groups_cmp(e->cpu, event_cgroup(e), e->group_index,
1672 __node_2_pe(b)) < 0;
1675 struct __group_key {
1677 struct cgroup *cgroup;
1680 static inline int __group_cmp(const void *key, const struct rb_node *node)
1682 const struct __group_key *a = key;
1683 const struct perf_event *b = __node_2_pe(node);
1685 /* partial/subtree match: @cpu, @cgroup; ignore: @group_index */
1686 return perf_event_groups_cmp(a->cpu, a->cgroup, b->group_index, b);
1690 * Insert @event into @groups' tree; using {@event->cpu, ++@groups->index} for
1691 * key (see perf_event_groups_less). This places it last inside the CPU
1695 perf_event_groups_insert(struct perf_event_groups *groups,
1696 struct perf_event *event)
1698 event->group_index = ++groups->index;
1700 rb_add(&event->group_node, &groups->tree, __group_less);
1704 * Helper function to insert event into the pinned or flexible groups.
1707 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1709 struct perf_event_groups *groups;
1711 groups = get_event_groups(event, ctx);
1712 perf_event_groups_insert(groups, event);
1716 * Delete a group from a tree.
1719 perf_event_groups_delete(struct perf_event_groups *groups,
1720 struct perf_event *event)
1722 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1723 RB_EMPTY_ROOT(&groups->tree));
1725 rb_erase(&event->group_node, &groups->tree);
1726 init_event_group(event);
1730 * Helper function to delete event from its groups.
1733 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1735 struct perf_event_groups *groups;
1737 groups = get_event_groups(event, ctx);
1738 perf_event_groups_delete(groups, event);
1742 * Get the leftmost event in the cpu/cgroup subtree.
1744 static struct perf_event *
1745 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1746 struct cgroup *cgrp)
1748 struct __group_key key = {
1752 struct rb_node *node;
1754 node = rb_find_first(&key, &groups->tree, __group_cmp);
1756 return __node_2_pe(node);
1762 * Like rb_entry_next_safe() for the @cpu subtree.
1764 static struct perf_event *
1765 perf_event_groups_next(struct perf_event *event)
1767 struct __group_key key = {
1769 .cgroup = event_cgroup(event),
1771 struct rb_node *next;
1773 next = rb_next_match(&key, &event->group_node, __group_cmp);
1775 return __node_2_pe(next);
1781 * Iterate through the whole groups tree.
1783 #define perf_event_groups_for_each(event, groups) \
1784 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1785 typeof(*event), group_node); event; \
1786 event = rb_entry_safe(rb_next(&event->group_node), \
1787 typeof(*event), group_node))
1790 * Add an event from the lists for its context.
1791 * Must be called with ctx->mutex and ctx->lock held.
1794 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1796 lockdep_assert_held(&ctx->lock);
1798 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1799 event->attach_state |= PERF_ATTACH_CONTEXT;
1801 event->tstamp = perf_event_time(event);
1804 * If we're a stand alone event or group leader, we go to the context
1805 * list, group events are kept attached to the group so that
1806 * perf_group_detach can, at all times, locate all siblings.
1808 if (event->group_leader == event) {
1809 event->group_caps = event->event_caps;
1810 add_event_to_groups(event, ctx);
1813 list_add_rcu(&event->event_entry, &ctx->event_list);
1815 if (event->attr.inherit_stat)
1818 if (event->state > PERF_EVENT_STATE_OFF)
1819 perf_cgroup_event_enable(event, ctx);
1825 * Initialize event state based on the perf_event_attr::disabled.
1827 static inline void perf_event__state_init(struct perf_event *event)
1829 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1830 PERF_EVENT_STATE_INACTIVE;
1833 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1835 int entry = sizeof(u64); /* value */
1839 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1840 size += sizeof(u64);
1842 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1843 size += sizeof(u64);
1845 if (event->attr.read_format & PERF_FORMAT_ID)
1846 entry += sizeof(u64);
1848 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1850 size += sizeof(u64);
1854 event->read_size = size;
1857 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1859 struct perf_sample_data *data;
1862 if (sample_type & PERF_SAMPLE_IP)
1863 size += sizeof(data->ip);
1865 if (sample_type & PERF_SAMPLE_ADDR)
1866 size += sizeof(data->addr);
1868 if (sample_type & PERF_SAMPLE_PERIOD)
1869 size += sizeof(data->period);
1871 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
1872 size += sizeof(data->weight.full);
1874 if (sample_type & PERF_SAMPLE_READ)
1875 size += event->read_size;
1877 if (sample_type & PERF_SAMPLE_DATA_SRC)
1878 size += sizeof(data->data_src.val);
1880 if (sample_type & PERF_SAMPLE_TRANSACTION)
1881 size += sizeof(data->txn);
1883 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1884 size += sizeof(data->phys_addr);
1886 if (sample_type & PERF_SAMPLE_CGROUP)
1887 size += sizeof(data->cgroup);
1889 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
1890 size += sizeof(data->data_page_size);
1892 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
1893 size += sizeof(data->code_page_size);
1895 event->header_size = size;
1899 * Called at perf_event creation and when events are attached/detached from a
1902 static void perf_event__header_size(struct perf_event *event)
1904 __perf_event_read_size(event,
1905 event->group_leader->nr_siblings);
1906 __perf_event_header_size(event, event->attr.sample_type);
1909 static void perf_event__id_header_size(struct perf_event *event)
1911 struct perf_sample_data *data;
1912 u64 sample_type = event->attr.sample_type;
1915 if (sample_type & PERF_SAMPLE_TID)
1916 size += sizeof(data->tid_entry);
1918 if (sample_type & PERF_SAMPLE_TIME)
1919 size += sizeof(data->time);
1921 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1922 size += sizeof(data->id);
1924 if (sample_type & PERF_SAMPLE_ID)
1925 size += sizeof(data->id);
1927 if (sample_type & PERF_SAMPLE_STREAM_ID)
1928 size += sizeof(data->stream_id);
1930 if (sample_type & PERF_SAMPLE_CPU)
1931 size += sizeof(data->cpu_entry);
1933 event->id_header_size = size;
1936 static bool perf_event_validate_size(struct perf_event *event)
1939 * The values computed here will be over-written when we actually
1942 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1943 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1944 perf_event__id_header_size(event);
1947 * Sum the lot; should not exceed the 64k limit we have on records.
1948 * Conservative limit to allow for callchains and other variable fields.
1950 if (event->read_size + event->header_size +
1951 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1957 static void perf_group_attach(struct perf_event *event)
1959 struct perf_event *group_leader = event->group_leader, *pos;
1961 lockdep_assert_held(&event->ctx->lock);
1964 * We can have double attach due to group movement in perf_event_open.
1966 if (event->attach_state & PERF_ATTACH_GROUP)
1969 event->attach_state |= PERF_ATTACH_GROUP;
1971 if (group_leader == event)
1974 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1976 group_leader->group_caps &= event->event_caps;
1978 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
1979 group_leader->nr_siblings++;
1981 perf_event__header_size(group_leader);
1983 for_each_sibling_event(pos, group_leader)
1984 perf_event__header_size(pos);
1988 * Remove an event from the lists for its context.
1989 * Must be called with ctx->mutex and ctx->lock held.
1992 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1994 WARN_ON_ONCE(event->ctx != ctx);
1995 lockdep_assert_held(&ctx->lock);
1998 * We can have double detach due to exit/hot-unplug + close.
2000 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
2003 event->attach_state &= ~PERF_ATTACH_CONTEXT;
2006 if (event->attr.inherit_stat)
2009 list_del_rcu(&event->event_entry);
2011 if (event->group_leader == event)
2012 del_event_from_groups(event, ctx);
2015 * If event was in error state, then keep it
2016 * that way, otherwise bogus counts will be
2017 * returned on read(). The only way to get out
2018 * of error state is by explicit re-enabling
2021 if (event->state > PERF_EVENT_STATE_OFF) {
2022 perf_cgroup_event_disable(event, ctx);
2023 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2030 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2032 if (!has_aux(aux_event))
2035 if (!event->pmu->aux_output_match)
2038 return event->pmu->aux_output_match(aux_event);
2041 static void put_event(struct perf_event *event);
2042 static void event_sched_out(struct perf_event *event,
2043 struct perf_cpu_context *cpuctx,
2044 struct perf_event_context *ctx);
2046 static void perf_put_aux_event(struct perf_event *event)
2048 struct perf_event_context *ctx = event->ctx;
2049 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2050 struct perf_event *iter;
2053 * If event uses aux_event tear down the link
2055 if (event->aux_event) {
2056 iter = event->aux_event;
2057 event->aux_event = NULL;
2063 * If the event is an aux_event, tear down all links to
2064 * it from other events.
2066 for_each_sibling_event(iter, event->group_leader) {
2067 if (iter->aux_event != event)
2070 iter->aux_event = NULL;
2074 * If it's ACTIVE, schedule it out and put it into ERROR
2075 * state so that we don't try to schedule it again. Note
2076 * that perf_event_enable() will clear the ERROR status.
2078 event_sched_out(iter, cpuctx, ctx);
2079 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2083 static bool perf_need_aux_event(struct perf_event *event)
2085 return !!event->attr.aux_output || !!event->attr.aux_sample_size;
2088 static int perf_get_aux_event(struct perf_event *event,
2089 struct perf_event *group_leader)
2092 * Our group leader must be an aux event if we want to be
2093 * an aux_output. This way, the aux event will precede its
2094 * aux_output events in the group, and therefore will always
2101 * aux_output and aux_sample_size are mutually exclusive.
2103 if (event->attr.aux_output && event->attr.aux_sample_size)
2106 if (event->attr.aux_output &&
2107 !perf_aux_output_match(event, group_leader))
2110 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2113 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2117 * Link aux_outputs to their aux event; this is undone in
2118 * perf_group_detach() by perf_put_aux_event(). When the
2119 * group in torn down, the aux_output events loose their
2120 * link to the aux_event and can't schedule any more.
2122 event->aux_event = group_leader;
2127 static inline struct list_head *get_event_list(struct perf_event *event)
2129 struct perf_event_context *ctx = event->ctx;
2130 return event->attr.pinned ? &ctx->pinned_active : &ctx->flexible_active;
2134 * Events that have PERF_EV_CAP_SIBLING require being part of a group and
2135 * cannot exist on their own, schedule them out and move them into the ERROR
2136 * state. Also see _perf_event_enable(), it will not be able to recover
2139 static inline void perf_remove_sibling_event(struct perf_event *event)
2141 struct perf_event_context *ctx = event->ctx;
2142 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2144 event_sched_out(event, cpuctx, ctx);
2145 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2148 static void perf_group_detach(struct perf_event *event)
2150 struct perf_event *leader = event->group_leader;
2151 struct perf_event *sibling, *tmp;
2152 struct perf_event_context *ctx = event->ctx;
2154 lockdep_assert_held(&ctx->lock);
2157 * We can have double detach due to exit/hot-unplug + close.
2159 if (!(event->attach_state & PERF_ATTACH_GROUP))
2162 event->attach_state &= ~PERF_ATTACH_GROUP;
2164 perf_put_aux_event(event);
2167 * If this is a sibling, remove it from its group.
2169 if (leader != event) {
2170 list_del_init(&event->sibling_list);
2171 event->group_leader->nr_siblings--;
2176 * If this was a group event with sibling events then
2177 * upgrade the siblings to singleton events by adding them
2178 * to whatever list we are on.
2180 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2182 if (sibling->event_caps & PERF_EV_CAP_SIBLING)
2183 perf_remove_sibling_event(sibling);
2185 sibling->group_leader = sibling;
2186 list_del_init(&sibling->sibling_list);
2188 /* Inherit group flags from the previous leader */
2189 sibling->group_caps = event->group_caps;
2191 if (!RB_EMPTY_NODE(&event->group_node)) {
2192 add_event_to_groups(sibling, event->ctx);
2194 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2195 list_add_tail(&sibling->active_list, get_event_list(sibling));
2198 WARN_ON_ONCE(sibling->ctx != event->ctx);
2202 for_each_sibling_event(tmp, leader)
2203 perf_event__header_size(tmp);
2205 perf_event__header_size(leader);
2208 static bool is_orphaned_event(struct perf_event *event)
2210 return event->state == PERF_EVENT_STATE_DEAD;
2213 static inline int __pmu_filter_match(struct perf_event *event)
2215 struct pmu *pmu = event->pmu;
2216 return pmu->filter_match ? pmu->filter_match(event) : 1;
2220 * Check whether we should attempt to schedule an event group based on
2221 * PMU-specific filtering. An event group can consist of HW and SW events,
2222 * potentially with a SW leader, so we must check all the filters, to
2223 * determine whether a group is schedulable:
2225 static inline int pmu_filter_match(struct perf_event *event)
2227 struct perf_event *sibling;
2229 if (!__pmu_filter_match(event))
2232 for_each_sibling_event(sibling, event) {
2233 if (!__pmu_filter_match(sibling))
2241 event_filter_match(struct perf_event *event)
2243 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2244 perf_cgroup_match(event) && pmu_filter_match(event);
2248 event_sched_out(struct perf_event *event,
2249 struct perf_cpu_context *cpuctx,
2250 struct perf_event_context *ctx)
2252 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2254 WARN_ON_ONCE(event->ctx != ctx);
2255 lockdep_assert_held(&ctx->lock);
2257 if (event->state != PERF_EVENT_STATE_ACTIVE)
2261 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2262 * we can schedule events _OUT_ individually through things like
2263 * __perf_remove_from_context().
2265 list_del_init(&event->active_list);
2267 perf_pmu_disable(event->pmu);
2269 event->pmu->del(event, 0);
2272 if (READ_ONCE(event->pending_disable) >= 0) {
2273 WRITE_ONCE(event->pending_disable, -1);
2274 perf_cgroup_event_disable(event, ctx);
2275 state = PERF_EVENT_STATE_OFF;
2277 perf_event_set_state(event, state);
2279 if (!is_software_event(event))
2280 cpuctx->active_oncpu--;
2281 if (!--ctx->nr_active)
2282 perf_event_ctx_deactivate(ctx);
2283 if (event->attr.freq && event->attr.sample_freq)
2285 if (event->attr.exclusive || !cpuctx->active_oncpu)
2286 cpuctx->exclusive = 0;
2288 perf_pmu_enable(event->pmu);
2292 group_sched_out(struct perf_event *group_event,
2293 struct perf_cpu_context *cpuctx,
2294 struct perf_event_context *ctx)
2296 struct perf_event *event;
2298 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2301 perf_pmu_disable(ctx->pmu);
2303 event_sched_out(group_event, cpuctx, ctx);
2306 * Schedule out siblings (if any):
2308 for_each_sibling_event(event, group_event)
2309 event_sched_out(event, cpuctx, ctx);
2311 perf_pmu_enable(ctx->pmu);
2314 #define DETACH_GROUP 0x01UL
2317 * Cross CPU call to remove a performance event
2319 * We disable the event on the hardware level first. After that we
2320 * remove it from the context list.
2323 __perf_remove_from_context(struct perf_event *event,
2324 struct perf_cpu_context *cpuctx,
2325 struct perf_event_context *ctx,
2328 unsigned long flags = (unsigned long)info;
2330 if (ctx->is_active & EVENT_TIME) {
2331 update_context_time(ctx);
2332 update_cgrp_time_from_cpuctx(cpuctx);
2335 event_sched_out(event, cpuctx, ctx);
2336 if (flags & DETACH_GROUP)
2337 perf_group_detach(event);
2338 list_del_event(event, ctx);
2340 if (!ctx->nr_events && ctx->is_active) {
2342 ctx->rotate_necessary = 0;
2344 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2345 cpuctx->task_ctx = NULL;
2351 * Remove the event from a task's (or a CPU's) list of events.
2353 * If event->ctx is a cloned context, callers must make sure that
2354 * every task struct that event->ctx->task could possibly point to
2355 * remains valid. This is OK when called from perf_release since
2356 * that only calls us on the top-level context, which can't be a clone.
2357 * When called from perf_event_exit_task, it's OK because the
2358 * context has been detached from its task.
2360 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2362 struct perf_event_context *ctx = event->ctx;
2364 lockdep_assert_held(&ctx->mutex);
2366 event_function_call(event, __perf_remove_from_context, (void *)flags);
2369 * The above event_function_call() can NO-OP when it hits
2370 * TASK_TOMBSTONE. In that case we must already have been detached
2371 * from the context (by perf_event_exit_event()) but the grouping
2372 * might still be in-tact.
2374 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
2375 if ((flags & DETACH_GROUP) &&
2376 (event->attach_state & PERF_ATTACH_GROUP)) {
2378 * Since in that case we cannot possibly be scheduled, simply
2381 raw_spin_lock_irq(&ctx->lock);
2382 perf_group_detach(event);
2383 raw_spin_unlock_irq(&ctx->lock);
2388 * Cross CPU call to disable a performance event
2390 static void __perf_event_disable(struct perf_event *event,
2391 struct perf_cpu_context *cpuctx,
2392 struct perf_event_context *ctx,
2395 if (event->state < PERF_EVENT_STATE_INACTIVE)
2398 if (ctx->is_active & EVENT_TIME) {
2399 update_context_time(ctx);
2400 update_cgrp_time_from_event(event);
2403 if (event == event->group_leader)
2404 group_sched_out(event, cpuctx, ctx);
2406 event_sched_out(event, cpuctx, ctx);
2408 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2409 perf_cgroup_event_disable(event, ctx);
2415 * If event->ctx is a cloned context, callers must make sure that
2416 * every task struct that event->ctx->task could possibly point to
2417 * remains valid. This condition is satisfied when called through
2418 * perf_event_for_each_child or perf_event_for_each because they
2419 * hold the top-level event's child_mutex, so any descendant that
2420 * goes to exit will block in perf_event_exit_event().
2422 * When called from perf_pending_event it's OK because event->ctx
2423 * is the current context on this CPU and preemption is disabled,
2424 * hence we can't get into perf_event_task_sched_out for this context.
2426 static void _perf_event_disable(struct perf_event *event)
2428 struct perf_event_context *ctx = event->ctx;
2430 raw_spin_lock_irq(&ctx->lock);
2431 if (event->state <= PERF_EVENT_STATE_OFF) {
2432 raw_spin_unlock_irq(&ctx->lock);
2435 raw_spin_unlock_irq(&ctx->lock);
2437 event_function_call(event, __perf_event_disable, NULL);
2440 void perf_event_disable_local(struct perf_event *event)
2442 event_function_local(event, __perf_event_disable, NULL);
2446 * Strictly speaking kernel users cannot create groups and therefore this
2447 * interface does not need the perf_event_ctx_lock() magic.
2449 void perf_event_disable(struct perf_event *event)
2451 struct perf_event_context *ctx;
2453 ctx = perf_event_ctx_lock(event);
2454 _perf_event_disable(event);
2455 perf_event_ctx_unlock(event, ctx);
2457 EXPORT_SYMBOL_GPL(perf_event_disable);
2459 void perf_event_disable_inatomic(struct perf_event *event)
2461 WRITE_ONCE(event->pending_disable, smp_processor_id());
2462 /* can fail, see perf_pending_event_disable() */
2463 irq_work_queue(&event->pending);
2466 static void perf_set_shadow_time(struct perf_event *event,
2467 struct perf_event_context *ctx)
2470 * use the correct time source for the time snapshot
2472 * We could get by without this by leveraging the
2473 * fact that to get to this function, the caller
2474 * has most likely already called update_context_time()
2475 * and update_cgrp_time_xx() and thus both timestamp
2476 * are identical (or very close). Given that tstamp is,
2477 * already adjusted for cgroup, we could say that:
2478 * tstamp - ctx->timestamp
2480 * tstamp - cgrp->timestamp.
2482 * Then, in perf_output_read(), the calculation would
2483 * work with no changes because:
2484 * - event is guaranteed scheduled in
2485 * - no scheduled out in between
2486 * - thus the timestamp would be the same
2488 * But this is a bit hairy.
2490 * So instead, we have an explicit cgroup call to remain
2491 * within the time source all along. We believe it
2492 * is cleaner and simpler to understand.
2494 if (is_cgroup_event(event))
2495 perf_cgroup_set_shadow_time(event, event->tstamp);
2497 event->shadow_ctx_time = event->tstamp - ctx->timestamp;
2500 #define MAX_INTERRUPTS (~0ULL)
2502 static void perf_log_throttle(struct perf_event *event, int enable);
2503 static void perf_log_itrace_start(struct perf_event *event);
2506 event_sched_in(struct perf_event *event,
2507 struct perf_cpu_context *cpuctx,
2508 struct perf_event_context *ctx)
2512 WARN_ON_ONCE(event->ctx != ctx);
2514 lockdep_assert_held(&ctx->lock);
2516 if (event->state <= PERF_EVENT_STATE_OFF)
2519 WRITE_ONCE(event->oncpu, smp_processor_id());
2521 * Order event::oncpu write to happen before the ACTIVE state is
2522 * visible. This allows perf_event_{stop,read}() to observe the correct
2523 * ->oncpu if it sees ACTIVE.
2526 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2529 * Unthrottle events, since we scheduled we might have missed several
2530 * ticks already, also for a heavily scheduling task there is little
2531 * guarantee it'll get a tick in a timely manner.
2533 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2534 perf_log_throttle(event, 1);
2535 event->hw.interrupts = 0;
2538 perf_pmu_disable(event->pmu);
2540 perf_set_shadow_time(event, ctx);
2542 perf_log_itrace_start(event);
2544 if (event->pmu->add(event, PERF_EF_START)) {
2545 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2551 if (!is_software_event(event))
2552 cpuctx->active_oncpu++;
2553 if (!ctx->nr_active++)
2554 perf_event_ctx_activate(ctx);
2555 if (event->attr.freq && event->attr.sample_freq)
2558 if (event->attr.exclusive)
2559 cpuctx->exclusive = 1;
2562 perf_pmu_enable(event->pmu);
2568 group_sched_in(struct perf_event *group_event,
2569 struct perf_cpu_context *cpuctx,
2570 struct perf_event_context *ctx)
2572 struct perf_event *event, *partial_group = NULL;
2573 struct pmu *pmu = ctx->pmu;
2575 if (group_event->state == PERF_EVENT_STATE_OFF)
2578 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2580 if (event_sched_in(group_event, cpuctx, ctx))
2584 * Schedule in siblings as one group (if any):
2586 for_each_sibling_event(event, group_event) {
2587 if (event_sched_in(event, cpuctx, ctx)) {
2588 partial_group = event;
2593 if (!pmu->commit_txn(pmu))
2598 * Groups can be scheduled in as one unit only, so undo any
2599 * partial group before returning:
2600 * The events up to the failed event are scheduled out normally.
2602 for_each_sibling_event(event, group_event) {
2603 if (event == partial_group)
2606 event_sched_out(event, cpuctx, ctx);
2608 event_sched_out(group_event, cpuctx, ctx);
2611 pmu->cancel_txn(pmu);
2616 * Work out whether we can put this event group on the CPU now.
2618 static int group_can_go_on(struct perf_event *event,
2619 struct perf_cpu_context *cpuctx,
2623 * Groups consisting entirely of software events can always go on.
2625 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2628 * If an exclusive group is already on, no other hardware
2631 if (cpuctx->exclusive)
2634 * If this group is exclusive and there are already
2635 * events on the CPU, it can't go on.
2637 if (event->attr.exclusive && !list_empty(get_event_list(event)))
2640 * Otherwise, try to add it if all previous groups were able
2646 static void add_event_to_ctx(struct perf_event *event,
2647 struct perf_event_context *ctx)
2649 list_add_event(event, ctx);
2650 perf_group_attach(event);
2653 static void ctx_sched_out(struct perf_event_context *ctx,
2654 struct perf_cpu_context *cpuctx,
2655 enum event_type_t event_type);
2657 ctx_sched_in(struct perf_event_context *ctx,
2658 struct perf_cpu_context *cpuctx,
2659 enum event_type_t event_type,
2660 struct task_struct *task);
2662 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2663 struct perf_event_context *ctx,
2664 enum event_type_t event_type)
2666 if (!cpuctx->task_ctx)
2669 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2672 ctx_sched_out(ctx, cpuctx, event_type);
2675 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2676 struct perf_event_context *ctx,
2677 struct task_struct *task)
2679 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2681 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2682 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2684 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2688 * We want to maintain the following priority of scheduling:
2689 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2690 * - task pinned (EVENT_PINNED)
2691 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2692 * - task flexible (EVENT_FLEXIBLE).
2694 * In order to avoid unscheduling and scheduling back in everything every
2695 * time an event is added, only do it for the groups of equal priority and
2698 * This can be called after a batch operation on task events, in which case
2699 * event_type is a bit mask of the types of events involved. For CPU events,
2700 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2702 static void ctx_resched(struct perf_cpu_context *cpuctx,
2703 struct perf_event_context *task_ctx,
2704 enum event_type_t event_type)
2706 enum event_type_t ctx_event_type;
2707 bool cpu_event = !!(event_type & EVENT_CPU);
2710 * If pinned groups are involved, flexible groups also need to be
2713 if (event_type & EVENT_PINNED)
2714 event_type |= EVENT_FLEXIBLE;
2716 ctx_event_type = event_type & EVENT_ALL;
2718 perf_pmu_disable(cpuctx->ctx.pmu);
2720 task_ctx_sched_out(cpuctx, task_ctx, event_type);
2723 * Decide which cpu ctx groups to schedule out based on the types
2724 * of events that caused rescheduling:
2725 * - EVENT_CPU: schedule out corresponding groups;
2726 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2727 * - otherwise, do nothing more.
2730 cpu_ctx_sched_out(cpuctx, ctx_event_type);
2731 else if (ctx_event_type & EVENT_PINNED)
2732 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2734 perf_event_sched_in(cpuctx, task_ctx, current);
2735 perf_pmu_enable(cpuctx->ctx.pmu);
2738 void perf_pmu_resched(struct pmu *pmu)
2740 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2741 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2743 perf_ctx_lock(cpuctx, task_ctx);
2744 ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2745 perf_ctx_unlock(cpuctx, task_ctx);
2749 * Cross CPU call to install and enable a performance event
2751 * Very similar to remote_function() + event_function() but cannot assume that
2752 * things like ctx->is_active and cpuctx->task_ctx are set.
2754 static int __perf_install_in_context(void *info)
2756 struct perf_event *event = info;
2757 struct perf_event_context *ctx = event->ctx;
2758 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2759 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2760 bool reprogram = true;
2763 raw_spin_lock(&cpuctx->ctx.lock);
2765 raw_spin_lock(&ctx->lock);
2768 reprogram = (ctx->task == current);
2771 * If the task is running, it must be running on this CPU,
2772 * otherwise we cannot reprogram things.
2774 * If its not running, we don't care, ctx->lock will
2775 * serialize against it becoming runnable.
2777 if (task_curr(ctx->task) && !reprogram) {
2782 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2783 } else if (task_ctx) {
2784 raw_spin_lock(&task_ctx->lock);
2787 #ifdef CONFIG_CGROUP_PERF
2788 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2790 * If the current cgroup doesn't match the event's
2791 * cgroup, we should not try to schedule it.
2793 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2794 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2795 event->cgrp->css.cgroup);
2800 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2801 add_event_to_ctx(event, ctx);
2802 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2804 add_event_to_ctx(event, ctx);
2808 perf_ctx_unlock(cpuctx, task_ctx);
2813 static bool exclusive_event_installable(struct perf_event *event,
2814 struct perf_event_context *ctx);
2817 * Attach a performance event to a context.
2819 * Very similar to event_function_call, see comment there.
2822 perf_install_in_context(struct perf_event_context *ctx,
2823 struct perf_event *event,
2826 struct task_struct *task = READ_ONCE(ctx->task);
2828 lockdep_assert_held(&ctx->mutex);
2830 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2832 if (event->cpu != -1)
2836 * Ensures that if we can observe event->ctx, both the event and ctx
2837 * will be 'complete'. See perf_iterate_sb_cpu().
2839 smp_store_release(&event->ctx, ctx);
2842 * perf_event_attr::disabled events will not run and can be initialized
2843 * without IPI. Except when this is the first event for the context, in
2844 * that case we need the magic of the IPI to set ctx->is_active.
2846 * The IOC_ENABLE that is sure to follow the creation of a disabled
2847 * event will issue the IPI and reprogram the hardware.
2849 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF && ctx->nr_events) {
2850 raw_spin_lock_irq(&ctx->lock);
2851 if (ctx->task == TASK_TOMBSTONE) {
2852 raw_spin_unlock_irq(&ctx->lock);
2855 add_event_to_ctx(event, ctx);
2856 raw_spin_unlock_irq(&ctx->lock);
2861 cpu_function_call(cpu, __perf_install_in_context, event);
2866 * Should not happen, we validate the ctx is still alive before calling.
2868 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2872 * Installing events is tricky because we cannot rely on ctx->is_active
2873 * to be set in case this is the nr_events 0 -> 1 transition.
2875 * Instead we use task_curr(), which tells us if the task is running.
2876 * However, since we use task_curr() outside of rq::lock, we can race
2877 * against the actual state. This means the result can be wrong.
2879 * If we get a false positive, we retry, this is harmless.
2881 * If we get a false negative, things are complicated. If we are after
2882 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2883 * value must be correct. If we're before, it doesn't matter since
2884 * perf_event_context_sched_in() will program the counter.
2886 * However, this hinges on the remote context switch having observed
2887 * our task->perf_event_ctxp[] store, such that it will in fact take
2888 * ctx::lock in perf_event_context_sched_in().
2890 * We do this by task_function_call(), if the IPI fails to hit the task
2891 * we know any future context switch of task must see the
2892 * perf_event_ctpx[] store.
2896 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2897 * task_cpu() load, such that if the IPI then does not find the task
2898 * running, a future context switch of that task must observe the
2903 if (!task_function_call(task, __perf_install_in_context, event))
2906 raw_spin_lock_irq(&ctx->lock);
2908 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2910 * Cannot happen because we already checked above (which also
2911 * cannot happen), and we hold ctx->mutex, which serializes us
2912 * against perf_event_exit_task_context().
2914 raw_spin_unlock_irq(&ctx->lock);
2918 * If the task is not running, ctx->lock will avoid it becoming so,
2919 * thus we can safely install the event.
2921 if (task_curr(task)) {
2922 raw_spin_unlock_irq(&ctx->lock);
2925 add_event_to_ctx(event, ctx);
2926 raw_spin_unlock_irq(&ctx->lock);
2930 * Cross CPU call to enable a performance event
2932 static void __perf_event_enable(struct perf_event *event,
2933 struct perf_cpu_context *cpuctx,
2934 struct perf_event_context *ctx,
2937 struct perf_event *leader = event->group_leader;
2938 struct perf_event_context *task_ctx;
2940 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2941 event->state <= PERF_EVENT_STATE_ERROR)
2945 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2947 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2948 perf_cgroup_event_enable(event, ctx);
2950 if (!ctx->is_active)
2953 if (!event_filter_match(event)) {
2954 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2959 * If the event is in a group and isn't the group leader,
2960 * then don't put it on unless the group is on.
2962 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2963 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2967 task_ctx = cpuctx->task_ctx;
2969 WARN_ON_ONCE(task_ctx != ctx);
2971 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2977 * If event->ctx is a cloned context, callers must make sure that
2978 * every task struct that event->ctx->task could possibly point to
2979 * remains valid. This condition is satisfied when called through
2980 * perf_event_for_each_child or perf_event_for_each as described
2981 * for perf_event_disable.
2983 static void _perf_event_enable(struct perf_event *event)
2985 struct perf_event_context *ctx = event->ctx;
2987 raw_spin_lock_irq(&ctx->lock);
2988 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2989 event->state < PERF_EVENT_STATE_ERROR) {
2991 raw_spin_unlock_irq(&ctx->lock);
2996 * If the event is in error state, clear that first.
2998 * That way, if we see the event in error state below, we know that it
2999 * has gone back into error state, as distinct from the task having
3000 * been scheduled away before the cross-call arrived.
3002 if (event->state == PERF_EVENT_STATE_ERROR) {
3004 * Detached SIBLING events cannot leave ERROR state.
3006 if (event->event_caps & PERF_EV_CAP_SIBLING &&
3007 event->group_leader == event)
3010 event->state = PERF_EVENT_STATE_OFF;
3012 raw_spin_unlock_irq(&ctx->lock);
3014 event_function_call(event, __perf_event_enable, NULL);
3018 * See perf_event_disable();
3020 void perf_event_enable(struct perf_event *event)
3022 struct perf_event_context *ctx;
3024 ctx = perf_event_ctx_lock(event);
3025 _perf_event_enable(event);
3026 perf_event_ctx_unlock(event, ctx);
3028 EXPORT_SYMBOL_GPL(perf_event_enable);
3030 struct stop_event_data {
3031 struct perf_event *event;
3032 unsigned int restart;
3035 static int __perf_event_stop(void *info)
3037 struct stop_event_data *sd = info;
3038 struct perf_event *event = sd->event;
3040 /* if it's already INACTIVE, do nothing */
3041 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3044 /* matches smp_wmb() in event_sched_in() */
3048 * There is a window with interrupts enabled before we get here,
3049 * so we need to check again lest we try to stop another CPU's event.
3051 if (READ_ONCE(event->oncpu) != smp_processor_id())
3054 event->pmu->stop(event, PERF_EF_UPDATE);
3057 * May race with the actual stop (through perf_pmu_output_stop()),
3058 * but it is only used for events with AUX ring buffer, and such
3059 * events will refuse to restart because of rb::aux_mmap_count==0,
3060 * see comments in perf_aux_output_begin().
3062 * Since this is happening on an event-local CPU, no trace is lost
3066 event->pmu->start(event, 0);
3071 static int perf_event_stop(struct perf_event *event, int restart)
3073 struct stop_event_data sd = {
3080 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3083 /* matches smp_wmb() in event_sched_in() */
3087 * We only want to restart ACTIVE events, so if the event goes
3088 * inactive here (event->oncpu==-1), there's nothing more to do;
3089 * fall through with ret==-ENXIO.
3091 ret = cpu_function_call(READ_ONCE(event->oncpu),
3092 __perf_event_stop, &sd);
3093 } while (ret == -EAGAIN);
3099 * In order to contain the amount of racy and tricky in the address filter
3100 * configuration management, it is a two part process:
3102 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3103 * we update the addresses of corresponding vmas in
3104 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3105 * (p2) when an event is scheduled in (pmu::add), it calls
3106 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3107 * if the generation has changed since the previous call.
3109 * If (p1) happens while the event is active, we restart it to force (p2).
3111 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3112 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3114 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3115 * registered mapping, called for every new mmap(), with mm::mmap_lock down
3117 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3120 void perf_event_addr_filters_sync(struct perf_event *event)
3122 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3124 if (!has_addr_filter(event))
3127 raw_spin_lock(&ifh->lock);
3128 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3129 event->pmu->addr_filters_sync(event);
3130 event->hw.addr_filters_gen = event->addr_filters_gen;
3132 raw_spin_unlock(&ifh->lock);
3134 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3136 static int _perf_event_refresh(struct perf_event *event, int refresh)
3139 * not supported on inherited events
3141 if (event->attr.inherit || !is_sampling_event(event))
3144 atomic_add(refresh, &event->event_limit);
3145 _perf_event_enable(event);
3151 * See perf_event_disable()
3153 int perf_event_refresh(struct perf_event *event, int refresh)
3155 struct perf_event_context *ctx;
3158 ctx = perf_event_ctx_lock(event);
3159 ret = _perf_event_refresh(event, refresh);
3160 perf_event_ctx_unlock(event, ctx);
3164 EXPORT_SYMBOL_GPL(perf_event_refresh);
3166 static int perf_event_modify_breakpoint(struct perf_event *bp,
3167 struct perf_event_attr *attr)
3171 _perf_event_disable(bp);
3173 err = modify_user_hw_breakpoint_check(bp, attr, true);
3175 if (!bp->attr.disabled)
3176 _perf_event_enable(bp);
3181 static int perf_event_modify_attr(struct perf_event *event,
3182 struct perf_event_attr *attr)
3184 if (event->attr.type != attr->type)
3187 switch (event->attr.type) {
3188 case PERF_TYPE_BREAKPOINT:
3189 return perf_event_modify_breakpoint(event, attr);
3191 /* Place holder for future additions. */
3196 static void ctx_sched_out(struct perf_event_context *ctx,
3197 struct perf_cpu_context *cpuctx,
3198 enum event_type_t event_type)
3200 struct perf_event *event, *tmp;
3201 int is_active = ctx->is_active;
3203 lockdep_assert_held(&ctx->lock);
3205 if (likely(!ctx->nr_events)) {
3207 * See __perf_remove_from_context().
3209 WARN_ON_ONCE(ctx->is_active);
3211 WARN_ON_ONCE(cpuctx->task_ctx);
3215 ctx->is_active &= ~event_type;
3216 if (!(ctx->is_active & EVENT_ALL))
3220 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3221 if (!ctx->is_active)
3222 cpuctx->task_ctx = NULL;
3226 * Always update time if it was set; not only when it changes.
3227 * Otherwise we can 'forget' to update time for any but the last
3228 * context we sched out. For example:
3230 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3231 * ctx_sched_out(.event_type = EVENT_PINNED)
3233 * would only update time for the pinned events.
3235 if (is_active & EVENT_TIME) {
3236 /* update (and stop) ctx time */
3237 update_context_time(ctx);
3238 update_cgrp_time_from_cpuctx(cpuctx);
3241 is_active ^= ctx->is_active; /* changed bits */
3243 if (!ctx->nr_active || !(is_active & EVENT_ALL))
3246 perf_pmu_disable(ctx->pmu);
3247 if (is_active & EVENT_PINNED) {
3248 list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list)
3249 group_sched_out(event, cpuctx, ctx);
3252 if (is_active & EVENT_FLEXIBLE) {
3253 list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list)
3254 group_sched_out(event, cpuctx, ctx);
3257 * Since we cleared EVENT_FLEXIBLE, also clear
3258 * rotate_necessary, is will be reset by
3259 * ctx_flexible_sched_in() when needed.
3261 ctx->rotate_necessary = 0;
3263 perf_pmu_enable(ctx->pmu);
3267 * Test whether two contexts are equivalent, i.e. whether they have both been
3268 * cloned from the same version of the same context.
3270 * Equivalence is measured using a generation number in the context that is
3271 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3272 * and list_del_event().
3274 static int context_equiv(struct perf_event_context *ctx1,
3275 struct perf_event_context *ctx2)
3277 lockdep_assert_held(&ctx1->lock);
3278 lockdep_assert_held(&ctx2->lock);
3280 /* Pinning disables the swap optimization */
3281 if (ctx1->pin_count || ctx2->pin_count)
3284 /* If ctx1 is the parent of ctx2 */
3285 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3288 /* If ctx2 is the parent of ctx1 */
3289 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3293 * If ctx1 and ctx2 have the same parent; we flatten the parent
3294 * hierarchy, see perf_event_init_context().
3296 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3297 ctx1->parent_gen == ctx2->parent_gen)
3304 static void __perf_event_sync_stat(struct perf_event *event,
3305 struct perf_event *next_event)
3309 if (!event->attr.inherit_stat)
3313 * Update the event value, we cannot use perf_event_read()
3314 * because we're in the middle of a context switch and have IRQs
3315 * disabled, which upsets smp_call_function_single(), however
3316 * we know the event must be on the current CPU, therefore we
3317 * don't need to use it.
3319 if (event->state == PERF_EVENT_STATE_ACTIVE)
3320 event->pmu->read(event);
3322 perf_event_update_time(event);
3325 * In order to keep per-task stats reliable we need to flip the event
3326 * values when we flip the contexts.
3328 value = local64_read(&next_event->count);
3329 value = local64_xchg(&event->count, value);
3330 local64_set(&next_event->count, value);
3332 swap(event->total_time_enabled, next_event->total_time_enabled);
3333 swap(event->total_time_running, next_event->total_time_running);
3336 * Since we swizzled the values, update the user visible data too.
3338 perf_event_update_userpage(event);
3339 perf_event_update_userpage(next_event);
3342 static void perf_event_sync_stat(struct perf_event_context *ctx,
3343 struct perf_event_context *next_ctx)
3345 struct perf_event *event, *next_event;
3350 update_context_time(ctx);
3352 event = list_first_entry(&ctx->event_list,
3353 struct perf_event, event_entry);
3355 next_event = list_first_entry(&next_ctx->event_list,
3356 struct perf_event, event_entry);
3358 while (&event->event_entry != &ctx->event_list &&
3359 &next_event->event_entry != &next_ctx->event_list) {
3361 __perf_event_sync_stat(event, next_event);
3363 event = list_next_entry(event, event_entry);
3364 next_event = list_next_entry(next_event, event_entry);
3368 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
3369 struct task_struct *next)
3371 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
3372 struct perf_event_context *next_ctx;
3373 struct perf_event_context *parent, *next_parent;
3374 struct perf_cpu_context *cpuctx;
3382 cpuctx = __get_cpu_context(ctx);
3383 if (!cpuctx->task_ctx)
3387 next_ctx = next->perf_event_ctxp[ctxn];
3391 parent = rcu_dereference(ctx->parent_ctx);
3392 next_parent = rcu_dereference(next_ctx->parent_ctx);
3394 /* If neither context have a parent context; they cannot be clones. */
3395 if (!parent && !next_parent)
3398 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3400 * Looks like the two contexts are clones, so we might be
3401 * able to optimize the context switch. We lock both
3402 * contexts and check that they are clones under the
3403 * lock (including re-checking that neither has been
3404 * uncloned in the meantime). It doesn't matter which
3405 * order we take the locks because no other cpu could
3406 * be trying to lock both of these tasks.
3408 raw_spin_lock(&ctx->lock);
3409 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3410 if (context_equiv(ctx, next_ctx)) {
3412 WRITE_ONCE(ctx->task, next);
3413 WRITE_ONCE(next_ctx->task, task);
3415 perf_pmu_disable(pmu);
3417 if (cpuctx->sched_cb_usage && pmu->sched_task)
3418 pmu->sched_task(ctx, false);
3421 * PMU specific parts of task perf context can require
3422 * additional synchronization. As an example of such
3423 * synchronization see implementation details of Intel
3424 * LBR call stack data profiling;
3426 if (pmu->swap_task_ctx)
3427 pmu->swap_task_ctx(ctx, next_ctx);
3429 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
3431 perf_pmu_enable(pmu);
3434 * RCU_INIT_POINTER here is safe because we've not
3435 * modified the ctx and the above modification of
3436 * ctx->task and ctx->task_ctx_data are immaterial
3437 * since those values are always verified under
3438 * ctx->lock which we're now holding.
3440 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
3441 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
3445 perf_event_sync_stat(ctx, next_ctx);
3447 raw_spin_unlock(&next_ctx->lock);
3448 raw_spin_unlock(&ctx->lock);
3454 raw_spin_lock(&ctx->lock);
3455 perf_pmu_disable(pmu);
3457 if (cpuctx->sched_cb_usage && pmu->sched_task)
3458 pmu->sched_task(ctx, false);
3459 task_ctx_sched_out(cpuctx, ctx, EVENT_ALL);
3461 perf_pmu_enable(pmu);
3462 raw_spin_unlock(&ctx->lock);
3466 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3468 void perf_sched_cb_dec(struct pmu *pmu)
3470 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3472 this_cpu_dec(perf_sched_cb_usages);
3474 if (!--cpuctx->sched_cb_usage)
3475 list_del(&cpuctx->sched_cb_entry);
3479 void perf_sched_cb_inc(struct pmu *pmu)
3481 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3483 if (!cpuctx->sched_cb_usage++)
3484 list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3486 this_cpu_inc(perf_sched_cb_usages);
3490 * This function provides the context switch callback to the lower code
3491 * layer. It is invoked ONLY when the context switch callback is enabled.
3493 * This callback is relevant even to per-cpu events; for example multi event
3494 * PEBS requires this to provide PID/TID information. This requires we flush
3495 * all queued PEBS records before we context switch to a new task.
3497 static void __perf_pmu_sched_task(struct perf_cpu_context *cpuctx, bool sched_in)
3501 pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */
3503 if (WARN_ON_ONCE(!pmu->sched_task))
3506 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3507 perf_pmu_disable(pmu);
3509 pmu->sched_task(cpuctx->task_ctx, sched_in);
3511 perf_pmu_enable(pmu);
3512 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3515 static void perf_pmu_sched_task(struct task_struct *prev,
3516 struct task_struct *next,
3519 struct perf_cpu_context *cpuctx;
3524 list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
3525 /* will be handled in perf_event_context_sched_in/out */
3526 if (cpuctx->task_ctx)
3529 __perf_pmu_sched_task(cpuctx, sched_in);
3533 static void perf_event_switch(struct task_struct *task,
3534 struct task_struct *next_prev, bool sched_in);
3536 #define for_each_task_context_nr(ctxn) \
3537 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
3540 * Called from scheduler to remove the events of the current task,
3541 * with interrupts disabled.
3543 * We stop each event and update the event value in event->count.
3545 * This does not protect us against NMI, but disable()
3546 * sets the disabled bit in the control field of event _before_
3547 * accessing the event control register. If a NMI hits, then it will
3548 * not restart the event.
3550 void __perf_event_task_sched_out(struct task_struct *task,
3551 struct task_struct *next)
3555 if (__this_cpu_read(perf_sched_cb_usages))
3556 perf_pmu_sched_task(task, next, false);
3558 if (atomic_read(&nr_switch_events))
3559 perf_event_switch(task, next, false);
3561 for_each_task_context_nr(ctxn)
3562 perf_event_context_sched_out(task, ctxn, next);
3565 * if cgroup events exist on this CPU, then we need
3566 * to check if we have to switch out PMU state.
3567 * cgroup event are system-wide mode only
3569 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3570 perf_cgroup_sched_out(task, next);
3574 * Called with IRQs disabled
3576 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3577 enum event_type_t event_type)
3579 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
3582 static bool perf_less_group_idx(const void *l, const void *r)
3584 const struct perf_event *le = *(const struct perf_event **)l;
3585 const struct perf_event *re = *(const struct perf_event **)r;
3587 return le->group_index < re->group_index;
3590 static void swap_ptr(void *l, void *r)
3592 void **lp = l, **rp = r;
3597 static const struct min_heap_callbacks perf_min_heap = {
3598 .elem_size = sizeof(struct perf_event *),
3599 .less = perf_less_group_idx,
3603 static void __heap_add(struct min_heap *heap, struct perf_event *event)
3605 struct perf_event **itrs = heap->data;
3608 itrs[heap->nr] = event;
3613 static noinline int visit_groups_merge(struct perf_cpu_context *cpuctx,
3614 struct perf_event_groups *groups, int cpu,
3615 int (*func)(struct perf_event *, void *),
3618 #ifdef CONFIG_CGROUP_PERF
3619 struct cgroup_subsys_state *css = NULL;
3621 /* Space for per CPU and/or any CPU event iterators. */
3622 struct perf_event *itrs[2];
3623 struct min_heap event_heap;
3624 struct perf_event **evt;
3628 event_heap = (struct min_heap){
3629 .data = cpuctx->heap,
3631 .size = cpuctx->heap_size,
3634 lockdep_assert_held(&cpuctx->ctx.lock);
3636 #ifdef CONFIG_CGROUP_PERF
3638 css = &cpuctx->cgrp->css;
3641 event_heap = (struct min_heap){
3644 .size = ARRAY_SIZE(itrs),
3646 /* Events not within a CPU context may be on any CPU. */
3647 __heap_add(&event_heap, perf_event_groups_first(groups, -1, NULL));
3649 evt = event_heap.data;
3651 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, NULL));
3653 #ifdef CONFIG_CGROUP_PERF
3654 for (; css; css = css->parent)
3655 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, css->cgroup));
3658 min_heapify_all(&event_heap, &perf_min_heap);
3660 while (event_heap.nr) {
3661 ret = func(*evt, data);
3665 *evt = perf_event_groups_next(*evt);
3667 min_heapify(&event_heap, 0, &perf_min_heap);
3669 min_heap_pop(&event_heap, &perf_min_heap);
3675 static int merge_sched_in(struct perf_event *event, void *data)
3677 struct perf_event_context *ctx = event->ctx;
3678 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3679 int *can_add_hw = data;
3681 if (event->state <= PERF_EVENT_STATE_OFF)
3684 if (!event_filter_match(event))
3687 if (group_can_go_on(event, cpuctx, *can_add_hw)) {
3688 if (!group_sched_in(event, cpuctx, ctx))
3689 list_add_tail(&event->active_list, get_event_list(event));
3692 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3693 if (event->attr.pinned) {
3694 perf_cgroup_event_disable(event, ctx);
3695 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3699 ctx->rotate_necessary = 1;
3700 perf_mux_hrtimer_restart(cpuctx);
3707 ctx_pinned_sched_in(struct perf_event_context *ctx,
3708 struct perf_cpu_context *cpuctx)
3712 if (ctx != &cpuctx->ctx)
3715 visit_groups_merge(cpuctx, &ctx->pinned_groups,
3717 merge_sched_in, &can_add_hw);
3721 ctx_flexible_sched_in(struct perf_event_context *ctx,
3722 struct perf_cpu_context *cpuctx)
3726 if (ctx != &cpuctx->ctx)
3729 visit_groups_merge(cpuctx, &ctx->flexible_groups,
3731 merge_sched_in, &can_add_hw);
3735 ctx_sched_in(struct perf_event_context *ctx,
3736 struct perf_cpu_context *cpuctx,
3737 enum event_type_t event_type,
3738 struct task_struct *task)
3740 int is_active = ctx->is_active;
3743 lockdep_assert_held(&ctx->lock);
3745 if (likely(!ctx->nr_events))
3748 ctx->is_active |= (event_type | EVENT_TIME);
3751 cpuctx->task_ctx = ctx;
3753 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3756 is_active ^= ctx->is_active; /* changed bits */
3758 if (is_active & EVENT_TIME) {
3759 /* start ctx time */
3761 ctx->timestamp = now;
3762 perf_cgroup_set_timestamp(task, ctx);
3766 * First go through the list and put on any pinned groups
3767 * in order to give them the best chance of going on.
3769 if (is_active & EVENT_PINNED)
3770 ctx_pinned_sched_in(ctx, cpuctx);
3772 /* Then walk through the lower prio flexible groups */
3773 if (is_active & EVENT_FLEXIBLE)
3774 ctx_flexible_sched_in(ctx, cpuctx);
3777 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3778 enum event_type_t event_type,
3779 struct task_struct *task)
3781 struct perf_event_context *ctx = &cpuctx->ctx;
3783 ctx_sched_in(ctx, cpuctx, event_type, task);
3786 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3787 struct task_struct *task)
3789 struct perf_cpu_context *cpuctx;
3790 struct pmu *pmu = ctx->pmu;
3792 cpuctx = __get_cpu_context(ctx);
3793 if (cpuctx->task_ctx == ctx) {
3794 if (cpuctx->sched_cb_usage)
3795 __perf_pmu_sched_task(cpuctx, true);
3799 perf_ctx_lock(cpuctx, ctx);
3801 * We must check ctx->nr_events while holding ctx->lock, such
3802 * that we serialize against perf_install_in_context().
3804 if (!ctx->nr_events)
3807 perf_pmu_disable(pmu);
3809 * We want to keep the following priority order:
3810 * cpu pinned (that don't need to move), task pinned,
3811 * cpu flexible, task flexible.
3813 * However, if task's ctx is not carrying any pinned
3814 * events, no need to flip the cpuctx's events around.
3816 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3817 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3818 perf_event_sched_in(cpuctx, ctx, task);
3820 if (cpuctx->sched_cb_usage && pmu->sched_task)
3821 pmu->sched_task(cpuctx->task_ctx, true);
3823 perf_pmu_enable(pmu);
3826 perf_ctx_unlock(cpuctx, ctx);
3830 * Called from scheduler to add the events of the current task
3831 * with interrupts disabled.
3833 * We restore the event value and then enable it.
3835 * This does not protect us against NMI, but enable()
3836 * sets the enabled bit in the control field of event _before_
3837 * accessing the event control register. If a NMI hits, then it will
3838 * keep the event running.
3840 void __perf_event_task_sched_in(struct task_struct *prev,
3841 struct task_struct *task)
3843 struct perf_event_context *ctx;
3847 * If cgroup events exist on this CPU, then we need to check if we have
3848 * to switch in PMU state; cgroup event are system-wide mode only.
3850 * Since cgroup events are CPU events, we must schedule these in before
3851 * we schedule in the task events.
3853 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3854 perf_cgroup_sched_in(prev, task);
3856 for_each_task_context_nr(ctxn) {
3857 ctx = task->perf_event_ctxp[ctxn];
3861 perf_event_context_sched_in(ctx, task);
3864 if (atomic_read(&nr_switch_events))
3865 perf_event_switch(task, prev, true);
3867 if (__this_cpu_read(perf_sched_cb_usages))
3868 perf_pmu_sched_task(prev, task, true);
3871 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3873 u64 frequency = event->attr.sample_freq;
3874 u64 sec = NSEC_PER_SEC;
3875 u64 divisor, dividend;
3877 int count_fls, nsec_fls, frequency_fls, sec_fls;
3879 count_fls = fls64(count);
3880 nsec_fls = fls64(nsec);
3881 frequency_fls = fls64(frequency);
3885 * We got @count in @nsec, with a target of sample_freq HZ
3886 * the target period becomes:
3889 * period = -------------------
3890 * @nsec * sample_freq
3895 * Reduce accuracy by one bit such that @a and @b converge
3896 * to a similar magnitude.
3898 #define REDUCE_FLS(a, b) \
3900 if (a##_fls > b##_fls) { \
3910 * Reduce accuracy until either term fits in a u64, then proceed with
3911 * the other, so that finally we can do a u64/u64 division.
3913 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3914 REDUCE_FLS(nsec, frequency);
3915 REDUCE_FLS(sec, count);
3918 if (count_fls + sec_fls > 64) {
3919 divisor = nsec * frequency;
3921 while (count_fls + sec_fls > 64) {
3922 REDUCE_FLS(count, sec);
3926 dividend = count * sec;
3928 dividend = count * sec;
3930 while (nsec_fls + frequency_fls > 64) {
3931 REDUCE_FLS(nsec, frequency);
3935 divisor = nsec * frequency;
3941 return div64_u64(dividend, divisor);
3944 static DEFINE_PER_CPU(int, perf_throttled_count);
3945 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3947 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3949 struct hw_perf_event *hwc = &event->hw;
3950 s64 period, sample_period;
3953 period = perf_calculate_period(event, nsec, count);
3955 delta = (s64)(period - hwc->sample_period);
3956 delta = (delta + 7) / 8; /* low pass filter */
3958 sample_period = hwc->sample_period + delta;
3963 hwc->sample_period = sample_period;
3965 if (local64_read(&hwc->period_left) > 8*sample_period) {
3967 event->pmu->stop(event, PERF_EF_UPDATE);
3969 local64_set(&hwc->period_left, 0);
3972 event->pmu->start(event, PERF_EF_RELOAD);
3977 * combine freq adjustment with unthrottling to avoid two passes over the
3978 * events. At the same time, make sure, having freq events does not change
3979 * the rate of unthrottling as that would introduce bias.
3981 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3984 struct perf_event *event;
3985 struct hw_perf_event *hwc;
3986 u64 now, period = TICK_NSEC;
3990 * only need to iterate over all events iff:
3991 * - context have events in frequency mode (needs freq adjust)
3992 * - there are events to unthrottle on this cpu
3994 if (!(ctx->nr_freq || needs_unthr))
3997 raw_spin_lock(&ctx->lock);
3998 perf_pmu_disable(ctx->pmu);
4000 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4001 if (event->state != PERF_EVENT_STATE_ACTIVE)
4004 if (!event_filter_match(event))
4007 perf_pmu_disable(event->pmu);
4011 if (hwc->interrupts == MAX_INTERRUPTS) {
4012 hwc->interrupts = 0;
4013 perf_log_throttle(event, 1);
4014 event->pmu->start(event, 0);
4017 if (!event->attr.freq || !event->attr.sample_freq)
4021 * stop the event and update event->count
4023 event->pmu->stop(event, PERF_EF_UPDATE);
4025 now = local64_read(&event->count);
4026 delta = now - hwc->freq_count_stamp;
4027 hwc->freq_count_stamp = now;
4031 * reload only if value has changed
4032 * we have stopped the event so tell that
4033 * to perf_adjust_period() to avoid stopping it
4037 perf_adjust_period(event, period, delta, false);
4039 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
4041 perf_pmu_enable(event->pmu);
4044 perf_pmu_enable(ctx->pmu);
4045 raw_spin_unlock(&ctx->lock);
4049 * Move @event to the tail of the @ctx's elegible events.
4051 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4054 * Rotate the first entry last of non-pinned groups. Rotation might be
4055 * disabled by the inheritance code.
4057 if (ctx->rotate_disable)
4060 perf_event_groups_delete(&ctx->flexible_groups, event);
4061 perf_event_groups_insert(&ctx->flexible_groups, event);
4064 /* pick an event from the flexible_groups to rotate */
4065 static inline struct perf_event *
4066 ctx_event_to_rotate(struct perf_event_context *ctx)
4068 struct perf_event *event;
4070 /* pick the first active flexible event */
4071 event = list_first_entry_or_null(&ctx->flexible_active,
4072 struct perf_event, active_list);
4074 /* if no active flexible event, pick the first event */
4076 event = rb_entry_safe(rb_first(&ctx->flexible_groups.tree),
4077 typeof(*event), group_node);
4081 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4082 * finds there are unschedulable events, it will set it again.
4084 ctx->rotate_necessary = 0;
4089 static bool perf_rotate_context(struct perf_cpu_context *cpuctx)
4091 struct perf_event *cpu_event = NULL, *task_event = NULL;
4092 struct perf_event_context *task_ctx = NULL;
4093 int cpu_rotate, task_rotate;
4096 * Since we run this from IRQ context, nobody can install new
4097 * events, thus the event count values are stable.
4100 cpu_rotate = cpuctx->ctx.rotate_necessary;
4101 task_ctx = cpuctx->task_ctx;
4102 task_rotate = task_ctx ? task_ctx->rotate_necessary : 0;
4104 if (!(cpu_rotate || task_rotate))
4107 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4108 perf_pmu_disable(cpuctx->ctx.pmu);
4111 task_event = ctx_event_to_rotate(task_ctx);
4113 cpu_event = ctx_event_to_rotate(&cpuctx->ctx);
4116 * As per the order given at ctx_resched() first 'pop' task flexible
4117 * and then, if needed CPU flexible.
4119 if (task_event || (task_ctx && cpu_event))
4120 ctx_sched_out(task_ctx, cpuctx, EVENT_FLEXIBLE);
4122 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
4125 rotate_ctx(task_ctx, task_event);
4127 rotate_ctx(&cpuctx->ctx, cpu_event);
4129 perf_event_sched_in(cpuctx, task_ctx, current);
4131 perf_pmu_enable(cpuctx->ctx.pmu);
4132 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4137 void perf_event_task_tick(void)
4139 struct list_head *head = this_cpu_ptr(&active_ctx_list);
4140 struct perf_event_context *ctx, *tmp;
4143 lockdep_assert_irqs_disabled();
4145 __this_cpu_inc(perf_throttled_seq);
4146 throttled = __this_cpu_xchg(perf_throttled_count, 0);
4147 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4149 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
4150 perf_adjust_freq_unthr_context(ctx, throttled);
4153 static int event_enable_on_exec(struct perf_event *event,
4154 struct perf_event_context *ctx)
4156 if (!event->attr.enable_on_exec)
4159 event->attr.enable_on_exec = 0;
4160 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4163 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4169 * Enable all of a task's events that have been marked enable-on-exec.
4170 * This expects task == current.
4172 static void perf_event_enable_on_exec(int ctxn)
4174 struct perf_event_context *ctx, *clone_ctx = NULL;
4175 enum event_type_t event_type = 0;
4176 struct perf_cpu_context *cpuctx;
4177 struct perf_event *event;
4178 unsigned long flags;
4181 local_irq_save(flags);
4182 ctx = current->perf_event_ctxp[ctxn];
4183 if (!ctx || !ctx->nr_events)
4186 cpuctx = __get_cpu_context(ctx);
4187 perf_ctx_lock(cpuctx, ctx);
4188 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
4189 list_for_each_entry(event, &ctx->event_list, event_entry) {
4190 enabled |= event_enable_on_exec(event, ctx);
4191 event_type |= get_event_type(event);
4195 * Unclone and reschedule this context if we enabled any event.
4198 clone_ctx = unclone_ctx(ctx);
4199 ctx_resched(cpuctx, ctx, event_type);
4201 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
4203 perf_ctx_unlock(cpuctx, ctx);
4206 local_irq_restore(flags);
4212 struct perf_read_data {
4213 struct perf_event *event;
4218 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4220 u16 local_pkg, event_pkg;
4222 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4223 int local_cpu = smp_processor_id();
4225 event_pkg = topology_physical_package_id(event_cpu);
4226 local_pkg = topology_physical_package_id(local_cpu);
4228 if (event_pkg == local_pkg)
4236 * Cross CPU call to read the hardware event
4238 static void __perf_event_read(void *info)
4240 struct perf_read_data *data = info;
4241 struct perf_event *sub, *event = data->event;
4242 struct perf_event_context *ctx = event->ctx;
4243 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
4244 struct pmu *pmu = event->pmu;
4247 * If this is a task context, we need to check whether it is
4248 * the current task context of this cpu. If not it has been
4249 * scheduled out before the smp call arrived. In that case
4250 * event->count would have been updated to a recent sample
4251 * when the event was scheduled out.
4253 if (ctx->task && cpuctx->task_ctx != ctx)
4256 raw_spin_lock(&ctx->lock);
4257 if (ctx->is_active & EVENT_TIME) {
4258 update_context_time(ctx);
4259 update_cgrp_time_from_event(event);
4262 perf_event_update_time(event);
4264 perf_event_update_sibling_time(event);
4266 if (event->state != PERF_EVENT_STATE_ACTIVE)
4275 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4279 for_each_sibling_event(sub, event) {
4280 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4282 * Use sibling's PMU rather than @event's since
4283 * sibling could be on different (eg: software) PMU.
4285 sub->pmu->read(sub);
4289 data->ret = pmu->commit_txn(pmu);
4292 raw_spin_unlock(&ctx->lock);
4295 static inline u64 perf_event_count(struct perf_event *event)
4297 return local64_read(&event->count) + atomic64_read(&event->child_count);
4301 * NMI-safe method to read a local event, that is an event that
4303 * - either for the current task, or for this CPU
4304 * - does not have inherit set, for inherited task events
4305 * will not be local and we cannot read them atomically
4306 * - must not have a pmu::count method
4308 int perf_event_read_local(struct perf_event *event, u64 *value,
4309 u64 *enabled, u64 *running)
4311 unsigned long flags;
4315 * Disabling interrupts avoids all counter scheduling (context
4316 * switches, timer based rotation and IPIs).
4318 local_irq_save(flags);
4321 * It must not be an event with inherit set, we cannot read
4322 * all child counters from atomic context.
4324 if (event->attr.inherit) {
4329 /* If this is a per-task event, it must be for current */
4330 if ((event->attach_state & PERF_ATTACH_TASK) &&
4331 event->hw.target != current) {
4336 /* If this is a per-CPU event, it must be for this CPU */
4337 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4338 event->cpu != smp_processor_id()) {
4343 /* If this is a pinned event it must be running on this CPU */
4344 if (event->attr.pinned && event->oncpu != smp_processor_id()) {
4350 * If the event is currently on this CPU, its either a per-task event,
4351 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4354 if (event->oncpu == smp_processor_id())
4355 event->pmu->read(event);
4357 *value = local64_read(&event->count);
4358 if (enabled || running) {
4359 u64 now = event->shadow_ctx_time + perf_clock();
4360 u64 __enabled, __running;
4362 __perf_update_times(event, now, &__enabled, &__running);
4364 *enabled = __enabled;
4366 *running = __running;
4369 local_irq_restore(flags);
4374 static int perf_event_read(struct perf_event *event, bool group)
4376 enum perf_event_state state = READ_ONCE(event->state);
4377 int event_cpu, ret = 0;
4380 * If event is enabled and currently active on a CPU, update the
4381 * value in the event structure:
4384 if (state == PERF_EVENT_STATE_ACTIVE) {
4385 struct perf_read_data data;
4388 * Orders the ->state and ->oncpu loads such that if we see
4389 * ACTIVE we must also see the right ->oncpu.
4391 * Matches the smp_wmb() from event_sched_in().
4395 event_cpu = READ_ONCE(event->oncpu);
4396 if ((unsigned)event_cpu >= nr_cpu_ids)
4399 data = (struct perf_read_data){
4406 event_cpu = __perf_event_read_cpu(event, event_cpu);
4409 * Purposely ignore the smp_call_function_single() return
4412 * If event_cpu isn't a valid CPU it means the event got
4413 * scheduled out and that will have updated the event count.
4415 * Therefore, either way, we'll have an up-to-date event count
4418 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4422 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4423 struct perf_event_context *ctx = event->ctx;
4424 unsigned long flags;
4426 raw_spin_lock_irqsave(&ctx->lock, flags);
4427 state = event->state;
4428 if (state != PERF_EVENT_STATE_INACTIVE) {
4429 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4434 * May read while context is not active (e.g., thread is
4435 * blocked), in that case we cannot update context time
4437 if (ctx->is_active & EVENT_TIME) {
4438 update_context_time(ctx);
4439 update_cgrp_time_from_event(event);
4442 perf_event_update_time(event);
4444 perf_event_update_sibling_time(event);
4445 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4452 * Initialize the perf_event context in a task_struct:
4454 static void __perf_event_init_context(struct perf_event_context *ctx)
4456 raw_spin_lock_init(&ctx->lock);
4457 mutex_init(&ctx->mutex);
4458 INIT_LIST_HEAD(&ctx->active_ctx_list);
4459 perf_event_groups_init(&ctx->pinned_groups);
4460 perf_event_groups_init(&ctx->flexible_groups);
4461 INIT_LIST_HEAD(&ctx->event_list);
4462 INIT_LIST_HEAD(&ctx->pinned_active);
4463 INIT_LIST_HEAD(&ctx->flexible_active);
4464 refcount_set(&ctx->refcount, 1);
4467 static struct perf_event_context *
4468 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
4470 struct perf_event_context *ctx;
4472 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4476 __perf_event_init_context(ctx);
4478 ctx->task = get_task_struct(task);
4484 static struct task_struct *
4485 find_lively_task_by_vpid(pid_t vpid)
4487 struct task_struct *task;
4493 task = find_task_by_vpid(vpid);
4495 get_task_struct(task);
4499 return ERR_PTR(-ESRCH);
4505 * Returns a matching context with refcount and pincount.
4507 static struct perf_event_context *
4508 find_get_context(struct pmu *pmu, struct task_struct *task,
4509 struct perf_event *event)
4511 struct perf_event_context *ctx, *clone_ctx = NULL;
4512 struct perf_cpu_context *cpuctx;
4513 void *task_ctx_data = NULL;
4514 unsigned long flags;
4516 int cpu = event->cpu;
4519 /* Must be root to operate on a CPU event: */
4520 err = perf_allow_cpu(&event->attr);
4522 return ERR_PTR(err);
4524 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
4533 ctxn = pmu->task_ctx_nr;
4537 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4538 task_ctx_data = alloc_task_ctx_data(pmu);
4539 if (!task_ctx_data) {
4546 ctx = perf_lock_task_context(task, ctxn, &flags);
4548 clone_ctx = unclone_ctx(ctx);
4551 if (task_ctx_data && !ctx->task_ctx_data) {
4552 ctx->task_ctx_data = task_ctx_data;
4553 task_ctx_data = NULL;
4555 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4560 ctx = alloc_perf_context(pmu, task);
4565 if (task_ctx_data) {
4566 ctx->task_ctx_data = task_ctx_data;
4567 task_ctx_data = NULL;
4571 mutex_lock(&task->perf_event_mutex);
4573 * If it has already passed perf_event_exit_task().
4574 * we must see PF_EXITING, it takes this mutex too.
4576 if (task->flags & PF_EXITING)
4578 else if (task->perf_event_ctxp[ctxn])
4583 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
4585 mutex_unlock(&task->perf_event_mutex);
4587 if (unlikely(err)) {
4596 free_task_ctx_data(pmu, task_ctx_data);
4600 free_task_ctx_data(pmu, task_ctx_data);
4601 return ERR_PTR(err);
4604 static void perf_event_free_filter(struct perf_event *event);
4605 static void perf_event_free_bpf_prog(struct perf_event *event);
4607 static void free_event_rcu(struct rcu_head *head)
4609 struct perf_event *event;
4611 event = container_of(head, struct perf_event, rcu_head);
4613 put_pid_ns(event->ns);
4614 perf_event_free_filter(event);
4615 kmem_cache_free(perf_event_cache, event);
4618 static void ring_buffer_attach(struct perf_event *event,
4619 struct perf_buffer *rb);
4621 static void detach_sb_event(struct perf_event *event)
4623 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4625 raw_spin_lock(&pel->lock);
4626 list_del_rcu(&event->sb_list);
4627 raw_spin_unlock(&pel->lock);
4630 static bool is_sb_event(struct perf_event *event)
4632 struct perf_event_attr *attr = &event->attr;
4637 if (event->attach_state & PERF_ATTACH_TASK)
4640 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4641 attr->comm || attr->comm_exec ||
4642 attr->task || attr->ksymbol ||
4643 attr->context_switch || attr->text_poke ||
4649 static void unaccount_pmu_sb_event(struct perf_event *event)
4651 if (is_sb_event(event))
4652 detach_sb_event(event);
4655 static void unaccount_event_cpu(struct perf_event *event, int cpu)
4660 if (is_cgroup_event(event))
4661 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
4664 #ifdef CONFIG_NO_HZ_FULL
4665 static DEFINE_SPINLOCK(nr_freq_lock);
4668 static void unaccount_freq_event_nohz(void)
4670 #ifdef CONFIG_NO_HZ_FULL
4671 spin_lock(&nr_freq_lock);
4672 if (atomic_dec_and_test(&nr_freq_events))
4673 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4674 spin_unlock(&nr_freq_lock);
4678 static void unaccount_freq_event(void)
4680 if (tick_nohz_full_enabled())
4681 unaccount_freq_event_nohz();
4683 atomic_dec(&nr_freq_events);
4686 static void unaccount_event(struct perf_event *event)
4693 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
4695 if (event->attr.mmap || event->attr.mmap_data)
4696 atomic_dec(&nr_mmap_events);
4697 if (event->attr.build_id)
4698 atomic_dec(&nr_build_id_events);
4699 if (event->attr.comm)
4700 atomic_dec(&nr_comm_events);
4701 if (event->attr.namespaces)
4702 atomic_dec(&nr_namespaces_events);
4703 if (event->attr.cgroup)
4704 atomic_dec(&nr_cgroup_events);
4705 if (event->attr.task)
4706 atomic_dec(&nr_task_events);
4707 if (event->attr.freq)
4708 unaccount_freq_event();
4709 if (event->attr.context_switch) {
4711 atomic_dec(&nr_switch_events);
4713 if (is_cgroup_event(event))
4715 if (has_branch_stack(event))
4717 if (event->attr.ksymbol)
4718 atomic_dec(&nr_ksymbol_events);
4719 if (event->attr.bpf_event)
4720 atomic_dec(&nr_bpf_events);
4721 if (event->attr.text_poke)
4722 atomic_dec(&nr_text_poke_events);
4725 if (!atomic_add_unless(&perf_sched_count, -1, 1))
4726 schedule_delayed_work(&perf_sched_work, HZ);
4729 unaccount_event_cpu(event, event->cpu);
4731 unaccount_pmu_sb_event(event);
4734 static void perf_sched_delayed(struct work_struct *work)
4736 mutex_lock(&perf_sched_mutex);
4737 if (atomic_dec_and_test(&perf_sched_count))
4738 static_branch_disable(&perf_sched_events);
4739 mutex_unlock(&perf_sched_mutex);
4743 * The following implement mutual exclusion of events on "exclusive" pmus
4744 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
4745 * at a time, so we disallow creating events that might conflict, namely:
4747 * 1) cpu-wide events in the presence of per-task events,
4748 * 2) per-task events in the presence of cpu-wide events,
4749 * 3) two matching events on the same context.
4751 * The former two cases are handled in the allocation path (perf_event_alloc(),
4752 * _free_event()), the latter -- before the first perf_install_in_context().
4754 static int exclusive_event_init(struct perf_event *event)
4756 struct pmu *pmu = event->pmu;
4758 if (!is_exclusive_pmu(pmu))
4762 * Prevent co-existence of per-task and cpu-wide events on the
4763 * same exclusive pmu.
4765 * Negative pmu::exclusive_cnt means there are cpu-wide
4766 * events on this "exclusive" pmu, positive means there are
4769 * Since this is called in perf_event_alloc() path, event::ctx
4770 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4771 * to mean "per-task event", because unlike other attach states it
4772 * never gets cleared.
4774 if (event->attach_state & PERF_ATTACH_TASK) {
4775 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4778 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4785 static void exclusive_event_destroy(struct perf_event *event)
4787 struct pmu *pmu = event->pmu;
4789 if (!is_exclusive_pmu(pmu))
4792 /* see comment in exclusive_event_init() */
4793 if (event->attach_state & PERF_ATTACH_TASK)
4794 atomic_dec(&pmu->exclusive_cnt);
4796 atomic_inc(&pmu->exclusive_cnt);
4799 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4801 if ((e1->pmu == e2->pmu) &&
4802 (e1->cpu == e2->cpu ||
4809 static bool exclusive_event_installable(struct perf_event *event,
4810 struct perf_event_context *ctx)
4812 struct perf_event *iter_event;
4813 struct pmu *pmu = event->pmu;
4815 lockdep_assert_held(&ctx->mutex);
4817 if (!is_exclusive_pmu(pmu))
4820 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4821 if (exclusive_event_match(iter_event, event))
4828 static void perf_addr_filters_splice(struct perf_event *event,
4829 struct list_head *head);
4831 static void _free_event(struct perf_event *event)
4833 irq_work_sync(&event->pending);
4835 unaccount_event(event);
4837 security_perf_event_free(event);
4841 * Can happen when we close an event with re-directed output.
4843 * Since we have a 0 refcount, perf_mmap_close() will skip
4844 * over us; possibly making our ring_buffer_put() the last.
4846 mutex_lock(&event->mmap_mutex);
4847 ring_buffer_attach(event, NULL);
4848 mutex_unlock(&event->mmap_mutex);
4851 if (is_cgroup_event(event))
4852 perf_detach_cgroup(event);
4854 if (!event->parent) {
4855 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4856 put_callchain_buffers();
4859 perf_event_free_bpf_prog(event);
4860 perf_addr_filters_splice(event, NULL);
4861 kfree(event->addr_filter_ranges);
4864 event->destroy(event);
4867 * Must be after ->destroy(), due to uprobe_perf_close() using
4870 if (event->hw.target)
4871 put_task_struct(event->hw.target);
4874 * perf_event_free_task() relies on put_ctx() being 'last', in particular
4875 * all task references must be cleaned up.
4878 put_ctx(event->ctx);
4880 exclusive_event_destroy(event);
4881 module_put(event->pmu->module);
4883 call_rcu(&event->rcu_head, free_event_rcu);
4887 * Used to free events which have a known refcount of 1, such as in error paths
4888 * where the event isn't exposed yet and inherited events.
4890 static void free_event(struct perf_event *event)
4892 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
4893 "unexpected event refcount: %ld; ptr=%p\n",
4894 atomic_long_read(&event->refcount), event)) {
4895 /* leak to avoid use-after-free */
4903 * Remove user event from the owner task.
4905 static void perf_remove_from_owner(struct perf_event *event)
4907 struct task_struct *owner;
4911 * Matches the smp_store_release() in perf_event_exit_task(). If we
4912 * observe !owner it means the list deletion is complete and we can
4913 * indeed free this event, otherwise we need to serialize on
4914 * owner->perf_event_mutex.
4916 owner = READ_ONCE(event->owner);
4919 * Since delayed_put_task_struct() also drops the last
4920 * task reference we can safely take a new reference
4921 * while holding the rcu_read_lock().
4923 get_task_struct(owner);
4929 * If we're here through perf_event_exit_task() we're already
4930 * holding ctx->mutex which would be an inversion wrt. the
4931 * normal lock order.
4933 * However we can safely take this lock because its the child
4936 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
4939 * We have to re-check the event->owner field, if it is cleared
4940 * we raced with perf_event_exit_task(), acquiring the mutex
4941 * ensured they're done, and we can proceed with freeing the
4945 list_del_init(&event->owner_entry);
4946 smp_store_release(&event->owner, NULL);
4948 mutex_unlock(&owner->perf_event_mutex);
4949 put_task_struct(owner);
4953 static void put_event(struct perf_event *event)
4955 if (!atomic_long_dec_and_test(&event->refcount))
4962 * Kill an event dead; while event:refcount will preserve the event
4963 * object, it will not preserve its functionality. Once the last 'user'
4964 * gives up the object, we'll destroy the thing.
4966 int perf_event_release_kernel(struct perf_event *event)
4968 struct perf_event_context *ctx = event->ctx;
4969 struct perf_event *child, *tmp;
4970 LIST_HEAD(free_list);
4973 * If we got here through err_file: fput(event_file); we will not have
4974 * attached to a context yet.
4977 WARN_ON_ONCE(event->attach_state &
4978 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
4982 if (!is_kernel_event(event))
4983 perf_remove_from_owner(event);
4985 ctx = perf_event_ctx_lock(event);
4986 WARN_ON_ONCE(ctx->parent_ctx);
4987 perf_remove_from_context(event, DETACH_GROUP);
4989 raw_spin_lock_irq(&ctx->lock);
4991 * Mark this event as STATE_DEAD, there is no external reference to it
4994 * Anybody acquiring event->child_mutex after the below loop _must_
4995 * also see this, most importantly inherit_event() which will avoid
4996 * placing more children on the list.
4998 * Thus this guarantees that we will in fact observe and kill _ALL_
5001 event->state = PERF_EVENT_STATE_DEAD;
5002 raw_spin_unlock_irq(&ctx->lock);
5004 perf_event_ctx_unlock(event, ctx);
5007 mutex_lock(&event->child_mutex);
5008 list_for_each_entry(child, &event->child_list, child_list) {
5011 * Cannot change, child events are not migrated, see the
5012 * comment with perf_event_ctx_lock_nested().
5014 ctx = READ_ONCE(child->ctx);
5016 * Since child_mutex nests inside ctx::mutex, we must jump
5017 * through hoops. We start by grabbing a reference on the ctx.
5019 * Since the event cannot get freed while we hold the
5020 * child_mutex, the context must also exist and have a !0
5026 * Now that we have a ctx ref, we can drop child_mutex, and
5027 * acquire ctx::mutex without fear of it going away. Then we
5028 * can re-acquire child_mutex.
5030 mutex_unlock(&event->child_mutex);
5031 mutex_lock(&ctx->mutex);
5032 mutex_lock(&event->child_mutex);
5035 * Now that we hold ctx::mutex and child_mutex, revalidate our
5036 * state, if child is still the first entry, it didn't get freed
5037 * and we can continue doing so.
5039 tmp = list_first_entry_or_null(&event->child_list,
5040 struct perf_event, child_list);
5042 perf_remove_from_context(child, DETACH_GROUP);
5043 list_move(&child->child_list, &free_list);
5045 * This matches the refcount bump in inherit_event();
5046 * this can't be the last reference.
5051 mutex_unlock(&event->child_mutex);
5052 mutex_unlock(&ctx->mutex);
5056 mutex_unlock(&event->child_mutex);
5058 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
5059 void *var = &child->ctx->refcount;
5061 list_del(&child->child_list);
5065 * Wake any perf_event_free_task() waiting for this event to be
5068 smp_mb(); /* pairs with wait_var_event() */
5073 put_event(event); /* Must be the 'last' reference */
5076 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5079 * Called when the last reference to the file is gone.
5081 static int perf_release(struct inode *inode, struct file *file)
5083 perf_event_release_kernel(file->private_data);
5087 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5089 struct perf_event *child;
5095 mutex_lock(&event->child_mutex);
5097 (void)perf_event_read(event, false);
5098 total += perf_event_count(event);
5100 *enabled += event->total_time_enabled +
5101 atomic64_read(&event->child_total_time_enabled);
5102 *running += event->total_time_running +
5103 atomic64_read(&event->child_total_time_running);
5105 list_for_each_entry(child, &event->child_list, child_list) {
5106 (void)perf_event_read(child, false);
5107 total += perf_event_count(child);
5108 *enabled += child->total_time_enabled;
5109 *running += child->total_time_running;
5111 mutex_unlock(&event->child_mutex);
5116 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5118 struct perf_event_context *ctx;
5121 ctx = perf_event_ctx_lock(event);
5122 count = __perf_event_read_value(event, enabled, running);
5123 perf_event_ctx_unlock(event, ctx);
5127 EXPORT_SYMBOL_GPL(perf_event_read_value);
5129 static int __perf_read_group_add(struct perf_event *leader,
5130 u64 read_format, u64 *values)
5132 struct perf_event_context *ctx = leader->ctx;
5133 struct perf_event *sub;
5134 unsigned long flags;
5135 int n = 1; /* skip @nr */
5138 ret = perf_event_read(leader, true);
5142 raw_spin_lock_irqsave(&ctx->lock, flags);
5145 * Since we co-schedule groups, {enabled,running} times of siblings
5146 * will be identical to those of the leader, so we only publish one
5149 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5150 values[n++] += leader->total_time_enabled +
5151 atomic64_read(&leader->child_total_time_enabled);
5154 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5155 values[n++] += leader->total_time_running +
5156 atomic64_read(&leader->child_total_time_running);
5160 * Write {count,id} tuples for every sibling.
5162 values[n++] += perf_event_count(leader);
5163 if (read_format & PERF_FORMAT_ID)
5164 values[n++] = primary_event_id(leader);
5166 for_each_sibling_event(sub, leader) {
5167 values[n++] += perf_event_count(sub);
5168 if (read_format & PERF_FORMAT_ID)
5169 values[n++] = primary_event_id(sub);
5172 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5176 static int perf_read_group(struct perf_event *event,
5177 u64 read_format, char __user *buf)
5179 struct perf_event *leader = event->group_leader, *child;
5180 struct perf_event_context *ctx = leader->ctx;
5184 lockdep_assert_held(&ctx->mutex);
5186 values = kzalloc(event->read_size, GFP_KERNEL);
5190 values[0] = 1 + leader->nr_siblings;
5193 * By locking the child_mutex of the leader we effectively
5194 * lock the child list of all siblings.. XXX explain how.
5196 mutex_lock(&leader->child_mutex);
5198 ret = __perf_read_group_add(leader, read_format, values);
5202 list_for_each_entry(child, &leader->child_list, child_list) {
5203 ret = __perf_read_group_add(child, read_format, values);
5208 mutex_unlock(&leader->child_mutex);
5210 ret = event->read_size;
5211 if (copy_to_user(buf, values, event->read_size))
5216 mutex_unlock(&leader->child_mutex);
5222 static int perf_read_one(struct perf_event *event,
5223 u64 read_format, char __user *buf)
5225 u64 enabled, running;
5229 values[n++] = __perf_event_read_value(event, &enabled, &running);
5230 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5231 values[n++] = enabled;
5232 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5233 values[n++] = running;
5234 if (read_format & PERF_FORMAT_ID)
5235 values[n++] = primary_event_id(event);
5237 if (copy_to_user(buf, values, n * sizeof(u64)))
5240 return n * sizeof(u64);
5243 static bool is_event_hup(struct perf_event *event)
5247 if (event->state > PERF_EVENT_STATE_EXIT)
5250 mutex_lock(&event->child_mutex);
5251 no_children = list_empty(&event->child_list);
5252 mutex_unlock(&event->child_mutex);
5257 * Read the performance event - simple non blocking version for now
5260 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5262 u64 read_format = event->attr.read_format;
5266 * Return end-of-file for a read on an event that is in
5267 * error state (i.e. because it was pinned but it couldn't be
5268 * scheduled on to the CPU at some point).
5270 if (event->state == PERF_EVENT_STATE_ERROR)
5273 if (count < event->read_size)
5276 WARN_ON_ONCE(event->ctx->parent_ctx);
5277 if (read_format & PERF_FORMAT_GROUP)
5278 ret = perf_read_group(event, read_format, buf);
5280 ret = perf_read_one(event, read_format, buf);
5286 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5288 struct perf_event *event = file->private_data;
5289 struct perf_event_context *ctx;
5292 ret = security_perf_event_read(event);
5296 ctx = perf_event_ctx_lock(event);
5297 ret = __perf_read(event, buf, count);
5298 perf_event_ctx_unlock(event, ctx);
5303 static __poll_t perf_poll(struct file *file, poll_table *wait)
5305 struct perf_event *event = file->private_data;
5306 struct perf_buffer *rb;
5307 __poll_t events = EPOLLHUP;
5309 poll_wait(file, &event->waitq, wait);
5311 if (is_event_hup(event))
5315 * Pin the event->rb by taking event->mmap_mutex; otherwise
5316 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5318 mutex_lock(&event->mmap_mutex);
5321 events = atomic_xchg(&rb->poll, 0);
5322 mutex_unlock(&event->mmap_mutex);
5326 static void _perf_event_reset(struct perf_event *event)
5328 (void)perf_event_read(event, false);
5329 local64_set(&event->count, 0);
5330 perf_event_update_userpage(event);
5333 /* Assume it's not an event with inherit set. */
5334 u64 perf_event_pause(struct perf_event *event, bool reset)
5336 struct perf_event_context *ctx;
5339 ctx = perf_event_ctx_lock(event);
5340 WARN_ON_ONCE(event->attr.inherit);
5341 _perf_event_disable(event);
5342 count = local64_read(&event->count);
5344 local64_set(&event->count, 0);
5345 perf_event_ctx_unlock(event, ctx);
5349 EXPORT_SYMBOL_GPL(perf_event_pause);
5352 * Holding the top-level event's child_mutex means that any
5353 * descendant process that has inherited this event will block
5354 * in perf_event_exit_event() if it goes to exit, thus satisfying the
5355 * task existence requirements of perf_event_enable/disable.
5357 static void perf_event_for_each_child(struct perf_event *event,
5358 void (*func)(struct perf_event *))
5360 struct perf_event *child;
5362 WARN_ON_ONCE(event->ctx->parent_ctx);
5364 mutex_lock(&event->child_mutex);
5366 list_for_each_entry(child, &event->child_list, child_list)
5368 mutex_unlock(&event->child_mutex);
5371 static void perf_event_for_each(struct perf_event *event,
5372 void (*func)(struct perf_event *))
5374 struct perf_event_context *ctx = event->ctx;
5375 struct perf_event *sibling;
5377 lockdep_assert_held(&ctx->mutex);
5379 event = event->group_leader;
5381 perf_event_for_each_child(event, func);
5382 for_each_sibling_event(sibling, event)
5383 perf_event_for_each_child(sibling, func);
5386 static void __perf_event_period(struct perf_event *event,
5387 struct perf_cpu_context *cpuctx,
5388 struct perf_event_context *ctx,
5391 u64 value = *((u64 *)info);
5394 if (event->attr.freq) {
5395 event->attr.sample_freq = value;
5397 event->attr.sample_period = value;
5398 event->hw.sample_period = value;
5401 active = (event->state == PERF_EVENT_STATE_ACTIVE);
5403 perf_pmu_disable(ctx->pmu);
5405 * We could be throttled; unthrottle now to avoid the tick
5406 * trying to unthrottle while we already re-started the event.
5408 if (event->hw.interrupts == MAX_INTERRUPTS) {
5409 event->hw.interrupts = 0;
5410 perf_log_throttle(event, 1);
5412 event->pmu->stop(event, PERF_EF_UPDATE);
5415 local64_set(&event->hw.period_left, 0);
5418 event->pmu->start(event, PERF_EF_RELOAD);
5419 perf_pmu_enable(ctx->pmu);
5423 static int perf_event_check_period(struct perf_event *event, u64 value)
5425 return event->pmu->check_period(event, value);
5428 static int _perf_event_period(struct perf_event *event, u64 value)
5430 if (!is_sampling_event(event))
5436 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5439 if (perf_event_check_period(event, value))
5442 if (!event->attr.freq && (value & (1ULL << 63)))
5445 event_function_call(event, __perf_event_period, &value);
5450 int perf_event_period(struct perf_event *event, u64 value)
5452 struct perf_event_context *ctx;
5455 ctx = perf_event_ctx_lock(event);
5456 ret = _perf_event_period(event, value);
5457 perf_event_ctx_unlock(event, ctx);
5461 EXPORT_SYMBOL_GPL(perf_event_period);
5463 static const struct file_operations perf_fops;
5465 static inline int perf_fget_light(int fd, struct fd *p)
5467 struct fd f = fdget(fd);
5471 if (f.file->f_op != &perf_fops) {
5479 static int perf_event_set_output(struct perf_event *event,
5480 struct perf_event *output_event);
5481 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5482 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
5483 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5484 struct perf_event_attr *attr);
5486 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5488 void (*func)(struct perf_event *);
5492 case PERF_EVENT_IOC_ENABLE:
5493 func = _perf_event_enable;
5495 case PERF_EVENT_IOC_DISABLE:
5496 func = _perf_event_disable;
5498 case PERF_EVENT_IOC_RESET:
5499 func = _perf_event_reset;
5502 case PERF_EVENT_IOC_REFRESH:
5503 return _perf_event_refresh(event, arg);
5505 case PERF_EVENT_IOC_PERIOD:
5509 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
5512 return _perf_event_period(event, value);
5514 case PERF_EVENT_IOC_ID:
5516 u64 id = primary_event_id(event);
5518 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5523 case PERF_EVENT_IOC_SET_OUTPUT:
5527 struct perf_event *output_event;
5529 ret = perf_fget_light(arg, &output);
5532 output_event = output.file->private_data;
5533 ret = perf_event_set_output(event, output_event);
5536 ret = perf_event_set_output(event, NULL);
5541 case PERF_EVENT_IOC_SET_FILTER:
5542 return perf_event_set_filter(event, (void __user *)arg);
5544 case PERF_EVENT_IOC_SET_BPF:
5545 return perf_event_set_bpf_prog(event, arg);
5547 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5548 struct perf_buffer *rb;
5551 rb = rcu_dereference(event->rb);
5552 if (!rb || !rb->nr_pages) {
5556 rb_toggle_paused(rb, !!arg);
5561 case PERF_EVENT_IOC_QUERY_BPF:
5562 return perf_event_query_prog_array(event, (void __user *)arg);
5564 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5565 struct perf_event_attr new_attr;
5566 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5572 return perf_event_modify_attr(event, &new_attr);
5578 if (flags & PERF_IOC_FLAG_GROUP)
5579 perf_event_for_each(event, func);
5581 perf_event_for_each_child(event, func);
5586 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5588 struct perf_event *event = file->private_data;
5589 struct perf_event_context *ctx;
5592 /* Treat ioctl like writes as it is likely a mutating operation. */
5593 ret = security_perf_event_write(event);
5597 ctx = perf_event_ctx_lock(event);
5598 ret = _perf_ioctl(event, cmd, arg);
5599 perf_event_ctx_unlock(event, ctx);
5604 #ifdef CONFIG_COMPAT
5605 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5608 switch (_IOC_NR(cmd)) {
5609 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5610 case _IOC_NR(PERF_EVENT_IOC_ID):
5611 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5612 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
5613 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5614 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5615 cmd &= ~IOCSIZE_MASK;
5616 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5620 return perf_ioctl(file, cmd, arg);
5623 # define perf_compat_ioctl NULL
5626 int perf_event_task_enable(void)
5628 struct perf_event_context *ctx;
5629 struct perf_event *event;
5631 mutex_lock(¤t->perf_event_mutex);
5632 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5633 ctx = perf_event_ctx_lock(event);
5634 perf_event_for_each_child(event, _perf_event_enable);
5635 perf_event_ctx_unlock(event, ctx);
5637 mutex_unlock(¤t->perf_event_mutex);
5642 int perf_event_task_disable(void)
5644 struct perf_event_context *ctx;
5645 struct perf_event *event;
5647 mutex_lock(¤t->perf_event_mutex);
5648 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5649 ctx = perf_event_ctx_lock(event);
5650 perf_event_for_each_child(event, _perf_event_disable);
5651 perf_event_ctx_unlock(event, ctx);
5653 mutex_unlock(¤t->perf_event_mutex);
5658 static int perf_event_index(struct perf_event *event)
5660 if (event->hw.state & PERF_HES_STOPPED)
5663 if (event->state != PERF_EVENT_STATE_ACTIVE)
5666 return event->pmu->event_idx(event);
5669 static void calc_timer_values(struct perf_event *event,
5676 *now = perf_clock();
5677 ctx_time = event->shadow_ctx_time + *now;
5678 __perf_update_times(event, ctx_time, enabled, running);
5681 static void perf_event_init_userpage(struct perf_event *event)
5683 struct perf_event_mmap_page *userpg;
5684 struct perf_buffer *rb;
5687 rb = rcu_dereference(event->rb);
5691 userpg = rb->user_page;
5693 /* Allow new userspace to detect that bit 0 is deprecated */
5694 userpg->cap_bit0_is_deprecated = 1;
5695 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
5696 userpg->data_offset = PAGE_SIZE;
5697 userpg->data_size = perf_data_size(rb);
5703 void __weak arch_perf_update_userpage(
5704 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
5709 * Callers need to ensure there can be no nesting of this function, otherwise
5710 * the seqlock logic goes bad. We can not serialize this because the arch
5711 * code calls this from NMI context.
5713 void perf_event_update_userpage(struct perf_event *event)
5715 struct perf_event_mmap_page *userpg;
5716 struct perf_buffer *rb;
5717 u64 enabled, running, now;
5720 rb = rcu_dereference(event->rb);
5725 * compute total_time_enabled, total_time_running
5726 * based on snapshot values taken when the event
5727 * was last scheduled in.
5729 * we cannot simply called update_context_time()
5730 * because of locking issue as we can be called in
5733 calc_timer_values(event, &now, &enabled, &running);
5735 userpg = rb->user_page;
5737 * Disable preemption to guarantee consistent time stamps are stored to
5743 userpg->index = perf_event_index(event);
5744 userpg->offset = perf_event_count(event);
5746 userpg->offset -= local64_read(&event->hw.prev_count);
5748 userpg->time_enabled = enabled +
5749 atomic64_read(&event->child_total_time_enabled);
5751 userpg->time_running = running +
5752 atomic64_read(&event->child_total_time_running);
5754 arch_perf_update_userpage(event, userpg, now);
5762 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
5764 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
5766 struct perf_event *event = vmf->vma->vm_file->private_data;
5767 struct perf_buffer *rb;
5768 vm_fault_t ret = VM_FAULT_SIGBUS;
5770 if (vmf->flags & FAULT_FLAG_MKWRITE) {
5771 if (vmf->pgoff == 0)
5777 rb = rcu_dereference(event->rb);
5781 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
5784 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
5788 get_page(vmf->page);
5789 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
5790 vmf->page->index = vmf->pgoff;
5799 static void ring_buffer_attach(struct perf_event *event,
5800 struct perf_buffer *rb)
5802 struct perf_buffer *old_rb = NULL;
5803 unsigned long flags;
5807 * Should be impossible, we set this when removing
5808 * event->rb_entry and wait/clear when adding event->rb_entry.
5810 WARN_ON_ONCE(event->rcu_pending);
5813 spin_lock_irqsave(&old_rb->event_lock, flags);
5814 list_del_rcu(&event->rb_entry);
5815 spin_unlock_irqrestore(&old_rb->event_lock, flags);
5817 event->rcu_batches = get_state_synchronize_rcu();
5818 event->rcu_pending = 1;
5822 if (event->rcu_pending) {
5823 cond_synchronize_rcu(event->rcu_batches);
5824 event->rcu_pending = 0;
5827 spin_lock_irqsave(&rb->event_lock, flags);
5828 list_add_rcu(&event->rb_entry, &rb->event_list);
5829 spin_unlock_irqrestore(&rb->event_lock, flags);
5833 * Avoid racing with perf_mmap_close(AUX): stop the event
5834 * before swizzling the event::rb pointer; if it's getting
5835 * unmapped, its aux_mmap_count will be 0 and it won't
5836 * restart. See the comment in __perf_pmu_output_stop().
5838 * Data will inevitably be lost when set_output is done in
5839 * mid-air, but then again, whoever does it like this is
5840 * not in for the data anyway.
5843 perf_event_stop(event, 0);
5845 rcu_assign_pointer(event->rb, rb);
5848 ring_buffer_put(old_rb);
5850 * Since we detached before setting the new rb, so that we
5851 * could attach the new rb, we could have missed a wakeup.
5854 wake_up_all(&event->waitq);
5858 static void ring_buffer_wakeup(struct perf_event *event)
5860 struct perf_buffer *rb;
5863 rb = rcu_dereference(event->rb);
5865 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
5866 wake_up_all(&event->waitq);
5871 struct perf_buffer *ring_buffer_get(struct perf_event *event)
5873 struct perf_buffer *rb;
5876 rb = rcu_dereference(event->rb);
5878 if (!refcount_inc_not_zero(&rb->refcount))
5886 void ring_buffer_put(struct perf_buffer *rb)
5888 if (!refcount_dec_and_test(&rb->refcount))
5891 WARN_ON_ONCE(!list_empty(&rb->event_list));
5893 call_rcu(&rb->rcu_head, rb_free_rcu);
5896 static void perf_mmap_open(struct vm_area_struct *vma)
5898 struct perf_event *event = vma->vm_file->private_data;
5900 atomic_inc(&event->mmap_count);
5901 atomic_inc(&event->rb->mmap_count);
5904 atomic_inc(&event->rb->aux_mmap_count);
5906 if (event->pmu->event_mapped)
5907 event->pmu->event_mapped(event, vma->vm_mm);
5910 static void perf_pmu_output_stop(struct perf_event *event);
5913 * A buffer can be mmap()ed multiple times; either directly through the same
5914 * event, or through other events by use of perf_event_set_output().
5916 * In order to undo the VM accounting done by perf_mmap() we need to destroy
5917 * the buffer here, where we still have a VM context. This means we need
5918 * to detach all events redirecting to us.
5920 static void perf_mmap_close(struct vm_area_struct *vma)
5922 struct perf_event *event = vma->vm_file->private_data;
5923 struct perf_buffer *rb = ring_buffer_get(event);
5924 struct user_struct *mmap_user = rb->mmap_user;
5925 int mmap_locked = rb->mmap_locked;
5926 unsigned long size = perf_data_size(rb);
5927 bool detach_rest = false;
5929 if (event->pmu->event_unmapped)
5930 event->pmu->event_unmapped(event, vma->vm_mm);
5933 * rb->aux_mmap_count will always drop before rb->mmap_count and
5934 * event->mmap_count, so it is ok to use event->mmap_mutex to
5935 * serialize with perf_mmap here.
5937 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
5938 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
5940 * Stop all AUX events that are writing to this buffer,
5941 * so that we can free its AUX pages and corresponding PMU
5942 * data. Note that after rb::aux_mmap_count dropped to zero,
5943 * they won't start any more (see perf_aux_output_begin()).
5945 perf_pmu_output_stop(event);
5947 /* now it's safe to free the pages */
5948 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
5949 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
5951 /* this has to be the last one */
5953 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
5955 mutex_unlock(&event->mmap_mutex);
5958 if (atomic_dec_and_test(&rb->mmap_count))
5961 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
5964 ring_buffer_attach(event, NULL);
5965 mutex_unlock(&event->mmap_mutex);
5967 /* If there's still other mmap()s of this buffer, we're done. */
5972 * No other mmap()s, detach from all other events that might redirect
5973 * into the now unreachable buffer. Somewhat complicated by the
5974 * fact that rb::event_lock otherwise nests inside mmap_mutex.
5978 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
5979 if (!atomic_long_inc_not_zero(&event->refcount)) {
5981 * This event is en-route to free_event() which will
5982 * detach it and remove it from the list.
5988 mutex_lock(&event->mmap_mutex);
5990 * Check we didn't race with perf_event_set_output() which can
5991 * swizzle the rb from under us while we were waiting to
5992 * acquire mmap_mutex.
5994 * If we find a different rb; ignore this event, a next
5995 * iteration will no longer find it on the list. We have to
5996 * still restart the iteration to make sure we're not now
5997 * iterating the wrong list.
5999 if (event->rb == rb)
6000 ring_buffer_attach(event, NULL);
6002 mutex_unlock(&event->mmap_mutex);
6006 * Restart the iteration; either we're on the wrong list or
6007 * destroyed its integrity by doing a deletion.
6014 * It could be there's still a few 0-ref events on the list; they'll
6015 * get cleaned up by free_event() -- they'll also still have their
6016 * ref on the rb and will free it whenever they are done with it.
6018 * Aside from that, this buffer is 'fully' detached and unmapped,
6019 * undo the VM accounting.
6022 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
6023 &mmap_user->locked_vm);
6024 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
6025 free_uid(mmap_user);
6028 ring_buffer_put(rb); /* could be last */
6031 static const struct vm_operations_struct perf_mmap_vmops = {
6032 .open = perf_mmap_open,
6033 .close = perf_mmap_close, /* non mergeable */
6034 .fault = perf_mmap_fault,
6035 .page_mkwrite = perf_mmap_fault,
6038 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
6040 struct perf_event *event = file->private_data;
6041 unsigned long user_locked, user_lock_limit;
6042 struct user_struct *user = current_user();
6043 struct perf_buffer *rb = NULL;
6044 unsigned long locked, lock_limit;
6045 unsigned long vma_size;
6046 unsigned long nr_pages;
6047 long user_extra = 0, extra = 0;
6048 int ret = 0, flags = 0;
6051 * Don't allow mmap() of inherited per-task counters. This would
6052 * create a performance issue due to all children writing to the
6055 if (event->cpu == -1 && event->attr.inherit)
6058 if (!(vma->vm_flags & VM_SHARED))
6061 ret = security_perf_event_read(event);
6065 vma_size = vma->vm_end - vma->vm_start;
6067 if (vma->vm_pgoff == 0) {
6068 nr_pages = (vma_size / PAGE_SIZE) - 1;
6071 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
6072 * mapped, all subsequent mappings should have the same size
6073 * and offset. Must be above the normal perf buffer.
6075 u64 aux_offset, aux_size;
6080 nr_pages = vma_size / PAGE_SIZE;
6082 mutex_lock(&event->mmap_mutex);
6089 aux_offset = READ_ONCE(rb->user_page->aux_offset);
6090 aux_size = READ_ONCE(rb->user_page->aux_size);
6092 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6095 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6098 /* already mapped with a different offset */
6099 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6102 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6105 /* already mapped with a different size */
6106 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6109 if (!is_power_of_2(nr_pages))
6112 if (!atomic_inc_not_zero(&rb->mmap_count))
6115 if (rb_has_aux(rb)) {
6116 atomic_inc(&rb->aux_mmap_count);
6121 atomic_set(&rb->aux_mmap_count, 1);
6122 user_extra = nr_pages;
6128 * If we have rb pages ensure they're a power-of-two number, so we
6129 * can do bitmasks instead of modulo.
6131 if (nr_pages != 0 && !is_power_of_2(nr_pages))
6134 if (vma_size != PAGE_SIZE * (1 + nr_pages))
6137 WARN_ON_ONCE(event->ctx->parent_ctx);
6139 mutex_lock(&event->mmap_mutex);
6141 if (event->rb->nr_pages != nr_pages) {
6146 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6148 * Raced against perf_mmap_close() through
6149 * perf_event_set_output(). Try again, hope for better
6152 mutex_unlock(&event->mmap_mutex);
6159 user_extra = nr_pages + 1;
6162 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6165 * Increase the limit linearly with more CPUs:
6167 user_lock_limit *= num_online_cpus();
6169 user_locked = atomic_long_read(&user->locked_vm);
6172 * sysctl_perf_event_mlock may have changed, so that
6173 * user->locked_vm > user_lock_limit
6175 if (user_locked > user_lock_limit)
6176 user_locked = user_lock_limit;
6177 user_locked += user_extra;
6179 if (user_locked > user_lock_limit) {
6181 * charge locked_vm until it hits user_lock_limit;
6182 * charge the rest from pinned_vm
6184 extra = user_locked - user_lock_limit;
6185 user_extra -= extra;
6188 lock_limit = rlimit(RLIMIT_MEMLOCK);
6189 lock_limit >>= PAGE_SHIFT;
6190 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
6192 if ((locked > lock_limit) && perf_is_paranoid() &&
6193 !capable(CAP_IPC_LOCK)) {
6198 WARN_ON(!rb && event->rb);
6200 if (vma->vm_flags & VM_WRITE)
6201 flags |= RING_BUFFER_WRITABLE;
6204 rb = rb_alloc(nr_pages,
6205 event->attr.watermark ? event->attr.wakeup_watermark : 0,
6213 atomic_set(&rb->mmap_count, 1);
6214 rb->mmap_user = get_current_user();
6215 rb->mmap_locked = extra;
6217 ring_buffer_attach(event, rb);
6219 perf_event_init_userpage(event);
6220 perf_event_update_userpage(event);
6222 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6223 event->attr.aux_watermark, flags);
6225 rb->aux_mmap_locked = extra;
6230 atomic_long_add(user_extra, &user->locked_vm);
6231 atomic64_add(extra, &vma->vm_mm->pinned_vm);
6233 atomic_inc(&event->mmap_count);
6235 atomic_dec(&rb->mmap_count);
6238 mutex_unlock(&event->mmap_mutex);
6241 * Since pinned accounting is per vm we cannot allow fork() to copy our
6244 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
6245 vma->vm_ops = &perf_mmap_vmops;
6247 if (event->pmu->event_mapped)
6248 event->pmu->event_mapped(event, vma->vm_mm);
6253 static int perf_fasync(int fd, struct file *filp, int on)
6255 struct inode *inode = file_inode(filp);
6256 struct perf_event *event = filp->private_data;
6260 retval = fasync_helper(fd, filp, on, &event->fasync);
6261 inode_unlock(inode);
6269 static const struct file_operations perf_fops = {
6270 .llseek = no_llseek,
6271 .release = perf_release,
6274 .unlocked_ioctl = perf_ioctl,
6275 .compat_ioctl = perf_compat_ioctl,
6277 .fasync = perf_fasync,
6283 * If there's data, ensure we set the poll() state and publish everything
6284 * to user-space before waking everybody up.
6287 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
6289 /* only the parent has fasync state */
6291 event = event->parent;
6292 return &event->fasync;
6295 void perf_event_wakeup(struct perf_event *event)
6297 ring_buffer_wakeup(event);
6299 if (event->pending_kill) {
6300 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6301 event->pending_kill = 0;
6305 static void perf_pending_event_disable(struct perf_event *event)
6307 int cpu = READ_ONCE(event->pending_disable);
6312 if (cpu == smp_processor_id()) {
6313 WRITE_ONCE(event->pending_disable, -1);
6314 perf_event_disable_local(event);
6321 * perf_event_disable_inatomic()
6322 * @pending_disable = CPU-A;
6326 * @pending_disable = -1;
6329 * perf_event_disable_inatomic()
6330 * @pending_disable = CPU-B;
6331 * irq_work_queue(); // FAILS
6334 * perf_pending_event()
6336 * But the event runs on CPU-B and wants disabling there.
6338 irq_work_queue_on(&event->pending, cpu);
6341 static void perf_pending_event(struct irq_work *entry)
6343 struct perf_event *event = container_of(entry, struct perf_event, pending);
6346 rctx = perf_swevent_get_recursion_context();
6348 * If we 'fail' here, that's OK, it means recursion is already disabled
6349 * and we won't recurse 'further'.
6352 perf_pending_event_disable(event);
6354 if (event->pending_wakeup) {
6355 event->pending_wakeup = 0;
6356 perf_event_wakeup(event);
6360 perf_swevent_put_recursion_context(rctx);
6364 * We assume there is only KVM supporting the callbacks.
6365 * Later on, we might change it to a list if there is
6366 * another virtualization implementation supporting the callbacks.
6368 struct perf_guest_info_callbacks *perf_guest_cbs;
6370 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6372 perf_guest_cbs = cbs;
6375 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6377 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6379 perf_guest_cbs = NULL;
6382 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6385 perf_output_sample_regs(struct perf_output_handle *handle,
6386 struct pt_regs *regs, u64 mask)
6389 DECLARE_BITMAP(_mask, 64);
6391 bitmap_from_u64(_mask, mask);
6392 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
6395 val = perf_reg_value(regs, bit);
6396 perf_output_put(handle, val);
6400 static void perf_sample_regs_user(struct perf_regs *regs_user,
6401 struct pt_regs *regs)
6403 if (user_mode(regs)) {
6404 regs_user->abi = perf_reg_abi(current);
6405 regs_user->regs = regs;
6406 } else if (!(current->flags & PF_KTHREAD)) {
6407 perf_get_regs_user(regs_user, regs);
6409 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6410 regs_user->regs = NULL;
6414 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6415 struct pt_regs *regs)
6417 regs_intr->regs = regs;
6418 regs_intr->abi = perf_reg_abi(current);
6423 * Get remaining task size from user stack pointer.
6425 * It'd be better to take stack vma map and limit this more
6426 * precisely, but there's no way to get it safely under interrupt,
6427 * so using TASK_SIZE as limit.
6429 static u64 perf_ustack_task_size(struct pt_regs *regs)
6431 unsigned long addr = perf_user_stack_pointer(regs);
6433 if (!addr || addr >= TASK_SIZE)
6436 return TASK_SIZE - addr;
6440 perf_sample_ustack_size(u16 stack_size, u16 header_size,
6441 struct pt_regs *regs)
6445 /* No regs, no stack pointer, no dump. */
6450 * Check if we fit in with the requested stack size into the:
6452 * If we don't, we limit the size to the TASK_SIZE.
6454 * - remaining sample size
6455 * If we don't, we customize the stack size to
6456 * fit in to the remaining sample size.
6459 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6460 stack_size = min(stack_size, (u16) task_size);
6462 /* Current header size plus static size and dynamic size. */
6463 header_size += 2 * sizeof(u64);
6465 /* Do we fit in with the current stack dump size? */
6466 if ((u16) (header_size + stack_size) < header_size) {
6468 * If we overflow the maximum size for the sample,
6469 * we customize the stack dump size to fit in.
6471 stack_size = USHRT_MAX - header_size - sizeof(u64);
6472 stack_size = round_up(stack_size, sizeof(u64));
6479 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6480 struct pt_regs *regs)
6482 /* Case of a kernel thread, nothing to dump */
6485 perf_output_put(handle, size);
6495 * - the size requested by user or the best one we can fit
6496 * in to the sample max size
6498 * - user stack dump data
6500 * - the actual dumped size
6504 perf_output_put(handle, dump_size);
6507 sp = perf_user_stack_pointer(regs);
6508 fs = force_uaccess_begin();
6509 rem = __output_copy_user(handle, (void *) sp, dump_size);
6510 force_uaccess_end(fs);
6511 dyn_size = dump_size - rem;
6513 perf_output_skip(handle, rem);
6516 perf_output_put(handle, dyn_size);
6520 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
6521 struct perf_sample_data *data,
6524 struct perf_event *sampler = event->aux_event;
6525 struct perf_buffer *rb;
6532 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
6535 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
6538 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6543 * If this is an NMI hit inside sampling code, don't take
6544 * the sample. See also perf_aux_sample_output().
6546 if (READ_ONCE(rb->aux_in_sampling)) {
6549 size = min_t(size_t, size, perf_aux_size(rb));
6550 data->aux_size = ALIGN(size, sizeof(u64));
6552 ring_buffer_put(rb);
6555 return data->aux_size;
6558 long perf_pmu_snapshot_aux(struct perf_buffer *rb,
6559 struct perf_event *event,
6560 struct perf_output_handle *handle,
6563 unsigned long flags;
6567 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
6568 * paths. If we start calling them in NMI context, they may race with
6569 * the IRQ ones, that is, for example, re-starting an event that's just
6570 * been stopped, which is why we're using a separate callback that
6571 * doesn't change the event state.
6573 * IRQs need to be disabled to prevent IPIs from racing with us.
6575 local_irq_save(flags);
6577 * Guard against NMI hits inside the critical section;
6578 * see also perf_prepare_sample_aux().
6580 WRITE_ONCE(rb->aux_in_sampling, 1);
6583 ret = event->pmu->snapshot_aux(event, handle, size);
6586 WRITE_ONCE(rb->aux_in_sampling, 0);
6587 local_irq_restore(flags);
6592 static void perf_aux_sample_output(struct perf_event *event,
6593 struct perf_output_handle *handle,
6594 struct perf_sample_data *data)
6596 struct perf_event *sampler = event->aux_event;
6597 struct perf_buffer *rb;
6601 if (WARN_ON_ONCE(!sampler || !data->aux_size))
6604 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6608 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
6611 * An error here means that perf_output_copy() failed (returned a
6612 * non-zero surplus that it didn't copy), which in its current
6613 * enlightened implementation is not possible. If that changes, we'd
6616 if (WARN_ON_ONCE(size < 0))
6620 * The pad comes from ALIGN()ing data->aux_size up to u64 in
6621 * perf_prepare_sample_aux(), so should not be more than that.
6623 pad = data->aux_size - size;
6624 if (WARN_ON_ONCE(pad >= sizeof(u64)))
6629 perf_output_copy(handle, &zero, pad);
6633 ring_buffer_put(rb);
6636 static void __perf_event_header__init_id(struct perf_event_header *header,
6637 struct perf_sample_data *data,
6638 struct perf_event *event)
6640 u64 sample_type = event->attr.sample_type;
6642 data->type = sample_type;
6643 header->size += event->id_header_size;
6645 if (sample_type & PERF_SAMPLE_TID) {
6646 /* namespace issues */
6647 data->tid_entry.pid = perf_event_pid(event, current);
6648 data->tid_entry.tid = perf_event_tid(event, current);
6651 if (sample_type & PERF_SAMPLE_TIME)
6652 data->time = perf_event_clock(event);
6654 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
6655 data->id = primary_event_id(event);
6657 if (sample_type & PERF_SAMPLE_STREAM_ID)
6658 data->stream_id = event->id;
6660 if (sample_type & PERF_SAMPLE_CPU) {
6661 data->cpu_entry.cpu = raw_smp_processor_id();
6662 data->cpu_entry.reserved = 0;
6666 void perf_event_header__init_id(struct perf_event_header *header,
6667 struct perf_sample_data *data,
6668 struct perf_event *event)
6670 if (event->attr.sample_id_all)
6671 __perf_event_header__init_id(header, data, event);
6674 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
6675 struct perf_sample_data *data)
6677 u64 sample_type = data->type;
6679 if (sample_type & PERF_SAMPLE_TID)
6680 perf_output_put(handle, data->tid_entry);
6682 if (sample_type & PERF_SAMPLE_TIME)
6683 perf_output_put(handle, data->time);
6685 if (sample_type & PERF_SAMPLE_ID)
6686 perf_output_put(handle, data->id);
6688 if (sample_type & PERF_SAMPLE_STREAM_ID)
6689 perf_output_put(handle, data->stream_id);
6691 if (sample_type & PERF_SAMPLE_CPU)
6692 perf_output_put(handle, data->cpu_entry);
6694 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6695 perf_output_put(handle, data->id);
6698 void perf_event__output_id_sample(struct perf_event *event,
6699 struct perf_output_handle *handle,
6700 struct perf_sample_data *sample)
6702 if (event->attr.sample_id_all)
6703 __perf_event__output_id_sample(handle, sample);
6706 static void perf_output_read_one(struct perf_output_handle *handle,
6707 struct perf_event *event,
6708 u64 enabled, u64 running)
6710 u64 read_format = event->attr.read_format;
6714 values[n++] = perf_event_count(event);
6715 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
6716 values[n++] = enabled +
6717 atomic64_read(&event->child_total_time_enabled);
6719 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
6720 values[n++] = running +
6721 atomic64_read(&event->child_total_time_running);
6723 if (read_format & PERF_FORMAT_ID)
6724 values[n++] = primary_event_id(event);
6726 __output_copy(handle, values, n * sizeof(u64));
6729 static void perf_output_read_group(struct perf_output_handle *handle,
6730 struct perf_event *event,
6731 u64 enabled, u64 running)
6733 struct perf_event *leader = event->group_leader, *sub;
6734 u64 read_format = event->attr.read_format;
6738 values[n++] = 1 + leader->nr_siblings;
6740 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6741 values[n++] = enabled;
6743 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6744 values[n++] = running;
6746 if ((leader != event) &&
6747 (leader->state == PERF_EVENT_STATE_ACTIVE))
6748 leader->pmu->read(leader);
6750 values[n++] = perf_event_count(leader);
6751 if (read_format & PERF_FORMAT_ID)
6752 values[n++] = primary_event_id(leader);
6754 __output_copy(handle, values, n * sizeof(u64));
6756 for_each_sibling_event(sub, leader) {
6759 if ((sub != event) &&
6760 (sub->state == PERF_EVENT_STATE_ACTIVE))
6761 sub->pmu->read(sub);
6763 values[n++] = perf_event_count(sub);
6764 if (read_format & PERF_FORMAT_ID)
6765 values[n++] = primary_event_id(sub);
6767 __output_copy(handle, values, n * sizeof(u64));
6771 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
6772 PERF_FORMAT_TOTAL_TIME_RUNNING)
6775 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
6777 * The problem is that its both hard and excessively expensive to iterate the
6778 * child list, not to mention that its impossible to IPI the children running
6779 * on another CPU, from interrupt/NMI context.
6781 static void perf_output_read(struct perf_output_handle *handle,
6782 struct perf_event *event)
6784 u64 enabled = 0, running = 0, now;
6785 u64 read_format = event->attr.read_format;
6788 * compute total_time_enabled, total_time_running
6789 * based on snapshot values taken when the event
6790 * was last scheduled in.
6792 * we cannot simply called update_context_time()
6793 * because of locking issue as we are called in
6796 if (read_format & PERF_FORMAT_TOTAL_TIMES)
6797 calc_timer_values(event, &now, &enabled, &running);
6799 if (event->attr.read_format & PERF_FORMAT_GROUP)
6800 perf_output_read_group(handle, event, enabled, running);
6802 perf_output_read_one(handle, event, enabled, running);
6805 static inline bool perf_sample_save_hw_index(struct perf_event *event)
6807 return event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX;
6810 void perf_output_sample(struct perf_output_handle *handle,
6811 struct perf_event_header *header,
6812 struct perf_sample_data *data,
6813 struct perf_event *event)
6815 u64 sample_type = data->type;
6817 perf_output_put(handle, *header);
6819 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6820 perf_output_put(handle, data->id);
6822 if (sample_type & PERF_SAMPLE_IP)
6823 perf_output_put(handle, data->ip);
6825 if (sample_type & PERF_SAMPLE_TID)
6826 perf_output_put(handle, data->tid_entry);
6828 if (sample_type & PERF_SAMPLE_TIME)
6829 perf_output_put(handle, data->time);
6831 if (sample_type & PERF_SAMPLE_ADDR)
6832 perf_output_put(handle, data->addr);
6834 if (sample_type & PERF_SAMPLE_ID)
6835 perf_output_put(handle, data->id);
6837 if (sample_type & PERF_SAMPLE_STREAM_ID)
6838 perf_output_put(handle, data->stream_id);
6840 if (sample_type & PERF_SAMPLE_CPU)
6841 perf_output_put(handle, data->cpu_entry);
6843 if (sample_type & PERF_SAMPLE_PERIOD)
6844 perf_output_put(handle, data->period);
6846 if (sample_type & PERF_SAMPLE_READ)
6847 perf_output_read(handle, event);
6849 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
6852 size += data->callchain->nr;
6853 size *= sizeof(u64);
6854 __output_copy(handle, data->callchain, size);
6857 if (sample_type & PERF_SAMPLE_RAW) {
6858 struct perf_raw_record *raw = data->raw;
6861 struct perf_raw_frag *frag = &raw->frag;
6863 perf_output_put(handle, raw->size);
6866 __output_custom(handle, frag->copy,
6867 frag->data, frag->size);
6869 __output_copy(handle, frag->data,
6872 if (perf_raw_frag_last(frag))
6877 __output_skip(handle, NULL, frag->pad);
6883 .size = sizeof(u32),
6886 perf_output_put(handle, raw);
6890 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
6891 if (data->br_stack) {
6894 size = data->br_stack->nr
6895 * sizeof(struct perf_branch_entry);
6897 perf_output_put(handle, data->br_stack->nr);
6898 if (perf_sample_save_hw_index(event))
6899 perf_output_put(handle, data->br_stack->hw_idx);
6900 perf_output_copy(handle, data->br_stack->entries, size);
6903 * we always store at least the value of nr
6906 perf_output_put(handle, nr);
6910 if (sample_type & PERF_SAMPLE_REGS_USER) {
6911 u64 abi = data->regs_user.abi;
6914 * If there are no regs to dump, notice it through
6915 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6917 perf_output_put(handle, abi);
6920 u64 mask = event->attr.sample_regs_user;
6921 perf_output_sample_regs(handle,
6922 data->regs_user.regs,
6927 if (sample_type & PERF_SAMPLE_STACK_USER) {
6928 perf_output_sample_ustack(handle,
6929 data->stack_user_size,
6930 data->regs_user.regs);
6933 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
6934 perf_output_put(handle, data->weight.full);
6936 if (sample_type & PERF_SAMPLE_DATA_SRC)
6937 perf_output_put(handle, data->data_src.val);
6939 if (sample_type & PERF_SAMPLE_TRANSACTION)
6940 perf_output_put(handle, data->txn);
6942 if (sample_type & PERF_SAMPLE_REGS_INTR) {
6943 u64 abi = data->regs_intr.abi;
6945 * If there are no regs to dump, notice it through
6946 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6948 perf_output_put(handle, abi);
6951 u64 mask = event->attr.sample_regs_intr;
6953 perf_output_sample_regs(handle,
6954 data->regs_intr.regs,
6959 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
6960 perf_output_put(handle, data->phys_addr);
6962 if (sample_type & PERF_SAMPLE_CGROUP)
6963 perf_output_put(handle, data->cgroup);
6965 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
6966 perf_output_put(handle, data->data_page_size);
6968 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
6969 perf_output_put(handle, data->code_page_size);
6971 if (sample_type & PERF_SAMPLE_AUX) {
6972 perf_output_put(handle, data->aux_size);
6975 perf_aux_sample_output(event, handle, data);
6978 if (!event->attr.watermark) {
6979 int wakeup_events = event->attr.wakeup_events;
6981 if (wakeup_events) {
6982 struct perf_buffer *rb = handle->rb;
6983 int events = local_inc_return(&rb->events);
6985 if (events >= wakeup_events) {
6986 local_sub(wakeup_events, &rb->events);
6987 local_inc(&rb->wakeup);
6993 static u64 perf_virt_to_phys(u64 virt)
6996 struct page *p = NULL;
7001 if (virt >= TASK_SIZE) {
7002 /* If it's vmalloc()d memory, leave phys_addr as 0 */
7003 if (virt_addr_valid((void *)(uintptr_t)virt) &&
7004 !(virt >= VMALLOC_START && virt < VMALLOC_END))
7005 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
7008 * Walking the pages tables for user address.
7009 * Interrupts are disabled, so it prevents any tear down
7010 * of the page tables.
7011 * Try IRQ-safe get_user_page_fast_only first.
7012 * If failed, leave phys_addr as 0.
7014 if (current->mm != NULL) {
7015 pagefault_disable();
7016 if (get_user_page_fast_only(virt, 0, &p))
7017 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
7029 * Return the pagetable size of a given virtual address.
7031 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
7035 #ifdef CONFIG_HAVE_FAST_GUP
7042 pgdp = pgd_offset(mm, addr);
7043 pgd = READ_ONCE(*pgdp);
7048 return pgd_leaf_size(pgd);
7050 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
7051 p4d = READ_ONCE(*p4dp);
7052 if (!p4d_present(p4d))
7056 return p4d_leaf_size(p4d);
7058 pudp = pud_offset_lockless(p4dp, p4d, addr);
7059 pud = READ_ONCE(*pudp);
7060 if (!pud_present(pud))
7064 return pud_leaf_size(pud);
7066 pmdp = pmd_offset_lockless(pudp, pud, addr);
7067 pmd = READ_ONCE(*pmdp);
7068 if (!pmd_present(pmd))
7072 return pmd_leaf_size(pmd);
7074 ptep = pte_offset_map(&pmd, addr);
7075 pte = ptep_get_lockless(ptep);
7076 if (pte_present(pte))
7077 size = pte_leaf_size(pte);
7079 #endif /* CONFIG_HAVE_FAST_GUP */
7084 static u64 perf_get_page_size(unsigned long addr)
7086 struct mm_struct *mm;
7087 unsigned long flags;
7094 * Software page-table walkers must disable IRQs,
7095 * which prevents any tear down of the page tables.
7097 local_irq_save(flags);
7102 * For kernel threads and the like, use init_mm so that
7103 * we can find kernel memory.
7108 size = perf_get_pgtable_size(mm, addr);
7110 local_irq_restore(flags);
7115 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
7117 struct perf_callchain_entry *
7118 perf_callchain(struct perf_event *event, struct pt_regs *regs)
7120 bool kernel = !event->attr.exclude_callchain_kernel;
7121 bool user = !event->attr.exclude_callchain_user;
7122 /* Disallow cross-task user callchains. */
7123 bool crosstask = event->ctx->task && event->ctx->task != current;
7124 const u32 max_stack = event->attr.sample_max_stack;
7125 struct perf_callchain_entry *callchain;
7127 if (!kernel && !user)
7128 return &__empty_callchain;
7130 callchain = get_perf_callchain(regs, 0, kernel, user,
7131 max_stack, crosstask, true);
7132 return callchain ?: &__empty_callchain;
7135 void perf_prepare_sample(struct perf_event_header *header,
7136 struct perf_sample_data *data,
7137 struct perf_event *event,
7138 struct pt_regs *regs)
7140 u64 sample_type = event->attr.sample_type;
7142 header->type = PERF_RECORD_SAMPLE;
7143 header->size = sizeof(*header) + event->header_size;
7146 header->misc |= perf_misc_flags(regs);
7148 __perf_event_header__init_id(header, data, event);
7150 if (sample_type & (PERF_SAMPLE_IP | PERF_SAMPLE_CODE_PAGE_SIZE))
7151 data->ip = perf_instruction_pointer(regs);
7153 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7156 if (!(sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
7157 data->callchain = perf_callchain(event, regs);
7159 size += data->callchain->nr;
7161 header->size += size * sizeof(u64);
7164 if (sample_type & PERF_SAMPLE_RAW) {
7165 struct perf_raw_record *raw = data->raw;
7169 struct perf_raw_frag *frag = &raw->frag;
7174 if (perf_raw_frag_last(frag))
7179 size = round_up(sum + sizeof(u32), sizeof(u64));
7180 raw->size = size - sizeof(u32);
7181 frag->pad = raw->size - sum;
7186 header->size += size;
7189 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7190 int size = sizeof(u64); /* nr */
7191 if (data->br_stack) {
7192 if (perf_sample_save_hw_index(event))
7193 size += sizeof(u64);
7195 size += data->br_stack->nr
7196 * sizeof(struct perf_branch_entry);
7198 header->size += size;
7201 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
7202 perf_sample_regs_user(&data->regs_user, regs);
7204 if (sample_type & PERF_SAMPLE_REGS_USER) {
7205 /* regs dump ABI info */
7206 int size = sizeof(u64);
7208 if (data->regs_user.regs) {
7209 u64 mask = event->attr.sample_regs_user;
7210 size += hweight64(mask) * sizeof(u64);
7213 header->size += size;
7216 if (sample_type & PERF_SAMPLE_STACK_USER) {
7218 * Either we need PERF_SAMPLE_STACK_USER bit to be always
7219 * processed as the last one or have additional check added
7220 * in case new sample type is added, because we could eat
7221 * up the rest of the sample size.
7223 u16 stack_size = event->attr.sample_stack_user;
7224 u16 size = sizeof(u64);
7226 stack_size = perf_sample_ustack_size(stack_size, header->size,
7227 data->regs_user.regs);
7230 * If there is something to dump, add space for the dump
7231 * itself and for the field that tells the dynamic size,
7232 * which is how many have been actually dumped.
7235 size += sizeof(u64) + stack_size;
7237 data->stack_user_size = stack_size;
7238 header->size += size;
7241 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7242 /* regs dump ABI info */
7243 int size = sizeof(u64);
7245 perf_sample_regs_intr(&data->regs_intr, regs);
7247 if (data->regs_intr.regs) {
7248 u64 mask = event->attr.sample_regs_intr;
7250 size += hweight64(mask) * sizeof(u64);
7253 header->size += size;
7256 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7257 data->phys_addr = perf_virt_to_phys(data->addr);
7259 #ifdef CONFIG_CGROUP_PERF
7260 if (sample_type & PERF_SAMPLE_CGROUP) {
7261 struct cgroup *cgrp;
7263 /* protected by RCU */
7264 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
7265 data->cgroup = cgroup_id(cgrp);
7270 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't
7271 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr,
7272 * but the value will not dump to the userspace.
7274 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
7275 data->data_page_size = perf_get_page_size(data->addr);
7277 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
7278 data->code_page_size = perf_get_page_size(data->ip);
7280 if (sample_type & PERF_SAMPLE_AUX) {
7283 header->size += sizeof(u64); /* size */
7286 * Given the 16bit nature of header::size, an AUX sample can
7287 * easily overflow it, what with all the preceding sample bits.
7288 * Make sure this doesn't happen by using up to U16_MAX bytes
7289 * per sample in total (rounded down to 8 byte boundary).
7291 size = min_t(size_t, U16_MAX - header->size,
7292 event->attr.aux_sample_size);
7293 size = rounddown(size, 8);
7294 size = perf_prepare_sample_aux(event, data, size);
7296 WARN_ON_ONCE(size + header->size > U16_MAX);
7297 header->size += size;
7300 * If you're adding more sample types here, you likely need to do
7301 * something about the overflowing header::size, like repurpose the
7302 * lowest 3 bits of size, which should be always zero at the moment.
7303 * This raises a more important question, do we really need 512k sized
7304 * samples and why, so good argumentation is in order for whatever you
7307 WARN_ON_ONCE(header->size & 7);
7310 static __always_inline int
7311 __perf_event_output(struct perf_event *event,
7312 struct perf_sample_data *data,
7313 struct pt_regs *regs,
7314 int (*output_begin)(struct perf_output_handle *,
7315 struct perf_sample_data *,
7316 struct perf_event *,
7319 struct perf_output_handle handle;
7320 struct perf_event_header header;
7323 /* protect the callchain buffers */
7326 perf_prepare_sample(&header, data, event, regs);
7328 err = output_begin(&handle, data, event, header.size);
7332 perf_output_sample(&handle, &header, data, event);
7334 perf_output_end(&handle);
7342 perf_event_output_forward(struct perf_event *event,
7343 struct perf_sample_data *data,
7344 struct pt_regs *regs)
7346 __perf_event_output(event, data, regs, perf_output_begin_forward);
7350 perf_event_output_backward(struct perf_event *event,
7351 struct perf_sample_data *data,
7352 struct pt_regs *regs)
7354 __perf_event_output(event, data, regs, perf_output_begin_backward);
7358 perf_event_output(struct perf_event *event,
7359 struct perf_sample_data *data,
7360 struct pt_regs *regs)
7362 return __perf_event_output(event, data, regs, perf_output_begin);
7369 struct perf_read_event {
7370 struct perf_event_header header;
7377 perf_event_read_event(struct perf_event *event,
7378 struct task_struct *task)
7380 struct perf_output_handle handle;
7381 struct perf_sample_data sample;
7382 struct perf_read_event read_event = {
7384 .type = PERF_RECORD_READ,
7386 .size = sizeof(read_event) + event->read_size,
7388 .pid = perf_event_pid(event, task),
7389 .tid = perf_event_tid(event, task),
7393 perf_event_header__init_id(&read_event.header, &sample, event);
7394 ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
7398 perf_output_put(&handle, read_event);
7399 perf_output_read(&handle, event);
7400 perf_event__output_id_sample(event, &handle, &sample);
7402 perf_output_end(&handle);
7405 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
7408 perf_iterate_ctx(struct perf_event_context *ctx,
7409 perf_iterate_f output,
7410 void *data, bool all)
7412 struct perf_event *event;
7414 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7416 if (event->state < PERF_EVENT_STATE_INACTIVE)
7418 if (!event_filter_match(event))
7422 output(event, data);
7426 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
7428 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
7429 struct perf_event *event;
7431 list_for_each_entry_rcu(event, &pel->list, sb_list) {
7433 * Skip events that are not fully formed yet; ensure that
7434 * if we observe event->ctx, both event and ctx will be
7435 * complete enough. See perf_install_in_context().
7437 if (!smp_load_acquire(&event->ctx))
7440 if (event->state < PERF_EVENT_STATE_INACTIVE)
7442 if (!event_filter_match(event))
7444 output(event, data);
7449 * Iterate all events that need to receive side-band events.
7451 * For new callers; ensure that account_pmu_sb_event() includes
7452 * your event, otherwise it might not get delivered.
7455 perf_iterate_sb(perf_iterate_f output, void *data,
7456 struct perf_event_context *task_ctx)
7458 struct perf_event_context *ctx;
7465 * If we have task_ctx != NULL we only notify the task context itself.
7466 * The task_ctx is set only for EXIT events before releasing task
7470 perf_iterate_ctx(task_ctx, output, data, false);
7474 perf_iterate_sb_cpu(output, data);
7476 for_each_task_context_nr(ctxn) {
7477 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7479 perf_iterate_ctx(ctx, output, data, false);
7487 * Clear all file-based filters at exec, they'll have to be
7488 * re-instated when/if these objects are mmapped again.
7490 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
7492 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7493 struct perf_addr_filter *filter;
7494 unsigned int restart = 0, count = 0;
7495 unsigned long flags;
7497 if (!has_addr_filter(event))
7500 raw_spin_lock_irqsave(&ifh->lock, flags);
7501 list_for_each_entry(filter, &ifh->list, entry) {
7502 if (filter->path.dentry) {
7503 event->addr_filter_ranges[count].start = 0;
7504 event->addr_filter_ranges[count].size = 0;
7512 event->addr_filters_gen++;
7513 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7516 perf_event_stop(event, 1);
7519 void perf_event_exec(void)
7521 struct perf_event_context *ctx;
7525 for_each_task_context_nr(ctxn) {
7526 ctx = current->perf_event_ctxp[ctxn];
7530 perf_event_enable_on_exec(ctxn);
7532 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
7538 struct remote_output {
7539 struct perf_buffer *rb;
7543 static void __perf_event_output_stop(struct perf_event *event, void *data)
7545 struct perf_event *parent = event->parent;
7546 struct remote_output *ro = data;
7547 struct perf_buffer *rb = ro->rb;
7548 struct stop_event_data sd = {
7552 if (!has_aux(event))
7559 * In case of inheritance, it will be the parent that links to the
7560 * ring-buffer, but it will be the child that's actually using it.
7562 * We are using event::rb to determine if the event should be stopped,
7563 * however this may race with ring_buffer_attach() (through set_output),
7564 * which will make us skip the event that actually needs to be stopped.
7565 * So ring_buffer_attach() has to stop an aux event before re-assigning
7568 if (rcu_dereference(parent->rb) == rb)
7569 ro->err = __perf_event_stop(&sd);
7572 static int __perf_pmu_output_stop(void *info)
7574 struct perf_event *event = info;
7575 struct pmu *pmu = event->ctx->pmu;
7576 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7577 struct remote_output ro = {
7582 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
7583 if (cpuctx->task_ctx)
7584 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
7591 static void perf_pmu_output_stop(struct perf_event *event)
7593 struct perf_event *iter;
7598 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
7600 * For per-CPU events, we need to make sure that neither they
7601 * nor their children are running; for cpu==-1 events it's
7602 * sufficient to stop the event itself if it's active, since
7603 * it can't have children.
7607 cpu = READ_ONCE(iter->oncpu);
7612 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
7613 if (err == -EAGAIN) {
7622 * task tracking -- fork/exit
7624 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
7627 struct perf_task_event {
7628 struct task_struct *task;
7629 struct perf_event_context *task_ctx;
7632 struct perf_event_header header;
7642 static int perf_event_task_match(struct perf_event *event)
7644 return event->attr.comm || event->attr.mmap ||
7645 event->attr.mmap2 || event->attr.mmap_data ||
7649 static void perf_event_task_output(struct perf_event *event,
7652 struct perf_task_event *task_event = data;
7653 struct perf_output_handle handle;
7654 struct perf_sample_data sample;
7655 struct task_struct *task = task_event->task;
7656 int ret, size = task_event->event_id.header.size;
7658 if (!perf_event_task_match(event))
7661 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
7663 ret = perf_output_begin(&handle, &sample, event,
7664 task_event->event_id.header.size);
7668 task_event->event_id.pid = perf_event_pid(event, task);
7669 task_event->event_id.tid = perf_event_tid(event, task);
7671 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
7672 task_event->event_id.ppid = perf_event_pid(event,
7674 task_event->event_id.ptid = perf_event_pid(event,
7676 } else { /* PERF_RECORD_FORK */
7677 task_event->event_id.ppid = perf_event_pid(event, current);
7678 task_event->event_id.ptid = perf_event_tid(event, current);
7681 task_event->event_id.time = perf_event_clock(event);
7683 perf_output_put(&handle, task_event->event_id);
7685 perf_event__output_id_sample(event, &handle, &sample);
7687 perf_output_end(&handle);
7689 task_event->event_id.header.size = size;
7692 static void perf_event_task(struct task_struct *task,
7693 struct perf_event_context *task_ctx,
7696 struct perf_task_event task_event;
7698 if (!atomic_read(&nr_comm_events) &&
7699 !atomic_read(&nr_mmap_events) &&
7700 !atomic_read(&nr_task_events))
7703 task_event = (struct perf_task_event){
7705 .task_ctx = task_ctx,
7708 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
7710 .size = sizeof(task_event.event_id),
7720 perf_iterate_sb(perf_event_task_output,
7725 void perf_event_fork(struct task_struct *task)
7727 perf_event_task(task, NULL, 1);
7728 perf_event_namespaces(task);
7735 struct perf_comm_event {
7736 struct task_struct *task;
7741 struct perf_event_header header;
7748 static int perf_event_comm_match(struct perf_event *event)
7750 return event->attr.comm;
7753 static void perf_event_comm_output(struct perf_event *event,
7756 struct perf_comm_event *comm_event = data;
7757 struct perf_output_handle handle;
7758 struct perf_sample_data sample;
7759 int size = comm_event->event_id.header.size;
7762 if (!perf_event_comm_match(event))
7765 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
7766 ret = perf_output_begin(&handle, &sample, event,
7767 comm_event->event_id.header.size);
7772 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
7773 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
7775 perf_output_put(&handle, comm_event->event_id);
7776 __output_copy(&handle, comm_event->comm,
7777 comm_event->comm_size);
7779 perf_event__output_id_sample(event, &handle, &sample);
7781 perf_output_end(&handle);
7783 comm_event->event_id.header.size = size;
7786 static void perf_event_comm_event(struct perf_comm_event *comm_event)
7788 char comm[TASK_COMM_LEN];
7791 memset(comm, 0, sizeof(comm));
7792 strlcpy(comm, comm_event->task->comm, sizeof(comm));
7793 size = ALIGN(strlen(comm)+1, sizeof(u64));
7795 comm_event->comm = comm;
7796 comm_event->comm_size = size;
7798 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
7800 perf_iterate_sb(perf_event_comm_output,
7805 void perf_event_comm(struct task_struct *task, bool exec)
7807 struct perf_comm_event comm_event;
7809 if (!atomic_read(&nr_comm_events))
7812 comm_event = (struct perf_comm_event){
7818 .type = PERF_RECORD_COMM,
7819 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
7827 perf_event_comm_event(&comm_event);
7831 * namespaces tracking
7834 struct perf_namespaces_event {
7835 struct task_struct *task;
7838 struct perf_event_header header;
7843 struct perf_ns_link_info link_info[NR_NAMESPACES];
7847 static int perf_event_namespaces_match(struct perf_event *event)
7849 return event->attr.namespaces;
7852 static void perf_event_namespaces_output(struct perf_event *event,
7855 struct perf_namespaces_event *namespaces_event = data;
7856 struct perf_output_handle handle;
7857 struct perf_sample_data sample;
7858 u16 header_size = namespaces_event->event_id.header.size;
7861 if (!perf_event_namespaces_match(event))
7864 perf_event_header__init_id(&namespaces_event->event_id.header,
7866 ret = perf_output_begin(&handle, &sample, event,
7867 namespaces_event->event_id.header.size);
7871 namespaces_event->event_id.pid = perf_event_pid(event,
7872 namespaces_event->task);
7873 namespaces_event->event_id.tid = perf_event_tid(event,
7874 namespaces_event->task);
7876 perf_output_put(&handle, namespaces_event->event_id);
7878 perf_event__output_id_sample(event, &handle, &sample);
7880 perf_output_end(&handle);
7882 namespaces_event->event_id.header.size = header_size;
7885 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
7886 struct task_struct *task,
7887 const struct proc_ns_operations *ns_ops)
7889 struct path ns_path;
7890 struct inode *ns_inode;
7893 error = ns_get_path(&ns_path, task, ns_ops);
7895 ns_inode = ns_path.dentry->d_inode;
7896 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
7897 ns_link_info->ino = ns_inode->i_ino;
7902 void perf_event_namespaces(struct task_struct *task)
7904 struct perf_namespaces_event namespaces_event;
7905 struct perf_ns_link_info *ns_link_info;
7907 if (!atomic_read(&nr_namespaces_events))
7910 namespaces_event = (struct perf_namespaces_event){
7914 .type = PERF_RECORD_NAMESPACES,
7916 .size = sizeof(namespaces_event.event_id),
7920 .nr_namespaces = NR_NAMESPACES,
7921 /* .link_info[NR_NAMESPACES] */
7925 ns_link_info = namespaces_event.event_id.link_info;
7927 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
7928 task, &mntns_operations);
7930 #ifdef CONFIG_USER_NS
7931 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
7932 task, &userns_operations);
7934 #ifdef CONFIG_NET_NS
7935 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
7936 task, &netns_operations);
7938 #ifdef CONFIG_UTS_NS
7939 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
7940 task, &utsns_operations);
7942 #ifdef CONFIG_IPC_NS
7943 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
7944 task, &ipcns_operations);
7946 #ifdef CONFIG_PID_NS
7947 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
7948 task, &pidns_operations);
7950 #ifdef CONFIG_CGROUPS
7951 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
7952 task, &cgroupns_operations);
7955 perf_iterate_sb(perf_event_namespaces_output,
7963 #ifdef CONFIG_CGROUP_PERF
7965 struct perf_cgroup_event {
7969 struct perf_event_header header;
7975 static int perf_event_cgroup_match(struct perf_event *event)
7977 return event->attr.cgroup;
7980 static void perf_event_cgroup_output(struct perf_event *event, void *data)
7982 struct perf_cgroup_event *cgroup_event = data;
7983 struct perf_output_handle handle;
7984 struct perf_sample_data sample;
7985 u16 header_size = cgroup_event->event_id.header.size;
7988 if (!perf_event_cgroup_match(event))
7991 perf_event_header__init_id(&cgroup_event->event_id.header,
7993 ret = perf_output_begin(&handle, &sample, event,
7994 cgroup_event->event_id.header.size);
7998 perf_output_put(&handle, cgroup_event->event_id);
7999 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
8001 perf_event__output_id_sample(event, &handle, &sample);
8003 perf_output_end(&handle);
8005 cgroup_event->event_id.header.size = header_size;
8008 static void perf_event_cgroup(struct cgroup *cgrp)
8010 struct perf_cgroup_event cgroup_event;
8011 char path_enomem[16] = "//enomem";
8015 if (!atomic_read(&nr_cgroup_events))
8018 cgroup_event = (struct perf_cgroup_event){
8021 .type = PERF_RECORD_CGROUP,
8023 .size = sizeof(cgroup_event.event_id),
8025 .id = cgroup_id(cgrp),
8029 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
8030 if (pathname == NULL) {
8031 cgroup_event.path = path_enomem;
8033 /* just to be sure to have enough space for alignment */
8034 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
8035 cgroup_event.path = pathname;
8039 * Since our buffer works in 8 byte units we need to align our string
8040 * size to a multiple of 8. However, we must guarantee the tail end is
8041 * zero'd out to avoid leaking random bits to userspace.
8043 size = strlen(cgroup_event.path) + 1;
8044 while (!IS_ALIGNED(size, sizeof(u64)))
8045 cgroup_event.path[size++] = '\0';
8047 cgroup_event.event_id.header.size += size;
8048 cgroup_event.path_size = size;
8050 perf_iterate_sb(perf_event_cgroup_output,
8063 struct perf_mmap_event {
8064 struct vm_area_struct *vma;
8066 const char *file_name;
8072 u8 build_id[BUILD_ID_SIZE_MAX];
8076 struct perf_event_header header;
8086 static int perf_event_mmap_match(struct perf_event *event,
8089 struct perf_mmap_event *mmap_event = data;
8090 struct vm_area_struct *vma = mmap_event->vma;
8091 int executable = vma->vm_flags & VM_EXEC;
8093 return (!executable && event->attr.mmap_data) ||
8094 (executable && (event->attr.mmap || event->attr.mmap2));
8097 static void perf_event_mmap_output(struct perf_event *event,
8100 struct perf_mmap_event *mmap_event = data;
8101 struct perf_output_handle handle;
8102 struct perf_sample_data sample;
8103 int size = mmap_event->event_id.header.size;
8104 u32 type = mmap_event->event_id.header.type;
8108 if (!perf_event_mmap_match(event, data))
8111 if (event->attr.mmap2) {
8112 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
8113 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
8114 mmap_event->event_id.header.size += sizeof(mmap_event->min);
8115 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
8116 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
8117 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
8118 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
8121 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
8122 ret = perf_output_begin(&handle, &sample, event,
8123 mmap_event->event_id.header.size);
8127 mmap_event->event_id.pid = perf_event_pid(event, current);
8128 mmap_event->event_id.tid = perf_event_tid(event, current);
8130 use_build_id = event->attr.build_id && mmap_event->build_id_size;
8132 if (event->attr.mmap2 && use_build_id)
8133 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
8135 perf_output_put(&handle, mmap_event->event_id);
8137 if (event->attr.mmap2) {
8139 u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 };
8141 __output_copy(&handle, size, 4);
8142 __output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX);
8144 perf_output_put(&handle, mmap_event->maj);
8145 perf_output_put(&handle, mmap_event->min);
8146 perf_output_put(&handle, mmap_event->ino);
8147 perf_output_put(&handle, mmap_event->ino_generation);
8149 perf_output_put(&handle, mmap_event->prot);
8150 perf_output_put(&handle, mmap_event->flags);
8153 __output_copy(&handle, mmap_event->file_name,
8154 mmap_event->file_size);
8156 perf_event__output_id_sample(event, &handle, &sample);
8158 perf_output_end(&handle);
8160 mmap_event->event_id.header.size = size;
8161 mmap_event->event_id.header.type = type;
8164 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
8166 struct vm_area_struct *vma = mmap_event->vma;
8167 struct file *file = vma->vm_file;
8168 int maj = 0, min = 0;
8169 u64 ino = 0, gen = 0;
8170 u32 prot = 0, flags = 0;
8176 if (vma->vm_flags & VM_READ)
8178 if (vma->vm_flags & VM_WRITE)
8180 if (vma->vm_flags & VM_EXEC)
8183 if (vma->vm_flags & VM_MAYSHARE)
8186 flags = MAP_PRIVATE;
8188 if (vma->vm_flags & VM_DENYWRITE)
8189 flags |= MAP_DENYWRITE;
8190 if (vma->vm_flags & VM_MAYEXEC)
8191 flags |= MAP_EXECUTABLE;
8192 if (vma->vm_flags & VM_LOCKED)
8193 flags |= MAP_LOCKED;
8194 if (is_vm_hugetlb_page(vma))
8195 flags |= MAP_HUGETLB;
8198 struct inode *inode;
8201 buf = kmalloc(PATH_MAX, GFP_KERNEL);
8207 * d_path() works from the end of the rb backwards, so we
8208 * need to add enough zero bytes after the string to handle
8209 * the 64bit alignment we do later.
8211 name = file_path(file, buf, PATH_MAX - sizeof(u64));
8216 inode = file_inode(vma->vm_file);
8217 dev = inode->i_sb->s_dev;
8219 gen = inode->i_generation;
8225 if (vma->vm_ops && vma->vm_ops->name) {
8226 name = (char *) vma->vm_ops->name(vma);
8231 name = (char *)arch_vma_name(vma);
8235 if (vma->vm_start <= vma->vm_mm->start_brk &&
8236 vma->vm_end >= vma->vm_mm->brk) {
8240 if (vma->vm_start <= vma->vm_mm->start_stack &&
8241 vma->vm_end >= vma->vm_mm->start_stack) {
8251 strlcpy(tmp, name, sizeof(tmp));
8255 * Since our buffer works in 8 byte units we need to align our string
8256 * size to a multiple of 8. However, we must guarantee the tail end is
8257 * zero'd out to avoid leaking random bits to userspace.
8259 size = strlen(name)+1;
8260 while (!IS_ALIGNED(size, sizeof(u64)))
8261 name[size++] = '\0';
8263 mmap_event->file_name = name;
8264 mmap_event->file_size = size;
8265 mmap_event->maj = maj;
8266 mmap_event->min = min;
8267 mmap_event->ino = ino;
8268 mmap_event->ino_generation = gen;
8269 mmap_event->prot = prot;
8270 mmap_event->flags = flags;
8272 if (!(vma->vm_flags & VM_EXEC))
8273 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
8275 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
8277 if (atomic_read(&nr_build_id_events))
8278 build_id_parse(vma, mmap_event->build_id, &mmap_event->build_id_size);
8280 perf_iterate_sb(perf_event_mmap_output,
8288 * Check whether inode and address range match filter criteria.
8290 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
8291 struct file *file, unsigned long offset,
8294 /* d_inode(NULL) won't be equal to any mapped user-space file */
8295 if (!filter->path.dentry)
8298 if (d_inode(filter->path.dentry) != file_inode(file))
8301 if (filter->offset > offset + size)
8304 if (filter->offset + filter->size < offset)
8310 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
8311 struct vm_area_struct *vma,
8312 struct perf_addr_filter_range *fr)
8314 unsigned long vma_size = vma->vm_end - vma->vm_start;
8315 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8316 struct file *file = vma->vm_file;
8318 if (!perf_addr_filter_match(filter, file, off, vma_size))
8321 if (filter->offset < off) {
8322 fr->start = vma->vm_start;
8323 fr->size = min(vma_size, filter->size - (off - filter->offset));
8325 fr->start = vma->vm_start + filter->offset - off;
8326 fr->size = min(vma->vm_end - fr->start, filter->size);
8332 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
8334 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8335 struct vm_area_struct *vma = data;
8336 struct perf_addr_filter *filter;
8337 unsigned int restart = 0, count = 0;
8338 unsigned long flags;
8340 if (!has_addr_filter(event))
8346 raw_spin_lock_irqsave(&ifh->lock, flags);
8347 list_for_each_entry(filter, &ifh->list, entry) {
8348 if (perf_addr_filter_vma_adjust(filter, vma,
8349 &event->addr_filter_ranges[count]))
8356 event->addr_filters_gen++;
8357 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8360 perf_event_stop(event, 1);
8364 * Adjust all task's events' filters to the new vma
8366 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
8368 struct perf_event_context *ctx;
8372 * Data tracing isn't supported yet and as such there is no need
8373 * to keep track of anything that isn't related to executable code:
8375 if (!(vma->vm_flags & VM_EXEC))
8379 for_each_task_context_nr(ctxn) {
8380 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
8384 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
8389 void perf_event_mmap(struct vm_area_struct *vma)
8391 struct perf_mmap_event mmap_event;
8393 if (!atomic_read(&nr_mmap_events))
8396 mmap_event = (struct perf_mmap_event){
8402 .type = PERF_RECORD_MMAP,
8403 .misc = PERF_RECORD_MISC_USER,
8408 .start = vma->vm_start,
8409 .len = vma->vm_end - vma->vm_start,
8410 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
8412 /* .maj (attr_mmap2 only) */
8413 /* .min (attr_mmap2 only) */
8414 /* .ino (attr_mmap2 only) */
8415 /* .ino_generation (attr_mmap2 only) */
8416 /* .prot (attr_mmap2 only) */
8417 /* .flags (attr_mmap2 only) */
8420 perf_addr_filters_adjust(vma);
8421 perf_event_mmap_event(&mmap_event);
8424 void perf_event_aux_event(struct perf_event *event, unsigned long head,
8425 unsigned long size, u64 flags)
8427 struct perf_output_handle handle;
8428 struct perf_sample_data sample;
8429 struct perf_aux_event {
8430 struct perf_event_header header;
8436 .type = PERF_RECORD_AUX,
8438 .size = sizeof(rec),
8446 perf_event_header__init_id(&rec.header, &sample, event);
8447 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8452 perf_output_put(&handle, rec);
8453 perf_event__output_id_sample(event, &handle, &sample);
8455 perf_output_end(&handle);
8459 * Lost/dropped samples logging
8461 void perf_log_lost_samples(struct perf_event *event, u64 lost)
8463 struct perf_output_handle handle;
8464 struct perf_sample_data sample;
8468 struct perf_event_header header;
8470 } lost_samples_event = {
8472 .type = PERF_RECORD_LOST_SAMPLES,
8474 .size = sizeof(lost_samples_event),
8479 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
8481 ret = perf_output_begin(&handle, &sample, event,
8482 lost_samples_event.header.size);
8486 perf_output_put(&handle, lost_samples_event);
8487 perf_event__output_id_sample(event, &handle, &sample);
8488 perf_output_end(&handle);
8492 * context_switch tracking
8495 struct perf_switch_event {
8496 struct task_struct *task;
8497 struct task_struct *next_prev;
8500 struct perf_event_header header;
8506 static int perf_event_switch_match(struct perf_event *event)
8508 return event->attr.context_switch;
8511 static void perf_event_switch_output(struct perf_event *event, void *data)
8513 struct perf_switch_event *se = data;
8514 struct perf_output_handle handle;
8515 struct perf_sample_data sample;
8518 if (!perf_event_switch_match(event))
8521 /* Only CPU-wide events are allowed to see next/prev pid/tid */
8522 if (event->ctx->task) {
8523 se->event_id.header.type = PERF_RECORD_SWITCH;
8524 se->event_id.header.size = sizeof(se->event_id.header);
8526 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
8527 se->event_id.header.size = sizeof(se->event_id);
8528 se->event_id.next_prev_pid =
8529 perf_event_pid(event, se->next_prev);
8530 se->event_id.next_prev_tid =
8531 perf_event_tid(event, se->next_prev);
8534 perf_event_header__init_id(&se->event_id.header, &sample, event);
8536 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
8540 if (event->ctx->task)
8541 perf_output_put(&handle, se->event_id.header);
8543 perf_output_put(&handle, se->event_id);
8545 perf_event__output_id_sample(event, &handle, &sample);
8547 perf_output_end(&handle);
8550 static void perf_event_switch(struct task_struct *task,
8551 struct task_struct *next_prev, bool sched_in)
8553 struct perf_switch_event switch_event;
8555 /* N.B. caller checks nr_switch_events != 0 */
8557 switch_event = (struct perf_switch_event){
8559 .next_prev = next_prev,
8563 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
8566 /* .next_prev_pid */
8567 /* .next_prev_tid */
8571 if (!sched_in && task->state == TASK_RUNNING)
8572 switch_event.event_id.header.misc |=
8573 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
8575 perf_iterate_sb(perf_event_switch_output,
8581 * IRQ throttle logging
8584 static void perf_log_throttle(struct perf_event *event, int enable)
8586 struct perf_output_handle handle;
8587 struct perf_sample_data sample;
8591 struct perf_event_header header;
8595 } throttle_event = {
8597 .type = PERF_RECORD_THROTTLE,
8599 .size = sizeof(throttle_event),
8601 .time = perf_event_clock(event),
8602 .id = primary_event_id(event),
8603 .stream_id = event->id,
8607 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
8609 perf_event_header__init_id(&throttle_event.header, &sample, event);
8611 ret = perf_output_begin(&handle, &sample, event,
8612 throttle_event.header.size);
8616 perf_output_put(&handle, throttle_event);
8617 perf_event__output_id_sample(event, &handle, &sample);
8618 perf_output_end(&handle);
8622 * ksymbol register/unregister tracking
8625 struct perf_ksymbol_event {
8629 struct perf_event_header header;
8637 static int perf_event_ksymbol_match(struct perf_event *event)
8639 return event->attr.ksymbol;
8642 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
8644 struct perf_ksymbol_event *ksymbol_event = data;
8645 struct perf_output_handle handle;
8646 struct perf_sample_data sample;
8649 if (!perf_event_ksymbol_match(event))
8652 perf_event_header__init_id(&ksymbol_event->event_id.header,
8654 ret = perf_output_begin(&handle, &sample, event,
8655 ksymbol_event->event_id.header.size);
8659 perf_output_put(&handle, ksymbol_event->event_id);
8660 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
8661 perf_event__output_id_sample(event, &handle, &sample);
8663 perf_output_end(&handle);
8666 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
8669 struct perf_ksymbol_event ksymbol_event;
8670 char name[KSYM_NAME_LEN];
8674 if (!atomic_read(&nr_ksymbol_events))
8677 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
8678 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
8681 strlcpy(name, sym, KSYM_NAME_LEN);
8682 name_len = strlen(name) + 1;
8683 while (!IS_ALIGNED(name_len, sizeof(u64)))
8684 name[name_len++] = '\0';
8685 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
8688 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
8690 ksymbol_event = (struct perf_ksymbol_event){
8692 .name_len = name_len,
8695 .type = PERF_RECORD_KSYMBOL,
8696 .size = sizeof(ksymbol_event.event_id) +
8701 .ksym_type = ksym_type,
8706 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
8709 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
8713 * bpf program load/unload tracking
8716 struct perf_bpf_event {
8717 struct bpf_prog *prog;
8719 struct perf_event_header header;
8723 u8 tag[BPF_TAG_SIZE];
8727 static int perf_event_bpf_match(struct perf_event *event)
8729 return event->attr.bpf_event;
8732 static void perf_event_bpf_output(struct perf_event *event, void *data)
8734 struct perf_bpf_event *bpf_event = data;
8735 struct perf_output_handle handle;
8736 struct perf_sample_data sample;
8739 if (!perf_event_bpf_match(event))
8742 perf_event_header__init_id(&bpf_event->event_id.header,
8744 ret = perf_output_begin(&handle, data, event,
8745 bpf_event->event_id.header.size);
8749 perf_output_put(&handle, bpf_event->event_id);
8750 perf_event__output_id_sample(event, &handle, &sample);
8752 perf_output_end(&handle);
8755 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
8756 enum perf_bpf_event_type type)
8758 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
8761 if (prog->aux->func_cnt == 0) {
8762 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
8763 (u64)(unsigned long)prog->bpf_func,
8764 prog->jited_len, unregister,
8765 prog->aux->ksym.name);
8767 for (i = 0; i < prog->aux->func_cnt; i++) {
8768 struct bpf_prog *subprog = prog->aux->func[i];
8771 PERF_RECORD_KSYMBOL_TYPE_BPF,
8772 (u64)(unsigned long)subprog->bpf_func,
8773 subprog->jited_len, unregister,
8774 prog->aux->ksym.name);
8779 void perf_event_bpf_event(struct bpf_prog *prog,
8780 enum perf_bpf_event_type type,
8783 struct perf_bpf_event bpf_event;
8785 if (type <= PERF_BPF_EVENT_UNKNOWN ||
8786 type >= PERF_BPF_EVENT_MAX)
8790 case PERF_BPF_EVENT_PROG_LOAD:
8791 case PERF_BPF_EVENT_PROG_UNLOAD:
8792 if (atomic_read(&nr_ksymbol_events))
8793 perf_event_bpf_emit_ksymbols(prog, type);
8799 if (!atomic_read(&nr_bpf_events))
8802 bpf_event = (struct perf_bpf_event){
8806 .type = PERF_RECORD_BPF_EVENT,
8807 .size = sizeof(bpf_event.event_id),
8811 .id = prog->aux->id,
8815 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
8817 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
8818 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
8821 struct perf_text_poke_event {
8822 const void *old_bytes;
8823 const void *new_bytes;
8829 struct perf_event_header header;
8835 static int perf_event_text_poke_match(struct perf_event *event)
8837 return event->attr.text_poke;
8840 static void perf_event_text_poke_output(struct perf_event *event, void *data)
8842 struct perf_text_poke_event *text_poke_event = data;
8843 struct perf_output_handle handle;
8844 struct perf_sample_data sample;
8848 if (!perf_event_text_poke_match(event))
8851 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
8853 ret = perf_output_begin(&handle, &sample, event,
8854 text_poke_event->event_id.header.size);
8858 perf_output_put(&handle, text_poke_event->event_id);
8859 perf_output_put(&handle, text_poke_event->old_len);
8860 perf_output_put(&handle, text_poke_event->new_len);
8862 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
8863 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
8865 if (text_poke_event->pad)
8866 __output_copy(&handle, &padding, text_poke_event->pad);
8868 perf_event__output_id_sample(event, &handle, &sample);
8870 perf_output_end(&handle);
8873 void perf_event_text_poke(const void *addr, const void *old_bytes,
8874 size_t old_len, const void *new_bytes, size_t new_len)
8876 struct perf_text_poke_event text_poke_event;
8879 if (!atomic_read(&nr_text_poke_events))
8882 tot = sizeof(text_poke_event.old_len) + old_len;
8883 tot += sizeof(text_poke_event.new_len) + new_len;
8884 pad = ALIGN(tot, sizeof(u64)) - tot;
8886 text_poke_event = (struct perf_text_poke_event){
8887 .old_bytes = old_bytes,
8888 .new_bytes = new_bytes,
8894 .type = PERF_RECORD_TEXT_POKE,
8895 .misc = PERF_RECORD_MISC_KERNEL,
8896 .size = sizeof(text_poke_event.event_id) + tot + pad,
8898 .addr = (unsigned long)addr,
8902 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
8905 void perf_event_itrace_started(struct perf_event *event)
8907 event->attach_state |= PERF_ATTACH_ITRACE;
8910 static void perf_log_itrace_start(struct perf_event *event)
8912 struct perf_output_handle handle;
8913 struct perf_sample_data sample;
8914 struct perf_aux_event {
8915 struct perf_event_header header;
8922 event = event->parent;
8924 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
8925 event->attach_state & PERF_ATTACH_ITRACE)
8928 rec.header.type = PERF_RECORD_ITRACE_START;
8929 rec.header.misc = 0;
8930 rec.header.size = sizeof(rec);
8931 rec.pid = perf_event_pid(event, current);
8932 rec.tid = perf_event_tid(event, current);
8934 perf_event_header__init_id(&rec.header, &sample, event);
8935 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8940 perf_output_put(&handle, rec);
8941 perf_event__output_id_sample(event, &handle, &sample);
8943 perf_output_end(&handle);
8947 __perf_event_account_interrupt(struct perf_event *event, int throttle)
8949 struct hw_perf_event *hwc = &event->hw;
8953 seq = __this_cpu_read(perf_throttled_seq);
8954 if (seq != hwc->interrupts_seq) {
8955 hwc->interrupts_seq = seq;
8956 hwc->interrupts = 1;
8959 if (unlikely(throttle
8960 && hwc->interrupts >= max_samples_per_tick)) {
8961 __this_cpu_inc(perf_throttled_count);
8962 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
8963 hwc->interrupts = MAX_INTERRUPTS;
8964 perf_log_throttle(event, 0);
8969 if (event->attr.freq) {
8970 u64 now = perf_clock();
8971 s64 delta = now - hwc->freq_time_stamp;
8973 hwc->freq_time_stamp = now;
8975 if (delta > 0 && delta < 2*TICK_NSEC)
8976 perf_adjust_period(event, delta, hwc->last_period, true);
8982 int perf_event_account_interrupt(struct perf_event *event)
8984 return __perf_event_account_interrupt(event, 1);
8988 * Generic event overflow handling, sampling.
8991 static int __perf_event_overflow(struct perf_event *event,
8992 int throttle, struct perf_sample_data *data,
8993 struct pt_regs *regs)
8995 int events = atomic_read(&event->event_limit);
8999 * Non-sampling counters might still use the PMI to fold short
9000 * hardware counters, ignore those.
9002 if (unlikely(!is_sampling_event(event)))
9005 ret = __perf_event_account_interrupt(event, throttle);
9008 * XXX event_limit might not quite work as expected on inherited
9012 event->pending_kill = POLL_IN;
9013 if (events && atomic_dec_and_test(&event->event_limit)) {
9015 event->pending_kill = POLL_HUP;
9017 perf_event_disable_inatomic(event);
9020 READ_ONCE(event->overflow_handler)(event, data, regs);
9022 if (*perf_event_fasync(event) && event->pending_kill) {
9023 event->pending_wakeup = 1;
9024 irq_work_queue(&event->pending);
9030 int perf_event_overflow(struct perf_event *event,
9031 struct perf_sample_data *data,
9032 struct pt_regs *regs)
9034 return __perf_event_overflow(event, 1, data, regs);
9038 * Generic software event infrastructure
9041 struct swevent_htable {
9042 struct swevent_hlist *swevent_hlist;
9043 struct mutex hlist_mutex;
9046 /* Recursion avoidance in each contexts */
9047 int recursion[PERF_NR_CONTEXTS];
9050 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
9053 * We directly increment event->count and keep a second value in
9054 * event->hw.period_left to count intervals. This period event
9055 * is kept in the range [-sample_period, 0] so that we can use the
9059 u64 perf_swevent_set_period(struct perf_event *event)
9061 struct hw_perf_event *hwc = &event->hw;
9062 u64 period = hwc->last_period;
9066 hwc->last_period = hwc->sample_period;
9069 old = val = local64_read(&hwc->period_left);
9073 nr = div64_u64(period + val, period);
9074 offset = nr * period;
9076 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
9082 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
9083 struct perf_sample_data *data,
9084 struct pt_regs *regs)
9086 struct hw_perf_event *hwc = &event->hw;
9090 overflow = perf_swevent_set_period(event);
9092 if (hwc->interrupts == MAX_INTERRUPTS)
9095 for (; overflow; overflow--) {
9096 if (__perf_event_overflow(event, throttle,
9099 * We inhibit the overflow from happening when
9100 * hwc->interrupts == MAX_INTERRUPTS.
9108 static void perf_swevent_event(struct perf_event *event, u64 nr,
9109 struct perf_sample_data *data,
9110 struct pt_regs *regs)
9112 struct hw_perf_event *hwc = &event->hw;
9114 local64_add(nr, &event->count);
9119 if (!is_sampling_event(event))
9122 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
9124 return perf_swevent_overflow(event, 1, data, regs);
9126 data->period = event->hw.last_period;
9128 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
9129 return perf_swevent_overflow(event, 1, data, regs);
9131 if (local64_add_negative(nr, &hwc->period_left))
9134 perf_swevent_overflow(event, 0, data, regs);
9137 static int perf_exclude_event(struct perf_event *event,
9138 struct pt_regs *regs)
9140 if (event->hw.state & PERF_HES_STOPPED)
9144 if (event->attr.exclude_user && user_mode(regs))
9147 if (event->attr.exclude_kernel && !user_mode(regs))
9154 static int perf_swevent_match(struct perf_event *event,
9155 enum perf_type_id type,
9157 struct perf_sample_data *data,
9158 struct pt_regs *regs)
9160 if (event->attr.type != type)
9163 if (event->attr.config != event_id)
9166 if (perf_exclude_event(event, regs))
9172 static inline u64 swevent_hash(u64 type, u32 event_id)
9174 u64 val = event_id | (type << 32);
9176 return hash_64(val, SWEVENT_HLIST_BITS);
9179 static inline struct hlist_head *
9180 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
9182 u64 hash = swevent_hash(type, event_id);
9184 return &hlist->heads[hash];
9187 /* For the read side: events when they trigger */
9188 static inline struct hlist_head *
9189 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
9191 struct swevent_hlist *hlist;
9193 hlist = rcu_dereference(swhash->swevent_hlist);
9197 return __find_swevent_head(hlist, type, event_id);
9200 /* For the event head insertion and removal in the hlist */
9201 static inline struct hlist_head *
9202 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
9204 struct swevent_hlist *hlist;
9205 u32 event_id = event->attr.config;
9206 u64 type = event->attr.type;
9209 * Event scheduling is always serialized against hlist allocation
9210 * and release. Which makes the protected version suitable here.
9211 * The context lock guarantees that.
9213 hlist = rcu_dereference_protected(swhash->swevent_hlist,
9214 lockdep_is_held(&event->ctx->lock));
9218 return __find_swevent_head(hlist, type, event_id);
9221 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
9223 struct perf_sample_data *data,
9224 struct pt_regs *regs)
9226 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9227 struct perf_event *event;
9228 struct hlist_head *head;
9231 head = find_swevent_head_rcu(swhash, type, event_id);
9235 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9236 if (perf_swevent_match(event, type, event_id, data, regs))
9237 perf_swevent_event(event, nr, data, regs);
9243 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
9245 int perf_swevent_get_recursion_context(void)
9247 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9249 return get_recursion_context(swhash->recursion);
9251 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
9253 void perf_swevent_put_recursion_context(int rctx)
9255 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9257 put_recursion_context(swhash->recursion, rctx);
9260 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9262 struct perf_sample_data data;
9264 if (WARN_ON_ONCE(!regs))
9267 perf_sample_data_init(&data, addr, 0);
9268 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
9271 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9275 preempt_disable_notrace();
9276 rctx = perf_swevent_get_recursion_context();
9277 if (unlikely(rctx < 0))
9280 ___perf_sw_event(event_id, nr, regs, addr);
9282 perf_swevent_put_recursion_context(rctx);
9284 preempt_enable_notrace();
9287 static void perf_swevent_read(struct perf_event *event)
9291 static int perf_swevent_add(struct perf_event *event, int flags)
9293 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9294 struct hw_perf_event *hwc = &event->hw;
9295 struct hlist_head *head;
9297 if (is_sampling_event(event)) {
9298 hwc->last_period = hwc->sample_period;
9299 perf_swevent_set_period(event);
9302 hwc->state = !(flags & PERF_EF_START);
9304 head = find_swevent_head(swhash, event);
9305 if (WARN_ON_ONCE(!head))
9308 hlist_add_head_rcu(&event->hlist_entry, head);
9309 perf_event_update_userpage(event);
9314 static void perf_swevent_del(struct perf_event *event, int flags)
9316 hlist_del_rcu(&event->hlist_entry);
9319 static void perf_swevent_start(struct perf_event *event, int flags)
9321 event->hw.state = 0;
9324 static void perf_swevent_stop(struct perf_event *event, int flags)
9326 event->hw.state = PERF_HES_STOPPED;
9329 /* Deref the hlist from the update side */
9330 static inline struct swevent_hlist *
9331 swevent_hlist_deref(struct swevent_htable *swhash)
9333 return rcu_dereference_protected(swhash->swevent_hlist,
9334 lockdep_is_held(&swhash->hlist_mutex));
9337 static void swevent_hlist_release(struct swevent_htable *swhash)
9339 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
9344 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
9345 kfree_rcu(hlist, rcu_head);
9348 static void swevent_hlist_put_cpu(int cpu)
9350 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9352 mutex_lock(&swhash->hlist_mutex);
9354 if (!--swhash->hlist_refcount)
9355 swevent_hlist_release(swhash);
9357 mutex_unlock(&swhash->hlist_mutex);
9360 static void swevent_hlist_put(void)
9364 for_each_possible_cpu(cpu)
9365 swevent_hlist_put_cpu(cpu);
9368 static int swevent_hlist_get_cpu(int cpu)
9370 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9373 mutex_lock(&swhash->hlist_mutex);
9374 if (!swevent_hlist_deref(swhash) &&
9375 cpumask_test_cpu(cpu, perf_online_mask)) {
9376 struct swevent_hlist *hlist;
9378 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
9383 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9385 swhash->hlist_refcount++;
9387 mutex_unlock(&swhash->hlist_mutex);
9392 static int swevent_hlist_get(void)
9394 int err, cpu, failed_cpu;
9396 mutex_lock(&pmus_lock);
9397 for_each_possible_cpu(cpu) {
9398 err = swevent_hlist_get_cpu(cpu);
9404 mutex_unlock(&pmus_lock);
9407 for_each_possible_cpu(cpu) {
9408 if (cpu == failed_cpu)
9410 swevent_hlist_put_cpu(cpu);
9412 mutex_unlock(&pmus_lock);
9416 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
9418 static void sw_perf_event_destroy(struct perf_event *event)
9420 u64 event_id = event->attr.config;
9422 WARN_ON(event->parent);
9424 static_key_slow_dec(&perf_swevent_enabled[event_id]);
9425 swevent_hlist_put();
9428 static int perf_swevent_init(struct perf_event *event)
9430 u64 event_id = event->attr.config;
9432 if (event->attr.type != PERF_TYPE_SOFTWARE)
9436 * no branch sampling for software events
9438 if (has_branch_stack(event))
9442 case PERF_COUNT_SW_CPU_CLOCK:
9443 case PERF_COUNT_SW_TASK_CLOCK:
9450 if (event_id >= PERF_COUNT_SW_MAX)
9453 if (!event->parent) {
9456 err = swevent_hlist_get();
9460 static_key_slow_inc(&perf_swevent_enabled[event_id]);
9461 event->destroy = sw_perf_event_destroy;
9467 static struct pmu perf_swevent = {
9468 .task_ctx_nr = perf_sw_context,
9470 .capabilities = PERF_PMU_CAP_NO_NMI,
9472 .event_init = perf_swevent_init,
9473 .add = perf_swevent_add,
9474 .del = perf_swevent_del,
9475 .start = perf_swevent_start,
9476 .stop = perf_swevent_stop,
9477 .read = perf_swevent_read,
9480 #ifdef CONFIG_EVENT_TRACING
9482 static int perf_tp_filter_match(struct perf_event *event,
9483 struct perf_sample_data *data)
9485 void *record = data->raw->frag.data;
9487 /* only top level events have filters set */
9489 event = event->parent;
9491 if (likely(!event->filter) || filter_match_preds(event->filter, record))
9496 static int perf_tp_event_match(struct perf_event *event,
9497 struct perf_sample_data *data,
9498 struct pt_regs *regs)
9500 if (event->hw.state & PERF_HES_STOPPED)
9503 * If exclude_kernel, only trace user-space tracepoints (uprobes)
9505 if (event->attr.exclude_kernel && !user_mode(regs))
9508 if (!perf_tp_filter_match(event, data))
9514 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
9515 struct trace_event_call *call, u64 count,
9516 struct pt_regs *regs, struct hlist_head *head,
9517 struct task_struct *task)
9519 if (bpf_prog_array_valid(call)) {
9520 *(struct pt_regs **)raw_data = regs;
9521 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
9522 perf_swevent_put_recursion_context(rctx);
9526 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
9529 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
9531 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
9532 struct pt_regs *regs, struct hlist_head *head, int rctx,
9533 struct task_struct *task)
9535 struct perf_sample_data data;
9536 struct perf_event *event;
9538 struct perf_raw_record raw = {
9545 perf_sample_data_init(&data, 0, 0);
9548 perf_trace_buf_update(record, event_type);
9550 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9551 if (perf_tp_event_match(event, &data, regs))
9552 perf_swevent_event(event, count, &data, regs);
9556 * If we got specified a target task, also iterate its context and
9557 * deliver this event there too.
9559 if (task && task != current) {
9560 struct perf_event_context *ctx;
9561 struct trace_entry *entry = record;
9564 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
9568 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
9569 if (event->cpu != smp_processor_id())
9571 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9573 if (event->attr.config != entry->type)
9575 if (perf_tp_event_match(event, &data, regs))
9576 perf_swevent_event(event, count, &data, regs);
9582 perf_swevent_put_recursion_context(rctx);
9584 EXPORT_SYMBOL_GPL(perf_tp_event);
9586 static void tp_perf_event_destroy(struct perf_event *event)
9588 perf_trace_destroy(event);
9591 static int perf_tp_event_init(struct perf_event *event)
9595 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9599 * no branch sampling for tracepoint events
9601 if (has_branch_stack(event))
9604 err = perf_trace_init(event);
9608 event->destroy = tp_perf_event_destroy;
9613 static struct pmu perf_tracepoint = {
9614 .task_ctx_nr = perf_sw_context,
9616 .event_init = perf_tp_event_init,
9617 .add = perf_trace_add,
9618 .del = perf_trace_del,
9619 .start = perf_swevent_start,
9620 .stop = perf_swevent_stop,
9621 .read = perf_swevent_read,
9624 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
9626 * Flags in config, used by dynamic PMU kprobe and uprobe
9627 * The flags should match following PMU_FORMAT_ATTR().
9629 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
9630 * if not set, create kprobe/uprobe
9632 * The following values specify a reference counter (or semaphore in the
9633 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
9634 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
9636 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
9637 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
9639 enum perf_probe_config {
9640 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
9641 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
9642 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
9645 PMU_FORMAT_ATTR(retprobe, "config:0");
9648 #ifdef CONFIG_KPROBE_EVENTS
9649 static struct attribute *kprobe_attrs[] = {
9650 &format_attr_retprobe.attr,
9654 static struct attribute_group kprobe_format_group = {
9656 .attrs = kprobe_attrs,
9659 static const struct attribute_group *kprobe_attr_groups[] = {
9660 &kprobe_format_group,
9664 static int perf_kprobe_event_init(struct perf_event *event);
9665 static struct pmu perf_kprobe = {
9666 .task_ctx_nr = perf_sw_context,
9667 .event_init = perf_kprobe_event_init,
9668 .add = perf_trace_add,
9669 .del = perf_trace_del,
9670 .start = perf_swevent_start,
9671 .stop = perf_swevent_stop,
9672 .read = perf_swevent_read,
9673 .attr_groups = kprobe_attr_groups,
9676 static int perf_kprobe_event_init(struct perf_event *event)
9681 if (event->attr.type != perf_kprobe.type)
9684 if (!perfmon_capable())
9688 * no branch sampling for probe events
9690 if (has_branch_stack(event))
9693 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9694 err = perf_kprobe_init(event, is_retprobe);
9698 event->destroy = perf_kprobe_destroy;
9702 #endif /* CONFIG_KPROBE_EVENTS */
9704 #ifdef CONFIG_UPROBE_EVENTS
9705 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
9707 static struct attribute *uprobe_attrs[] = {
9708 &format_attr_retprobe.attr,
9709 &format_attr_ref_ctr_offset.attr,
9713 static struct attribute_group uprobe_format_group = {
9715 .attrs = uprobe_attrs,
9718 static const struct attribute_group *uprobe_attr_groups[] = {
9719 &uprobe_format_group,
9723 static int perf_uprobe_event_init(struct perf_event *event);
9724 static struct pmu perf_uprobe = {
9725 .task_ctx_nr = perf_sw_context,
9726 .event_init = perf_uprobe_event_init,
9727 .add = perf_trace_add,
9728 .del = perf_trace_del,
9729 .start = perf_swevent_start,
9730 .stop = perf_swevent_stop,
9731 .read = perf_swevent_read,
9732 .attr_groups = uprobe_attr_groups,
9735 static int perf_uprobe_event_init(struct perf_event *event)
9738 unsigned long ref_ctr_offset;
9741 if (event->attr.type != perf_uprobe.type)
9744 if (!perfmon_capable())
9748 * no branch sampling for probe events
9750 if (has_branch_stack(event))
9753 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9754 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9755 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
9759 event->destroy = perf_uprobe_destroy;
9763 #endif /* CONFIG_UPROBE_EVENTS */
9765 static inline void perf_tp_register(void)
9767 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
9768 #ifdef CONFIG_KPROBE_EVENTS
9769 perf_pmu_register(&perf_kprobe, "kprobe", -1);
9771 #ifdef CONFIG_UPROBE_EVENTS
9772 perf_pmu_register(&perf_uprobe, "uprobe", -1);
9776 static void perf_event_free_filter(struct perf_event *event)
9778 ftrace_profile_free_filter(event);
9781 #ifdef CONFIG_BPF_SYSCALL
9782 static void bpf_overflow_handler(struct perf_event *event,
9783 struct perf_sample_data *data,
9784 struct pt_regs *regs)
9786 struct bpf_perf_event_data_kern ctx = {
9792 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
9793 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
9796 ret = BPF_PROG_RUN(event->prog, &ctx);
9799 __this_cpu_dec(bpf_prog_active);
9803 event->orig_overflow_handler(event, data, regs);
9806 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9808 struct bpf_prog *prog;
9810 if (event->overflow_handler_context)
9811 /* hw breakpoint or kernel counter */
9817 prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
9819 return PTR_ERR(prog);
9821 if (event->attr.precise_ip &&
9822 prog->call_get_stack &&
9823 (!(event->attr.sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY) ||
9824 event->attr.exclude_callchain_kernel ||
9825 event->attr.exclude_callchain_user)) {
9827 * On perf_event with precise_ip, calling bpf_get_stack()
9828 * may trigger unwinder warnings and occasional crashes.
9829 * bpf_get_[stack|stackid] works around this issue by using
9830 * callchain attached to perf_sample_data. If the
9831 * perf_event does not full (kernel and user) callchain
9832 * attached to perf_sample_data, do not allow attaching BPF
9833 * program that calls bpf_get_[stack|stackid].
9840 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
9841 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
9845 static void perf_event_free_bpf_handler(struct perf_event *event)
9847 struct bpf_prog *prog = event->prog;
9852 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
9857 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9861 static void perf_event_free_bpf_handler(struct perf_event *event)
9867 * returns true if the event is a tracepoint, or a kprobe/upprobe created
9868 * with perf_event_open()
9870 static inline bool perf_event_is_tracing(struct perf_event *event)
9872 if (event->pmu == &perf_tracepoint)
9874 #ifdef CONFIG_KPROBE_EVENTS
9875 if (event->pmu == &perf_kprobe)
9878 #ifdef CONFIG_UPROBE_EVENTS
9879 if (event->pmu == &perf_uprobe)
9885 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9887 bool is_kprobe, is_tracepoint, is_syscall_tp;
9888 struct bpf_prog *prog;
9891 if (!perf_event_is_tracing(event))
9892 return perf_event_set_bpf_handler(event, prog_fd);
9894 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
9895 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
9896 is_syscall_tp = is_syscall_trace_event(event->tp_event);
9897 if (!is_kprobe && !is_tracepoint && !is_syscall_tp)
9898 /* bpf programs can only be attached to u/kprobe or tracepoint */
9901 prog = bpf_prog_get(prog_fd);
9903 return PTR_ERR(prog);
9905 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
9906 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
9907 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
9908 /* valid fd, but invalid bpf program type */
9913 /* Kprobe override only works for kprobes, not uprobes. */
9914 if (prog->kprobe_override &&
9915 !(event->tp_event->flags & TRACE_EVENT_FL_KPROBE)) {
9920 if (is_tracepoint || is_syscall_tp) {
9921 int off = trace_event_get_offsets(event->tp_event);
9923 if (prog->aux->max_ctx_offset > off) {
9929 ret = perf_event_attach_bpf_prog(event, prog);
9935 static void perf_event_free_bpf_prog(struct perf_event *event)
9937 if (!perf_event_is_tracing(event)) {
9938 perf_event_free_bpf_handler(event);
9941 perf_event_detach_bpf_prog(event);
9946 static inline void perf_tp_register(void)
9950 static void perf_event_free_filter(struct perf_event *event)
9954 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9959 static void perf_event_free_bpf_prog(struct perf_event *event)
9962 #endif /* CONFIG_EVENT_TRACING */
9964 #ifdef CONFIG_HAVE_HW_BREAKPOINT
9965 void perf_bp_event(struct perf_event *bp, void *data)
9967 struct perf_sample_data sample;
9968 struct pt_regs *regs = data;
9970 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
9972 if (!bp->hw.state && !perf_exclude_event(bp, regs))
9973 perf_swevent_event(bp, 1, &sample, regs);
9978 * Allocate a new address filter
9980 static struct perf_addr_filter *
9981 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
9983 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
9984 struct perf_addr_filter *filter;
9986 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
9990 INIT_LIST_HEAD(&filter->entry);
9991 list_add_tail(&filter->entry, filters);
9996 static void free_filters_list(struct list_head *filters)
9998 struct perf_addr_filter *filter, *iter;
10000 list_for_each_entry_safe(filter, iter, filters, entry) {
10001 path_put(&filter->path);
10002 list_del(&filter->entry);
10008 * Free existing address filters and optionally install new ones
10010 static void perf_addr_filters_splice(struct perf_event *event,
10011 struct list_head *head)
10013 unsigned long flags;
10016 if (!has_addr_filter(event))
10019 /* don't bother with children, they don't have their own filters */
10023 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
10025 list_splice_init(&event->addr_filters.list, &list);
10027 list_splice(head, &event->addr_filters.list);
10029 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
10031 free_filters_list(&list);
10035 * Scan through mm's vmas and see if one of them matches the
10036 * @filter; if so, adjust filter's address range.
10037 * Called with mm::mmap_lock down for reading.
10039 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
10040 struct mm_struct *mm,
10041 struct perf_addr_filter_range *fr)
10043 struct vm_area_struct *vma;
10045 for (vma = mm->mmap; vma; vma = vma->vm_next) {
10049 if (perf_addr_filter_vma_adjust(filter, vma, fr))
10055 * Update event's address range filters based on the
10056 * task's existing mappings, if any.
10058 static void perf_event_addr_filters_apply(struct perf_event *event)
10060 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
10061 struct task_struct *task = READ_ONCE(event->ctx->task);
10062 struct perf_addr_filter *filter;
10063 struct mm_struct *mm = NULL;
10064 unsigned int count = 0;
10065 unsigned long flags;
10068 * We may observe TASK_TOMBSTONE, which means that the event tear-down
10069 * will stop on the parent's child_mutex that our caller is also holding
10071 if (task == TASK_TOMBSTONE)
10074 if (ifh->nr_file_filters) {
10075 mm = get_task_mm(event->ctx->task);
10079 mmap_read_lock(mm);
10082 raw_spin_lock_irqsave(&ifh->lock, flags);
10083 list_for_each_entry(filter, &ifh->list, entry) {
10084 if (filter->path.dentry) {
10086 * Adjust base offset if the filter is associated to a
10087 * binary that needs to be mapped:
10089 event->addr_filter_ranges[count].start = 0;
10090 event->addr_filter_ranges[count].size = 0;
10092 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
10094 event->addr_filter_ranges[count].start = filter->offset;
10095 event->addr_filter_ranges[count].size = filter->size;
10101 event->addr_filters_gen++;
10102 raw_spin_unlock_irqrestore(&ifh->lock, flags);
10104 if (ifh->nr_file_filters) {
10105 mmap_read_unlock(mm);
10111 perf_event_stop(event, 1);
10115 * Address range filtering: limiting the data to certain
10116 * instruction address ranges. Filters are ioctl()ed to us from
10117 * userspace as ascii strings.
10119 * Filter string format:
10121 * ACTION RANGE_SPEC
10122 * where ACTION is one of the
10123 * * "filter": limit the trace to this region
10124 * * "start": start tracing from this address
10125 * * "stop": stop tracing at this address/region;
10127 * * for kernel addresses: <start address>[/<size>]
10128 * * for object files: <start address>[/<size>]@</path/to/object/file>
10130 * if <size> is not specified or is zero, the range is treated as a single
10131 * address; not valid for ACTION=="filter".
10145 IF_STATE_ACTION = 0,
10150 static const match_table_t if_tokens = {
10151 { IF_ACT_FILTER, "filter" },
10152 { IF_ACT_START, "start" },
10153 { IF_ACT_STOP, "stop" },
10154 { IF_SRC_FILE, "%u/%u@%s" },
10155 { IF_SRC_KERNEL, "%u/%u" },
10156 { IF_SRC_FILEADDR, "%u@%s" },
10157 { IF_SRC_KERNELADDR, "%u" },
10158 { IF_ACT_NONE, NULL },
10162 * Address filter string parser
10165 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
10166 struct list_head *filters)
10168 struct perf_addr_filter *filter = NULL;
10169 char *start, *orig, *filename = NULL;
10170 substring_t args[MAX_OPT_ARGS];
10171 int state = IF_STATE_ACTION, token;
10172 unsigned int kernel = 0;
10175 orig = fstr = kstrdup(fstr, GFP_KERNEL);
10179 while ((start = strsep(&fstr, " ,\n")) != NULL) {
10180 static const enum perf_addr_filter_action_t actions[] = {
10181 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
10182 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
10183 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
10190 /* filter definition begins */
10191 if (state == IF_STATE_ACTION) {
10192 filter = perf_addr_filter_new(event, filters);
10197 token = match_token(start, if_tokens, args);
10199 case IF_ACT_FILTER:
10202 if (state != IF_STATE_ACTION)
10205 filter->action = actions[token];
10206 state = IF_STATE_SOURCE;
10209 case IF_SRC_KERNELADDR:
10210 case IF_SRC_KERNEL:
10214 case IF_SRC_FILEADDR:
10216 if (state != IF_STATE_SOURCE)
10220 ret = kstrtoul(args[0].from, 0, &filter->offset);
10224 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
10226 ret = kstrtoul(args[1].from, 0, &filter->size);
10231 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
10232 int fpos = token == IF_SRC_FILE ? 2 : 1;
10235 filename = match_strdup(&args[fpos]);
10242 state = IF_STATE_END;
10250 * Filter definition is fully parsed, validate and install it.
10251 * Make sure that it doesn't contradict itself or the event's
10254 if (state == IF_STATE_END) {
10256 if (kernel && event->attr.exclude_kernel)
10260 * ACTION "filter" must have a non-zero length region
10263 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
10272 * For now, we only support file-based filters
10273 * in per-task events; doing so for CPU-wide
10274 * events requires additional context switching
10275 * trickery, since same object code will be
10276 * mapped at different virtual addresses in
10277 * different processes.
10280 if (!event->ctx->task)
10283 /* look up the path and grab its inode */
10284 ret = kern_path(filename, LOOKUP_FOLLOW,
10290 if (!filter->path.dentry ||
10291 !S_ISREG(d_inode(filter->path.dentry)
10295 event->addr_filters.nr_file_filters++;
10298 /* ready to consume more filters */
10299 state = IF_STATE_ACTION;
10304 if (state != IF_STATE_ACTION)
10314 free_filters_list(filters);
10321 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
10323 LIST_HEAD(filters);
10327 * Since this is called in perf_ioctl() path, we're already holding
10330 lockdep_assert_held(&event->ctx->mutex);
10332 if (WARN_ON_ONCE(event->parent))
10335 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
10337 goto fail_clear_files;
10339 ret = event->pmu->addr_filters_validate(&filters);
10341 goto fail_free_filters;
10343 /* remove existing filters, if any */
10344 perf_addr_filters_splice(event, &filters);
10346 /* install new filters */
10347 perf_event_for_each_child(event, perf_event_addr_filters_apply);
10352 free_filters_list(&filters);
10355 event->addr_filters.nr_file_filters = 0;
10360 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
10365 filter_str = strndup_user(arg, PAGE_SIZE);
10366 if (IS_ERR(filter_str))
10367 return PTR_ERR(filter_str);
10369 #ifdef CONFIG_EVENT_TRACING
10370 if (perf_event_is_tracing(event)) {
10371 struct perf_event_context *ctx = event->ctx;
10374 * Beware, here be dragons!!
10376 * the tracepoint muck will deadlock against ctx->mutex, but
10377 * the tracepoint stuff does not actually need it. So
10378 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
10379 * already have a reference on ctx.
10381 * This can result in event getting moved to a different ctx,
10382 * but that does not affect the tracepoint state.
10384 mutex_unlock(&ctx->mutex);
10385 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
10386 mutex_lock(&ctx->mutex);
10389 if (has_addr_filter(event))
10390 ret = perf_event_set_addr_filter(event, filter_str);
10397 * hrtimer based swevent callback
10400 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
10402 enum hrtimer_restart ret = HRTIMER_RESTART;
10403 struct perf_sample_data data;
10404 struct pt_regs *regs;
10405 struct perf_event *event;
10408 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
10410 if (event->state != PERF_EVENT_STATE_ACTIVE)
10411 return HRTIMER_NORESTART;
10413 event->pmu->read(event);
10415 perf_sample_data_init(&data, 0, event->hw.last_period);
10416 regs = get_irq_regs();
10418 if (regs && !perf_exclude_event(event, regs)) {
10419 if (!(event->attr.exclude_idle && is_idle_task(current)))
10420 if (__perf_event_overflow(event, 1, &data, regs))
10421 ret = HRTIMER_NORESTART;
10424 period = max_t(u64, 10000, event->hw.sample_period);
10425 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
10430 static void perf_swevent_start_hrtimer(struct perf_event *event)
10432 struct hw_perf_event *hwc = &event->hw;
10435 if (!is_sampling_event(event))
10438 period = local64_read(&hwc->period_left);
10443 local64_set(&hwc->period_left, 0);
10445 period = max_t(u64, 10000, hwc->sample_period);
10447 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
10448 HRTIMER_MODE_REL_PINNED_HARD);
10451 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
10453 struct hw_perf_event *hwc = &event->hw;
10455 if (is_sampling_event(event)) {
10456 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
10457 local64_set(&hwc->period_left, ktime_to_ns(remaining));
10459 hrtimer_cancel(&hwc->hrtimer);
10463 static void perf_swevent_init_hrtimer(struct perf_event *event)
10465 struct hw_perf_event *hwc = &event->hw;
10467 if (!is_sampling_event(event))
10470 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
10471 hwc->hrtimer.function = perf_swevent_hrtimer;
10474 * Since hrtimers have a fixed rate, we can do a static freq->period
10475 * mapping and avoid the whole period adjust feedback stuff.
10477 if (event->attr.freq) {
10478 long freq = event->attr.sample_freq;
10480 event->attr.sample_period = NSEC_PER_SEC / freq;
10481 hwc->sample_period = event->attr.sample_period;
10482 local64_set(&hwc->period_left, hwc->sample_period);
10483 hwc->last_period = hwc->sample_period;
10484 event->attr.freq = 0;
10489 * Software event: cpu wall time clock
10492 static void cpu_clock_event_update(struct perf_event *event)
10497 now = local_clock();
10498 prev = local64_xchg(&event->hw.prev_count, now);
10499 local64_add(now - prev, &event->count);
10502 static void cpu_clock_event_start(struct perf_event *event, int flags)
10504 local64_set(&event->hw.prev_count, local_clock());
10505 perf_swevent_start_hrtimer(event);
10508 static void cpu_clock_event_stop(struct perf_event *event, int flags)
10510 perf_swevent_cancel_hrtimer(event);
10511 cpu_clock_event_update(event);
10514 static int cpu_clock_event_add(struct perf_event *event, int flags)
10516 if (flags & PERF_EF_START)
10517 cpu_clock_event_start(event, flags);
10518 perf_event_update_userpage(event);
10523 static void cpu_clock_event_del(struct perf_event *event, int flags)
10525 cpu_clock_event_stop(event, flags);
10528 static void cpu_clock_event_read(struct perf_event *event)
10530 cpu_clock_event_update(event);
10533 static int cpu_clock_event_init(struct perf_event *event)
10535 if (event->attr.type != PERF_TYPE_SOFTWARE)
10538 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
10542 * no branch sampling for software events
10544 if (has_branch_stack(event))
10545 return -EOPNOTSUPP;
10547 perf_swevent_init_hrtimer(event);
10552 static struct pmu perf_cpu_clock = {
10553 .task_ctx_nr = perf_sw_context,
10555 .capabilities = PERF_PMU_CAP_NO_NMI,
10557 .event_init = cpu_clock_event_init,
10558 .add = cpu_clock_event_add,
10559 .del = cpu_clock_event_del,
10560 .start = cpu_clock_event_start,
10561 .stop = cpu_clock_event_stop,
10562 .read = cpu_clock_event_read,
10566 * Software event: task time clock
10569 static void task_clock_event_update(struct perf_event *event, u64 now)
10574 prev = local64_xchg(&event->hw.prev_count, now);
10575 delta = now - prev;
10576 local64_add(delta, &event->count);
10579 static void task_clock_event_start(struct perf_event *event, int flags)
10581 local64_set(&event->hw.prev_count, event->ctx->time);
10582 perf_swevent_start_hrtimer(event);
10585 static void task_clock_event_stop(struct perf_event *event, int flags)
10587 perf_swevent_cancel_hrtimer(event);
10588 task_clock_event_update(event, event->ctx->time);
10591 static int task_clock_event_add(struct perf_event *event, int flags)
10593 if (flags & PERF_EF_START)
10594 task_clock_event_start(event, flags);
10595 perf_event_update_userpage(event);
10600 static void task_clock_event_del(struct perf_event *event, int flags)
10602 task_clock_event_stop(event, PERF_EF_UPDATE);
10605 static void task_clock_event_read(struct perf_event *event)
10607 u64 now = perf_clock();
10608 u64 delta = now - event->ctx->timestamp;
10609 u64 time = event->ctx->time + delta;
10611 task_clock_event_update(event, time);
10614 static int task_clock_event_init(struct perf_event *event)
10616 if (event->attr.type != PERF_TYPE_SOFTWARE)
10619 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
10623 * no branch sampling for software events
10625 if (has_branch_stack(event))
10626 return -EOPNOTSUPP;
10628 perf_swevent_init_hrtimer(event);
10633 static struct pmu perf_task_clock = {
10634 .task_ctx_nr = perf_sw_context,
10636 .capabilities = PERF_PMU_CAP_NO_NMI,
10638 .event_init = task_clock_event_init,
10639 .add = task_clock_event_add,
10640 .del = task_clock_event_del,
10641 .start = task_clock_event_start,
10642 .stop = task_clock_event_stop,
10643 .read = task_clock_event_read,
10646 static void perf_pmu_nop_void(struct pmu *pmu)
10650 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
10654 static int perf_pmu_nop_int(struct pmu *pmu)
10659 static int perf_event_nop_int(struct perf_event *event, u64 value)
10664 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
10666 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
10668 __this_cpu_write(nop_txn_flags, flags);
10670 if (flags & ~PERF_PMU_TXN_ADD)
10673 perf_pmu_disable(pmu);
10676 static int perf_pmu_commit_txn(struct pmu *pmu)
10678 unsigned int flags = __this_cpu_read(nop_txn_flags);
10680 __this_cpu_write(nop_txn_flags, 0);
10682 if (flags & ~PERF_PMU_TXN_ADD)
10685 perf_pmu_enable(pmu);
10689 static void perf_pmu_cancel_txn(struct pmu *pmu)
10691 unsigned int flags = __this_cpu_read(nop_txn_flags);
10693 __this_cpu_write(nop_txn_flags, 0);
10695 if (flags & ~PERF_PMU_TXN_ADD)
10698 perf_pmu_enable(pmu);
10701 static int perf_event_idx_default(struct perf_event *event)
10707 * Ensures all contexts with the same task_ctx_nr have the same
10708 * pmu_cpu_context too.
10710 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
10717 list_for_each_entry(pmu, &pmus, entry) {
10718 if (pmu->task_ctx_nr == ctxn)
10719 return pmu->pmu_cpu_context;
10725 static void free_pmu_context(struct pmu *pmu)
10728 * Static contexts such as perf_sw_context have a global lifetime
10729 * and may be shared between different PMUs. Avoid freeing them
10730 * when a single PMU is going away.
10732 if (pmu->task_ctx_nr > perf_invalid_context)
10735 free_percpu(pmu->pmu_cpu_context);
10739 * Let userspace know that this PMU supports address range filtering:
10741 static ssize_t nr_addr_filters_show(struct device *dev,
10742 struct device_attribute *attr,
10745 struct pmu *pmu = dev_get_drvdata(dev);
10747 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
10749 DEVICE_ATTR_RO(nr_addr_filters);
10751 static struct idr pmu_idr;
10754 type_show(struct device *dev, struct device_attribute *attr, char *page)
10756 struct pmu *pmu = dev_get_drvdata(dev);
10758 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
10760 static DEVICE_ATTR_RO(type);
10763 perf_event_mux_interval_ms_show(struct device *dev,
10764 struct device_attribute *attr,
10767 struct pmu *pmu = dev_get_drvdata(dev);
10769 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
10772 static DEFINE_MUTEX(mux_interval_mutex);
10775 perf_event_mux_interval_ms_store(struct device *dev,
10776 struct device_attribute *attr,
10777 const char *buf, size_t count)
10779 struct pmu *pmu = dev_get_drvdata(dev);
10780 int timer, cpu, ret;
10782 ret = kstrtoint(buf, 0, &timer);
10789 /* same value, noting to do */
10790 if (timer == pmu->hrtimer_interval_ms)
10793 mutex_lock(&mux_interval_mutex);
10794 pmu->hrtimer_interval_ms = timer;
10796 /* update all cpuctx for this PMU */
10798 for_each_online_cpu(cpu) {
10799 struct perf_cpu_context *cpuctx;
10800 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10801 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
10803 cpu_function_call(cpu,
10804 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
10806 cpus_read_unlock();
10807 mutex_unlock(&mux_interval_mutex);
10811 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
10813 static struct attribute *pmu_dev_attrs[] = {
10814 &dev_attr_type.attr,
10815 &dev_attr_perf_event_mux_interval_ms.attr,
10818 ATTRIBUTE_GROUPS(pmu_dev);
10820 static int pmu_bus_running;
10821 static struct bus_type pmu_bus = {
10822 .name = "event_source",
10823 .dev_groups = pmu_dev_groups,
10826 static void pmu_dev_release(struct device *dev)
10831 static int pmu_dev_alloc(struct pmu *pmu)
10835 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
10839 pmu->dev->groups = pmu->attr_groups;
10840 device_initialize(pmu->dev);
10841 ret = dev_set_name(pmu->dev, "%s", pmu->name);
10845 dev_set_drvdata(pmu->dev, pmu);
10846 pmu->dev->bus = &pmu_bus;
10847 pmu->dev->release = pmu_dev_release;
10848 ret = device_add(pmu->dev);
10852 /* For PMUs with address filters, throw in an extra attribute: */
10853 if (pmu->nr_addr_filters)
10854 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
10859 if (pmu->attr_update)
10860 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
10869 device_del(pmu->dev);
10872 put_device(pmu->dev);
10876 static struct lock_class_key cpuctx_mutex;
10877 static struct lock_class_key cpuctx_lock;
10879 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
10881 int cpu, ret, max = PERF_TYPE_MAX;
10883 mutex_lock(&pmus_lock);
10885 pmu->pmu_disable_count = alloc_percpu(int);
10886 if (!pmu->pmu_disable_count)
10894 if (type != PERF_TYPE_SOFTWARE) {
10898 ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL);
10902 WARN_ON(type >= 0 && ret != type);
10908 if (pmu_bus_running) {
10909 ret = pmu_dev_alloc(pmu);
10915 if (pmu->task_ctx_nr == perf_hw_context) {
10916 static int hw_context_taken = 0;
10919 * Other than systems with heterogeneous CPUs, it never makes
10920 * sense for two PMUs to share perf_hw_context. PMUs which are
10921 * uncore must use perf_invalid_context.
10923 if (WARN_ON_ONCE(hw_context_taken &&
10924 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
10925 pmu->task_ctx_nr = perf_invalid_context;
10927 hw_context_taken = 1;
10930 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
10931 if (pmu->pmu_cpu_context)
10932 goto got_cpu_context;
10935 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
10936 if (!pmu->pmu_cpu_context)
10939 for_each_possible_cpu(cpu) {
10940 struct perf_cpu_context *cpuctx;
10942 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10943 __perf_event_init_context(&cpuctx->ctx);
10944 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
10945 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
10946 cpuctx->ctx.pmu = pmu;
10947 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
10949 __perf_mux_hrtimer_init(cpuctx, cpu);
10951 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
10952 cpuctx->heap = cpuctx->heap_default;
10956 if (!pmu->start_txn) {
10957 if (pmu->pmu_enable) {
10959 * If we have pmu_enable/pmu_disable calls, install
10960 * transaction stubs that use that to try and batch
10961 * hardware accesses.
10963 pmu->start_txn = perf_pmu_start_txn;
10964 pmu->commit_txn = perf_pmu_commit_txn;
10965 pmu->cancel_txn = perf_pmu_cancel_txn;
10967 pmu->start_txn = perf_pmu_nop_txn;
10968 pmu->commit_txn = perf_pmu_nop_int;
10969 pmu->cancel_txn = perf_pmu_nop_void;
10973 if (!pmu->pmu_enable) {
10974 pmu->pmu_enable = perf_pmu_nop_void;
10975 pmu->pmu_disable = perf_pmu_nop_void;
10978 if (!pmu->check_period)
10979 pmu->check_period = perf_event_nop_int;
10981 if (!pmu->event_idx)
10982 pmu->event_idx = perf_event_idx_default;
10985 * Ensure the TYPE_SOFTWARE PMUs are at the head of the list,
10986 * since these cannot be in the IDR. This way the linear search
10987 * is fast, provided a valid software event is provided.
10989 if (type == PERF_TYPE_SOFTWARE || !name)
10990 list_add_rcu(&pmu->entry, &pmus);
10992 list_add_tail_rcu(&pmu->entry, &pmus);
10994 atomic_set(&pmu->exclusive_cnt, 0);
10997 mutex_unlock(&pmus_lock);
11002 device_del(pmu->dev);
11003 put_device(pmu->dev);
11006 if (pmu->type != PERF_TYPE_SOFTWARE)
11007 idr_remove(&pmu_idr, pmu->type);
11010 free_percpu(pmu->pmu_disable_count);
11013 EXPORT_SYMBOL_GPL(perf_pmu_register);
11015 void perf_pmu_unregister(struct pmu *pmu)
11017 mutex_lock(&pmus_lock);
11018 list_del_rcu(&pmu->entry);
11021 * We dereference the pmu list under both SRCU and regular RCU, so
11022 * synchronize against both of those.
11024 synchronize_srcu(&pmus_srcu);
11027 free_percpu(pmu->pmu_disable_count);
11028 if (pmu->type != PERF_TYPE_SOFTWARE)
11029 idr_remove(&pmu_idr, pmu->type);
11030 if (pmu_bus_running) {
11031 if (pmu->nr_addr_filters)
11032 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
11033 device_del(pmu->dev);
11034 put_device(pmu->dev);
11036 free_pmu_context(pmu);
11037 mutex_unlock(&pmus_lock);
11039 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
11041 static inline bool has_extended_regs(struct perf_event *event)
11043 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
11044 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
11047 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
11049 struct perf_event_context *ctx = NULL;
11052 if (!try_module_get(pmu->module))
11056 * A number of pmu->event_init() methods iterate the sibling_list to,
11057 * for example, validate if the group fits on the PMU. Therefore,
11058 * if this is a sibling event, acquire the ctx->mutex to protect
11059 * the sibling_list.
11061 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
11063 * This ctx->mutex can nest when we're called through
11064 * inheritance. See the perf_event_ctx_lock_nested() comment.
11066 ctx = perf_event_ctx_lock_nested(event->group_leader,
11067 SINGLE_DEPTH_NESTING);
11072 ret = pmu->event_init(event);
11075 perf_event_ctx_unlock(event->group_leader, ctx);
11078 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
11079 has_extended_regs(event))
11082 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
11083 event_has_any_exclude_flag(event))
11086 if (ret && event->destroy)
11087 event->destroy(event);
11091 module_put(pmu->module);
11096 static struct pmu *perf_init_event(struct perf_event *event)
11098 int idx, type, ret;
11101 idx = srcu_read_lock(&pmus_srcu);
11103 /* Try parent's PMU first: */
11104 if (event->parent && event->parent->pmu) {
11105 pmu = event->parent->pmu;
11106 ret = perf_try_init_event(pmu, event);
11112 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
11113 * are often aliases for PERF_TYPE_RAW.
11115 type = event->attr.type;
11116 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE)
11117 type = PERF_TYPE_RAW;
11121 pmu = idr_find(&pmu_idr, type);
11124 ret = perf_try_init_event(pmu, event);
11125 if (ret == -ENOENT && event->attr.type != type) {
11126 type = event->attr.type;
11131 pmu = ERR_PTR(ret);
11136 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
11137 ret = perf_try_init_event(pmu, event);
11141 if (ret != -ENOENT) {
11142 pmu = ERR_PTR(ret);
11146 pmu = ERR_PTR(-ENOENT);
11148 srcu_read_unlock(&pmus_srcu, idx);
11153 static void attach_sb_event(struct perf_event *event)
11155 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
11157 raw_spin_lock(&pel->lock);
11158 list_add_rcu(&event->sb_list, &pel->list);
11159 raw_spin_unlock(&pel->lock);
11163 * We keep a list of all !task (and therefore per-cpu) events
11164 * that need to receive side-band records.
11166 * This avoids having to scan all the various PMU per-cpu contexts
11167 * looking for them.
11169 static void account_pmu_sb_event(struct perf_event *event)
11171 if (is_sb_event(event))
11172 attach_sb_event(event);
11175 static void account_event_cpu(struct perf_event *event, int cpu)
11180 if (is_cgroup_event(event))
11181 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
11184 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
11185 static void account_freq_event_nohz(void)
11187 #ifdef CONFIG_NO_HZ_FULL
11188 /* Lock so we don't race with concurrent unaccount */
11189 spin_lock(&nr_freq_lock);
11190 if (atomic_inc_return(&nr_freq_events) == 1)
11191 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
11192 spin_unlock(&nr_freq_lock);
11196 static void account_freq_event(void)
11198 if (tick_nohz_full_enabled())
11199 account_freq_event_nohz();
11201 atomic_inc(&nr_freq_events);
11205 static void account_event(struct perf_event *event)
11212 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
11214 if (event->attr.mmap || event->attr.mmap_data)
11215 atomic_inc(&nr_mmap_events);
11216 if (event->attr.build_id)
11217 atomic_inc(&nr_build_id_events);
11218 if (event->attr.comm)
11219 atomic_inc(&nr_comm_events);
11220 if (event->attr.namespaces)
11221 atomic_inc(&nr_namespaces_events);
11222 if (event->attr.cgroup)
11223 atomic_inc(&nr_cgroup_events);
11224 if (event->attr.task)
11225 atomic_inc(&nr_task_events);
11226 if (event->attr.freq)
11227 account_freq_event();
11228 if (event->attr.context_switch) {
11229 atomic_inc(&nr_switch_events);
11232 if (has_branch_stack(event))
11234 if (is_cgroup_event(event))
11236 if (event->attr.ksymbol)
11237 atomic_inc(&nr_ksymbol_events);
11238 if (event->attr.bpf_event)
11239 atomic_inc(&nr_bpf_events);
11240 if (event->attr.text_poke)
11241 atomic_inc(&nr_text_poke_events);
11245 * We need the mutex here because static_branch_enable()
11246 * must complete *before* the perf_sched_count increment
11249 if (atomic_inc_not_zero(&perf_sched_count))
11252 mutex_lock(&perf_sched_mutex);
11253 if (!atomic_read(&perf_sched_count)) {
11254 static_branch_enable(&perf_sched_events);
11256 * Guarantee that all CPUs observe they key change and
11257 * call the perf scheduling hooks before proceeding to
11258 * install events that need them.
11263 * Now that we have waited for the sync_sched(), allow further
11264 * increments to by-pass the mutex.
11266 atomic_inc(&perf_sched_count);
11267 mutex_unlock(&perf_sched_mutex);
11271 account_event_cpu(event, event->cpu);
11273 account_pmu_sb_event(event);
11277 * Allocate and initialize an event structure
11279 static struct perf_event *
11280 perf_event_alloc(struct perf_event_attr *attr, int cpu,
11281 struct task_struct *task,
11282 struct perf_event *group_leader,
11283 struct perf_event *parent_event,
11284 perf_overflow_handler_t overflow_handler,
11285 void *context, int cgroup_fd)
11288 struct perf_event *event;
11289 struct hw_perf_event *hwc;
11290 long err = -EINVAL;
11293 if ((unsigned)cpu >= nr_cpu_ids) {
11294 if (!task || cpu != -1)
11295 return ERR_PTR(-EINVAL);
11298 node = (cpu >= 0) ? cpu_to_node(cpu) : -1;
11299 event = kmem_cache_alloc_node(perf_event_cache, GFP_KERNEL | __GFP_ZERO,
11302 return ERR_PTR(-ENOMEM);
11305 * Single events are their own group leaders, with an
11306 * empty sibling list:
11309 group_leader = event;
11311 mutex_init(&event->child_mutex);
11312 INIT_LIST_HEAD(&event->child_list);
11314 INIT_LIST_HEAD(&event->event_entry);
11315 INIT_LIST_HEAD(&event->sibling_list);
11316 INIT_LIST_HEAD(&event->active_list);
11317 init_event_group(event);
11318 INIT_LIST_HEAD(&event->rb_entry);
11319 INIT_LIST_HEAD(&event->active_entry);
11320 INIT_LIST_HEAD(&event->addr_filters.list);
11321 INIT_HLIST_NODE(&event->hlist_entry);
11324 init_waitqueue_head(&event->waitq);
11325 event->pending_disable = -1;
11326 init_irq_work(&event->pending, perf_pending_event);
11328 mutex_init(&event->mmap_mutex);
11329 raw_spin_lock_init(&event->addr_filters.lock);
11331 atomic_long_set(&event->refcount, 1);
11333 event->attr = *attr;
11334 event->group_leader = group_leader;
11338 event->parent = parent_event;
11340 event->ns = get_pid_ns(task_active_pid_ns(current));
11341 event->id = atomic64_inc_return(&perf_event_id);
11343 event->state = PERF_EVENT_STATE_INACTIVE;
11346 event->attach_state = PERF_ATTACH_TASK;
11348 * XXX pmu::event_init needs to know what task to account to
11349 * and we cannot use the ctx information because we need the
11350 * pmu before we get a ctx.
11352 event->hw.target = get_task_struct(task);
11355 event->clock = &local_clock;
11357 event->clock = parent_event->clock;
11359 if (!overflow_handler && parent_event) {
11360 overflow_handler = parent_event->overflow_handler;
11361 context = parent_event->overflow_handler_context;
11362 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
11363 if (overflow_handler == bpf_overflow_handler) {
11364 struct bpf_prog *prog = parent_event->prog;
11366 bpf_prog_inc(prog);
11367 event->prog = prog;
11368 event->orig_overflow_handler =
11369 parent_event->orig_overflow_handler;
11374 if (overflow_handler) {
11375 event->overflow_handler = overflow_handler;
11376 event->overflow_handler_context = context;
11377 } else if (is_write_backward(event)){
11378 event->overflow_handler = perf_event_output_backward;
11379 event->overflow_handler_context = NULL;
11381 event->overflow_handler = perf_event_output_forward;
11382 event->overflow_handler_context = NULL;
11385 perf_event__state_init(event);
11390 hwc->sample_period = attr->sample_period;
11391 if (attr->freq && attr->sample_freq)
11392 hwc->sample_period = 1;
11393 hwc->last_period = hwc->sample_period;
11395 local64_set(&hwc->period_left, hwc->sample_period);
11398 * We currently do not support PERF_SAMPLE_READ on inherited events.
11399 * See perf_output_read().
11401 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
11404 if (!has_branch_stack(event))
11405 event->attr.branch_sample_type = 0;
11407 pmu = perf_init_event(event);
11409 err = PTR_ERR(pmu);
11414 * Disallow uncore-cgroup events, they don't make sense as the cgroup will
11415 * be different on other CPUs in the uncore mask.
11417 if (pmu->task_ctx_nr == perf_invalid_context && cgroup_fd != -1) {
11422 if (event->attr.aux_output &&
11423 !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
11428 if (cgroup_fd != -1) {
11429 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
11434 err = exclusive_event_init(event);
11438 if (has_addr_filter(event)) {
11439 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
11440 sizeof(struct perf_addr_filter_range),
11442 if (!event->addr_filter_ranges) {
11448 * Clone the parent's vma offsets: they are valid until exec()
11449 * even if the mm is not shared with the parent.
11451 if (event->parent) {
11452 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11454 raw_spin_lock_irq(&ifh->lock);
11455 memcpy(event->addr_filter_ranges,
11456 event->parent->addr_filter_ranges,
11457 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
11458 raw_spin_unlock_irq(&ifh->lock);
11461 /* force hw sync on the address filters */
11462 event->addr_filters_gen = 1;
11465 if (!event->parent) {
11466 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
11467 err = get_callchain_buffers(attr->sample_max_stack);
11469 goto err_addr_filters;
11473 err = security_perf_event_alloc(event);
11475 goto err_callchain_buffer;
11477 /* symmetric to unaccount_event() in _free_event() */
11478 account_event(event);
11482 err_callchain_buffer:
11483 if (!event->parent) {
11484 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
11485 put_callchain_buffers();
11488 kfree(event->addr_filter_ranges);
11491 exclusive_event_destroy(event);
11494 if (is_cgroup_event(event))
11495 perf_detach_cgroup(event);
11496 if (event->destroy)
11497 event->destroy(event);
11498 module_put(pmu->module);
11501 put_pid_ns(event->ns);
11502 if (event->hw.target)
11503 put_task_struct(event->hw.target);
11504 kmem_cache_free(perf_event_cache, event);
11506 return ERR_PTR(err);
11509 static int perf_copy_attr(struct perf_event_attr __user *uattr,
11510 struct perf_event_attr *attr)
11515 /* Zero the full structure, so that a short copy will be nice. */
11516 memset(attr, 0, sizeof(*attr));
11518 ret = get_user(size, &uattr->size);
11522 /* ABI compatibility quirk: */
11524 size = PERF_ATTR_SIZE_VER0;
11525 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
11528 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
11537 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
11540 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
11543 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
11546 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
11547 u64 mask = attr->branch_sample_type;
11549 /* only using defined bits */
11550 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
11553 /* at least one branch bit must be set */
11554 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
11557 /* propagate priv level, when not set for branch */
11558 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
11560 /* exclude_kernel checked on syscall entry */
11561 if (!attr->exclude_kernel)
11562 mask |= PERF_SAMPLE_BRANCH_KERNEL;
11564 if (!attr->exclude_user)
11565 mask |= PERF_SAMPLE_BRANCH_USER;
11567 if (!attr->exclude_hv)
11568 mask |= PERF_SAMPLE_BRANCH_HV;
11570 * adjust user setting (for HW filter setup)
11572 attr->branch_sample_type = mask;
11574 /* privileged levels capture (kernel, hv): check permissions */
11575 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
11576 ret = perf_allow_kernel(attr);
11582 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
11583 ret = perf_reg_validate(attr->sample_regs_user);
11588 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
11589 if (!arch_perf_have_user_stack_dump())
11593 * We have __u32 type for the size, but so far
11594 * we can only use __u16 as maximum due to the
11595 * __u16 sample size limit.
11597 if (attr->sample_stack_user >= USHRT_MAX)
11599 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
11603 if (!attr->sample_max_stack)
11604 attr->sample_max_stack = sysctl_perf_event_max_stack;
11606 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
11607 ret = perf_reg_validate(attr->sample_regs_intr);
11609 #ifndef CONFIG_CGROUP_PERF
11610 if (attr->sample_type & PERF_SAMPLE_CGROUP)
11613 if ((attr->sample_type & PERF_SAMPLE_WEIGHT) &&
11614 (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT))
11621 put_user(sizeof(*attr), &uattr->size);
11627 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
11629 struct perf_buffer *rb = NULL;
11635 /* don't allow circular references */
11636 if (event == output_event)
11640 * Don't allow cross-cpu buffers
11642 if (output_event->cpu != event->cpu)
11646 * If its not a per-cpu rb, it must be the same task.
11648 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
11652 * Mixing clocks in the same buffer is trouble you don't need.
11654 if (output_event->clock != event->clock)
11658 * Either writing ring buffer from beginning or from end.
11659 * Mixing is not allowed.
11661 if (is_write_backward(output_event) != is_write_backward(event))
11665 * If both events generate aux data, they must be on the same PMU
11667 if (has_aux(event) && has_aux(output_event) &&
11668 event->pmu != output_event->pmu)
11672 mutex_lock(&event->mmap_mutex);
11673 /* Can't redirect output if we've got an active mmap() */
11674 if (atomic_read(&event->mmap_count))
11677 if (output_event) {
11678 /* get the rb we want to redirect to */
11679 rb = ring_buffer_get(output_event);
11684 ring_buffer_attach(event, rb);
11688 mutex_unlock(&event->mmap_mutex);
11694 static void mutex_lock_double(struct mutex *a, struct mutex *b)
11700 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
11703 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
11705 bool nmi_safe = false;
11708 case CLOCK_MONOTONIC:
11709 event->clock = &ktime_get_mono_fast_ns;
11713 case CLOCK_MONOTONIC_RAW:
11714 event->clock = &ktime_get_raw_fast_ns;
11718 case CLOCK_REALTIME:
11719 event->clock = &ktime_get_real_ns;
11722 case CLOCK_BOOTTIME:
11723 event->clock = &ktime_get_boottime_ns;
11727 event->clock = &ktime_get_clocktai_ns;
11734 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
11741 * Variation on perf_event_ctx_lock_nested(), except we take two context
11744 static struct perf_event_context *
11745 __perf_event_ctx_lock_double(struct perf_event *group_leader,
11746 struct perf_event_context *ctx)
11748 struct perf_event_context *gctx;
11752 gctx = READ_ONCE(group_leader->ctx);
11753 if (!refcount_inc_not_zero(&gctx->refcount)) {
11759 mutex_lock_double(&gctx->mutex, &ctx->mutex);
11761 if (group_leader->ctx != gctx) {
11762 mutex_unlock(&ctx->mutex);
11763 mutex_unlock(&gctx->mutex);
11772 * sys_perf_event_open - open a performance event, associate it to a task/cpu
11774 * @attr_uptr: event_id type attributes for monitoring/sampling
11777 * @group_fd: group leader event fd
11779 SYSCALL_DEFINE5(perf_event_open,
11780 struct perf_event_attr __user *, attr_uptr,
11781 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
11783 struct perf_event *group_leader = NULL, *output_event = NULL;
11784 struct perf_event *event, *sibling;
11785 struct perf_event_attr attr;
11786 struct perf_event_context *ctx, *gctx;
11787 struct file *event_file = NULL;
11788 struct fd group = {NULL, 0};
11789 struct task_struct *task = NULL;
11792 int move_group = 0;
11794 int f_flags = O_RDWR;
11795 int cgroup_fd = -1;
11797 /* for future expandability... */
11798 if (flags & ~PERF_FLAG_ALL)
11801 /* Do we allow access to perf_event_open(2) ? */
11802 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
11806 err = perf_copy_attr(attr_uptr, &attr);
11810 if (!attr.exclude_kernel) {
11811 err = perf_allow_kernel(&attr);
11816 if (attr.namespaces) {
11817 if (!perfmon_capable())
11822 if (attr.sample_freq > sysctl_perf_event_sample_rate)
11825 if (attr.sample_period & (1ULL << 63))
11829 /* Only privileged users can get physical addresses */
11830 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
11831 err = perf_allow_kernel(&attr);
11836 err = security_locked_down(LOCKDOWN_PERF);
11837 if (err && (attr.sample_type & PERF_SAMPLE_REGS_INTR))
11838 /* REGS_INTR can leak data, lockdown must prevent this */
11844 * In cgroup mode, the pid argument is used to pass the fd
11845 * opened to the cgroup directory in cgroupfs. The cpu argument
11846 * designates the cpu on which to monitor threads from that
11849 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
11852 if (flags & PERF_FLAG_FD_CLOEXEC)
11853 f_flags |= O_CLOEXEC;
11855 event_fd = get_unused_fd_flags(f_flags);
11859 if (group_fd != -1) {
11860 err = perf_fget_light(group_fd, &group);
11863 group_leader = group.file->private_data;
11864 if (flags & PERF_FLAG_FD_OUTPUT)
11865 output_event = group_leader;
11866 if (flags & PERF_FLAG_FD_NO_GROUP)
11867 group_leader = NULL;
11870 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
11871 task = find_lively_task_by_vpid(pid);
11872 if (IS_ERR(task)) {
11873 err = PTR_ERR(task);
11878 if (task && group_leader &&
11879 group_leader->attr.inherit != attr.inherit) {
11884 if (flags & PERF_FLAG_PID_CGROUP)
11887 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
11888 NULL, NULL, cgroup_fd);
11889 if (IS_ERR(event)) {
11890 err = PTR_ERR(event);
11894 if (is_sampling_event(event)) {
11895 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
11902 * Special case software events and allow them to be part of
11903 * any hardware group.
11907 if (attr.use_clockid) {
11908 err = perf_event_set_clock(event, attr.clockid);
11913 if (pmu->task_ctx_nr == perf_sw_context)
11914 event->event_caps |= PERF_EV_CAP_SOFTWARE;
11916 if (group_leader) {
11917 if (is_software_event(event) &&
11918 !in_software_context(group_leader)) {
11920 * If the event is a sw event, but the group_leader
11921 * is on hw context.
11923 * Allow the addition of software events to hw
11924 * groups, this is safe because software events
11925 * never fail to schedule.
11927 pmu = group_leader->ctx->pmu;
11928 } else if (!is_software_event(event) &&
11929 is_software_event(group_leader) &&
11930 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11932 * In case the group is a pure software group, and we
11933 * try to add a hardware event, move the whole group to
11934 * the hardware context.
11941 * Get the target context (task or percpu):
11943 ctx = find_get_context(pmu, task, event);
11945 err = PTR_ERR(ctx);
11950 * Look up the group leader (we will attach this event to it):
11952 if (group_leader) {
11956 * Do not allow a recursive hierarchy (this new sibling
11957 * becoming part of another group-sibling):
11959 if (group_leader->group_leader != group_leader)
11962 /* All events in a group should have the same clock */
11963 if (group_leader->clock != event->clock)
11967 * Make sure we're both events for the same CPU;
11968 * grouping events for different CPUs is broken; since
11969 * you can never concurrently schedule them anyhow.
11971 if (group_leader->cpu != event->cpu)
11975 * Make sure we're both on the same task, or both
11978 if (group_leader->ctx->task != ctx->task)
11982 * Do not allow to attach to a group in a different task
11983 * or CPU context. If we're moving SW events, we'll fix
11984 * this up later, so allow that.
11986 if (!move_group && group_leader->ctx != ctx)
11990 * Only a group leader can be exclusive or pinned
11992 if (attr.exclusive || attr.pinned)
11996 if (output_event) {
11997 err = perf_event_set_output(event, output_event);
12002 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
12004 if (IS_ERR(event_file)) {
12005 err = PTR_ERR(event_file);
12011 err = down_read_interruptible(&task->signal->exec_update_lock);
12016 * Preserve ptrace permission check for backwards compatibility.
12018 * We must hold exec_update_lock across this and any potential
12019 * perf_install_in_context() call for this new event to
12020 * serialize against exec() altering our credentials (and the
12021 * perf_event_exit_task() that could imply).
12024 if (!perfmon_capable() && !ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
12029 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
12031 if (gctx->task == TASK_TOMBSTONE) {
12037 * Check if we raced against another sys_perf_event_open() call
12038 * moving the software group underneath us.
12040 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
12042 * If someone moved the group out from under us, check
12043 * if this new event wound up on the same ctx, if so
12044 * its the regular !move_group case, otherwise fail.
12050 perf_event_ctx_unlock(group_leader, gctx);
12056 * Failure to create exclusive events returns -EBUSY.
12059 if (!exclusive_event_installable(group_leader, ctx))
12062 for_each_sibling_event(sibling, group_leader) {
12063 if (!exclusive_event_installable(sibling, ctx))
12067 mutex_lock(&ctx->mutex);
12070 if (ctx->task == TASK_TOMBSTONE) {
12075 if (!perf_event_validate_size(event)) {
12082 * Check if the @cpu we're creating an event for is online.
12084 * We use the perf_cpu_context::ctx::mutex to serialize against
12085 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12087 struct perf_cpu_context *cpuctx =
12088 container_of(ctx, struct perf_cpu_context, ctx);
12090 if (!cpuctx->online) {
12096 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
12102 * Must be under the same ctx::mutex as perf_install_in_context(),
12103 * because we need to serialize with concurrent event creation.
12105 if (!exclusive_event_installable(event, ctx)) {
12110 WARN_ON_ONCE(ctx->parent_ctx);
12113 * This is the point on no return; we cannot fail hereafter. This is
12114 * where we start modifying current state.
12119 * See perf_event_ctx_lock() for comments on the details
12120 * of swizzling perf_event::ctx.
12122 perf_remove_from_context(group_leader, 0);
12125 for_each_sibling_event(sibling, group_leader) {
12126 perf_remove_from_context(sibling, 0);
12131 * Wait for everybody to stop referencing the events through
12132 * the old lists, before installing it on new lists.
12137 * Install the group siblings before the group leader.
12139 * Because a group leader will try and install the entire group
12140 * (through the sibling list, which is still in-tact), we can
12141 * end up with siblings installed in the wrong context.
12143 * By installing siblings first we NO-OP because they're not
12144 * reachable through the group lists.
12146 for_each_sibling_event(sibling, group_leader) {
12147 perf_event__state_init(sibling);
12148 perf_install_in_context(ctx, sibling, sibling->cpu);
12153 * Removing from the context ends up with disabled
12154 * event. What we want here is event in the initial
12155 * startup state, ready to be add into new context.
12157 perf_event__state_init(group_leader);
12158 perf_install_in_context(ctx, group_leader, group_leader->cpu);
12163 * Precalculate sample_data sizes; do while holding ctx::mutex such
12164 * that we're serialized against further additions and before
12165 * perf_install_in_context() which is the point the event is active and
12166 * can use these values.
12168 perf_event__header_size(event);
12169 perf_event__id_header_size(event);
12171 event->owner = current;
12173 perf_install_in_context(ctx, event, event->cpu);
12174 perf_unpin_context(ctx);
12177 perf_event_ctx_unlock(group_leader, gctx);
12178 mutex_unlock(&ctx->mutex);
12181 up_read(&task->signal->exec_update_lock);
12182 put_task_struct(task);
12185 mutex_lock(¤t->perf_event_mutex);
12186 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
12187 mutex_unlock(¤t->perf_event_mutex);
12190 * Drop the reference on the group_event after placing the
12191 * new event on the sibling_list. This ensures destruction
12192 * of the group leader will find the pointer to itself in
12193 * perf_group_detach().
12196 fd_install(event_fd, event_file);
12201 perf_event_ctx_unlock(group_leader, gctx);
12202 mutex_unlock(&ctx->mutex);
12205 up_read(&task->signal->exec_update_lock);
12209 perf_unpin_context(ctx);
12213 * If event_file is set, the fput() above will have called ->release()
12214 * and that will take care of freeing the event.
12220 put_task_struct(task);
12224 put_unused_fd(event_fd);
12229 * perf_event_create_kernel_counter
12231 * @attr: attributes of the counter to create
12232 * @cpu: cpu in which the counter is bound
12233 * @task: task to profile (NULL for percpu)
12235 struct perf_event *
12236 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
12237 struct task_struct *task,
12238 perf_overflow_handler_t overflow_handler,
12241 struct perf_event_context *ctx;
12242 struct perf_event *event;
12246 * Grouping is not supported for kernel events, neither is 'AUX',
12247 * make sure the caller's intentions are adjusted.
12249 if (attr->aux_output)
12250 return ERR_PTR(-EINVAL);
12252 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
12253 overflow_handler, context, -1);
12254 if (IS_ERR(event)) {
12255 err = PTR_ERR(event);
12259 /* Mark owner so we could distinguish it from user events. */
12260 event->owner = TASK_TOMBSTONE;
12263 * Get the target context (task or percpu):
12265 ctx = find_get_context(event->pmu, task, event);
12267 err = PTR_ERR(ctx);
12271 WARN_ON_ONCE(ctx->parent_ctx);
12272 mutex_lock(&ctx->mutex);
12273 if (ctx->task == TASK_TOMBSTONE) {
12280 * Check if the @cpu we're creating an event for is online.
12282 * We use the perf_cpu_context::ctx::mutex to serialize against
12283 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12285 struct perf_cpu_context *cpuctx =
12286 container_of(ctx, struct perf_cpu_context, ctx);
12287 if (!cpuctx->online) {
12293 if (!exclusive_event_installable(event, ctx)) {
12298 perf_install_in_context(ctx, event, event->cpu);
12299 perf_unpin_context(ctx);
12300 mutex_unlock(&ctx->mutex);
12305 mutex_unlock(&ctx->mutex);
12306 perf_unpin_context(ctx);
12311 return ERR_PTR(err);
12313 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
12315 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
12317 struct perf_event_context *src_ctx;
12318 struct perf_event_context *dst_ctx;
12319 struct perf_event *event, *tmp;
12322 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
12323 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
12326 * See perf_event_ctx_lock() for comments on the details
12327 * of swizzling perf_event::ctx.
12329 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
12330 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
12332 perf_remove_from_context(event, 0);
12333 unaccount_event_cpu(event, src_cpu);
12335 list_add(&event->migrate_entry, &events);
12339 * Wait for the events to quiesce before re-instating them.
12344 * Re-instate events in 2 passes.
12346 * Skip over group leaders and only install siblings on this first
12347 * pass, siblings will not get enabled without a leader, however a
12348 * leader will enable its siblings, even if those are still on the old
12351 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12352 if (event->group_leader == event)
12355 list_del(&event->migrate_entry);
12356 if (event->state >= PERF_EVENT_STATE_OFF)
12357 event->state = PERF_EVENT_STATE_INACTIVE;
12358 account_event_cpu(event, dst_cpu);
12359 perf_install_in_context(dst_ctx, event, dst_cpu);
12364 * Once all the siblings are setup properly, install the group leaders
12367 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12368 list_del(&event->migrate_entry);
12369 if (event->state >= PERF_EVENT_STATE_OFF)
12370 event->state = PERF_EVENT_STATE_INACTIVE;
12371 account_event_cpu(event, dst_cpu);
12372 perf_install_in_context(dst_ctx, event, dst_cpu);
12375 mutex_unlock(&dst_ctx->mutex);
12376 mutex_unlock(&src_ctx->mutex);
12378 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
12380 static void sync_child_event(struct perf_event *child_event,
12381 struct task_struct *child)
12383 struct perf_event *parent_event = child_event->parent;
12386 if (child_event->attr.inherit_stat)
12387 perf_event_read_event(child_event, child);
12389 child_val = perf_event_count(child_event);
12392 * Add back the child's count to the parent's count:
12394 atomic64_add(child_val, &parent_event->child_count);
12395 atomic64_add(child_event->total_time_enabled,
12396 &parent_event->child_total_time_enabled);
12397 atomic64_add(child_event->total_time_running,
12398 &parent_event->child_total_time_running);
12402 perf_event_exit_event(struct perf_event *child_event,
12403 struct perf_event_context *child_ctx,
12404 struct task_struct *child)
12406 struct perf_event *parent_event = child_event->parent;
12409 * Do not destroy the 'original' grouping; because of the context
12410 * switch optimization the original events could've ended up in a
12411 * random child task.
12413 * If we were to destroy the original group, all group related
12414 * operations would cease to function properly after this random
12417 * Do destroy all inherited groups, we don't care about those
12418 * and being thorough is better.
12420 raw_spin_lock_irq(&child_ctx->lock);
12421 WARN_ON_ONCE(child_ctx->is_active);
12424 perf_group_detach(child_event);
12425 list_del_event(child_event, child_ctx);
12426 perf_event_set_state(child_event, PERF_EVENT_STATE_EXIT); /* is_event_hup() */
12427 raw_spin_unlock_irq(&child_ctx->lock);
12430 * Parent events are governed by their filedesc, retain them.
12432 if (!parent_event) {
12433 perf_event_wakeup(child_event);
12437 * Child events can be cleaned up.
12440 sync_child_event(child_event, child);
12443 * Remove this event from the parent's list
12445 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
12446 mutex_lock(&parent_event->child_mutex);
12447 list_del_init(&child_event->child_list);
12448 mutex_unlock(&parent_event->child_mutex);
12451 * Kick perf_poll() for is_event_hup().
12453 perf_event_wakeup(parent_event);
12454 free_event(child_event);
12455 put_event(parent_event);
12458 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
12460 struct perf_event_context *child_ctx, *clone_ctx = NULL;
12461 struct perf_event *child_event, *next;
12463 WARN_ON_ONCE(child != current);
12465 child_ctx = perf_pin_task_context(child, ctxn);
12470 * In order to reduce the amount of tricky in ctx tear-down, we hold
12471 * ctx::mutex over the entire thing. This serializes against almost
12472 * everything that wants to access the ctx.
12474 * The exception is sys_perf_event_open() /
12475 * perf_event_create_kernel_count() which does find_get_context()
12476 * without ctx::mutex (it cannot because of the move_group double mutex
12477 * lock thing). See the comments in perf_install_in_context().
12479 mutex_lock(&child_ctx->mutex);
12482 * In a single ctx::lock section, de-schedule the events and detach the
12483 * context from the task such that we cannot ever get it scheduled back
12486 raw_spin_lock_irq(&child_ctx->lock);
12487 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL);
12490 * Now that the context is inactive, destroy the task <-> ctx relation
12491 * and mark the context dead.
12493 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
12494 put_ctx(child_ctx); /* cannot be last */
12495 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
12496 put_task_struct(current); /* cannot be last */
12498 clone_ctx = unclone_ctx(child_ctx);
12499 raw_spin_unlock_irq(&child_ctx->lock);
12502 put_ctx(clone_ctx);
12505 * Report the task dead after unscheduling the events so that we
12506 * won't get any samples after PERF_RECORD_EXIT. We can however still
12507 * get a few PERF_RECORD_READ events.
12509 perf_event_task(child, child_ctx, 0);
12511 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
12512 perf_event_exit_event(child_event, child_ctx, child);
12514 mutex_unlock(&child_ctx->mutex);
12516 put_ctx(child_ctx);
12520 * When a child task exits, feed back event values to parent events.
12522 * Can be called with exec_update_lock held when called from
12523 * setup_new_exec().
12525 void perf_event_exit_task(struct task_struct *child)
12527 struct perf_event *event, *tmp;
12530 mutex_lock(&child->perf_event_mutex);
12531 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
12533 list_del_init(&event->owner_entry);
12536 * Ensure the list deletion is visible before we clear
12537 * the owner, closes a race against perf_release() where
12538 * we need to serialize on the owner->perf_event_mutex.
12540 smp_store_release(&event->owner, NULL);
12542 mutex_unlock(&child->perf_event_mutex);
12544 for_each_task_context_nr(ctxn)
12545 perf_event_exit_task_context(child, ctxn);
12548 * The perf_event_exit_task_context calls perf_event_task
12549 * with child's task_ctx, which generates EXIT events for
12550 * child contexts and sets child->perf_event_ctxp[] to NULL.
12551 * At this point we need to send EXIT events to cpu contexts.
12553 perf_event_task(child, NULL, 0);
12556 static void perf_free_event(struct perf_event *event,
12557 struct perf_event_context *ctx)
12559 struct perf_event *parent = event->parent;
12561 if (WARN_ON_ONCE(!parent))
12564 mutex_lock(&parent->child_mutex);
12565 list_del_init(&event->child_list);
12566 mutex_unlock(&parent->child_mutex);
12570 raw_spin_lock_irq(&ctx->lock);
12571 perf_group_detach(event);
12572 list_del_event(event, ctx);
12573 raw_spin_unlock_irq(&ctx->lock);
12578 * Free a context as created by inheritance by perf_event_init_task() below,
12579 * used by fork() in case of fail.
12581 * Even though the task has never lived, the context and events have been
12582 * exposed through the child_list, so we must take care tearing it all down.
12584 void perf_event_free_task(struct task_struct *task)
12586 struct perf_event_context *ctx;
12587 struct perf_event *event, *tmp;
12590 for_each_task_context_nr(ctxn) {
12591 ctx = task->perf_event_ctxp[ctxn];
12595 mutex_lock(&ctx->mutex);
12596 raw_spin_lock_irq(&ctx->lock);
12598 * Destroy the task <-> ctx relation and mark the context dead.
12600 * This is important because even though the task hasn't been
12601 * exposed yet the context has been (through child_list).
12603 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
12604 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
12605 put_task_struct(task); /* cannot be last */
12606 raw_spin_unlock_irq(&ctx->lock);
12608 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
12609 perf_free_event(event, ctx);
12611 mutex_unlock(&ctx->mutex);
12614 * perf_event_release_kernel() could've stolen some of our
12615 * child events and still have them on its free_list. In that
12616 * case we must wait for these events to have been freed (in
12617 * particular all their references to this task must've been
12620 * Without this copy_process() will unconditionally free this
12621 * task (irrespective of its reference count) and
12622 * _free_event()'s put_task_struct(event->hw.target) will be a
12625 * Wait for all events to drop their context reference.
12627 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
12628 put_ctx(ctx); /* must be last */
12632 void perf_event_delayed_put(struct task_struct *task)
12636 for_each_task_context_nr(ctxn)
12637 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
12640 struct file *perf_event_get(unsigned int fd)
12642 struct file *file = fget(fd);
12644 return ERR_PTR(-EBADF);
12646 if (file->f_op != &perf_fops) {
12648 return ERR_PTR(-EBADF);
12654 const struct perf_event *perf_get_event(struct file *file)
12656 if (file->f_op != &perf_fops)
12657 return ERR_PTR(-EINVAL);
12659 return file->private_data;
12662 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
12665 return ERR_PTR(-EINVAL);
12667 return &event->attr;
12671 * Inherit an event from parent task to child task.
12674 * - valid pointer on success
12675 * - NULL for orphaned events
12676 * - IS_ERR() on error
12678 static struct perf_event *
12679 inherit_event(struct perf_event *parent_event,
12680 struct task_struct *parent,
12681 struct perf_event_context *parent_ctx,
12682 struct task_struct *child,
12683 struct perf_event *group_leader,
12684 struct perf_event_context *child_ctx)
12686 enum perf_event_state parent_state = parent_event->state;
12687 struct perf_event *child_event;
12688 unsigned long flags;
12691 * Instead of creating recursive hierarchies of events,
12692 * we link inherited events back to the original parent,
12693 * which has a filp for sure, which we use as the reference
12696 if (parent_event->parent)
12697 parent_event = parent_event->parent;
12699 child_event = perf_event_alloc(&parent_event->attr,
12702 group_leader, parent_event,
12704 if (IS_ERR(child_event))
12705 return child_event;
12708 if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) &&
12709 !child_ctx->task_ctx_data) {
12710 struct pmu *pmu = child_event->pmu;
12712 child_ctx->task_ctx_data = alloc_task_ctx_data(pmu);
12713 if (!child_ctx->task_ctx_data) {
12714 free_event(child_event);
12715 return ERR_PTR(-ENOMEM);
12720 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
12721 * must be under the same lock in order to serialize against
12722 * perf_event_release_kernel(), such that either we must observe
12723 * is_orphaned_event() or they will observe us on the child_list.
12725 mutex_lock(&parent_event->child_mutex);
12726 if (is_orphaned_event(parent_event) ||
12727 !atomic_long_inc_not_zero(&parent_event->refcount)) {
12728 mutex_unlock(&parent_event->child_mutex);
12729 /* task_ctx_data is freed with child_ctx */
12730 free_event(child_event);
12734 get_ctx(child_ctx);
12737 * Make the child state follow the state of the parent event,
12738 * not its attr.disabled bit. We hold the parent's mutex,
12739 * so we won't race with perf_event_{en, dis}able_family.
12741 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
12742 child_event->state = PERF_EVENT_STATE_INACTIVE;
12744 child_event->state = PERF_EVENT_STATE_OFF;
12746 if (parent_event->attr.freq) {
12747 u64 sample_period = parent_event->hw.sample_period;
12748 struct hw_perf_event *hwc = &child_event->hw;
12750 hwc->sample_period = sample_period;
12751 hwc->last_period = sample_period;
12753 local64_set(&hwc->period_left, sample_period);
12756 child_event->ctx = child_ctx;
12757 child_event->overflow_handler = parent_event->overflow_handler;
12758 child_event->overflow_handler_context
12759 = parent_event->overflow_handler_context;
12762 * Precalculate sample_data sizes
12764 perf_event__header_size(child_event);
12765 perf_event__id_header_size(child_event);
12768 * Link it up in the child's context:
12770 raw_spin_lock_irqsave(&child_ctx->lock, flags);
12771 add_event_to_ctx(child_event, child_ctx);
12772 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
12775 * Link this into the parent event's child list
12777 list_add_tail(&child_event->child_list, &parent_event->child_list);
12778 mutex_unlock(&parent_event->child_mutex);
12780 return child_event;
12784 * Inherits an event group.
12786 * This will quietly suppress orphaned events; !inherit_event() is not an error.
12787 * This matches with perf_event_release_kernel() removing all child events.
12793 static int inherit_group(struct perf_event *parent_event,
12794 struct task_struct *parent,
12795 struct perf_event_context *parent_ctx,
12796 struct task_struct *child,
12797 struct perf_event_context *child_ctx)
12799 struct perf_event *leader;
12800 struct perf_event *sub;
12801 struct perf_event *child_ctr;
12803 leader = inherit_event(parent_event, parent, parent_ctx,
12804 child, NULL, child_ctx);
12805 if (IS_ERR(leader))
12806 return PTR_ERR(leader);
12808 * @leader can be NULL here because of is_orphaned_event(). In this
12809 * case inherit_event() will create individual events, similar to what
12810 * perf_group_detach() would do anyway.
12812 for_each_sibling_event(sub, parent_event) {
12813 child_ctr = inherit_event(sub, parent, parent_ctx,
12814 child, leader, child_ctx);
12815 if (IS_ERR(child_ctr))
12816 return PTR_ERR(child_ctr);
12818 if (sub->aux_event == parent_event && child_ctr &&
12819 !perf_get_aux_event(child_ctr, leader))
12826 * Creates the child task context and tries to inherit the event-group.
12828 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
12829 * inherited_all set when we 'fail' to inherit an orphaned event; this is
12830 * consistent with perf_event_release_kernel() removing all child events.
12837 inherit_task_group(struct perf_event *event, struct task_struct *parent,
12838 struct perf_event_context *parent_ctx,
12839 struct task_struct *child, int ctxn,
12840 int *inherited_all)
12843 struct perf_event_context *child_ctx;
12845 if (!event->attr.inherit) {
12846 *inherited_all = 0;
12850 child_ctx = child->perf_event_ctxp[ctxn];
12853 * This is executed from the parent task context, so
12854 * inherit events that have been marked for cloning.
12855 * First allocate and initialize a context for the
12858 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
12862 child->perf_event_ctxp[ctxn] = child_ctx;
12865 ret = inherit_group(event, parent, parent_ctx,
12869 *inherited_all = 0;
12875 * Initialize the perf_event context in task_struct
12877 static int perf_event_init_context(struct task_struct *child, int ctxn)
12879 struct perf_event_context *child_ctx, *parent_ctx;
12880 struct perf_event_context *cloned_ctx;
12881 struct perf_event *event;
12882 struct task_struct *parent = current;
12883 int inherited_all = 1;
12884 unsigned long flags;
12887 if (likely(!parent->perf_event_ctxp[ctxn]))
12891 * If the parent's context is a clone, pin it so it won't get
12892 * swapped under us.
12894 parent_ctx = perf_pin_task_context(parent, ctxn);
12899 * No need to check if parent_ctx != NULL here; since we saw
12900 * it non-NULL earlier, the only reason for it to become NULL
12901 * is if we exit, and since we're currently in the middle of
12902 * a fork we can't be exiting at the same time.
12906 * Lock the parent list. No need to lock the child - not PID
12907 * hashed yet and not running, so nobody can access it.
12909 mutex_lock(&parent_ctx->mutex);
12912 * We dont have to disable NMIs - we are only looking at
12913 * the list, not manipulating it:
12915 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
12916 ret = inherit_task_group(event, parent, parent_ctx,
12917 child, ctxn, &inherited_all);
12923 * We can't hold ctx->lock when iterating the ->flexible_group list due
12924 * to allocations, but we need to prevent rotation because
12925 * rotate_ctx() will change the list from interrupt context.
12927 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12928 parent_ctx->rotate_disable = 1;
12929 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12931 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
12932 ret = inherit_task_group(event, parent, parent_ctx,
12933 child, ctxn, &inherited_all);
12938 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12939 parent_ctx->rotate_disable = 0;
12941 child_ctx = child->perf_event_ctxp[ctxn];
12943 if (child_ctx && inherited_all) {
12945 * Mark the child context as a clone of the parent
12946 * context, or of whatever the parent is a clone of.
12948 * Note that if the parent is a clone, the holding of
12949 * parent_ctx->lock avoids it from being uncloned.
12951 cloned_ctx = parent_ctx->parent_ctx;
12953 child_ctx->parent_ctx = cloned_ctx;
12954 child_ctx->parent_gen = parent_ctx->parent_gen;
12956 child_ctx->parent_ctx = parent_ctx;
12957 child_ctx->parent_gen = parent_ctx->generation;
12959 get_ctx(child_ctx->parent_ctx);
12962 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12964 mutex_unlock(&parent_ctx->mutex);
12966 perf_unpin_context(parent_ctx);
12967 put_ctx(parent_ctx);
12973 * Initialize the perf_event context in task_struct
12975 int perf_event_init_task(struct task_struct *child)
12979 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
12980 mutex_init(&child->perf_event_mutex);
12981 INIT_LIST_HEAD(&child->perf_event_list);
12983 for_each_task_context_nr(ctxn) {
12984 ret = perf_event_init_context(child, ctxn);
12986 perf_event_free_task(child);
12994 static void __init perf_event_init_all_cpus(void)
12996 struct swevent_htable *swhash;
12999 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
13001 for_each_possible_cpu(cpu) {
13002 swhash = &per_cpu(swevent_htable, cpu);
13003 mutex_init(&swhash->hlist_mutex);
13004 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
13006 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
13007 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
13009 #ifdef CONFIG_CGROUP_PERF
13010 INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu));
13012 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
13016 static void perf_swevent_init_cpu(unsigned int cpu)
13018 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
13020 mutex_lock(&swhash->hlist_mutex);
13021 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
13022 struct swevent_hlist *hlist;
13024 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
13026 rcu_assign_pointer(swhash->swevent_hlist, hlist);
13028 mutex_unlock(&swhash->hlist_mutex);
13031 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
13032 static void __perf_event_exit_context(void *__info)
13034 struct perf_event_context *ctx = __info;
13035 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
13036 struct perf_event *event;
13038 raw_spin_lock(&ctx->lock);
13039 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
13040 list_for_each_entry(event, &ctx->event_list, event_entry)
13041 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
13042 raw_spin_unlock(&ctx->lock);
13045 static void perf_event_exit_cpu_context(int cpu)
13047 struct perf_cpu_context *cpuctx;
13048 struct perf_event_context *ctx;
13051 mutex_lock(&pmus_lock);
13052 list_for_each_entry(pmu, &pmus, entry) {
13053 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
13054 ctx = &cpuctx->ctx;
13056 mutex_lock(&ctx->mutex);
13057 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
13058 cpuctx->online = 0;
13059 mutex_unlock(&ctx->mutex);
13061 cpumask_clear_cpu(cpu, perf_online_mask);
13062 mutex_unlock(&pmus_lock);
13066 static void perf_event_exit_cpu_context(int cpu) { }
13070 int perf_event_init_cpu(unsigned int cpu)
13072 struct perf_cpu_context *cpuctx;
13073 struct perf_event_context *ctx;
13076 perf_swevent_init_cpu(cpu);
13078 mutex_lock(&pmus_lock);
13079 cpumask_set_cpu(cpu, perf_online_mask);
13080 list_for_each_entry(pmu, &pmus, entry) {
13081 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
13082 ctx = &cpuctx->ctx;
13084 mutex_lock(&ctx->mutex);
13085 cpuctx->online = 1;
13086 mutex_unlock(&ctx->mutex);
13088 mutex_unlock(&pmus_lock);
13093 int perf_event_exit_cpu(unsigned int cpu)
13095 perf_event_exit_cpu_context(cpu);
13100 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
13104 for_each_online_cpu(cpu)
13105 perf_event_exit_cpu(cpu);
13111 * Run the perf reboot notifier at the very last possible moment so that
13112 * the generic watchdog code runs as long as possible.
13114 static struct notifier_block perf_reboot_notifier = {
13115 .notifier_call = perf_reboot,
13116 .priority = INT_MIN,
13119 void __init perf_event_init(void)
13123 idr_init(&pmu_idr);
13125 perf_event_init_all_cpus();
13126 init_srcu_struct(&pmus_srcu);
13127 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
13128 perf_pmu_register(&perf_cpu_clock, NULL, -1);
13129 perf_pmu_register(&perf_task_clock, NULL, -1);
13130 perf_tp_register();
13131 perf_event_init_cpu(smp_processor_id());
13132 register_reboot_notifier(&perf_reboot_notifier);
13134 ret = init_hw_breakpoint();
13135 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
13137 perf_event_cache = KMEM_CACHE(perf_event, SLAB_PANIC);
13140 * Build time assertion that we keep the data_head at the intended
13141 * location. IOW, validation we got the __reserved[] size right.
13143 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
13147 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
13150 struct perf_pmu_events_attr *pmu_attr =
13151 container_of(attr, struct perf_pmu_events_attr, attr);
13153 if (pmu_attr->event_str)
13154 return sprintf(page, "%s\n", pmu_attr->event_str);
13158 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
13160 static int __init perf_event_sysfs_init(void)
13165 mutex_lock(&pmus_lock);
13167 ret = bus_register(&pmu_bus);
13171 list_for_each_entry(pmu, &pmus, entry) {
13172 if (!pmu->name || pmu->type < 0)
13175 ret = pmu_dev_alloc(pmu);
13176 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
13178 pmu_bus_running = 1;
13182 mutex_unlock(&pmus_lock);
13186 device_initcall(perf_event_sysfs_init);
13188 #ifdef CONFIG_CGROUP_PERF
13189 static struct cgroup_subsys_state *
13190 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
13192 struct perf_cgroup *jc;
13194 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
13196 return ERR_PTR(-ENOMEM);
13198 jc->info = alloc_percpu(struct perf_cgroup_info);
13201 return ERR_PTR(-ENOMEM);
13207 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
13209 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
13211 free_percpu(jc->info);
13215 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
13217 perf_event_cgroup(css->cgroup);
13221 static int __perf_cgroup_move(void *info)
13223 struct task_struct *task = info;
13225 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
13230 static void perf_cgroup_attach(struct cgroup_taskset *tset)
13232 struct task_struct *task;
13233 struct cgroup_subsys_state *css;
13235 cgroup_taskset_for_each(task, css, tset)
13236 task_function_call(task, __perf_cgroup_move, task);
13239 struct cgroup_subsys perf_event_cgrp_subsys = {
13240 .css_alloc = perf_cgroup_css_alloc,
13241 .css_free = perf_cgroup_css_free,
13242 .css_online = perf_cgroup_css_online,
13243 .attach = perf_cgroup_attach,
13245 * Implicitly enable on dfl hierarchy so that perf events can
13246 * always be filtered by cgroup2 path as long as perf_event
13247 * controller is not mounted on a legacy hierarchy.
13249 .implicit_on_dfl = true,
13252 #endif /* CONFIG_CGROUP_PERF */