1 // SPDX-License-Identifier: GPL-2.0
3 * Performance events core code:
5 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
6 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
7 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
8 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
13 #include <linux/cpu.h>
14 #include <linux/smp.h>
15 #include <linux/idr.h>
16 #include <linux/file.h>
17 #include <linux/poll.h>
18 #include <linux/slab.h>
19 #include <linux/hash.h>
20 #include <linux/tick.h>
21 #include <linux/sysfs.h>
22 #include <linux/dcache.h>
23 #include <linux/percpu.h>
24 #include <linux/ptrace.h>
25 #include <linux/reboot.h>
26 #include <linux/vmstat.h>
27 #include <linux/device.h>
28 #include <linux/export.h>
29 #include <linux/vmalloc.h>
30 #include <linux/hardirq.h>
31 #include <linux/hugetlb.h>
32 #include <linux/rculist.h>
33 #include <linux/uaccess.h>
34 #include <linux/syscalls.h>
35 #include <linux/anon_inodes.h>
36 #include <linux/kernel_stat.h>
37 #include <linux/cgroup.h>
38 #include <linux/perf_event.h>
39 #include <linux/trace_events.h>
40 #include <linux/hw_breakpoint.h>
41 #include <linux/mm_types.h>
42 #include <linux/module.h>
43 #include <linux/mman.h>
44 #include <linux/compat.h>
45 #include <linux/bpf.h>
46 #include <linux/filter.h>
47 #include <linux/namei.h>
48 #include <linux/parser.h>
49 #include <linux/sched/clock.h>
50 #include <linux/sched/mm.h>
51 #include <linux/proc_ns.h>
52 #include <linux/mount.h>
53 #include <linux/min_heap.h>
57 #include <asm/irq_regs.h>
59 typedef int (*remote_function_f)(void *);
61 struct remote_function_call {
62 struct task_struct *p;
63 remote_function_f func;
68 static void remote_function(void *data)
70 struct remote_function_call *tfc = data;
71 struct task_struct *p = tfc->p;
75 if (task_cpu(p) != smp_processor_id())
79 * Now that we're on right CPU with IRQs disabled, we can test
80 * if we hit the right task without races.
83 tfc->ret = -ESRCH; /* No such (running) process */
88 tfc->ret = tfc->func(tfc->info);
92 * task_function_call - call a function on the cpu on which a task runs
93 * @p: the task to evaluate
94 * @func: the function to be called
95 * @info: the function call argument
97 * Calls the function @func when the task is currently running. This might
98 * be on the current CPU, which just calls the function directly. This will
99 * retry due to any failures in smp_call_function_single(), such as if the
100 * task_cpu() goes offline concurrently.
102 * returns @func return value or -ESRCH when the process isn't running
105 task_function_call(struct task_struct *p, remote_function_f func, void *info)
107 struct remote_function_call data = {
116 ret = smp_call_function_single(task_cpu(p), remote_function,
118 ret = !ret ? data.ret : -EAGAIN;
130 * cpu_function_call - call a function on the cpu
131 * @func: the function to be called
132 * @info: the function call argument
134 * Calls the function @func on the remote cpu.
136 * returns: @func return value or -ENXIO when the cpu is offline
138 static int cpu_function_call(int cpu, remote_function_f func, void *info)
140 struct remote_function_call data = {
144 .ret = -ENXIO, /* No such CPU */
147 smp_call_function_single(cpu, remote_function, &data, 1);
152 static inline struct perf_cpu_context *
153 __get_cpu_context(struct perf_event_context *ctx)
155 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
158 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
159 struct perf_event_context *ctx)
161 raw_spin_lock(&cpuctx->ctx.lock);
163 raw_spin_lock(&ctx->lock);
166 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
167 struct perf_event_context *ctx)
170 raw_spin_unlock(&ctx->lock);
171 raw_spin_unlock(&cpuctx->ctx.lock);
174 #define TASK_TOMBSTONE ((void *)-1L)
176 static bool is_kernel_event(struct perf_event *event)
178 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
182 * On task ctx scheduling...
184 * When !ctx->nr_events a task context will not be scheduled. This means
185 * we can disable the scheduler hooks (for performance) without leaving
186 * pending task ctx state.
188 * This however results in two special cases:
190 * - removing the last event from a task ctx; this is relatively straight
191 * forward and is done in __perf_remove_from_context.
193 * - adding the first event to a task ctx; this is tricky because we cannot
194 * rely on ctx->is_active and therefore cannot use event_function_call().
195 * See perf_install_in_context().
197 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
200 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
201 struct perf_event_context *, void *);
203 struct event_function_struct {
204 struct perf_event *event;
209 static int event_function(void *info)
211 struct event_function_struct *efs = info;
212 struct perf_event *event = efs->event;
213 struct perf_event_context *ctx = event->ctx;
214 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
215 struct perf_event_context *task_ctx = cpuctx->task_ctx;
218 lockdep_assert_irqs_disabled();
220 perf_ctx_lock(cpuctx, task_ctx);
222 * Since we do the IPI call without holding ctx->lock things can have
223 * changed, double check we hit the task we set out to hit.
226 if (ctx->task != current) {
232 * We only use event_function_call() on established contexts,
233 * and event_function() is only ever called when active (or
234 * rather, we'll have bailed in task_function_call() or the
235 * above ctx->task != current test), therefore we must have
236 * ctx->is_active here.
238 WARN_ON_ONCE(!ctx->is_active);
240 * And since we have ctx->is_active, cpuctx->task_ctx must
243 WARN_ON_ONCE(task_ctx != ctx);
245 WARN_ON_ONCE(&cpuctx->ctx != ctx);
248 efs->func(event, cpuctx, ctx, efs->data);
250 perf_ctx_unlock(cpuctx, task_ctx);
255 static void event_function_call(struct perf_event *event, event_f func, void *data)
257 struct perf_event_context *ctx = event->ctx;
258 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
259 struct event_function_struct efs = {
265 if (!event->parent) {
267 * If this is a !child event, we must hold ctx::mutex to
268 * stabilize the the event->ctx relation. See
269 * perf_event_ctx_lock().
271 lockdep_assert_held(&ctx->mutex);
275 cpu_function_call(event->cpu, event_function, &efs);
279 if (task == TASK_TOMBSTONE)
283 if (!task_function_call(task, event_function, &efs))
286 raw_spin_lock_irq(&ctx->lock);
288 * Reload the task pointer, it might have been changed by
289 * a concurrent perf_event_context_sched_out().
292 if (task == TASK_TOMBSTONE) {
293 raw_spin_unlock_irq(&ctx->lock);
296 if (ctx->is_active) {
297 raw_spin_unlock_irq(&ctx->lock);
300 func(event, NULL, ctx, data);
301 raw_spin_unlock_irq(&ctx->lock);
305 * Similar to event_function_call() + event_function(), but hard assumes IRQs
306 * are already disabled and we're on the right CPU.
308 static void event_function_local(struct perf_event *event, event_f func, void *data)
310 struct perf_event_context *ctx = event->ctx;
311 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
312 struct task_struct *task = READ_ONCE(ctx->task);
313 struct perf_event_context *task_ctx = NULL;
315 lockdep_assert_irqs_disabled();
318 if (task == TASK_TOMBSTONE)
324 perf_ctx_lock(cpuctx, task_ctx);
327 if (task == TASK_TOMBSTONE)
332 * We must be either inactive or active and the right task,
333 * otherwise we're screwed, since we cannot IPI to somewhere
336 if (ctx->is_active) {
337 if (WARN_ON_ONCE(task != current))
340 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
344 WARN_ON_ONCE(&cpuctx->ctx != ctx);
347 func(event, cpuctx, ctx, data);
349 perf_ctx_unlock(cpuctx, task_ctx);
352 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
353 PERF_FLAG_FD_OUTPUT |\
354 PERF_FLAG_PID_CGROUP |\
355 PERF_FLAG_FD_CLOEXEC)
358 * branch priv levels that need permission checks
360 #define PERF_SAMPLE_BRANCH_PERM_PLM \
361 (PERF_SAMPLE_BRANCH_KERNEL |\
362 PERF_SAMPLE_BRANCH_HV)
365 EVENT_FLEXIBLE = 0x1,
368 /* see ctx_resched() for details */
370 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
374 * perf_sched_events : >0 events exist
375 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
378 static void perf_sched_delayed(struct work_struct *work);
379 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
380 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
381 static DEFINE_MUTEX(perf_sched_mutex);
382 static atomic_t perf_sched_count;
384 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
385 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
386 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
388 static atomic_t nr_mmap_events __read_mostly;
389 static atomic_t nr_comm_events __read_mostly;
390 static atomic_t nr_namespaces_events __read_mostly;
391 static atomic_t nr_task_events __read_mostly;
392 static atomic_t nr_freq_events __read_mostly;
393 static atomic_t nr_switch_events __read_mostly;
394 static atomic_t nr_ksymbol_events __read_mostly;
395 static atomic_t nr_bpf_events __read_mostly;
396 static atomic_t nr_cgroup_events __read_mostly;
397 static atomic_t nr_text_poke_events __read_mostly;
399 static LIST_HEAD(pmus);
400 static DEFINE_MUTEX(pmus_lock);
401 static struct srcu_struct pmus_srcu;
402 static cpumask_var_t perf_online_mask;
405 * perf event paranoia level:
406 * -1 - not paranoid at all
407 * 0 - disallow raw tracepoint access for unpriv
408 * 1 - disallow cpu events for unpriv
409 * 2 - disallow kernel profiling for unpriv
411 int sysctl_perf_event_paranoid __read_mostly = 2;
413 /* Minimum for 512 kiB + 1 user control page */
414 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
417 * max perf event sample rate
419 #define DEFAULT_MAX_SAMPLE_RATE 100000
420 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
421 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
423 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
425 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
426 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
428 static int perf_sample_allowed_ns __read_mostly =
429 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
431 static void update_perf_cpu_limits(void)
433 u64 tmp = perf_sample_period_ns;
435 tmp *= sysctl_perf_cpu_time_max_percent;
436 tmp = div_u64(tmp, 100);
440 WRITE_ONCE(perf_sample_allowed_ns, tmp);
443 static bool perf_rotate_context(struct perf_cpu_context *cpuctx);
445 int perf_proc_update_handler(struct ctl_table *table, int write,
446 void *buffer, size_t *lenp, loff_t *ppos)
449 int perf_cpu = sysctl_perf_cpu_time_max_percent;
451 * If throttling is disabled don't allow the write:
453 if (write && (perf_cpu == 100 || perf_cpu == 0))
456 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
460 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
461 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
462 update_perf_cpu_limits();
467 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
469 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
470 void *buffer, size_t *lenp, loff_t *ppos)
472 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
477 if (sysctl_perf_cpu_time_max_percent == 100 ||
478 sysctl_perf_cpu_time_max_percent == 0) {
480 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
481 WRITE_ONCE(perf_sample_allowed_ns, 0);
483 update_perf_cpu_limits();
490 * perf samples are done in some very critical code paths (NMIs).
491 * If they take too much CPU time, the system can lock up and not
492 * get any real work done. This will drop the sample rate when
493 * we detect that events are taking too long.
495 #define NR_ACCUMULATED_SAMPLES 128
496 static DEFINE_PER_CPU(u64, running_sample_length);
498 static u64 __report_avg;
499 static u64 __report_allowed;
501 static void perf_duration_warn(struct irq_work *w)
503 printk_ratelimited(KERN_INFO
504 "perf: interrupt took too long (%lld > %lld), lowering "
505 "kernel.perf_event_max_sample_rate to %d\n",
506 __report_avg, __report_allowed,
507 sysctl_perf_event_sample_rate);
510 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
512 void perf_sample_event_took(u64 sample_len_ns)
514 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
522 /* Decay the counter by 1 average sample. */
523 running_len = __this_cpu_read(running_sample_length);
524 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
525 running_len += sample_len_ns;
526 __this_cpu_write(running_sample_length, running_len);
529 * Note: this will be biased artifically low until we have
530 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
531 * from having to maintain a count.
533 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
534 if (avg_len <= max_len)
537 __report_avg = avg_len;
538 __report_allowed = max_len;
541 * Compute a throttle threshold 25% below the current duration.
543 avg_len += avg_len / 4;
544 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
550 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
551 WRITE_ONCE(max_samples_per_tick, max);
553 sysctl_perf_event_sample_rate = max * HZ;
554 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
556 if (!irq_work_queue(&perf_duration_work)) {
557 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
558 "kernel.perf_event_max_sample_rate to %d\n",
559 __report_avg, __report_allowed,
560 sysctl_perf_event_sample_rate);
564 static atomic64_t perf_event_id;
566 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
567 enum event_type_t event_type);
569 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
570 enum event_type_t event_type,
571 struct task_struct *task);
573 static void update_context_time(struct perf_event_context *ctx);
574 static u64 perf_event_time(struct perf_event *event);
576 void __weak perf_event_print_debug(void) { }
578 extern __weak const char *perf_pmu_name(void)
583 static inline u64 perf_clock(void)
585 return local_clock();
588 static inline u64 perf_event_clock(struct perf_event *event)
590 return event->clock();
594 * State based event timekeeping...
596 * The basic idea is to use event->state to determine which (if any) time
597 * fields to increment with the current delta. This means we only need to
598 * update timestamps when we change state or when they are explicitly requested
601 * Event groups make things a little more complicated, but not terribly so. The
602 * rules for a group are that if the group leader is OFF the entire group is
603 * OFF, irrespecive of what the group member states are. This results in
604 * __perf_effective_state().
606 * A futher ramification is that when a group leader flips between OFF and
607 * !OFF, we need to update all group member times.
610 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
611 * need to make sure the relevant context time is updated before we try and
612 * update our timestamps.
615 static __always_inline enum perf_event_state
616 __perf_effective_state(struct perf_event *event)
618 struct perf_event *leader = event->group_leader;
620 if (leader->state <= PERF_EVENT_STATE_OFF)
621 return leader->state;
626 static __always_inline void
627 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
629 enum perf_event_state state = __perf_effective_state(event);
630 u64 delta = now - event->tstamp;
632 *enabled = event->total_time_enabled;
633 if (state >= PERF_EVENT_STATE_INACTIVE)
636 *running = event->total_time_running;
637 if (state >= PERF_EVENT_STATE_ACTIVE)
641 static void perf_event_update_time(struct perf_event *event)
643 u64 now = perf_event_time(event);
645 __perf_update_times(event, now, &event->total_time_enabled,
646 &event->total_time_running);
650 static void perf_event_update_sibling_time(struct perf_event *leader)
652 struct perf_event *sibling;
654 for_each_sibling_event(sibling, leader)
655 perf_event_update_time(sibling);
659 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
661 if (event->state == state)
664 perf_event_update_time(event);
666 * If a group leader gets enabled/disabled all its siblings
669 if ((event->state < 0) ^ (state < 0))
670 perf_event_update_sibling_time(event);
672 WRITE_ONCE(event->state, state);
675 #ifdef CONFIG_CGROUP_PERF
678 perf_cgroup_match(struct perf_event *event)
680 struct perf_event_context *ctx = event->ctx;
681 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
683 /* @event doesn't care about cgroup */
687 /* wants specific cgroup scope but @cpuctx isn't associated with any */
692 * Cgroup scoping is recursive. An event enabled for a cgroup is
693 * also enabled for all its descendant cgroups. If @cpuctx's
694 * cgroup is a descendant of @event's (the test covers identity
695 * case), it's a match.
697 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
698 event->cgrp->css.cgroup);
701 static inline void perf_detach_cgroup(struct perf_event *event)
703 css_put(&event->cgrp->css);
707 static inline int is_cgroup_event(struct perf_event *event)
709 return event->cgrp != NULL;
712 static inline u64 perf_cgroup_event_time(struct perf_event *event)
714 struct perf_cgroup_info *t;
716 t = per_cpu_ptr(event->cgrp->info, event->cpu);
720 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
722 struct perf_cgroup_info *info;
727 info = this_cpu_ptr(cgrp->info);
729 info->time += now - info->timestamp;
730 info->timestamp = now;
733 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
735 struct perf_cgroup *cgrp = cpuctx->cgrp;
736 struct cgroup_subsys_state *css;
739 for (css = &cgrp->css; css; css = css->parent) {
740 cgrp = container_of(css, struct perf_cgroup, css);
741 __update_cgrp_time(cgrp);
746 static inline void update_cgrp_time_from_event(struct perf_event *event)
748 struct perf_cgroup *cgrp;
751 * ensure we access cgroup data only when needed and
752 * when we know the cgroup is pinned (css_get)
754 if (!is_cgroup_event(event))
757 cgrp = perf_cgroup_from_task(current, event->ctx);
759 * Do not update time when cgroup is not active
761 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
762 __update_cgrp_time(event->cgrp);
766 perf_cgroup_set_timestamp(struct task_struct *task,
767 struct perf_event_context *ctx)
769 struct perf_cgroup *cgrp;
770 struct perf_cgroup_info *info;
771 struct cgroup_subsys_state *css;
774 * ctx->lock held by caller
775 * ensure we do not access cgroup data
776 * unless we have the cgroup pinned (css_get)
778 if (!task || !ctx->nr_cgroups)
781 cgrp = perf_cgroup_from_task(task, ctx);
783 for (css = &cgrp->css; css; css = css->parent) {
784 cgrp = container_of(css, struct perf_cgroup, css);
785 info = this_cpu_ptr(cgrp->info);
786 info->timestamp = ctx->timestamp;
790 static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list);
792 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
793 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
796 * reschedule events based on the cgroup constraint of task.
798 * mode SWOUT : schedule out everything
799 * mode SWIN : schedule in based on cgroup for next
801 static void perf_cgroup_switch(struct task_struct *task, int mode)
803 struct perf_cpu_context *cpuctx;
804 struct list_head *list;
808 * Disable interrupts and preemption to avoid this CPU's
809 * cgrp_cpuctx_entry to change under us.
811 local_irq_save(flags);
813 list = this_cpu_ptr(&cgrp_cpuctx_list);
814 list_for_each_entry(cpuctx, list, cgrp_cpuctx_entry) {
815 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
817 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
818 perf_pmu_disable(cpuctx->ctx.pmu);
820 if (mode & PERF_CGROUP_SWOUT) {
821 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
823 * must not be done before ctxswout due
824 * to event_filter_match() in event_sched_out()
829 if (mode & PERF_CGROUP_SWIN) {
830 WARN_ON_ONCE(cpuctx->cgrp);
832 * set cgrp before ctxsw in to allow
833 * event_filter_match() to not have to pass
835 * we pass the cpuctx->ctx to perf_cgroup_from_task()
836 * because cgorup events are only per-cpu
838 cpuctx->cgrp = perf_cgroup_from_task(task,
840 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
842 perf_pmu_enable(cpuctx->ctx.pmu);
843 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
846 local_irq_restore(flags);
849 static inline void perf_cgroup_sched_out(struct task_struct *task,
850 struct task_struct *next)
852 struct perf_cgroup *cgrp1;
853 struct perf_cgroup *cgrp2 = NULL;
857 * we come here when we know perf_cgroup_events > 0
858 * we do not need to pass the ctx here because we know
859 * we are holding the rcu lock
861 cgrp1 = perf_cgroup_from_task(task, NULL);
862 cgrp2 = perf_cgroup_from_task(next, NULL);
865 * only schedule out current cgroup events if we know
866 * that we are switching to a different cgroup. Otherwise,
867 * do no touch the cgroup events.
870 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
875 static inline void perf_cgroup_sched_in(struct task_struct *prev,
876 struct task_struct *task)
878 struct perf_cgroup *cgrp1;
879 struct perf_cgroup *cgrp2 = NULL;
883 * we come here when we know perf_cgroup_events > 0
884 * we do not need to pass the ctx here because we know
885 * we are holding the rcu lock
887 cgrp1 = perf_cgroup_from_task(task, NULL);
888 cgrp2 = perf_cgroup_from_task(prev, NULL);
891 * only need to schedule in cgroup events if we are changing
892 * cgroup during ctxsw. Cgroup events were not scheduled
893 * out of ctxsw out if that was not the case.
896 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
901 static int perf_cgroup_ensure_storage(struct perf_event *event,
902 struct cgroup_subsys_state *css)
904 struct perf_cpu_context *cpuctx;
905 struct perf_event **storage;
906 int cpu, heap_size, ret = 0;
909 * Allow storage to have sufficent space for an iterator for each
910 * possibly nested cgroup plus an iterator for events with no cgroup.
912 for (heap_size = 1; css; css = css->parent)
915 for_each_possible_cpu(cpu) {
916 cpuctx = per_cpu_ptr(event->pmu->pmu_cpu_context, cpu);
917 if (heap_size <= cpuctx->heap_size)
920 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
921 GFP_KERNEL, cpu_to_node(cpu));
927 raw_spin_lock_irq(&cpuctx->ctx.lock);
928 if (cpuctx->heap_size < heap_size) {
929 swap(cpuctx->heap, storage);
930 if (storage == cpuctx->heap_default)
932 cpuctx->heap_size = heap_size;
934 raw_spin_unlock_irq(&cpuctx->ctx.lock);
942 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
943 struct perf_event_attr *attr,
944 struct perf_event *group_leader)
946 struct perf_cgroup *cgrp;
947 struct cgroup_subsys_state *css;
948 struct fd f = fdget(fd);
954 css = css_tryget_online_from_dir(f.file->f_path.dentry,
955 &perf_event_cgrp_subsys);
961 ret = perf_cgroup_ensure_storage(event, css);
965 cgrp = container_of(css, struct perf_cgroup, css);
969 * all events in a group must monitor
970 * the same cgroup because a task belongs
971 * to only one perf cgroup at a time
973 if (group_leader && group_leader->cgrp != cgrp) {
974 perf_detach_cgroup(event);
983 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
985 struct perf_cgroup_info *t;
986 t = per_cpu_ptr(event->cgrp->info, event->cpu);
987 event->shadow_ctx_time = now - t->timestamp;
991 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
993 struct perf_cpu_context *cpuctx;
995 if (!is_cgroup_event(event))
999 * Because cgroup events are always per-cpu events,
1000 * @ctx == &cpuctx->ctx.
1002 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1005 * Since setting cpuctx->cgrp is conditional on the current @cgrp
1006 * matching the event's cgroup, we must do this for every new event,
1007 * because if the first would mismatch, the second would not try again
1008 * and we would leave cpuctx->cgrp unset.
1010 if (ctx->is_active && !cpuctx->cgrp) {
1011 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
1013 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
1014 cpuctx->cgrp = cgrp;
1017 if (ctx->nr_cgroups++)
1020 list_add(&cpuctx->cgrp_cpuctx_entry,
1021 per_cpu_ptr(&cgrp_cpuctx_list, event->cpu));
1025 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1027 struct perf_cpu_context *cpuctx;
1029 if (!is_cgroup_event(event))
1033 * Because cgroup events are always per-cpu events,
1034 * @ctx == &cpuctx->ctx.
1036 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1038 if (--ctx->nr_cgroups)
1041 if (ctx->is_active && cpuctx->cgrp)
1042 cpuctx->cgrp = NULL;
1044 list_del(&cpuctx->cgrp_cpuctx_entry);
1047 #else /* !CONFIG_CGROUP_PERF */
1050 perf_cgroup_match(struct perf_event *event)
1055 static inline void perf_detach_cgroup(struct perf_event *event)
1058 static inline int is_cgroup_event(struct perf_event *event)
1063 static inline void update_cgrp_time_from_event(struct perf_event *event)
1067 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
1071 static inline void perf_cgroup_sched_out(struct task_struct *task,
1072 struct task_struct *next)
1076 static inline void perf_cgroup_sched_in(struct task_struct *prev,
1077 struct task_struct *task)
1081 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1082 struct perf_event_attr *attr,
1083 struct perf_event *group_leader)
1089 perf_cgroup_set_timestamp(struct task_struct *task,
1090 struct perf_event_context *ctx)
1095 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
1100 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
1104 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1110 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1115 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1121 * set default to be dependent on timer tick just
1122 * like original code
1124 #define PERF_CPU_HRTIMER (1000 / HZ)
1126 * function must be called with interrupts disabled
1128 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1130 struct perf_cpu_context *cpuctx;
1133 lockdep_assert_irqs_disabled();
1135 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
1136 rotations = perf_rotate_context(cpuctx);
1138 raw_spin_lock(&cpuctx->hrtimer_lock);
1140 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
1142 cpuctx->hrtimer_active = 0;
1143 raw_spin_unlock(&cpuctx->hrtimer_lock);
1145 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1148 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
1150 struct hrtimer *timer = &cpuctx->hrtimer;
1151 struct pmu *pmu = cpuctx->ctx.pmu;
1154 /* no multiplexing needed for SW PMU */
1155 if (pmu->task_ctx_nr == perf_sw_context)
1159 * check default is sane, if not set then force to
1160 * default interval (1/tick)
1162 interval = pmu->hrtimer_interval_ms;
1164 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1166 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1168 raw_spin_lock_init(&cpuctx->hrtimer_lock);
1169 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
1170 timer->function = perf_mux_hrtimer_handler;
1173 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1175 struct hrtimer *timer = &cpuctx->hrtimer;
1176 struct pmu *pmu = cpuctx->ctx.pmu;
1177 unsigned long flags;
1179 /* not for SW PMU */
1180 if (pmu->task_ctx_nr == perf_sw_context)
1183 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1184 if (!cpuctx->hrtimer_active) {
1185 cpuctx->hrtimer_active = 1;
1186 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1187 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1189 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1194 void perf_pmu_disable(struct pmu *pmu)
1196 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1198 pmu->pmu_disable(pmu);
1201 void perf_pmu_enable(struct pmu *pmu)
1203 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1205 pmu->pmu_enable(pmu);
1208 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1211 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1212 * perf_event_task_tick() are fully serialized because they're strictly cpu
1213 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1214 * disabled, while perf_event_task_tick is called from IRQ context.
1216 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1218 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1220 lockdep_assert_irqs_disabled();
1222 WARN_ON(!list_empty(&ctx->active_ctx_list));
1224 list_add(&ctx->active_ctx_list, head);
1227 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1229 lockdep_assert_irqs_disabled();
1231 WARN_ON(list_empty(&ctx->active_ctx_list));
1233 list_del_init(&ctx->active_ctx_list);
1236 static void get_ctx(struct perf_event_context *ctx)
1238 refcount_inc(&ctx->refcount);
1241 static void *alloc_task_ctx_data(struct pmu *pmu)
1243 if (pmu->task_ctx_cache)
1244 return kmem_cache_zalloc(pmu->task_ctx_cache, GFP_KERNEL);
1249 static void free_task_ctx_data(struct pmu *pmu, void *task_ctx_data)
1251 if (pmu->task_ctx_cache && task_ctx_data)
1252 kmem_cache_free(pmu->task_ctx_cache, task_ctx_data);
1255 static void free_ctx(struct rcu_head *head)
1257 struct perf_event_context *ctx;
1259 ctx = container_of(head, struct perf_event_context, rcu_head);
1260 free_task_ctx_data(ctx->pmu, ctx->task_ctx_data);
1264 static void put_ctx(struct perf_event_context *ctx)
1266 if (refcount_dec_and_test(&ctx->refcount)) {
1267 if (ctx->parent_ctx)
1268 put_ctx(ctx->parent_ctx);
1269 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1270 put_task_struct(ctx->task);
1271 call_rcu(&ctx->rcu_head, free_ctx);
1276 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1277 * perf_pmu_migrate_context() we need some magic.
1279 * Those places that change perf_event::ctx will hold both
1280 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1282 * Lock ordering is by mutex address. There are two other sites where
1283 * perf_event_context::mutex nests and those are:
1285 * - perf_event_exit_task_context() [ child , 0 ]
1286 * perf_event_exit_event()
1287 * put_event() [ parent, 1 ]
1289 * - perf_event_init_context() [ parent, 0 ]
1290 * inherit_task_group()
1293 * perf_event_alloc()
1295 * perf_try_init_event() [ child , 1 ]
1297 * While it appears there is an obvious deadlock here -- the parent and child
1298 * nesting levels are inverted between the two. This is in fact safe because
1299 * life-time rules separate them. That is an exiting task cannot fork, and a
1300 * spawning task cannot (yet) exit.
1302 * But remember that that these are parent<->child context relations, and
1303 * migration does not affect children, therefore these two orderings should not
1306 * The change in perf_event::ctx does not affect children (as claimed above)
1307 * because the sys_perf_event_open() case will install a new event and break
1308 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1309 * concerned with cpuctx and that doesn't have children.
1311 * The places that change perf_event::ctx will issue:
1313 * perf_remove_from_context();
1314 * synchronize_rcu();
1315 * perf_install_in_context();
1317 * to affect the change. The remove_from_context() + synchronize_rcu() should
1318 * quiesce the event, after which we can install it in the new location. This
1319 * means that only external vectors (perf_fops, prctl) can perturb the event
1320 * while in transit. Therefore all such accessors should also acquire
1321 * perf_event_context::mutex to serialize against this.
1323 * However; because event->ctx can change while we're waiting to acquire
1324 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1329 * task_struct::perf_event_mutex
1330 * perf_event_context::mutex
1331 * perf_event::child_mutex;
1332 * perf_event_context::lock
1333 * perf_event::mmap_mutex
1335 * perf_addr_filters_head::lock
1339 * cpuctx->mutex / perf_event_context::mutex
1341 static struct perf_event_context *
1342 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1344 struct perf_event_context *ctx;
1348 ctx = READ_ONCE(event->ctx);
1349 if (!refcount_inc_not_zero(&ctx->refcount)) {
1355 mutex_lock_nested(&ctx->mutex, nesting);
1356 if (event->ctx != ctx) {
1357 mutex_unlock(&ctx->mutex);
1365 static inline struct perf_event_context *
1366 perf_event_ctx_lock(struct perf_event *event)
1368 return perf_event_ctx_lock_nested(event, 0);
1371 static void perf_event_ctx_unlock(struct perf_event *event,
1372 struct perf_event_context *ctx)
1374 mutex_unlock(&ctx->mutex);
1379 * This must be done under the ctx->lock, such as to serialize against
1380 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1381 * calling scheduler related locks and ctx->lock nests inside those.
1383 static __must_check struct perf_event_context *
1384 unclone_ctx(struct perf_event_context *ctx)
1386 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1388 lockdep_assert_held(&ctx->lock);
1391 ctx->parent_ctx = NULL;
1397 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1402 * only top level events have the pid namespace they were created in
1405 event = event->parent;
1407 nr = __task_pid_nr_ns(p, type, event->ns);
1408 /* avoid -1 if it is idle thread or runs in another ns */
1409 if (!nr && !pid_alive(p))
1414 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1416 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1419 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1421 return perf_event_pid_type(event, p, PIDTYPE_PID);
1425 * If we inherit events we want to return the parent event id
1428 static u64 primary_event_id(struct perf_event *event)
1433 id = event->parent->id;
1439 * Get the perf_event_context for a task and lock it.
1441 * This has to cope with with the fact that until it is locked,
1442 * the context could get moved to another task.
1444 static struct perf_event_context *
1445 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1447 struct perf_event_context *ctx;
1451 * One of the few rules of preemptible RCU is that one cannot do
1452 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1453 * part of the read side critical section was irqs-enabled -- see
1454 * rcu_read_unlock_special().
1456 * Since ctx->lock nests under rq->lock we must ensure the entire read
1457 * side critical section has interrupts disabled.
1459 local_irq_save(*flags);
1461 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1464 * If this context is a clone of another, it might
1465 * get swapped for another underneath us by
1466 * perf_event_task_sched_out, though the
1467 * rcu_read_lock() protects us from any context
1468 * getting freed. Lock the context and check if it
1469 * got swapped before we could get the lock, and retry
1470 * if so. If we locked the right context, then it
1471 * can't get swapped on us any more.
1473 raw_spin_lock(&ctx->lock);
1474 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1475 raw_spin_unlock(&ctx->lock);
1477 local_irq_restore(*flags);
1481 if (ctx->task == TASK_TOMBSTONE ||
1482 !refcount_inc_not_zero(&ctx->refcount)) {
1483 raw_spin_unlock(&ctx->lock);
1486 WARN_ON_ONCE(ctx->task != task);
1491 local_irq_restore(*flags);
1496 * Get the context for a task and increment its pin_count so it
1497 * can't get swapped to another task. This also increments its
1498 * reference count so that the context can't get freed.
1500 static struct perf_event_context *
1501 perf_pin_task_context(struct task_struct *task, int ctxn)
1503 struct perf_event_context *ctx;
1504 unsigned long flags;
1506 ctx = perf_lock_task_context(task, ctxn, &flags);
1509 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1514 static void perf_unpin_context(struct perf_event_context *ctx)
1516 unsigned long flags;
1518 raw_spin_lock_irqsave(&ctx->lock, flags);
1520 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1524 * Update the record of the current time in a context.
1526 static void update_context_time(struct perf_event_context *ctx)
1528 u64 now = perf_clock();
1530 ctx->time += now - ctx->timestamp;
1531 ctx->timestamp = now;
1534 static u64 perf_event_time(struct perf_event *event)
1536 struct perf_event_context *ctx = event->ctx;
1538 if (is_cgroup_event(event))
1539 return perf_cgroup_event_time(event);
1541 return ctx ? ctx->time : 0;
1544 static enum event_type_t get_event_type(struct perf_event *event)
1546 struct perf_event_context *ctx = event->ctx;
1547 enum event_type_t event_type;
1549 lockdep_assert_held(&ctx->lock);
1552 * It's 'group type', really, because if our group leader is
1553 * pinned, so are we.
1555 if (event->group_leader != event)
1556 event = event->group_leader;
1558 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1560 event_type |= EVENT_CPU;
1566 * Helper function to initialize event group nodes.
1568 static void init_event_group(struct perf_event *event)
1570 RB_CLEAR_NODE(&event->group_node);
1571 event->group_index = 0;
1575 * Extract pinned or flexible groups from the context
1576 * based on event attrs bits.
1578 static struct perf_event_groups *
1579 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1581 if (event->attr.pinned)
1582 return &ctx->pinned_groups;
1584 return &ctx->flexible_groups;
1588 * Helper function to initializes perf_event_group trees.
1590 static void perf_event_groups_init(struct perf_event_groups *groups)
1592 groups->tree = RB_ROOT;
1597 * Compare function for event groups;
1599 * Implements complex key that first sorts by CPU and then by virtual index
1600 * which provides ordering when rotating groups for the same CPU.
1603 perf_event_groups_less(struct perf_event *left, struct perf_event *right)
1605 if (left->cpu < right->cpu)
1607 if (left->cpu > right->cpu)
1610 #ifdef CONFIG_CGROUP_PERF
1611 if (left->cgrp != right->cgrp) {
1612 if (!left->cgrp || !left->cgrp->css.cgroup) {
1614 * Left has no cgroup but right does, no cgroups come
1619 if (!right->cgrp || !right->cgrp->css.cgroup) {
1621 * Right has no cgroup but left does, no cgroups come
1626 /* Two dissimilar cgroups, order by id. */
1627 if (left->cgrp->css.cgroup->kn->id < right->cgrp->css.cgroup->kn->id)
1634 if (left->group_index < right->group_index)
1636 if (left->group_index > right->group_index)
1643 * Insert @event into @groups' tree; using {@event->cpu, ++@groups->index} for
1644 * key (see perf_event_groups_less). This places it last inside the CPU
1648 perf_event_groups_insert(struct perf_event_groups *groups,
1649 struct perf_event *event)
1651 struct perf_event *node_event;
1652 struct rb_node *parent;
1653 struct rb_node **node;
1655 event->group_index = ++groups->index;
1657 node = &groups->tree.rb_node;
1662 node_event = container_of(*node, struct perf_event, group_node);
1664 if (perf_event_groups_less(event, node_event))
1665 node = &parent->rb_left;
1667 node = &parent->rb_right;
1670 rb_link_node(&event->group_node, parent, node);
1671 rb_insert_color(&event->group_node, &groups->tree);
1675 * Helper function to insert event into the pinned or flexible groups.
1678 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1680 struct perf_event_groups *groups;
1682 groups = get_event_groups(event, ctx);
1683 perf_event_groups_insert(groups, event);
1687 * Delete a group from a tree.
1690 perf_event_groups_delete(struct perf_event_groups *groups,
1691 struct perf_event *event)
1693 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1694 RB_EMPTY_ROOT(&groups->tree));
1696 rb_erase(&event->group_node, &groups->tree);
1697 init_event_group(event);
1701 * Helper function to delete event from its groups.
1704 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1706 struct perf_event_groups *groups;
1708 groups = get_event_groups(event, ctx);
1709 perf_event_groups_delete(groups, event);
1713 * Get the leftmost event in the cpu/cgroup subtree.
1715 static struct perf_event *
1716 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1717 struct cgroup *cgrp)
1719 struct perf_event *node_event = NULL, *match = NULL;
1720 struct rb_node *node = groups->tree.rb_node;
1721 #ifdef CONFIG_CGROUP_PERF
1722 u64 node_cgrp_id, cgrp_id = 0;
1725 cgrp_id = cgrp->kn->id;
1729 node_event = container_of(node, struct perf_event, group_node);
1731 if (cpu < node_event->cpu) {
1732 node = node->rb_left;
1735 if (cpu > node_event->cpu) {
1736 node = node->rb_right;
1739 #ifdef CONFIG_CGROUP_PERF
1741 if (node_event->cgrp && node_event->cgrp->css.cgroup)
1742 node_cgrp_id = node_event->cgrp->css.cgroup->kn->id;
1744 if (cgrp_id < node_cgrp_id) {
1745 node = node->rb_left;
1748 if (cgrp_id > node_cgrp_id) {
1749 node = node->rb_right;
1754 node = node->rb_left;
1761 * Like rb_entry_next_safe() for the @cpu subtree.
1763 static struct perf_event *
1764 perf_event_groups_next(struct perf_event *event)
1766 struct perf_event *next;
1767 #ifdef CONFIG_CGROUP_PERF
1768 u64 curr_cgrp_id = 0;
1769 u64 next_cgrp_id = 0;
1772 next = rb_entry_safe(rb_next(&event->group_node), typeof(*event), group_node);
1773 if (next == NULL || next->cpu != event->cpu)
1776 #ifdef CONFIG_CGROUP_PERF
1777 if (event->cgrp && event->cgrp->css.cgroup)
1778 curr_cgrp_id = event->cgrp->css.cgroup->kn->id;
1780 if (next->cgrp && next->cgrp->css.cgroup)
1781 next_cgrp_id = next->cgrp->css.cgroup->kn->id;
1783 if (curr_cgrp_id != next_cgrp_id)
1790 * Iterate through the whole groups tree.
1792 #define perf_event_groups_for_each(event, groups) \
1793 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1794 typeof(*event), group_node); event; \
1795 event = rb_entry_safe(rb_next(&event->group_node), \
1796 typeof(*event), group_node))
1799 * Add an event from the lists for its context.
1800 * Must be called with ctx->mutex and ctx->lock held.
1803 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1805 lockdep_assert_held(&ctx->lock);
1807 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1808 event->attach_state |= PERF_ATTACH_CONTEXT;
1810 event->tstamp = perf_event_time(event);
1813 * If we're a stand alone event or group leader, we go to the context
1814 * list, group events are kept attached to the group so that
1815 * perf_group_detach can, at all times, locate all siblings.
1817 if (event->group_leader == event) {
1818 event->group_caps = event->event_caps;
1819 add_event_to_groups(event, ctx);
1822 list_add_rcu(&event->event_entry, &ctx->event_list);
1824 if (event->attr.inherit_stat)
1827 if (event->state > PERF_EVENT_STATE_OFF)
1828 perf_cgroup_event_enable(event, ctx);
1834 * Initialize event state based on the perf_event_attr::disabled.
1836 static inline void perf_event__state_init(struct perf_event *event)
1838 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1839 PERF_EVENT_STATE_INACTIVE;
1842 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1844 int entry = sizeof(u64); /* value */
1848 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1849 size += sizeof(u64);
1851 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1852 size += sizeof(u64);
1854 if (event->attr.read_format & PERF_FORMAT_ID)
1855 entry += sizeof(u64);
1857 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1859 size += sizeof(u64);
1863 event->read_size = size;
1866 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1868 struct perf_sample_data *data;
1871 if (sample_type & PERF_SAMPLE_IP)
1872 size += sizeof(data->ip);
1874 if (sample_type & PERF_SAMPLE_ADDR)
1875 size += sizeof(data->addr);
1877 if (sample_type & PERF_SAMPLE_PERIOD)
1878 size += sizeof(data->period);
1880 if (sample_type & PERF_SAMPLE_WEIGHT)
1881 size += sizeof(data->weight);
1883 if (sample_type & PERF_SAMPLE_READ)
1884 size += event->read_size;
1886 if (sample_type & PERF_SAMPLE_DATA_SRC)
1887 size += sizeof(data->data_src.val);
1889 if (sample_type & PERF_SAMPLE_TRANSACTION)
1890 size += sizeof(data->txn);
1892 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1893 size += sizeof(data->phys_addr);
1895 if (sample_type & PERF_SAMPLE_CGROUP)
1896 size += sizeof(data->cgroup);
1898 event->header_size = size;
1902 * Called at perf_event creation and when events are attached/detached from a
1905 static void perf_event__header_size(struct perf_event *event)
1907 __perf_event_read_size(event,
1908 event->group_leader->nr_siblings);
1909 __perf_event_header_size(event, event->attr.sample_type);
1912 static void perf_event__id_header_size(struct perf_event *event)
1914 struct perf_sample_data *data;
1915 u64 sample_type = event->attr.sample_type;
1918 if (sample_type & PERF_SAMPLE_TID)
1919 size += sizeof(data->tid_entry);
1921 if (sample_type & PERF_SAMPLE_TIME)
1922 size += sizeof(data->time);
1924 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1925 size += sizeof(data->id);
1927 if (sample_type & PERF_SAMPLE_ID)
1928 size += sizeof(data->id);
1930 if (sample_type & PERF_SAMPLE_STREAM_ID)
1931 size += sizeof(data->stream_id);
1933 if (sample_type & PERF_SAMPLE_CPU)
1934 size += sizeof(data->cpu_entry);
1936 event->id_header_size = size;
1939 static bool perf_event_validate_size(struct perf_event *event)
1942 * The values computed here will be over-written when we actually
1945 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1946 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1947 perf_event__id_header_size(event);
1950 * Sum the lot; should not exceed the 64k limit we have on records.
1951 * Conservative limit to allow for callchains and other variable fields.
1953 if (event->read_size + event->header_size +
1954 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1960 static void perf_group_attach(struct perf_event *event)
1962 struct perf_event *group_leader = event->group_leader, *pos;
1964 lockdep_assert_held(&event->ctx->lock);
1967 * We can have double attach due to group movement in perf_event_open.
1969 if (event->attach_state & PERF_ATTACH_GROUP)
1972 event->attach_state |= PERF_ATTACH_GROUP;
1974 if (group_leader == event)
1977 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1979 group_leader->group_caps &= event->event_caps;
1981 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
1982 group_leader->nr_siblings++;
1984 perf_event__header_size(group_leader);
1986 for_each_sibling_event(pos, group_leader)
1987 perf_event__header_size(pos);
1991 * Remove an event from the lists for its context.
1992 * Must be called with ctx->mutex and ctx->lock held.
1995 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1997 WARN_ON_ONCE(event->ctx != ctx);
1998 lockdep_assert_held(&ctx->lock);
2001 * We can have double detach due to exit/hot-unplug + close.
2003 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
2006 event->attach_state &= ~PERF_ATTACH_CONTEXT;
2009 if (event->attr.inherit_stat)
2012 list_del_rcu(&event->event_entry);
2014 if (event->group_leader == event)
2015 del_event_from_groups(event, ctx);
2018 * If event was in error state, then keep it
2019 * that way, otherwise bogus counts will be
2020 * returned on read(). The only way to get out
2021 * of error state is by explicit re-enabling
2024 if (event->state > PERF_EVENT_STATE_OFF) {
2025 perf_cgroup_event_disable(event, ctx);
2026 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2033 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2035 if (!has_aux(aux_event))
2038 if (!event->pmu->aux_output_match)
2041 return event->pmu->aux_output_match(aux_event);
2044 static void put_event(struct perf_event *event);
2045 static void event_sched_out(struct perf_event *event,
2046 struct perf_cpu_context *cpuctx,
2047 struct perf_event_context *ctx);
2049 static void perf_put_aux_event(struct perf_event *event)
2051 struct perf_event_context *ctx = event->ctx;
2052 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2053 struct perf_event *iter;
2056 * If event uses aux_event tear down the link
2058 if (event->aux_event) {
2059 iter = event->aux_event;
2060 event->aux_event = NULL;
2066 * If the event is an aux_event, tear down all links to
2067 * it from other events.
2069 for_each_sibling_event(iter, event->group_leader) {
2070 if (iter->aux_event != event)
2073 iter->aux_event = NULL;
2077 * If it's ACTIVE, schedule it out and put it into ERROR
2078 * state so that we don't try to schedule it again. Note
2079 * that perf_event_enable() will clear the ERROR status.
2081 event_sched_out(iter, cpuctx, ctx);
2082 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2086 static bool perf_need_aux_event(struct perf_event *event)
2088 return !!event->attr.aux_output || !!event->attr.aux_sample_size;
2091 static int perf_get_aux_event(struct perf_event *event,
2092 struct perf_event *group_leader)
2095 * Our group leader must be an aux event if we want to be
2096 * an aux_output. This way, the aux event will precede its
2097 * aux_output events in the group, and therefore will always
2104 * aux_output and aux_sample_size are mutually exclusive.
2106 if (event->attr.aux_output && event->attr.aux_sample_size)
2109 if (event->attr.aux_output &&
2110 !perf_aux_output_match(event, group_leader))
2113 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2116 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2120 * Link aux_outputs to their aux event; this is undone in
2121 * perf_group_detach() by perf_put_aux_event(). When the
2122 * group in torn down, the aux_output events loose their
2123 * link to the aux_event and can't schedule any more.
2125 event->aux_event = group_leader;
2130 static inline struct list_head *get_event_list(struct perf_event *event)
2132 struct perf_event_context *ctx = event->ctx;
2133 return event->attr.pinned ? &ctx->pinned_active : &ctx->flexible_active;
2136 static void perf_group_detach(struct perf_event *event)
2138 struct perf_event *sibling, *tmp;
2139 struct perf_event_context *ctx = event->ctx;
2141 lockdep_assert_held(&ctx->lock);
2144 * We can have double detach due to exit/hot-unplug + close.
2146 if (!(event->attach_state & PERF_ATTACH_GROUP))
2149 event->attach_state &= ~PERF_ATTACH_GROUP;
2151 perf_put_aux_event(event);
2154 * If this is a sibling, remove it from its group.
2156 if (event->group_leader != event) {
2157 list_del_init(&event->sibling_list);
2158 event->group_leader->nr_siblings--;
2163 * If this was a group event with sibling events then
2164 * upgrade the siblings to singleton events by adding them
2165 * to whatever list we are on.
2167 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2169 sibling->group_leader = sibling;
2170 list_del_init(&sibling->sibling_list);
2172 /* Inherit group flags from the previous leader */
2173 sibling->group_caps = event->group_caps;
2175 if (!RB_EMPTY_NODE(&event->group_node)) {
2176 add_event_to_groups(sibling, event->ctx);
2178 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2179 list_add_tail(&sibling->active_list, get_event_list(sibling));
2182 WARN_ON_ONCE(sibling->ctx != event->ctx);
2186 perf_event__header_size(event->group_leader);
2188 for_each_sibling_event(tmp, event->group_leader)
2189 perf_event__header_size(tmp);
2192 static bool is_orphaned_event(struct perf_event *event)
2194 return event->state == PERF_EVENT_STATE_DEAD;
2197 static inline int __pmu_filter_match(struct perf_event *event)
2199 struct pmu *pmu = event->pmu;
2200 return pmu->filter_match ? pmu->filter_match(event) : 1;
2204 * Check whether we should attempt to schedule an event group based on
2205 * PMU-specific filtering. An event group can consist of HW and SW events,
2206 * potentially with a SW leader, so we must check all the filters, to
2207 * determine whether a group is schedulable:
2209 static inline int pmu_filter_match(struct perf_event *event)
2211 struct perf_event *sibling;
2213 if (!__pmu_filter_match(event))
2216 for_each_sibling_event(sibling, event) {
2217 if (!__pmu_filter_match(sibling))
2225 event_filter_match(struct perf_event *event)
2227 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2228 perf_cgroup_match(event) && pmu_filter_match(event);
2232 event_sched_out(struct perf_event *event,
2233 struct perf_cpu_context *cpuctx,
2234 struct perf_event_context *ctx)
2236 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2238 WARN_ON_ONCE(event->ctx != ctx);
2239 lockdep_assert_held(&ctx->lock);
2241 if (event->state != PERF_EVENT_STATE_ACTIVE)
2245 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2246 * we can schedule events _OUT_ individually through things like
2247 * __perf_remove_from_context().
2249 list_del_init(&event->active_list);
2251 perf_pmu_disable(event->pmu);
2253 event->pmu->del(event, 0);
2256 if (READ_ONCE(event->pending_disable) >= 0) {
2257 WRITE_ONCE(event->pending_disable, -1);
2258 perf_cgroup_event_disable(event, ctx);
2259 state = PERF_EVENT_STATE_OFF;
2261 perf_event_set_state(event, state);
2263 if (!is_software_event(event))
2264 cpuctx->active_oncpu--;
2265 if (!--ctx->nr_active)
2266 perf_event_ctx_deactivate(ctx);
2267 if (event->attr.freq && event->attr.sample_freq)
2269 if (event->attr.exclusive || !cpuctx->active_oncpu)
2270 cpuctx->exclusive = 0;
2272 perf_pmu_enable(event->pmu);
2276 group_sched_out(struct perf_event *group_event,
2277 struct perf_cpu_context *cpuctx,
2278 struct perf_event_context *ctx)
2280 struct perf_event *event;
2282 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2285 perf_pmu_disable(ctx->pmu);
2287 event_sched_out(group_event, cpuctx, ctx);
2290 * Schedule out siblings (if any):
2292 for_each_sibling_event(event, group_event)
2293 event_sched_out(event, cpuctx, ctx);
2295 perf_pmu_enable(ctx->pmu);
2297 if (group_event->attr.exclusive)
2298 cpuctx->exclusive = 0;
2301 #define DETACH_GROUP 0x01UL
2304 * Cross CPU call to remove a performance event
2306 * We disable the event on the hardware level first. After that we
2307 * remove it from the context list.
2310 __perf_remove_from_context(struct perf_event *event,
2311 struct perf_cpu_context *cpuctx,
2312 struct perf_event_context *ctx,
2315 unsigned long flags = (unsigned long)info;
2317 if (ctx->is_active & EVENT_TIME) {
2318 update_context_time(ctx);
2319 update_cgrp_time_from_cpuctx(cpuctx);
2322 event_sched_out(event, cpuctx, ctx);
2323 if (flags & DETACH_GROUP)
2324 perf_group_detach(event);
2325 list_del_event(event, ctx);
2327 if (!ctx->nr_events && ctx->is_active) {
2329 ctx->rotate_necessary = 0;
2331 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2332 cpuctx->task_ctx = NULL;
2338 * Remove the event from a task's (or a CPU's) list of events.
2340 * If event->ctx is a cloned context, callers must make sure that
2341 * every task struct that event->ctx->task could possibly point to
2342 * remains valid. This is OK when called from perf_release since
2343 * that only calls us on the top-level context, which can't be a clone.
2344 * When called from perf_event_exit_task, it's OK because the
2345 * context has been detached from its task.
2347 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2349 struct perf_event_context *ctx = event->ctx;
2351 lockdep_assert_held(&ctx->mutex);
2353 event_function_call(event, __perf_remove_from_context, (void *)flags);
2356 * The above event_function_call() can NO-OP when it hits
2357 * TASK_TOMBSTONE. In that case we must already have been detached
2358 * from the context (by perf_event_exit_event()) but the grouping
2359 * might still be in-tact.
2361 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
2362 if ((flags & DETACH_GROUP) &&
2363 (event->attach_state & PERF_ATTACH_GROUP)) {
2365 * Since in that case we cannot possibly be scheduled, simply
2368 raw_spin_lock_irq(&ctx->lock);
2369 perf_group_detach(event);
2370 raw_spin_unlock_irq(&ctx->lock);
2375 * Cross CPU call to disable a performance event
2377 static void __perf_event_disable(struct perf_event *event,
2378 struct perf_cpu_context *cpuctx,
2379 struct perf_event_context *ctx,
2382 if (event->state < PERF_EVENT_STATE_INACTIVE)
2385 if (ctx->is_active & EVENT_TIME) {
2386 update_context_time(ctx);
2387 update_cgrp_time_from_event(event);
2390 if (event == event->group_leader)
2391 group_sched_out(event, cpuctx, ctx);
2393 event_sched_out(event, cpuctx, ctx);
2395 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2396 perf_cgroup_event_disable(event, ctx);
2402 * If event->ctx is a cloned context, callers must make sure that
2403 * every task struct that event->ctx->task could possibly point to
2404 * remains valid. This condition is satisfied when called through
2405 * perf_event_for_each_child or perf_event_for_each because they
2406 * hold the top-level event's child_mutex, so any descendant that
2407 * goes to exit will block in perf_event_exit_event().
2409 * When called from perf_pending_event it's OK because event->ctx
2410 * is the current context on this CPU and preemption is disabled,
2411 * hence we can't get into perf_event_task_sched_out for this context.
2413 static void _perf_event_disable(struct perf_event *event)
2415 struct perf_event_context *ctx = event->ctx;
2417 raw_spin_lock_irq(&ctx->lock);
2418 if (event->state <= PERF_EVENT_STATE_OFF) {
2419 raw_spin_unlock_irq(&ctx->lock);
2422 raw_spin_unlock_irq(&ctx->lock);
2424 event_function_call(event, __perf_event_disable, NULL);
2427 void perf_event_disable_local(struct perf_event *event)
2429 event_function_local(event, __perf_event_disable, NULL);
2433 * Strictly speaking kernel users cannot create groups and therefore this
2434 * interface does not need the perf_event_ctx_lock() magic.
2436 void perf_event_disable(struct perf_event *event)
2438 struct perf_event_context *ctx;
2440 ctx = perf_event_ctx_lock(event);
2441 _perf_event_disable(event);
2442 perf_event_ctx_unlock(event, ctx);
2444 EXPORT_SYMBOL_GPL(perf_event_disable);
2446 void perf_event_disable_inatomic(struct perf_event *event)
2448 WRITE_ONCE(event->pending_disable, smp_processor_id());
2449 /* can fail, see perf_pending_event_disable() */
2450 irq_work_queue(&event->pending);
2453 static void perf_set_shadow_time(struct perf_event *event,
2454 struct perf_event_context *ctx)
2457 * use the correct time source for the time snapshot
2459 * We could get by without this by leveraging the
2460 * fact that to get to this function, the caller
2461 * has most likely already called update_context_time()
2462 * and update_cgrp_time_xx() and thus both timestamp
2463 * are identical (or very close). Given that tstamp is,
2464 * already adjusted for cgroup, we could say that:
2465 * tstamp - ctx->timestamp
2467 * tstamp - cgrp->timestamp.
2469 * Then, in perf_output_read(), the calculation would
2470 * work with no changes because:
2471 * - event is guaranteed scheduled in
2472 * - no scheduled out in between
2473 * - thus the timestamp would be the same
2475 * But this is a bit hairy.
2477 * So instead, we have an explicit cgroup call to remain
2478 * within the time time source all along. We believe it
2479 * is cleaner and simpler to understand.
2481 if (is_cgroup_event(event))
2482 perf_cgroup_set_shadow_time(event, event->tstamp);
2484 event->shadow_ctx_time = event->tstamp - ctx->timestamp;
2487 #define MAX_INTERRUPTS (~0ULL)
2489 static void perf_log_throttle(struct perf_event *event, int enable);
2490 static void perf_log_itrace_start(struct perf_event *event);
2493 event_sched_in(struct perf_event *event,
2494 struct perf_cpu_context *cpuctx,
2495 struct perf_event_context *ctx)
2499 WARN_ON_ONCE(event->ctx != ctx);
2501 lockdep_assert_held(&ctx->lock);
2503 if (event->state <= PERF_EVENT_STATE_OFF)
2506 WRITE_ONCE(event->oncpu, smp_processor_id());
2508 * Order event::oncpu write to happen before the ACTIVE state is
2509 * visible. This allows perf_event_{stop,read}() to observe the correct
2510 * ->oncpu if it sees ACTIVE.
2513 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2516 * Unthrottle events, since we scheduled we might have missed several
2517 * ticks already, also for a heavily scheduling task there is little
2518 * guarantee it'll get a tick in a timely manner.
2520 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2521 perf_log_throttle(event, 1);
2522 event->hw.interrupts = 0;
2525 perf_pmu_disable(event->pmu);
2527 perf_set_shadow_time(event, ctx);
2529 perf_log_itrace_start(event);
2531 if (event->pmu->add(event, PERF_EF_START)) {
2532 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2538 if (!is_software_event(event))
2539 cpuctx->active_oncpu++;
2540 if (!ctx->nr_active++)
2541 perf_event_ctx_activate(ctx);
2542 if (event->attr.freq && event->attr.sample_freq)
2545 if (event->attr.exclusive)
2546 cpuctx->exclusive = 1;
2549 perf_pmu_enable(event->pmu);
2555 group_sched_in(struct perf_event *group_event,
2556 struct perf_cpu_context *cpuctx,
2557 struct perf_event_context *ctx)
2559 struct perf_event *event, *partial_group = NULL;
2560 struct pmu *pmu = ctx->pmu;
2562 if (group_event->state == PERF_EVENT_STATE_OFF)
2565 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2567 if (event_sched_in(group_event, cpuctx, ctx)) {
2568 pmu->cancel_txn(pmu);
2569 perf_mux_hrtimer_restart(cpuctx);
2574 * Schedule in siblings as one group (if any):
2576 for_each_sibling_event(event, group_event) {
2577 if (event_sched_in(event, cpuctx, ctx)) {
2578 partial_group = event;
2583 if (!pmu->commit_txn(pmu))
2588 * Groups can be scheduled in as one unit only, so undo any
2589 * partial group before returning:
2590 * The events up to the failed event are scheduled out normally.
2592 for_each_sibling_event(event, group_event) {
2593 if (event == partial_group)
2596 event_sched_out(event, cpuctx, ctx);
2598 event_sched_out(group_event, cpuctx, ctx);
2600 pmu->cancel_txn(pmu);
2602 perf_mux_hrtimer_restart(cpuctx);
2608 * Work out whether we can put this event group on the CPU now.
2610 static int group_can_go_on(struct perf_event *event,
2611 struct perf_cpu_context *cpuctx,
2615 * Groups consisting entirely of software events can always go on.
2617 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2620 * If an exclusive group is already on, no other hardware
2623 if (cpuctx->exclusive)
2626 * If this group is exclusive and there are already
2627 * events on the CPU, it can't go on.
2629 if (event->attr.exclusive && cpuctx->active_oncpu)
2632 * Otherwise, try to add it if all previous groups were able
2638 static void add_event_to_ctx(struct perf_event *event,
2639 struct perf_event_context *ctx)
2641 list_add_event(event, ctx);
2642 perf_group_attach(event);
2645 static void ctx_sched_out(struct perf_event_context *ctx,
2646 struct perf_cpu_context *cpuctx,
2647 enum event_type_t event_type);
2649 ctx_sched_in(struct perf_event_context *ctx,
2650 struct perf_cpu_context *cpuctx,
2651 enum event_type_t event_type,
2652 struct task_struct *task);
2654 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2655 struct perf_event_context *ctx,
2656 enum event_type_t event_type)
2658 if (!cpuctx->task_ctx)
2661 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2664 ctx_sched_out(ctx, cpuctx, event_type);
2667 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2668 struct perf_event_context *ctx,
2669 struct task_struct *task)
2671 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2673 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2674 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2676 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2680 * We want to maintain the following priority of scheduling:
2681 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2682 * - task pinned (EVENT_PINNED)
2683 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2684 * - task flexible (EVENT_FLEXIBLE).
2686 * In order to avoid unscheduling and scheduling back in everything every
2687 * time an event is added, only do it for the groups of equal priority and
2690 * This can be called after a batch operation on task events, in which case
2691 * event_type is a bit mask of the types of events involved. For CPU events,
2692 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2694 static void ctx_resched(struct perf_cpu_context *cpuctx,
2695 struct perf_event_context *task_ctx,
2696 enum event_type_t event_type)
2698 enum event_type_t ctx_event_type;
2699 bool cpu_event = !!(event_type & EVENT_CPU);
2702 * If pinned groups are involved, flexible groups also need to be
2705 if (event_type & EVENT_PINNED)
2706 event_type |= EVENT_FLEXIBLE;
2708 ctx_event_type = event_type & EVENT_ALL;
2710 perf_pmu_disable(cpuctx->ctx.pmu);
2712 task_ctx_sched_out(cpuctx, task_ctx, event_type);
2715 * Decide which cpu ctx groups to schedule out based on the types
2716 * of events that caused rescheduling:
2717 * - EVENT_CPU: schedule out corresponding groups;
2718 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2719 * - otherwise, do nothing more.
2722 cpu_ctx_sched_out(cpuctx, ctx_event_type);
2723 else if (ctx_event_type & EVENT_PINNED)
2724 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2726 perf_event_sched_in(cpuctx, task_ctx, current);
2727 perf_pmu_enable(cpuctx->ctx.pmu);
2730 void perf_pmu_resched(struct pmu *pmu)
2732 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2733 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2735 perf_ctx_lock(cpuctx, task_ctx);
2736 ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2737 perf_ctx_unlock(cpuctx, task_ctx);
2741 * Cross CPU call to install and enable a performance event
2743 * Very similar to remote_function() + event_function() but cannot assume that
2744 * things like ctx->is_active and cpuctx->task_ctx are set.
2746 static int __perf_install_in_context(void *info)
2748 struct perf_event *event = info;
2749 struct perf_event_context *ctx = event->ctx;
2750 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2751 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2752 bool reprogram = true;
2755 raw_spin_lock(&cpuctx->ctx.lock);
2757 raw_spin_lock(&ctx->lock);
2760 reprogram = (ctx->task == current);
2763 * If the task is running, it must be running on this CPU,
2764 * otherwise we cannot reprogram things.
2766 * If its not running, we don't care, ctx->lock will
2767 * serialize against it becoming runnable.
2769 if (task_curr(ctx->task) && !reprogram) {
2774 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2775 } else if (task_ctx) {
2776 raw_spin_lock(&task_ctx->lock);
2779 #ifdef CONFIG_CGROUP_PERF
2780 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2782 * If the current cgroup doesn't match the event's
2783 * cgroup, we should not try to schedule it.
2785 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2786 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2787 event->cgrp->css.cgroup);
2792 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2793 add_event_to_ctx(event, ctx);
2794 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2796 add_event_to_ctx(event, ctx);
2800 perf_ctx_unlock(cpuctx, task_ctx);
2805 static bool exclusive_event_installable(struct perf_event *event,
2806 struct perf_event_context *ctx);
2809 * Attach a performance event to a context.
2811 * Very similar to event_function_call, see comment there.
2814 perf_install_in_context(struct perf_event_context *ctx,
2815 struct perf_event *event,
2818 struct task_struct *task = READ_ONCE(ctx->task);
2820 lockdep_assert_held(&ctx->mutex);
2822 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2824 if (event->cpu != -1)
2828 * Ensures that if we can observe event->ctx, both the event and ctx
2829 * will be 'complete'. See perf_iterate_sb_cpu().
2831 smp_store_release(&event->ctx, ctx);
2834 * perf_event_attr::disabled events will not run and can be initialized
2835 * without IPI. Except when this is the first event for the context, in
2836 * that case we need the magic of the IPI to set ctx->is_active.
2838 * The IOC_ENABLE that is sure to follow the creation of a disabled
2839 * event will issue the IPI and reprogram the hardware.
2841 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF && ctx->nr_events) {
2842 raw_spin_lock_irq(&ctx->lock);
2843 if (ctx->task == TASK_TOMBSTONE) {
2844 raw_spin_unlock_irq(&ctx->lock);
2847 add_event_to_ctx(event, ctx);
2848 raw_spin_unlock_irq(&ctx->lock);
2853 cpu_function_call(cpu, __perf_install_in_context, event);
2858 * Should not happen, we validate the ctx is still alive before calling.
2860 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2864 * Installing events is tricky because we cannot rely on ctx->is_active
2865 * to be set in case this is the nr_events 0 -> 1 transition.
2867 * Instead we use task_curr(), which tells us if the task is running.
2868 * However, since we use task_curr() outside of rq::lock, we can race
2869 * against the actual state. This means the result can be wrong.
2871 * If we get a false positive, we retry, this is harmless.
2873 * If we get a false negative, things are complicated. If we are after
2874 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2875 * value must be correct. If we're before, it doesn't matter since
2876 * perf_event_context_sched_in() will program the counter.
2878 * However, this hinges on the remote context switch having observed
2879 * our task->perf_event_ctxp[] store, such that it will in fact take
2880 * ctx::lock in perf_event_context_sched_in().
2882 * We do this by task_function_call(), if the IPI fails to hit the task
2883 * we know any future context switch of task must see the
2884 * perf_event_ctpx[] store.
2888 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2889 * task_cpu() load, such that if the IPI then does not find the task
2890 * running, a future context switch of that task must observe the
2895 if (!task_function_call(task, __perf_install_in_context, event))
2898 raw_spin_lock_irq(&ctx->lock);
2900 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2902 * Cannot happen because we already checked above (which also
2903 * cannot happen), and we hold ctx->mutex, which serializes us
2904 * against perf_event_exit_task_context().
2906 raw_spin_unlock_irq(&ctx->lock);
2910 * If the task is not running, ctx->lock will avoid it becoming so,
2911 * thus we can safely install the event.
2913 if (task_curr(task)) {
2914 raw_spin_unlock_irq(&ctx->lock);
2917 add_event_to_ctx(event, ctx);
2918 raw_spin_unlock_irq(&ctx->lock);
2922 * Cross CPU call to enable a performance event
2924 static void __perf_event_enable(struct perf_event *event,
2925 struct perf_cpu_context *cpuctx,
2926 struct perf_event_context *ctx,
2929 struct perf_event *leader = event->group_leader;
2930 struct perf_event_context *task_ctx;
2932 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2933 event->state <= PERF_EVENT_STATE_ERROR)
2937 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2939 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2940 perf_cgroup_event_enable(event, ctx);
2942 if (!ctx->is_active)
2945 if (!event_filter_match(event)) {
2946 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2951 * If the event is in a group and isn't the group leader,
2952 * then don't put it on unless the group is on.
2954 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2955 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2959 task_ctx = cpuctx->task_ctx;
2961 WARN_ON_ONCE(task_ctx != ctx);
2963 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2969 * If event->ctx is a cloned context, callers must make sure that
2970 * every task struct that event->ctx->task could possibly point to
2971 * remains valid. This condition is satisfied when called through
2972 * perf_event_for_each_child or perf_event_for_each as described
2973 * for perf_event_disable.
2975 static void _perf_event_enable(struct perf_event *event)
2977 struct perf_event_context *ctx = event->ctx;
2979 raw_spin_lock_irq(&ctx->lock);
2980 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2981 event->state < PERF_EVENT_STATE_ERROR) {
2982 raw_spin_unlock_irq(&ctx->lock);
2987 * If the event is in error state, clear that first.
2989 * That way, if we see the event in error state below, we know that it
2990 * has gone back into error state, as distinct from the task having
2991 * been scheduled away before the cross-call arrived.
2993 if (event->state == PERF_EVENT_STATE_ERROR)
2994 event->state = PERF_EVENT_STATE_OFF;
2995 raw_spin_unlock_irq(&ctx->lock);
2997 event_function_call(event, __perf_event_enable, NULL);
3001 * See perf_event_disable();
3003 void perf_event_enable(struct perf_event *event)
3005 struct perf_event_context *ctx;
3007 ctx = perf_event_ctx_lock(event);
3008 _perf_event_enable(event);
3009 perf_event_ctx_unlock(event, ctx);
3011 EXPORT_SYMBOL_GPL(perf_event_enable);
3013 struct stop_event_data {
3014 struct perf_event *event;
3015 unsigned int restart;
3018 static int __perf_event_stop(void *info)
3020 struct stop_event_data *sd = info;
3021 struct perf_event *event = sd->event;
3023 /* if it's already INACTIVE, do nothing */
3024 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3027 /* matches smp_wmb() in event_sched_in() */
3031 * There is a window with interrupts enabled before we get here,
3032 * so we need to check again lest we try to stop another CPU's event.
3034 if (READ_ONCE(event->oncpu) != smp_processor_id())
3037 event->pmu->stop(event, PERF_EF_UPDATE);
3040 * May race with the actual stop (through perf_pmu_output_stop()),
3041 * but it is only used for events with AUX ring buffer, and such
3042 * events will refuse to restart because of rb::aux_mmap_count==0,
3043 * see comments in perf_aux_output_begin().
3045 * Since this is happening on an event-local CPU, no trace is lost
3049 event->pmu->start(event, 0);
3054 static int perf_event_stop(struct perf_event *event, int restart)
3056 struct stop_event_data sd = {
3063 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3066 /* matches smp_wmb() in event_sched_in() */
3070 * We only want to restart ACTIVE events, so if the event goes
3071 * inactive here (event->oncpu==-1), there's nothing more to do;
3072 * fall through with ret==-ENXIO.
3074 ret = cpu_function_call(READ_ONCE(event->oncpu),
3075 __perf_event_stop, &sd);
3076 } while (ret == -EAGAIN);
3082 * In order to contain the amount of racy and tricky in the address filter
3083 * configuration management, it is a two part process:
3085 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3086 * we update the addresses of corresponding vmas in
3087 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3088 * (p2) when an event is scheduled in (pmu::add), it calls
3089 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3090 * if the generation has changed since the previous call.
3092 * If (p1) happens while the event is active, we restart it to force (p2).
3094 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3095 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3097 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3098 * registered mapping, called for every new mmap(), with mm::mmap_lock down
3100 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3103 void perf_event_addr_filters_sync(struct perf_event *event)
3105 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3107 if (!has_addr_filter(event))
3110 raw_spin_lock(&ifh->lock);
3111 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3112 event->pmu->addr_filters_sync(event);
3113 event->hw.addr_filters_gen = event->addr_filters_gen;
3115 raw_spin_unlock(&ifh->lock);
3117 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3119 static int _perf_event_refresh(struct perf_event *event, int refresh)
3122 * not supported on inherited events
3124 if (event->attr.inherit || !is_sampling_event(event))
3127 atomic_add(refresh, &event->event_limit);
3128 _perf_event_enable(event);
3134 * See perf_event_disable()
3136 int perf_event_refresh(struct perf_event *event, int refresh)
3138 struct perf_event_context *ctx;
3141 ctx = perf_event_ctx_lock(event);
3142 ret = _perf_event_refresh(event, refresh);
3143 perf_event_ctx_unlock(event, ctx);
3147 EXPORT_SYMBOL_GPL(perf_event_refresh);
3149 static int perf_event_modify_breakpoint(struct perf_event *bp,
3150 struct perf_event_attr *attr)
3154 _perf_event_disable(bp);
3156 err = modify_user_hw_breakpoint_check(bp, attr, true);
3158 if (!bp->attr.disabled)
3159 _perf_event_enable(bp);
3164 static int perf_event_modify_attr(struct perf_event *event,
3165 struct perf_event_attr *attr)
3167 if (event->attr.type != attr->type)
3170 switch (event->attr.type) {
3171 case PERF_TYPE_BREAKPOINT:
3172 return perf_event_modify_breakpoint(event, attr);
3174 /* Place holder for future additions. */
3179 static void ctx_sched_out(struct perf_event_context *ctx,
3180 struct perf_cpu_context *cpuctx,
3181 enum event_type_t event_type)
3183 struct perf_event *event, *tmp;
3184 int is_active = ctx->is_active;
3186 lockdep_assert_held(&ctx->lock);
3188 if (likely(!ctx->nr_events)) {
3190 * See __perf_remove_from_context().
3192 WARN_ON_ONCE(ctx->is_active);
3194 WARN_ON_ONCE(cpuctx->task_ctx);
3198 ctx->is_active &= ~event_type;
3199 if (!(ctx->is_active & EVENT_ALL))
3203 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3204 if (!ctx->is_active)
3205 cpuctx->task_ctx = NULL;
3209 * Always update time if it was set; not only when it changes.
3210 * Otherwise we can 'forget' to update time for any but the last
3211 * context we sched out. For example:
3213 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3214 * ctx_sched_out(.event_type = EVENT_PINNED)
3216 * would only update time for the pinned events.
3218 if (is_active & EVENT_TIME) {
3219 /* update (and stop) ctx time */
3220 update_context_time(ctx);
3221 update_cgrp_time_from_cpuctx(cpuctx);
3224 is_active ^= ctx->is_active; /* changed bits */
3226 if (!ctx->nr_active || !(is_active & EVENT_ALL))
3229 perf_pmu_disable(ctx->pmu);
3230 if (is_active & EVENT_PINNED) {
3231 list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list)
3232 group_sched_out(event, cpuctx, ctx);
3235 if (is_active & EVENT_FLEXIBLE) {
3236 list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list)
3237 group_sched_out(event, cpuctx, ctx);
3240 * Since we cleared EVENT_FLEXIBLE, also clear
3241 * rotate_necessary, is will be reset by
3242 * ctx_flexible_sched_in() when needed.
3244 ctx->rotate_necessary = 0;
3246 perf_pmu_enable(ctx->pmu);
3250 * Test whether two contexts are equivalent, i.e. whether they have both been
3251 * cloned from the same version of the same context.
3253 * Equivalence is measured using a generation number in the context that is
3254 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3255 * and list_del_event().
3257 static int context_equiv(struct perf_event_context *ctx1,
3258 struct perf_event_context *ctx2)
3260 lockdep_assert_held(&ctx1->lock);
3261 lockdep_assert_held(&ctx2->lock);
3263 /* Pinning disables the swap optimization */
3264 if (ctx1->pin_count || ctx2->pin_count)
3267 /* If ctx1 is the parent of ctx2 */
3268 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3271 /* If ctx2 is the parent of ctx1 */
3272 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3276 * If ctx1 and ctx2 have the same parent; we flatten the parent
3277 * hierarchy, see perf_event_init_context().
3279 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3280 ctx1->parent_gen == ctx2->parent_gen)
3287 static void __perf_event_sync_stat(struct perf_event *event,
3288 struct perf_event *next_event)
3292 if (!event->attr.inherit_stat)
3296 * Update the event value, we cannot use perf_event_read()
3297 * because we're in the middle of a context switch and have IRQs
3298 * disabled, which upsets smp_call_function_single(), however
3299 * we know the event must be on the current CPU, therefore we
3300 * don't need to use it.
3302 if (event->state == PERF_EVENT_STATE_ACTIVE)
3303 event->pmu->read(event);
3305 perf_event_update_time(event);
3308 * In order to keep per-task stats reliable we need to flip the event
3309 * values when we flip the contexts.
3311 value = local64_read(&next_event->count);
3312 value = local64_xchg(&event->count, value);
3313 local64_set(&next_event->count, value);
3315 swap(event->total_time_enabled, next_event->total_time_enabled);
3316 swap(event->total_time_running, next_event->total_time_running);
3319 * Since we swizzled the values, update the user visible data too.
3321 perf_event_update_userpage(event);
3322 perf_event_update_userpage(next_event);
3325 static void perf_event_sync_stat(struct perf_event_context *ctx,
3326 struct perf_event_context *next_ctx)
3328 struct perf_event *event, *next_event;
3333 update_context_time(ctx);
3335 event = list_first_entry(&ctx->event_list,
3336 struct perf_event, event_entry);
3338 next_event = list_first_entry(&next_ctx->event_list,
3339 struct perf_event, event_entry);
3341 while (&event->event_entry != &ctx->event_list &&
3342 &next_event->event_entry != &next_ctx->event_list) {
3344 __perf_event_sync_stat(event, next_event);
3346 event = list_next_entry(event, event_entry);
3347 next_event = list_next_entry(next_event, event_entry);
3351 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
3352 struct task_struct *next)
3354 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
3355 struct perf_event_context *next_ctx;
3356 struct perf_event_context *parent, *next_parent;
3357 struct perf_cpu_context *cpuctx;
3363 cpuctx = __get_cpu_context(ctx);
3364 if (!cpuctx->task_ctx)
3368 next_ctx = next->perf_event_ctxp[ctxn];
3372 parent = rcu_dereference(ctx->parent_ctx);
3373 next_parent = rcu_dereference(next_ctx->parent_ctx);
3375 /* If neither context have a parent context; they cannot be clones. */
3376 if (!parent && !next_parent)
3379 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3381 * Looks like the two contexts are clones, so we might be
3382 * able to optimize the context switch. We lock both
3383 * contexts and check that they are clones under the
3384 * lock (including re-checking that neither has been
3385 * uncloned in the meantime). It doesn't matter which
3386 * order we take the locks because no other cpu could
3387 * be trying to lock both of these tasks.
3389 raw_spin_lock(&ctx->lock);
3390 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3391 if (context_equiv(ctx, next_ctx)) {
3392 struct pmu *pmu = ctx->pmu;
3394 WRITE_ONCE(ctx->task, next);
3395 WRITE_ONCE(next_ctx->task, task);
3398 * PMU specific parts of task perf context can require
3399 * additional synchronization. As an example of such
3400 * synchronization see implementation details of Intel
3401 * LBR call stack data profiling;
3403 if (pmu->swap_task_ctx)
3404 pmu->swap_task_ctx(ctx, next_ctx);
3406 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
3409 * RCU_INIT_POINTER here is safe because we've not
3410 * modified the ctx and the above modification of
3411 * ctx->task and ctx->task_ctx_data are immaterial
3412 * since those values are always verified under
3413 * ctx->lock which we're now holding.
3415 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
3416 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
3420 perf_event_sync_stat(ctx, next_ctx);
3422 raw_spin_unlock(&next_ctx->lock);
3423 raw_spin_unlock(&ctx->lock);
3429 raw_spin_lock(&ctx->lock);
3430 task_ctx_sched_out(cpuctx, ctx, EVENT_ALL);
3431 raw_spin_unlock(&ctx->lock);
3435 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3437 void perf_sched_cb_dec(struct pmu *pmu)
3439 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3441 this_cpu_dec(perf_sched_cb_usages);
3443 if (!--cpuctx->sched_cb_usage)
3444 list_del(&cpuctx->sched_cb_entry);
3448 void perf_sched_cb_inc(struct pmu *pmu)
3450 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3452 if (!cpuctx->sched_cb_usage++)
3453 list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3455 this_cpu_inc(perf_sched_cb_usages);
3459 * This function provides the context switch callback to the lower code
3460 * layer. It is invoked ONLY when the context switch callback is enabled.
3462 * This callback is relevant even to per-cpu events; for example multi event
3463 * PEBS requires this to provide PID/TID information. This requires we flush
3464 * all queued PEBS records before we context switch to a new task.
3466 static void perf_pmu_sched_task(struct task_struct *prev,
3467 struct task_struct *next,
3470 struct perf_cpu_context *cpuctx;
3476 list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
3477 pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */
3479 if (WARN_ON_ONCE(!pmu->sched_task))
3482 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3483 perf_pmu_disable(pmu);
3485 pmu->sched_task(cpuctx->task_ctx, sched_in);
3487 perf_pmu_enable(pmu);
3488 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3492 static void perf_event_switch(struct task_struct *task,
3493 struct task_struct *next_prev, bool sched_in);
3495 #define for_each_task_context_nr(ctxn) \
3496 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
3499 * Called from scheduler to remove the events of the current task,
3500 * with interrupts disabled.
3502 * We stop each event and update the event value in event->count.
3504 * This does not protect us against NMI, but disable()
3505 * sets the disabled bit in the control field of event _before_
3506 * accessing the event control register. If a NMI hits, then it will
3507 * not restart the event.
3509 void __perf_event_task_sched_out(struct task_struct *task,
3510 struct task_struct *next)
3514 if (__this_cpu_read(perf_sched_cb_usages))
3515 perf_pmu_sched_task(task, next, false);
3517 if (atomic_read(&nr_switch_events))
3518 perf_event_switch(task, next, false);
3520 for_each_task_context_nr(ctxn)
3521 perf_event_context_sched_out(task, ctxn, next);
3524 * if cgroup events exist on this CPU, then we need
3525 * to check if we have to switch out PMU state.
3526 * cgroup event are system-wide mode only
3528 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3529 perf_cgroup_sched_out(task, next);
3533 * Called with IRQs disabled
3535 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3536 enum event_type_t event_type)
3538 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
3541 static bool perf_less_group_idx(const void *l, const void *r)
3543 const struct perf_event *le = *(const struct perf_event **)l;
3544 const struct perf_event *re = *(const struct perf_event **)r;
3546 return le->group_index < re->group_index;
3549 static void swap_ptr(void *l, void *r)
3551 void **lp = l, **rp = r;
3556 static const struct min_heap_callbacks perf_min_heap = {
3557 .elem_size = sizeof(struct perf_event *),
3558 .less = perf_less_group_idx,
3562 static void __heap_add(struct min_heap *heap, struct perf_event *event)
3564 struct perf_event **itrs = heap->data;
3567 itrs[heap->nr] = event;
3572 static noinline int visit_groups_merge(struct perf_cpu_context *cpuctx,
3573 struct perf_event_groups *groups, int cpu,
3574 int (*func)(struct perf_event *, void *),
3577 #ifdef CONFIG_CGROUP_PERF
3578 struct cgroup_subsys_state *css = NULL;
3580 /* Space for per CPU and/or any CPU event iterators. */
3581 struct perf_event *itrs[2];
3582 struct min_heap event_heap;
3583 struct perf_event **evt;
3587 event_heap = (struct min_heap){
3588 .data = cpuctx->heap,
3590 .size = cpuctx->heap_size,
3593 lockdep_assert_held(&cpuctx->ctx.lock);
3595 #ifdef CONFIG_CGROUP_PERF
3597 css = &cpuctx->cgrp->css;
3600 event_heap = (struct min_heap){
3603 .size = ARRAY_SIZE(itrs),
3605 /* Events not within a CPU context may be on any CPU. */
3606 __heap_add(&event_heap, perf_event_groups_first(groups, -1, NULL));
3608 evt = event_heap.data;
3610 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, NULL));
3612 #ifdef CONFIG_CGROUP_PERF
3613 for (; css; css = css->parent)
3614 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, css->cgroup));
3617 min_heapify_all(&event_heap, &perf_min_heap);
3619 while (event_heap.nr) {
3620 ret = func(*evt, data);
3624 *evt = perf_event_groups_next(*evt);
3626 min_heapify(&event_heap, 0, &perf_min_heap);
3628 min_heap_pop(&event_heap, &perf_min_heap);
3634 static int merge_sched_in(struct perf_event *event, void *data)
3636 struct perf_event_context *ctx = event->ctx;
3637 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3638 int *can_add_hw = data;
3640 if (event->state <= PERF_EVENT_STATE_OFF)
3643 if (!event_filter_match(event))
3646 if (group_can_go_on(event, cpuctx, *can_add_hw)) {
3647 if (!group_sched_in(event, cpuctx, ctx))
3648 list_add_tail(&event->active_list, get_event_list(event));
3651 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3652 if (event->attr.pinned) {
3653 perf_cgroup_event_disable(event, ctx);
3654 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3658 ctx->rotate_necessary = 1;
3665 ctx_pinned_sched_in(struct perf_event_context *ctx,
3666 struct perf_cpu_context *cpuctx)
3670 if (ctx != &cpuctx->ctx)
3673 visit_groups_merge(cpuctx, &ctx->pinned_groups,
3675 merge_sched_in, &can_add_hw);
3679 ctx_flexible_sched_in(struct perf_event_context *ctx,
3680 struct perf_cpu_context *cpuctx)
3684 if (ctx != &cpuctx->ctx)
3687 visit_groups_merge(cpuctx, &ctx->flexible_groups,
3689 merge_sched_in, &can_add_hw);
3693 ctx_sched_in(struct perf_event_context *ctx,
3694 struct perf_cpu_context *cpuctx,
3695 enum event_type_t event_type,
3696 struct task_struct *task)
3698 int is_active = ctx->is_active;
3701 lockdep_assert_held(&ctx->lock);
3703 if (likely(!ctx->nr_events))
3706 ctx->is_active |= (event_type | EVENT_TIME);
3709 cpuctx->task_ctx = ctx;
3711 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3714 is_active ^= ctx->is_active; /* changed bits */
3716 if (is_active & EVENT_TIME) {
3717 /* start ctx time */
3719 ctx->timestamp = now;
3720 perf_cgroup_set_timestamp(task, ctx);
3724 * First go through the list and put on any pinned groups
3725 * in order to give them the best chance of going on.
3727 if (is_active & EVENT_PINNED)
3728 ctx_pinned_sched_in(ctx, cpuctx);
3730 /* Then walk through the lower prio flexible groups */
3731 if (is_active & EVENT_FLEXIBLE)
3732 ctx_flexible_sched_in(ctx, cpuctx);
3735 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3736 enum event_type_t event_type,
3737 struct task_struct *task)
3739 struct perf_event_context *ctx = &cpuctx->ctx;
3741 ctx_sched_in(ctx, cpuctx, event_type, task);
3744 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3745 struct task_struct *task)
3747 struct perf_cpu_context *cpuctx;
3749 cpuctx = __get_cpu_context(ctx);
3750 if (cpuctx->task_ctx == ctx)
3753 perf_ctx_lock(cpuctx, ctx);
3755 * We must check ctx->nr_events while holding ctx->lock, such
3756 * that we serialize against perf_install_in_context().
3758 if (!ctx->nr_events)
3761 perf_pmu_disable(ctx->pmu);
3763 * We want to keep the following priority order:
3764 * cpu pinned (that don't need to move), task pinned,
3765 * cpu flexible, task flexible.
3767 * However, if task's ctx is not carrying any pinned
3768 * events, no need to flip the cpuctx's events around.
3770 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3771 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3772 perf_event_sched_in(cpuctx, ctx, task);
3773 perf_pmu_enable(ctx->pmu);
3776 perf_ctx_unlock(cpuctx, ctx);
3780 * Called from scheduler to add the events of the current task
3781 * with interrupts disabled.
3783 * We restore the event value and then enable it.
3785 * This does not protect us against NMI, but enable()
3786 * sets the enabled bit in the control field of event _before_
3787 * accessing the event control register. If a NMI hits, then it will
3788 * keep the event running.
3790 void __perf_event_task_sched_in(struct task_struct *prev,
3791 struct task_struct *task)
3793 struct perf_event_context *ctx;
3797 * If cgroup events exist on this CPU, then we need to check if we have
3798 * to switch in PMU state; cgroup event are system-wide mode only.
3800 * Since cgroup events are CPU events, we must schedule these in before
3801 * we schedule in the task events.
3803 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3804 perf_cgroup_sched_in(prev, task);
3806 for_each_task_context_nr(ctxn) {
3807 ctx = task->perf_event_ctxp[ctxn];
3811 perf_event_context_sched_in(ctx, task);
3814 if (atomic_read(&nr_switch_events))
3815 perf_event_switch(task, prev, true);
3817 if (__this_cpu_read(perf_sched_cb_usages))
3818 perf_pmu_sched_task(prev, task, true);
3821 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3823 u64 frequency = event->attr.sample_freq;
3824 u64 sec = NSEC_PER_SEC;
3825 u64 divisor, dividend;
3827 int count_fls, nsec_fls, frequency_fls, sec_fls;
3829 count_fls = fls64(count);
3830 nsec_fls = fls64(nsec);
3831 frequency_fls = fls64(frequency);
3835 * We got @count in @nsec, with a target of sample_freq HZ
3836 * the target period becomes:
3839 * period = -------------------
3840 * @nsec * sample_freq
3845 * Reduce accuracy by one bit such that @a and @b converge
3846 * to a similar magnitude.
3848 #define REDUCE_FLS(a, b) \
3850 if (a##_fls > b##_fls) { \
3860 * Reduce accuracy until either term fits in a u64, then proceed with
3861 * the other, so that finally we can do a u64/u64 division.
3863 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3864 REDUCE_FLS(nsec, frequency);
3865 REDUCE_FLS(sec, count);
3868 if (count_fls + sec_fls > 64) {
3869 divisor = nsec * frequency;
3871 while (count_fls + sec_fls > 64) {
3872 REDUCE_FLS(count, sec);
3876 dividend = count * sec;
3878 dividend = count * sec;
3880 while (nsec_fls + frequency_fls > 64) {
3881 REDUCE_FLS(nsec, frequency);
3885 divisor = nsec * frequency;
3891 return div64_u64(dividend, divisor);
3894 static DEFINE_PER_CPU(int, perf_throttled_count);
3895 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3897 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3899 struct hw_perf_event *hwc = &event->hw;
3900 s64 period, sample_period;
3903 period = perf_calculate_period(event, nsec, count);
3905 delta = (s64)(period - hwc->sample_period);
3906 delta = (delta + 7) / 8; /* low pass filter */
3908 sample_period = hwc->sample_period + delta;
3913 hwc->sample_period = sample_period;
3915 if (local64_read(&hwc->period_left) > 8*sample_period) {
3917 event->pmu->stop(event, PERF_EF_UPDATE);
3919 local64_set(&hwc->period_left, 0);
3922 event->pmu->start(event, PERF_EF_RELOAD);
3927 * combine freq adjustment with unthrottling to avoid two passes over the
3928 * events. At the same time, make sure, having freq events does not change
3929 * the rate of unthrottling as that would introduce bias.
3931 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3934 struct perf_event *event;
3935 struct hw_perf_event *hwc;
3936 u64 now, period = TICK_NSEC;
3940 * only need to iterate over all events iff:
3941 * - context have events in frequency mode (needs freq adjust)
3942 * - there are events to unthrottle on this cpu
3944 if (!(ctx->nr_freq || needs_unthr))
3947 raw_spin_lock(&ctx->lock);
3948 perf_pmu_disable(ctx->pmu);
3950 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3951 if (event->state != PERF_EVENT_STATE_ACTIVE)
3954 if (!event_filter_match(event))
3957 perf_pmu_disable(event->pmu);
3961 if (hwc->interrupts == MAX_INTERRUPTS) {
3962 hwc->interrupts = 0;
3963 perf_log_throttle(event, 1);
3964 event->pmu->start(event, 0);
3967 if (!event->attr.freq || !event->attr.sample_freq)
3971 * stop the event and update event->count
3973 event->pmu->stop(event, PERF_EF_UPDATE);
3975 now = local64_read(&event->count);
3976 delta = now - hwc->freq_count_stamp;
3977 hwc->freq_count_stamp = now;
3981 * reload only if value has changed
3982 * we have stopped the event so tell that
3983 * to perf_adjust_period() to avoid stopping it
3987 perf_adjust_period(event, period, delta, false);
3989 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3991 perf_pmu_enable(event->pmu);
3994 perf_pmu_enable(ctx->pmu);
3995 raw_spin_unlock(&ctx->lock);
3999 * Move @event to the tail of the @ctx's elegible events.
4001 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4004 * Rotate the first entry last of non-pinned groups. Rotation might be
4005 * disabled by the inheritance code.
4007 if (ctx->rotate_disable)
4010 perf_event_groups_delete(&ctx->flexible_groups, event);
4011 perf_event_groups_insert(&ctx->flexible_groups, event);
4014 /* pick an event from the flexible_groups to rotate */
4015 static inline struct perf_event *
4016 ctx_event_to_rotate(struct perf_event_context *ctx)
4018 struct perf_event *event;
4020 /* pick the first active flexible event */
4021 event = list_first_entry_or_null(&ctx->flexible_active,
4022 struct perf_event, active_list);
4024 /* if no active flexible event, pick the first event */
4026 event = rb_entry_safe(rb_first(&ctx->flexible_groups.tree),
4027 typeof(*event), group_node);
4031 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4032 * finds there are unschedulable events, it will set it again.
4034 ctx->rotate_necessary = 0;
4039 static bool perf_rotate_context(struct perf_cpu_context *cpuctx)
4041 struct perf_event *cpu_event = NULL, *task_event = NULL;
4042 struct perf_event_context *task_ctx = NULL;
4043 int cpu_rotate, task_rotate;
4046 * Since we run this from IRQ context, nobody can install new
4047 * events, thus the event count values are stable.
4050 cpu_rotate = cpuctx->ctx.rotate_necessary;
4051 task_ctx = cpuctx->task_ctx;
4052 task_rotate = task_ctx ? task_ctx->rotate_necessary : 0;
4054 if (!(cpu_rotate || task_rotate))
4057 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4058 perf_pmu_disable(cpuctx->ctx.pmu);
4061 task_event = ctx_event_to_rotate(task_ctx);
4063 cpu_event = ctx_event_to_rotate(&cpuctx->ctx);
4066 * As per the order given at ctx_resched() first 'pop' task flexible
4067 * and then, if needed CPU flexible.
4069 if (task_event || (task_ctx && cpu_event))
4070 ctx_sched_out(task_ctx, cpuctx, EVENT_FLEXIBLE);
4072 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
4075 rotate_ctx(task_ctx, task_event);
4077 rotate_ctx(&cpuctx->ctx, cpu_event);
4079 perf_event_sched_in(cpuctx, task_ctx, current);
4081 perf_pmu_enable(cpuctx->ctx.pmu);
4082 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4087 void perf_event_task_tick(void)
4089 struct list_head *head = this_cpu_ptr(&active_ctx_list);
4090 struct perf_event_context *ctx, *tmp;
4093 lockdep_assert_irqs_disabled();
4095 __this_cpu_inc(perf_throttled_seq);
4096 throttled = __this_cpu_xchg(perf_throttled_count, 0);
4097 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4099 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
4100 perf_adjust_freq_unthr_context(ctx, throttled);
4103 static int event_enable_on_exec(struct perf_event *event,
4104 struct perf_event_context *ctx)
4106 if (!event->attr.enable_on_exec)
4109 event->attr.enable_on_exec = 0;
4110 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4113 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4119 * Enable all of a task's events that have been marked enable-on-exec.
4120 * This expects task == current.
4122 static void perf_event_enable_on_exec(int ctxn)
4124 struct perf_event_context *ctx, *clone_ctx = NULL;
4125 enum event_type_t event_type = 0;
4126 struct perf_cpu_context *cpuctx;
4127 struct perf_event *event;
4128 unsigned long flags;
4131 local_irq_save(flags);
4132 ctx = current->perf_event_ctxp[ctxn];
4133 if (!ctx || !ctx->nr_events)
4136 cpuctx = __get_cpu_context(ctx);
4137 perf_ctx_lock(cpuctx, ctx);
4138 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
4139 list_for_each_entry(event, &ctx->event_list, event_entry) {
4140 enabled |= event_enable_on_exec(event, ctx);
4141 event_type |= get_event_type(event);
4145 * Unclone and reschedule this context if we enabled any event.
4148 clone_ctx = unclone_ctx(ctx);
4149 ctx_resched(cpuctx, ctx, event_type);
4151 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
4153 perf_ctx_unlock(cpuctx, ctx);
4156 local_irq_restore(flags);
4162 struct perf_read_data {
4163 struct perf_event *event;
4168 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4170 u16 local_pkg, event_pkg;
4172 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4173 int local_cpu = smp_processor_id();
4175 event_pkg = topology_physical_package_id(event_cpu);
4176 local_pkg = topology_physical_package_id(local_cpu);
4178 if (event_pkg == local_pkg)
4186 * Cross CPU call to read the hardware event
4188 static void __perf_event_read(void *info)
4190 struct perf_read_data *data = info;
4191 struct perf_event *sub, *event = data->event;
4192 struct perf_event_context *ctx = event->ctx;
4193 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
4194 struct pmu *pmu = event->pmu;
4197 * If this is a task context, we need to check whether it is
4198 * the current task context of this cpu. If not it has been
4199 * scheduled out before the smp call arrived. In that case
4200 * event->count would have been updated to a recent sample
4201 * when the event was scheduled out.
4203 if (ctx->task && cpuctx->task_ctx != ctx)
4206 raw_spin_lock(&ctx->lock);
4207 if (ctx->is_active & EVENT_TIME) {
4208 update_context_time(ctx);
4209 update_cgrp_time_from_event(event);
4212 perf_event_update_time(event);
4214 perf_event_update_sibling_time(event);
4216 if (event->state != PERF_EVENT_STATE_ACTIVE)
4225 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4229 for_each_sibling_event(sub, event) {
4230 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4232 * Use sibling's PMU rather than @event's since
4233 * sibling could be on different (eg: software) PMU.
4235 sub->pmu->read(sub);
4239 data->ret = pmu->commit_txn(pmu);
4242 raw_spin_unlock(&ctx->lock);
4245 static inline u64 perf_event_count(struct perf_event *event)
4247 return local64_read(&event->count) + atomic64_read(&event->child_count);
4251 * NMI-safe method to read a local event, that is an event that
4253 * - either for the current task, or for this CPU
4254 * - does not have inherit set, for inherited task events
4255 * will not be local and we cannot read them atomically
4256 * - must not have a pmu::count method
4258 int perf_event_read_local(struct perf_event *event, u64 *value,
4259 u64 *enabled, u64 *running)
4261 unsigned long flags;
4265 * Disabling interrupts avoids all counter scheduling (context
4266 * switches, timer based rotation and IPIs).
4268 local_irq_save(flags);
4271 * It must not be an event with inherit set, we cannot read
4272 * all child counters from atomic context.
4274 if (event->attr.inherit) {
4279 /* If this is a per-task event, it must be for current */
4280 if ((event->attach_state & PERF_ATTACH_TASK) &&
4281 event->hw.target != current) {
4286 /* If this is a per-CPU event, it must be for this CPU */
4287 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4288 event->cpu != smp_processor_id()) {
4293 /* If this is a pinned event it must be running on this CPU */
4294 if (event->attr.pinned && event->oncpu != smp_processor_id()) {
4300 * If the event is currently on this CPU, its either a per-task event,
4301 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4304 if (event->oncpu == smp_processor_id())
4305 event->pmu->read(event);
4307 *value = local64_read(&event->count);
4308 if (enabled || running) {
4309 u64 now = event->shadow_ctx_time + perf_clock();
4310 u64 __enabled, __running;
4312 __perf_update_times(event, now, &__enabled, &__running);
4314 *enabled = __enabled;
4316 *running = __running;
4319 local_irq_restore(flags);
4324 static int perf_event_read(struct perf_event *event, bool group)
4326 enum perf_event_state state = READ_ONCE(event->state);
4327 int event_cpu, ret = 0;
4330 * If event is enabled and currently active on a CPU, update the
4331 * value in the event structure:
4334 if (state == PERF_EVENT_STATE_ACTIVE) {
4335 struct perf_read_data data;
4338 * Orders the ->state and ->oncpu loads such that if we see
4339 * ACTIVE we must also see the right ->oncpu.
4341 * Matches the smp_wmb() from event_sched_in().
4345 event_cpu = READ_ONCE(event->oncpu);
4346 if ((unsigned)event_cpu >= nr_cpu_ids)
4349 data = (struct perf_read_data){
4356 event_cpu = __perf_event_read_cpu(event, event_cpu);
4359 * Purposely ignore the smp_call_function_single() return
4362 * If event_cpu isn't a valid CPU it means the event got
4363 * scheduled out and that will have updated the event count.
4365 * Therefore, either way, we'll have an up-to-date event count
4368 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4372 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4373 struct perf_event_context *ctx = event->ctx;
4374 unsigned long flags;
4376 raw_spin_lock_irqsave(&ctx->lock, flags);
4377 state = event->state;
4378 if (state != PERF_EVENT_STATE_INACTIVE) {
4379 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4384 * May read while context is not active (e.g., thread is
4385 * blocked), in that case we cannot update context time
4387 if (ctx->is_active & EVENT_TIME) {
4388 update_context_time(ctx);
4389 update_cgrp_time_from_event(event);
4392 perf_event_update_time(event);
4394 perf_event_update_sibling_time(event);
4395 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4402 * Initialize the perf_event context in a task_struct:
4404 static void __perf_event_init_context(struct perf_event_context *ctx)
4406 raw_spin_lock_init(&ctx->lock);
4407 mutex_init(&ctx->mutex);
4408 INIT_LIST_HEAD(&ctx->active_ctx_list);
4409 perf_event_groups_init(&ctx->pinned_groups);
4410 perf_event_groups_init(&ctx->flexible_groups);
4411 INIT_LIST_HEAD(&ctx->event_list);
4412 INIT_LIST_HEAD(&ctx->pinned_active);
4413 INIT_LIST_HEAD(&ctx->flexible_active);
4414 refcount_set(&ctx->refcount, 1);
4417 static struct perf_event_context *
4418 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
4420 struct perf_event_context *ctx;
4422 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4426 __perf_event_init_context(ctx);
4428 ctx->task = get_task_struct(task);
4434 static struct task_struct *
4435 find_lively_task_by_vpid(pid_t vpid)
4437 struct task_struct *task;
4443 task = find_task_by_vpid(vpid);
4445 get_task_struct(task);
4449 return ERR_PTR(-ESRCH);
4455 * Returns a matching context with refcount and pincount.
4457 static struct perf_event_context *
4458 find_get_context(struct pmu *pmu, struct task_struct *task,
4459 struct perf_event *event)
4461 struct perf_event_context *ctx, *clone_ctx = NULL;
4462 struct perf_cpu_context *cpuctx;
4463 void *task_ctx_data = NULL;
4464 unsigned long flags;
4466 int cpu = event->cpu;
4469 /* Must be root to operate on a CPU event: */
4470 err = perf_allow_cpu(&event->attr);
4472 return ERR_PTR(err);
4474 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
4483 ctxn = pmu->task_ctx_nr;
4487 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4488 task_ctx_data = alloc_task_ctx_data(pmu);
4489 if (!task_ctx_data) {
4496 ctx = perf_lock_task_context(task, ctxn, &flags);
4498 clone_ctx = unclone_ctx(ctx);
4501 if (task_ctx_data && !ctx->task_ctx_data) {
4502 ctx->task_ctx_data = task_ctx_data;
4503 task_ctx_data = NULL;
4505 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4510 ctx = alloc_perf_context(pmu, task);
4515 if (task_ctx_data) {
4516 ctx->task_ctx_data = task_ctx_data;
4517 task_ctx_data = NULL;
4521 mutex_lock(&task->perf_event_mutex);
4523 * If it has already passed perf_event_exit_task().
4524 * we must see PF_EXITING, it takes this mutex too.
4526 if (task->flags & PF_EXITING)
4528 else if (task->perf_event_ctxp[ctxn])
4533 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
4535 mutex_unlock(&task->perf_event_mutex);
4537 if (unlikely(err)) {
4546 free_task_ctx_data(pmu, task_ctx_data);
4550 free_task_ctx_data(pmu, task_ctx_data);
4551 return ERR_PTR(err);
4554 static void perf_event_free_filter(struct perf_event *event);
4555 static void perf_event_free_bpf_prog(struct perf_event *event);
4557 static void free_event_rcu(struct rcu_head *head)
4559 struct perf_event *event;
4561 event = container_of(head, struct perf_event, rcu_head);
4563 put_pid_ns(event->ns);
4564 perf_event_free_filter(event);
4568 static void ring_buffer_attach(struct perf_event *event,
4569 struct perf_buffer *rb);
4571 static void detach_sb_event(struct perf_event *event)
4573 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4575 raw_spin_lock(&pel->lock);
4576 list_del_rcu(&event->sb_list);
4577 raw_spin_unlock(&pel->lock);
4580 static bool is_sb_event(struct perf_event *event)
4582 struct perf_event_attr *attr = &event->attr;
4587 if (event->attach_state & PERF_ATTACH_TASK)
4590 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4591 attr->comm || attr->comm_exec ||
4592 attr->task || attr->ksymbol ||
4593 attr->context_switch || attr->text_poke ||
4599 static void unaccount_pmu_sb_event(struct perf_event *event)
4601 if (is_sb_event(event))
4602 detach_sb_event(event);
4605 static void unaccount_event_cpu(struct perf_event *event, int cpu)
4610 if (is_cgroup_event(event))
4611 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
4614 #ifdef CONFIG_NO_HZ_FULL
4615 static DEFINE_SPINLOCK(nr_freq_lock);
4618 static void unaccount_freq_event_nohz(void)
4620 #ifdef CONFIG_NO_HZ_FULL
4621 spin_lock(&nr_freq_lock);
4622 if (atomic_dec_and_test(&nr_freq_events))
4623 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4624 spin_unlock(&nr_freq_lock);
4628 static void unaccount_freq_event(void)
4630 if (tick_nohz_full_enabled())
4631 unaccount_freq_event_nohz();
4633 atomic_dec(&nr_freq_events);
4636 static void unaccount_event(struct perf_event *event)
4643 if (event->attach_state & PERF_ATTACH_TASK)
4645 if (event->attr.mmap || event->attr.mmap_data)
4646 atomic_dec(&nr_mmap_events);
4647 if (event->attr.comm)
4648 atomic_dec(&nr_comm_events);
4649 if (event->attr.namespaces)
4650 atomic_dec(&nr_namespaces_events);
4651 if (event->attr.cgroup)
4652 atomic_dec(&nr_cgroup_events);
4653 if (event->attr.task)
4654 atomic_dec(&nr_task_events);
4655 if (event->attr.freq)
4656 unaccount_freq_event();
4657 if (event->attr.context_switch) {
4659 atomic_dec(&nr_switch_events);
4661 if (is_cgroup_event(event))
4663 if (has_branch_stack(event))
4665 if (event->attr.ksymbol)
4666 atomic_dec(&nr_ksymbol_events);
4667 if (event->attr.bpf_event)
4668 atomic_dec(&nr_bpf_events);
4669 if (event->attr.text_poke)
4670 atomic_dec(&nr_text_poke_events);
4673 if (!atomic_add_unless(&perf_sched_count, -1, 1))
4674 schedule_delayed_work(&perf_sched_work, HZ);
4677 unaccount_event_cpu(event, event->cpu);
4679 unaccount_pmu_sb_event(event);
4682 static void perf_sched_delayed(struct work_struct *work)
4684 mutex_lock(&perf_sched_mutex);
4685 if (atomic_dec_and_test(&perf_sched_count))
4686 static_branch_disable(&perf_sched_events);
4687 mutex_unlock(&perf_sched_mutex);
4691 * The following implement mutual exclusion of events on "exclusive" pmus
4692 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
4693 * at a time, so we disallow creating events that might conflict, namely:
4695 * 1) cpu-wide events in the presence of per-task events,
4696 * 2) per-task events in the presence of cpu-wide events,
4697 * 3) two matching events on the same context.
4699 * The former two cases are handled in the allocation path (perf_event_alloc(),
4700 * _free_event()), the latter -- before the first perf_install_in_context().
4702 static int exclusive_event_init(struct perf_event *event)
4704 struct pmu *pmu = event->pmu;
4706 if (!is_exclusive_pmu(pmu))
4710 * Prevent co-existence of per-task and cpu-wide events on the
4711 * same exclusive pmu.
4713 * Negative pmu::exclusive_cnt means there are cpu-wide
4714 * events on this "exclusive" pmu, positive means there are
4717 * Since this is called in perf_event_alloc() path, event::ctx
4718 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4719 * to mean "per-task event", because unlike other attach states it
4720 * never gets cleared.
4722 if (event->attach_state & PERF_ATTACH_TASK) {
4723 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4726 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4733 static void exclusive_event_destroy(struct perf_event *event)
4735 struct pmu *pmu = event->pmu;
4737 if (!is_exclusive_pmu(pmu))
4740 /* see comment in exclusive_event_init() */
4741 if (event->attach_state & PERF_ATTACH_TASK)
4742 atomic_dec(&pmu->exclusive_cnt);
4744 atomic_inc(&pmu->exclusive_cnt);
4747 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4749 if ((e1->pmu == e2->pmu) &&
4750 (e1->cpu == e2->cpu ||
4757 static bool exclusive_event_installable(struct perf_event *event,
4758 struct perf_event_context *ctx)
4760 struct perf_event *iter_event;
4761 struct pmu *pmu = event->pmu;
4763 lockdep_assert_held(&ctx->mutex);
4765 if (!is_exclusive_pmu(pmu))
4768 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4769 if (exclusive_event_match(iter_event, event))
4776 static void perf_addr_filters_splice(struct perf_event *event,
4777 struct list_head *head);
4779 static void _free_event(struct perf_event *event)
4781 irq_work_sync(&event->pending);
4783 unaccount_event(event);
4785 security_perf_event_free(event);
4789 * Can happen when we close an event with re-directed output.
4791 * Since we have a 0 refcount, perf_mmap_close() will skip
4792 * over us; possibly making our ring_buffer_put() the last.
4794 mutex_lock(&event->mmap_mutex);
4795 ring_buffer_attach(event, NULL);
4796 mutex_unlock(&event->mmap_mutex);
4799 if (is_cgroup_event(event))
4800 perf_detach_cgroup(event);
4802 if (!event->parent) {
4803 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4804 put_callchain_buffers();
4807 perf_event_free_bpf_prog(event);
4808 perf_addr_filters_splice(event, NULL);
4809 kfree(event->addr_filter_ranges);
4812 event->destroy(event);
4815 * Must be after ->destroy(), due to uprobe_perf_close() using
4818 if (event->hw.target)
4819 put_task_struct(event->hw.target);
4822 * perf_event_free_task() relies on put_ctx() being 'last', in particular
4823 * all task references must be cleaned up.
4826 put_ctx(event->ctx);
4828 exclusive_event_destroy(event);
4829 module_put(event->pmu->module);
4831 call_rcu(&event->rcu_head, free_event_rcu);
4835 * Used to free events which have a known refcount of 1, such as in error paths
4836 * where the event isn't exposed yet and inherited events.
4838 static void free_event(struct perf_event *event)
4840 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
4841 "unexpected event refcount: %ld; ptr=%p\n",
4842 atomic_long_read(&event->refcount), event)) {
4843 /* leak to avoid use-after-free */
4851 * Remove user event from the owner task.
4853 static void perf_remove_from_owner(struct perf_event *event)
4855 struct task_struct *owner;
4859 * Matches the smp_store_release() in perf_event_exit_task(). If we
4860 * observe !owner it means the list deletion is complete and we can
4861 * indeed free this event, otherwise we need to serialize on
4862 * owner->perf_event_mutex.
4864 owner = READ_ONCE(event->owner);
4867 * Since delayed_put_task_struct() also drops the last
4868 * task reference we can safely take a new reference
4869 * while holding the rcu_read_lock().
4871 get_task_struct(owner);
4877 * If we're here through perf_event_exit_task() we're already
4878 * holding ctx->mutex which would be an inversion wrt. the
4879 * normal lock order.
4881 * However we can safely take this lock because its the child
4884 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
4887 * We have to re-check the event->owner field, if it is cleared
4888 * we raced with perf_event_exit_task(), acquiring the mutex
4889 * ensured they're done, and we can proceed with freeing the
4893 list_del_init(&event->owner_entry);
4894 smp_store_release(&event->owner, NULL);
4896 mutex_unlock(&owner->perf_event_mutex);
4897 put_task_struct(owner);
4901 static void put_event(struct perf_event *event)
4903 if (!atomic_long_dec_and_test(&event->refcount))
4910 * Kill an event dead; while event:refcount will preserve the event
4911 * object, it will not preserve its functionality. Once the last 'user'
4912 * gives up the object, we'll destroy the thing.
4914 int perf_event_release_kernel(struct perf_event *event)
4916 struct perf_event_context *ctx = event->ctx;
4917 struct perf_event *child, *tmp;
4918 LIST_HEAD(free_list);
4921 * If we got here through err_file: fput(event_file); we will not have
4922 * attached to a context yet.
4925 WARN_ON_ONCE(event->attach_state &
4926 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
4930 if (!is_kernel_event(event))
4931 perf_remove_from_owner(event);
4933 ctx = perf_event_ctx_lock(event);
4934 WARN_ON_ONCE(ctx->parent_ctx);
4935 perf_remove_from_context(event, DETACH_GROUP);
4937 raw_spin_lock_irq(&ctx->lock);
4939 * Mark this event as STATE_DEAD, there is no external reference to it
4942 * Anybody acquiring event->child_mutex after the below loop _must_
4943 * also see this, most importantly inherit_event() which will avoid
4944 * placing more children on the list.
4946 * Thus this guarantees that we will in fact observe and kill _ALL_
4949 event->state = PERF_EVENT_STATE_DEAD;
4950 raw_spin_unlock_irq(&ctx->lock);
4952 perf_event_ctx_unlock(event, ctx);
4955 mutex_lock(&event->child_mutex);
4956 list_for_each_entry(child, &event->child_list, child_list) {
4959 * Cannot change, child events are not migrated, see the
4960 * comment with perf_event_ctx_lock_nested().
4962 ctx = READ_ONCE(child->ctx);
4964 * Since child_mutex nests inside ctx::mutex, we must jump
4965 * through hoops. We start by grabbing a reference on the ctx.
4967 * Since the event cannot get freed while we hold the
4968 * child_mutex, the context must also exist and have a !0
4974 * Now that we have a ctx ref, we can drop child_mutex, and
4975 * acquire ctx::mutex without fear of it going away. Then we
4976 * can re-acquire child_mutex.
4978 mutex_unlock(&event->child_mutex);
4979 mutex_lock(&ctx->mutex);
4980 mutex_lock(&event->child_mutex);
4983 * Now that we hold ctx::mutex and child_mutex, revalidate our
4984 * state, if child is still the first entry, it didn't get freed
4985 * and we can continue doing so.
4987 tmp = list_first_entry_or_null(&event->child_list,
4988 struct perf_event, child_list);
4990 perf_remove_from_context(child, DETACH_GROUP);
4991 list_move(&child->child_list, &free_list);
4993 * This matches the refcount bump in inherit_event();
4994 * this can't be the last reference.
4999 mutex_unlock(&event->child_mutex);
5000 mutex_unlock(&ctx->mutex);
5004 mutex_unlock(&event->child_mutex);
5006 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
5007 void *var = &child->ctx->refcount;
5009 list_del(&child->child_list);
5013 * Wake any perf_event_free_task() waiting for this event to be
5016 smp_mb(); /* pairs with wait_var_event() */
5021 put_event(event); /* Must be the 'last' reference */
5024 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5027 * Called when the last reference to the file is gone.
5029 static int perf_release(struct inode *inode, struct file *file)
5031 perf_event_release_kernel(file->private_data);
5035 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5037 struct perf_event *child;
5043 mutex_lock(&event->child_mutex);
5045 (void)perf_event_read(event, false);
5046 total += perf_event_count(event);
5048 *enabled += event->total_time_enabled +
5049 atomic64_read(&event->child_total_time_enabled);
5050 *running += event->total_time_running +
5051 atomic64_read(&event->child_total_time_running);
5053 list_for_each_entry(child, &event->child_list, child_list) {
5054 (void)perf_event_read(child, false);
5055 total += perf_event_count(child);
5056 *enabled += child->total_time_enabled;
5057 *running += child->total_time_running;
5059 mutex_unlock(&event->child_mutex);
5064 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5066 struct perf_event_context *ctx;
5069 ctx = perf_event_ctx_lock(event);
5070 count = __perf_event_read_value(event, enabled, running);
5071 perf_event_ctx_unlock(event, ctx);
5075 EXPORT_SYMBOL_GPL(perf_event_read_value);
5077 static int __perf_read_group_add(struct perf_event *leader,
5078 u64 read_format, u64 *values)
5080 struct perf_event_context *ctx = leader->ctx;
5081 struct perf_event *sub;
5082 unsigned long flags;
5083 int n = 1; /* skip @nr */
5086 ret = perf_event_read(leader, true);
5090 raw_spin_lock_irqsave(&ctx->lock, flags);
5093 * Since we co-schedule groups, {enabled,running} times of siblings
5094 * will be identical to those of the leader, so we only publish one
5097 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5098 values[n++] += leader->total_time_enabled +
5099 atomic64_read(&leader->child_total_time_enabled);
5102 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5103 values[n++] += leader->total_time_running +
5104 atomic64_read(&leader->child_total_time_running);
5108 * Write {count,id} tuples for every sibling.
5110 values[n++] += perf_event_count(leader);
5111 if (read_format & PERF_FORMAT_ID)
5112 values[n++] = primary_event_id(leader);
5114 for_each_sibling_event(sub, leader) {
5115 values[n++] += perf_event_count(sub);
5116 if (read_format & PERF_FORMAT_ID)
5117 values[n++] = primary_event_id(sub);
5120 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5124 static int perf_read_group(struct perf_event *event,
5125 u64 read_format, char __user *buf)
5127 struct perf_event *leader = event->group_leader, *child;
5128 struct perf_event_context *ctx = leader->ctx;
5132 lockdep_assert_held(&ctx->mutex);
5134 values = kzalloc(event->read_size, GFP_KERNEL);
5138 values[0] = 1 + leader->nr_siblings;
5141 * By locking the child_mutex of the leader we effectively
5142 * lock the child list of all siblings.. XXX explain how.
5144 mutex_lock(&leader->child_mutex);
5146 ret = __perf_read_group_add(leader, read_format, values);
5150 list_for_each_entry(child, &leader->child_list, child_list) {
5151 ret = __perf_read_group_add(child, read_format, values);
5156 mutex_unlock(&leader->child_mutex);
5158 ret = event->read_size;
5159 if (copy_to_user(buf, values, event->read_size))
5164 mutex_unlock(&leader->child_mutex);
5170 static int perf_read_one(struct perf_event *event,
5171 u64 read_format, char __user *buf)
5173 u64 enabled, running;
5177 values[n++] = __perf_event_read_value(event, &enabled, &running);
5178 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5179 values[n++] = enabled;
5180 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5181 values[n++] = running;
5182 if (read_format & PERF_FORMAT_ID)
5183 values[n++] = primary_event_id(event);
5185 if (copy_to_user(buf, values, n * sizeof(u64)))
5188 return n * sizeof(u64);
5191 static bool is_event_hup(struct perf_event *event)
5195 if (event->state > PERF_EVENT_STATE_EXIT)
5198 mutex_lock(&event->child_mutex);
5199 no_children = list_empty(&event->child_list);
5200 mutex_unlock(&event->child_mutex);
5205 * Read the performance event - simple non blocking version for now
5208 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5210 u64 read_format = event->attr.read_format;
5214 * Return end-of-file for a read on an event that is in
5215 * error state (i.e. because it was pinned but it couldn't be
5216 * scheduled on to the CPU at some point).
5218 if (event->state == PERF_EVENT_STATE_ERROR)
5221 if (count < event->read_size)
5224 WARN_ON_ONCE(event->ctx->parent_ctx);
5225 if (read_format & PERF_FORMAT_GROUP)
5226 ret = perf_read_group(event, read_format, buf);
5228 ret = perf_read_one(event, read_format, buf);
5234 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5236 struct perf_event *event = file->private_data;
5237 struct perf_event_context *ctx;
5240 ret = security_perf_event_read(event);
5244 ctx = perf_event_ctx_lock(event);
5245 ret = __perf_read(event, buf, count);
5246 perf_event_ctx_unlock(event, ctx);
5251 static __poll_t perf_poll(struct file *file, poll_table *wait)
5253 struct perf_event *event = file->private_data;
5254 struct perf_buffer *rb;
5255 __poll_t events = EPOLLHUP;
5257 poll_wait(file, &event->waitq, wait);
5259 if (is_event_hup(event))
5263 * Pin the event->rb by taking event->mmap_mutex; otherwise
5264 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5266 mutex_lock(&event->mmap_mutex);
5269 events = atomic_xchg(&rb->poll, 0);
5270 mutex_unlock(&event->mmap_mutex);
5274 static void _perf_event_reset(struct perf_event *event)
5276 (void)perf_event_read(event, false);
5277 local64_set(&event->count, 0);
5278 perf_event_update_userpage(event);
5281 /* Assume it's not an event with inherit set. */
5282 u64 perf_event_pause(struct perf_event *event, bool reset)
5284 struct perf_event_context *ctx;
5287 ctx = perf_event_ctx_lock(event);
5288 WARN_ON_ONCE(event->attr.inherit);
5289 _perf_event_disable(event);
5290 count = local64_read(&event->count);
5292 local64_set(&event->count, 0);
5293 perf_event_ctx_unlock(event, ctx);
5297 EXPORT_SYMBOL_GPL(perf_event_pause);
5300 * Holding the top-level event's child_mutex means that any
5301 * descendant process that has inherited this event will block
5302 * in perf_event_exit_event() if it goes to exit, thus satisfying the
5303 * task existence requirements of perf_event_enable/disable.
5305 static void perf_event_for_each_child(struct perf_event *event,
5306 void (*func)(struct perf_event *))
5308 struct perf_event *child;
5310 WARN_ON_ONCE(event->ctx->parent_ctx);
5312 mutex_lock(&event->child_mutex);
5314 list_for_each_entry(child, &event->child_list, child_list)
5316 mutex_unlock(&event->child_mutex);
5319 static void perf_event_for_each(struct perf_event *event,
5320 void (*func)(struct perf_event *))
5322 struct perf_event_context *ctx = event->ctx;
5323 struct perf_event *sibling;
5325 lockdep_assert_held(&ctx->mutex);
5327 event = event->group_leader;
5329 perf_event_for_each_child(event, func);
5330 for_each_sibling_event(sibling, event)
5331 perf_event_for_each_child(sibling, func);
5334 static void __perf_event_period(struct perf_event *event,
5335 struct perf_cpu_context *cpuctx,
5336 struct perf_event_context *ctx,
5339 u64 value = *((u64 *)info);
5342 if (event->attr.freq) {
5343 event->attr.sample_freq = value;
5345 event->attr.sample_period = value;
5346 event->hw.sample_period = value;
5349 active = (event->state == PERF_EVENT_STATE_ACTIVE);
5351 perf_pmu_disable(ctx->pmu);
5353 * We could be throttled; unthrottle now to avoid the tick
5354 * trying to unthrottle while we already re-started the event.
5356 if (event->hw.interrupts == MAX_INTERRUPTS) {
5357 event->hw.interrupts = 0;
5358 perf_log_throttle(event, 1);
5360 event->pmu->stop(event, PERF_EF_UPDATE);
5363 local64_set(&event->hw.period_left, 0);
5366 event->pmu->start(event, PERF_EF_RELOAD);
5367 perf_pmu_enable(ctx->pmu);
5371 static int perf_event_check_period(struct perf_event *event, u64 value)
5373 return event->pmu->check_period(event, value);
5376 static int _perf_event_period(struct perf_event *event, u64 value)
5378 if (!is_sampling_event(event))
5384 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5387 if (perf_event_check_period(event, value))
5390 if (!event->attr.freq && (value & (1ULL << 63)))
5393 event_function_call(event, __perf_event_period, &value);
5398 int perf_event_period(struct perf_event *event, u64 value)
5400 struct perf_event_context *ctx;
5403 ctx = perf_event_ctx_lock(event);
5404 ret = _perf_event_period(event, value);
5405 perf_event_ctx_unlock(event, ctx);
5409 EXPORT_SYMBOL_GPL(perf_event_period);
5411 static const struct file_operations perf_fops;
5413 static inline int perf_fget_light(int fd, struct fd *p)
5415 struct fd f = fdget(fd);
5419 if (f.file->f_op != &perf_fops) {
5427 static int perf_event_set_output(struct perf_event *event,
5428 struct perf_event *output_event);
5429 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5430 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
5431 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5432 struct perf_event_attr *attr);
5434 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5436 void (*func)(struct perf_event *);
5440 case PERF_EVENT_IOC_ENABLE:
5441 func = _perf_event_enable;
5443 case PERF_EVENT_IOC_DISABLE:
5444 func = _perf_event_disable;
5446 case PERF_EVENT_IOC_RESET:
5447 func = _perf_event_reset;
5450 case PERF_EVENT_IOC_REFRESH:
5451 return _perf_event_refresh(event, arg);
5453 case PERF_EVENT_IOC_PERIOD:
5457 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
5460 return _perf_event_period(event, value);
5462 case PERF_EVENT_IOC_ID:
5464 u64 id = primary_event_id(event);
5466 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5471 case PERF_EVENT_IOC_SET_OUTPUT:
5475 struct perf_event *output_event;
5477 ret = perf_fget_light(arg, &output);
5480 output_event = output.file->private_data;
5481 ret = perf_event_set_output(event, output_event);
5484 ret = perf_event_set_output(event, NULL);
5489 case PERF_EVENT_IOC_SET_FILTER:
5490 return perf_event_set_filter(event, (void __user *)arg);
5492 case PERF_EVENT_IOC_SET_BPF:
5493 return perf_event_set_bpf_prog(event, arg);
5495 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5496 struct perf_buffer *rb;
5499 rb = rcu_dereference(event->rb);
5500 if (!rb || !rb->nr_pages) {
5504 rb_toggle_paused(rb, !!arg);
5509 case PERF_EVENT_IOC_QUERY_BPF:
5510 return perf_event_query_prog_array(event, (void __user *)arg);
5512 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5513 struct perf_event_attr new_attr;
5514 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5520 return perf_event_modify_attr(event, &new_attr);
5526 if (flags & PERF_IOC_FLAG_GROUP)
5527 perf_event_for_each(event, func);
5529 perf_event_for_each_child(event, func);
5534 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5536 struct perf_event *event = file->private_data;
5537 struct perf_event_context *ctx;
5540 /* Treat ioctl like writes as it is likely a mutating operation. */
5541 ret = security_perf_event_write(event);
5545 ctx = perf_event_ctx_lock(event);
5546 ret = _perf_ioctl(event, cmd, arg);
5547 perf_event_ctx_unlock(event, ctx);
5552 #ifdef CONFIG_COMPAT
5553 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5556 switch (_IOC_NR(cmd)) {
5557 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5558 case _IOC_NR(PERF_EVENT_IOC_ID):
5559 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5560 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
5561 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5562 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5563 cmd &= ~IOCSIZE_MASK;
5564 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5568 return perf_ioctl(file, cmd, arg);
5571 # define perf_compat_ioctl NULL
5574 int perf_event_task_enable(void)
5576 struct perf_event_context *ctx;
5577 struct perf_event *event;
5579 mutex_lock(¤t->perf_event_mutex);
5580 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5581 ctx = perf_event_ctx_lock(event);
5582 perf_event_for_each_child(event, _perf_event_enable);
5583 perf_event_ctx_unlock(event, ctx);
5585 mutex_unlock(¤t->perf_event_mutex);
5590 int perf_event_task_disable(void)
5592 struct perf_event_context *ctx;
5593 struct perf_event *event;
5595 mutex_lock(¤t->perf_event_mutex);
5596 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5597 ctx = perf_event_ctx_lock(event);
5598 perf_event_for_each_child(event, _perf_event_disable);
5599 perf_event_ctx_unlock(event, ctx);
5601 mutex_unlock(¤t->perf_event_mutex);
5606 static int perf_event_index(struct perf_event *event)
5608 if (event->hw.state & PERF_HES_STOPPED)
5611 if (event->state != PERF_EVENT_STATE_ACTIVE)
5614 return event->pmu->event_idx(event);
5617 static void calc_timer_values(struct perf_event *event,
5624 *now = perf_clock();
5625 ctx_time = event->shadow_ctx_time + *now;
5626 __perf_update_times(event, ctx_time, enabled, running);
5629 static void perf_event_init_userpage(struct perf_event *event)
5631 struct perf_event_mmap_page *userpg;
5632 struct perf_buffer *rb;
5635 rb = rcu_dereference(event->rb);
5639 userpg = rb->user_page;
5641 /* Allow new userspace to detect that bit 0 is deprecated */
5642 userpg->cap_bit0_is_deprecated = 1;
5643 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
5644 userpg->data_offset = PAGE_SIZE;
5645 userpg->data_size = perf_data_size(rb);
5651 void __weak arch_perf_update_userpage(
5652 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
5657 * Callers need to ensure there can be no nesting of this function, otherwise
5658 * the seqlock logic goes bad. We can not serialize this because the arch
5659 * code calls this from NMI context.
5661 void perf_event_update_userpage(struct perf_event *event)
5663 struct perf_event_mmap_page *userpg;
5664 struct perf_buffer *rb;
5665 u64 enabled, running, now;
5668 rb = rcu_dereference(event->rb);
5673 * compute total_time_enabled, total_time_running
5674 * based on snapshot values taken when the event
5675 * was last scheduled in.
5677 * we cannot simply called update_context_time()
5678 * because of locking issue as we can be called in
5681 calc_timer_values(event, &now, &enabled, &running);
5683 userpg = rb->user_page;
5685 * Disable preemption to guarantee consistent time stamps are stored to
5691 userpg->index = perf_event_index(event);
5692 userpg->offset = perf_event_count(event);
5694 userpg->offset -= local64_read(&event->hw.prev_count);
5696 userpg->time_enabled = enabled +
5697 atomic64_read(&event->child_total_time_enabled);
5699 userpg->time_running = running +
5700 atomic64_read(&event->child_total_time_running);
5702 arch_perf_update_userpage(event, userpg, now);
5710 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
5712 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
5714 struct perf_event *event = vmf->vma->vm_file->private_data;
5715 struct perf_buffer *rb;
5716 vm_fault_t ret = VM_FAULT_SIGBUS;
5718 if (vmf->flags & FAULT_FLAG_MKWRITE) {
5719 if (vmf->pgoff == 0)
5725 rb = rcu_dereference(event->rb);
5729 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
5732 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
5736 get_page(vmf->page);
5737 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
5738 vmf->page->index = vmf->pgoff;
5747 static void ring_buffer_attach(struct perf_event *event,
5748 struct perf_buffer *rb)
5750 struct perf_buffer *old_rb = NULL;
5751 unsigned long flags;
5755 * Should be impossible, we set this when removing
5756 * event->rb_entry and wait/clear when adding event->rb_entry.
5758 WARN_ON_ONCE(event->rcu_pending);
5761 spin_lock_irqsave(&old_rb->event_lock, flags);
5762 list_del_rcu(&event->rb_entry);
5763 spin_unlock_irqrestore(&old_rb->event_lock, flags);
5765 event->rcu_batches = get_state_synchronize_rcu();
5766 event->rcu_pending = 1;
5770 if (event->rcu_pending) {
5771 cond_synchronize_rcu(event->rcu_batches);
5772 event->rcu_pending = 0;
5775 spin_lock_irqsave(&rb->event_lock, flags);
5776 list_add_rcu(&event->rb_entry, &rb->event_list);
5777 spin_unlock_irqrestore(&rb->event_lock, flags);
5781 * Avoid racing with perf_mmap_close(AUX): stop the event
5782 * before swizzling the event::rb pointer; if it's getting
5783 * unmapped, its aux_mmap_count will be 0 and it won't
5784 * restart. See the comment in __perf_pmu_output_stop().
5786 * Data will inevitably be lost when set_output is done in
5787 * mid-air, but then again, whoever does it like this is
5788 * not in for the data anyway.
5791 perf_event_stop(event, 0);
5793 rcu_assign_pointer(event->rb, rb);
5796 ring_buffer_put(old_rb);
5798 * Since we detached before setting the new rb, so that we
5799 * could attach the new rb, we could have missed a wakeup.
5802 wake_up_all(&event->waitq);
5806 static void ring_buffer_wakeup(struct perf_event *event)
5808 struct perf_buffer *rb;
5811 rb = rcu_dereference(event->rb);
5813 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
5814 wake_up_all(&event->waitq);
5819 struct perf_buffer *ring_buffer_get(struct perf_event *event)
5821 struct perf_buffer *rb;
5824 rb = rcu_dereference(event->rb);
5826 if (!refcount_inc_not_zero(&rb->refcount))
5834 void ring_buffer_put(struct perf_buffer *rb)
5836 if (!refcount_dec_and_test(&rb->refcount))
5839 WARN_ON_ONCE(!list_empty(&rb->event_list));
5841 call_rcu(&rb->rcu_head, rb_free_rcu);
5844 static void perf_mmap_open(struct vm_area_struct *vma)
5846 struct perf_event *event = vma->vm_file->private_data;
5848 atomic_inc(&event->mmap_count);
5849 atomic_inc(&event->rb->mmap_count);
5852 atomic_inc(&event->rb->aux_mmap_count);
5854 if (event->pmu->event_mapped)
5855 event->pmu->event_mapped(event, vma->vm_mm);
5858 static void perf_pmu_output_stop(struct perf_event *event);
5861 * A buffer can be mmap()ed multiple times; either directly through the same
5862 * event, or through other events by use of perf_event_set_output().
5864 * In order to undo the VM accounting done by perf_mmap() we need to destroy
5865 * the buffer here, where we still have a VM context. This means we need
5866 * to detach all events redirecting to us.
5868 static void perf_mmap_close(struct vm_area_struct *vma)
5870 struct perf_event *event = vma->vm_file->private_data;
5872 struct perf_buffer *rb = ring_buffer_get(event);
5873 struct user_struct *mmap_user = rb->mmap_user;
5874 int mmap_locked = rb->mmap_locked;
5875 unsigned long size = perf_data_size(rb);
5877 if (event->pmu->event_unmapped)
5878 event->pmu->event_unmapped(event, vma->vm_mm);
5881 * rb->aux_mmap_count will always drop before rb->mmap_count and
5882 * event->mmap_count, so it is ok to use event->mmap_mutex to
5883 * serialize with perf_mmap here.
5885 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
5886 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
5888 * Stop all AUX events that are writing to this buffer,
5889 * so that we can free its AUX pages and corresponding PMU
5890 * data. Note that after rb::aux_mmap_count dropped to zero,
5891 * they won't start any more (see perf_aux_output_begin()).
5893 perf_pmu_output_stop(event);
5895 /* now it's safe to free the pages */
5896 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
5897 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
5899 /* this has to be the last one */
5901 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
5903 mutex_unlock(&event->mmap_mutex);
5906 atomic_dec(&rb->mmap_count);
5908 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
5911 ring_buffer_attach(event, NULL);
5912 mutex_unlock(&event->mmap_mutex);
5914 /* If there's still other mmap()s of this buffer, we're done. */
5915 if (atomic_read(&rb->mmap_count))
5919 * No other mmap()s, detach from all other events that might redirect
5920 * into the now unreachable buffer. Somewhat complicated by the
5921 * fact that rb::event_lock otherwise nests inside mmap_mutex.
5925 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
5926 if (!atomic_long_inc_not_zero(&event->refcount)) {
5928 * This event is en-route to free_event() which will
5929 * detach it and remove it from the list.
5935 mutex_lock(&event->mmap_mutex);
5937 * Check we didn't race with perf_event_set_output() which can
5938 * swizzle the rb from under us while we were waiting to
5939 * acquire mmap_mutex.
5941 * If we find a different rb; ignore this event, a next
5942 * iteration will no longer find it on the list. We have to
5943 * still restart the iteration to make sure we're not now
5944 * iterating the wrong list.
5946 if (event->rb == rb)
5947 ring_buffer_attach(event, NULL);
5949 mutex_unlock(&event->mmap_mutex);
5953 * Restart the iteration; either we're on the wrong list or
5954 * destroyed its integrity by doing a deletion.
5961 * It could be there's still a few 0-ref events on the list; they'll
5962 * get cleaned up by free_event() -- they'll also still have their
5963 * ref on the rb and will free it whenever they are done with it.
5965 * Aside from that, this buffer is 'fully' detached and unmapped,
5966 * undo the VM accounting.
5969 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
5970 &mmap_user->locked_vm);
5971 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
5972 free_uid(mmap_user);
5975 ring_buffer_put(rb); /* could be last */
5978 static const struct vm_operations_struct perf_mmap_vmops = {
5979 .open = perf_mmap_open,
5980 .close = perf_mmap_close, /* non mergeable */
5981 .fault = perf_mmap_fault,
5982 .page_mkwrite = perf_mmap_fault,
5985 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
5987 struct perf_event *event = file->private_data;
5988 unsigned long user_locked, user_lock_limit;
5989 struct user_struct *user = current_user();
5990 struct perf_buffer *rb = NULL;
5991 unsigned long locked, lock_limit;
5992 unsigned long vma_size;
5993 unsigned long nr_pages;
5994 long user_extra = 0, extra = 0;
5995 int ret = 0, flags = 0;
5998 * Don't allow mmap() of inherited per-task counters. This would
5999 * create a performance issue due to all children writing to the
6002 if (event->cpu == -1 && event->attr.inherit)
6005 if (!(vma->vm_flags & VM_SHARED))
6008 ret = security_perf_event_read(event);
6012 vma_size = vma->vm_end - vma->vm_start;
6014 if (vma->vm_pgoff == 0) {
6015 nr_pages = (vma_size / PAGE_SIZE) - 1;
6018 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
6019 * mapped, all subsequent mappings should have the same size
6020 * and offset. Must be above the normal perf buffer.
6022 u64 aux_offset, aux_size;
6027 nr_pages = vma_size / PAGE_SIZE;
6029 mutex_lock(&event->mmap_mutex);
6036 aux_offset = READ_ONCE(rb->user_page->aux_offset);
6037 aux_size = READ_ONCE(rb->user_page->aux_size);
6039 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6042 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6045 /* already mapped with a different offset */
6046 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6049 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6052 /* already mapped with a different size */
6053 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6056 if (!is_power_of_2(nr_pages))
6059 if (!atomic_inc_not_zero(&rb->mmap_count))
6062 if (rb_has_aux(rb)) {
6063 atomic_inc(&rb->aux_mmap_count);
6068 atomic_set(&rb->aux_mmap_count, 1);
6069 user_extra = nr_pages;
6075 * If we have rb pages ensure they're a power-of-two number, so we
6076 * can do bitmasks instead of modulo.
6078 if (nr_pages != 0 && !is_power_of_2(nr_pages))
6081 if (vma_size != PAGE_SIZE * (1 + nr_pages))
6084 WARN_ON_ONCE(event->ctx->parent_ctx);
6086 mutex_lock(&event->mmap_mutex);
6088 if (event->rb->nr_pages != nr_pages) {
6093 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6095 * Raced against perf_mmap_close() through
6096 * perf_event_set_output(). Try again, hope for better
6099 mutex_unlock(&event->mmap_mutex);
6106 user_extra = nr_pages + 1;
6109 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6112 * Increase the limit linearly with more CPUs:
6114 user_lock_limit *= num_online_cpus();
6116 user_locked = atomic_long_read(&user->locked_vm);
6119 * sysctl_perf_event_mlock may have changed, so that
6120 * user->locked_vm > user_lock_limit
6122 if (user_locked > user_lock_limit)
6123 user_locked = user_lock_limit;
6124 user_locked += user_extra;
6126 if (user_locked > user_lock_limit) {
6128 * charge locked_vm until it hits user_lock_limit;
6129 * charge the rest from pinned_vm
6131 extra = user_locked - user_lock_limit;
6132 user_extra -= extra;
6135 lock_limit = rlimit(RLIMIT_MEMLOCK);
6136 lock_limit >>= PAGE_SHIFT;
6137 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
6139 if ((locked > lock_limit) && perf_is_paranoid() &&
6140 !capable(CAP_IPC_LOCK)) {
6145 WARN_ON(!rb && event->rb);
6147 if (vma->vm_flags & VM_WRITE)
6148 flags |= RING_BUFFER_WRITABLE;
6151 rb = rb_alloc(nr_pages,
6152 event->attr.watermark ? event->attr.wakeup_watermark : 0,
6160 atomic_set(&rb->mmap_count, 1);
6161 rb->mmap_user = get_current_user();
6162 rb->mmap_locked = extra;
6164 ring_buffer_attach(event, rb);
6166 perf_event_init_userpage(event);
6167 perf_event_update_userpage(event);
6169 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6170 event->attr.aux_watermark, flags);
6172 rb->aux_mmap_locked = extra;
6177 atomic_long_add(user_extra, &user->locked_vm);
6178 atomic64_add(extra, &vma->vm_mm->pinned_vm);
6180 atomic_inc(&event->mmap_count);
6182 atomic_dec(&rb->mmap_count);
6185 mutex_unlock(&event->mmap_mutex);
6188 * Since pinned accounting is per vm we cannot allow fork() to copy our
6191 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
6192 vma->vm_ops = &perf_mmap_vmops;
6194 if (event->pmu->event_mapped)
6195 event->pmu->event_mapped(event, vma->vm_mm);
6200 static int perf_fasync(int fd, struct file *filp, int on)
6202 struct inode *inode = file_inode(filp);
6203 struct perf_event *event = filp->private_data;
6207 retval = fasync_helper(fd, filp, on, &event->fasync);
6208 inode_unlock(inode);
6216 static const struct file_operations perf_fops = {
6217 .llseek = no_llseek,
6218 .release = perf_release,
6221 .unlocked_ioctl = perf_ioctl,
6222 .compat_ioctl = perf_compat_ioctl,
6224 .fasync = perf_fasync,
6230 * If there's data, ensure we set the poll() state and publish everything
6231 * to user-space before waking everybody up.
6234 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
6236 /* only the parent has fasync state */
6238 event = event->parent;
6239 return &event->fasync;
6242 void perf_event_wakeup(struct perf_event *event)
6244 ring_buffer_wakeup(event);
6246 if (event->pending_kill) {
6247 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6248 event->pending_kill = 0;
6252 static void perf_pending_event_disable(struct perf_event *event)
6254 int cpu = READ_ONCE(event->pending_disable);
6259 if (cpu == smp_processor_id()) {
6260 WRITE_ONCE(event->pending_disable, -1);
6261 perf_event_disable_local(event);
6268 * perf_event_disable_inatomic()
6269 * @pending_disable = CPU-A;
6273 * @pending_disable = -1;
6276 * perf_event_disable_inatomic()
6277 * @pending_disable = CPU-B;
6278 * irq_work_queue(); // FAILS
6281 * perf_pending_event()
6283 * But the event runs on CPU-B and wants disabling there.
6285 irq_work_queue_on(&event->pending, cpu);
6288 static void perf_pending_event(struct irq_work *entry)
6290 struct perf_event *event = container_of(entry, struct perf_event, pending);
6293 rctx = perf_swevent_get_recursion_context();
6295 * If we 'fail' here, that's OK, it means recursion is already disabled
6296 * and we won't recurse 'further'.
6299 perf_pending_event_disable(event);
6301 if (event->pending_wakeup) {
6302 event->pending_wakeup = 0;
6303 perf_event_wakeup(event);
6307 perf_swevent_put_recursion_context(rctx);
6311 * We assume there is only KVM supporting the callbacks.
6312 * Later on, we might change it to a list if there is
6313 * another virtualization implementation supporting the callbacks.
6315 struct perf_guest_info_callbacks *perf_guest_cbs;
6317 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6319 perf_guest_cbs = cbs;
6322 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6324 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6326 perf_guest_cbs = NULL;
6329 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6332 perf_output_sample_regs(struct perf_output_handle *handle,
6333 struct pt_regs *regs, u64 mask)
6336 DECLARE_BITMAP(_mask, 64);
6338 bitmap_from_u64(_mask, mask);
6339 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
6342 val = perf_reg_value(regs, bit);
6343 perf_output_put(handle, val);
6347 static void perf_sample_regs_user(struct perf_regs *regs_user,
6348 struct pt_regs *regs,
6349 struct pt_regs *regs_user_copy)
6351 if (user_mode(regs)) {
6352 regs_user->abi = perf_reg_abi(current);
6353 regs_user->regs = regs;
6354 } else if (!(current->flags & PF_KTHREAD)) {
6355 perf_get_regs_user(regs_user, regs, regs_user_copy);
6357 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6358 regs_user->regs = NULL;
6362 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6363 struct pt_regs *regs)
6365 regs_intr->regs = regs;
6366 regs_intr->abi = perf_reg_abi(current);
6371 * Get remaining task size from user stack pointer.
6373 * It'd be better to take stack vma map and limit this more
6374 * precisely, but there's no way to get it safely under interrupt,
6375 * so using TASK_SIZE as limit.
6377 static u64 perf_ustack_task_size(struct pt_regs *regs)
6379 unsigned long addr = perf_user_stack_pointer(regs);
6381 if (!addr || addr >= TASK_SIZE)
6384 return TASK_SIZE - addr;
6388 perf_sample_ustack_size(u16 stack_size, u16 header_size,
6389 struct pt_regs *regs)
6393 /* No regs, no stack pointer, no dump. */
6398 * Check if we fit in with the requested stack size into the:
6400 * If we don't, we limit the size to the TASK_SIZE.
6402 * - remaining sample size
6403 * If we don't, we customize the stack size to
6404 * fit in to the remaining sample size.
6407 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6408 stack_size = min(stack_size, (u16) task_size);
6410 /* Current header size plus static size and dynamic size. */
6411 header_size += 2 * sizeof(u64);
6413 /* Do we fit in with the current stack dump size? */
6414 if ((u16) (header_size + stack_size) < header_size) {
6416 * If we overflow the maximum size for the sample,
6417 * we customize the stack dump size to fit in.
6419 stack_size = USHRT_MAX - header_size - sizeof(u64);
6420 stack_size = round_up(stack_size, sizeof(u64));
6427 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6428 struct pt_regs *regs)
6430 /* Case of a kernel thread, nothing to dump */
6433 perf_output_put(handle, size);
6443 * - the size requested by user or the best one we can fit
6444 * in to the sample max size
6446 * - user stack dump data
6448 * - the actual dumped size
6452 perf_output_put(handle, dump_size);
6455 sp = perf_user_stack_pointer(regs);
6458 rem = __output_copy_user(handle, (void *) sp, dump_size);
6460 dyn_size = dump_size - rem;
6462 perf_output_skip(handle, rem);
6465 perf_output_put(handle, dyn_size);
6469 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
6470 struct perf_sample_data *data,
6473 struct perf_event *sampler = event->aux_event;
6474 struct perf_buffer *rb;
6481 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
6484 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
6487 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6492 * If this is an NMI hit inside sampling code, don't take
6493 * the sample. See also perf_aux_sample_output().
6495 if (READ_ONCE(rb->aux_in_sampling)) {
6498 size = min_t(size_t, size, perf_aux_size(rb));
6499 data->aux_size = ALIGN(size, sizeof(u64));
6501 ring_buffer_put(rb);
6504 return data->aux_size;
6507 long perf_pmu_snapshot_aux(struct perf_buffer *rb,
6508 struct perf_event *event,
6509 struct perf_output_handle *handle,
6512 unsigned long flags;
6516 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
6517 * paths. If we start calling them in NMI context, they may race with
6518 * the IRQ ones, that is, for example, re-starting an event that's just
6519 * been stopped, which is why we're using a separate callback that
6520 * doesn't change the event state.
6522 * IRQs need to be disabled to prevent IPIs from racing with us.
6524 local_irq_save(flags);
6526 * Guard against NMI hits inside the critical section;
6527 * see also perf_prepare_sample_aux().
6529 WRITE_ONCE(rb->aux_in_sampling, 1);
6532 ret = event->pmu->snapshot_aux(event, handle, size);
6535 WRITE_ONCE(rb->aux_in_sampling, 0);
6536 local_irq_restore(flags);
6541 static void perf_aux_sample_output(struct perf_event *event,
6542 struct perf_output_handle *handle,
6543 struct perf_sample_data *data)
6545 struct perf_event *sampler = event->aux_event;
6546 struct perf_buffer *rb;
6550 if (WARN_ON_ONCE(!sampler || !data->aux_size))
6553 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6557 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
6560 * An error here means that perf_output_copy() failed (returned a
6561 * non-zero surplus that it didn't copy), which in its current
6562 * enlightened implementation is not possible. If that changes, we'd
6565 if (WARN_ON_ONCE(size < 0))
6569 * The pad comes from ALIGN()ing data->aux_size up to u64 in
6570 * perf_prepare_sample_aux(), so should not be more than that.
6572 pad = data->aux_size - size;
6573 if (WARN_ON_ONCE(pad >= sizeof(u64)))
6578 perf_output_copy(handle, &zero, pad);
6582 ring_buffer_put(rb);
6585 static void __perf_event_header__init_id(struct perf_event_header *header,
6586 struct perf_sample_data *data,
6587 struct perf_event *event)
6589 u64 sample_type = event->attr.sample_type;
6591 data->type = sample_type;
6592 header->size += event->id_header_size;
6594 if (sample_type & PERF_SAMPLE_TID) {
6595 /* namespace issues */
6596 data->tid_entry.pid = perf_event_pid(event, current);
6597 data->tid_entry.tid = perf_event_tid(event, current);
6600 if (sample_type & PERF_SAMPLE_TIME)
6601 data->time = perf_event_clock(event);
6603 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
6604 data->id = primary_event_id(event);
6606 if (sample_type & PERF_SAMPLE_STREAM_ID)
6607 data->stream_id = event->id;
6609 if (sample_type & PERF_SAMPLE_CPU) {
6610 data->cpu_entry.cpu = raw_smp_processor_id();
6611 data->cpu_entry.reserved = 0;
6615 void perf_event_header__init_id(struct perf_event_header *header,
6616 struct perf_sample_data *data,
6617 struct perf_event *event)
6619 if (event->attr.sample_id_all)
6620 __perf_event_header__init_id(header, data, event);
6623 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
6624 struct perf_sample_data *data)
6626 u64 sample_type = data->type;
6628 if (sample_type & PERF_SAMPLE_TID)
6629 perf_output_put(handle, data->tid_entry);
6631 if (sample_type & PERF_SAMPLE_TIME)
6632 perf_output_put(handle, data->time);
6634 if (sample_type & PERF_SAMPLE_ID)
6635 perf_output_put(handle, data->id);
6637 if (sample_type & PERF_SAMPLE_STREAM_ID)
6638 perf_output_put(handle, data->stream_id);
6640 if (sample_type & PERF_SAMPLE_CPU)
6641 perf_output_put(handle, data->cpu_entry);
6643 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6644 perf_output_put(handle, data->id);
6647 void perf_event__output_id_sample(struct perf_event *event,
6648 struct perf_output_handle *handle,
6649 struct perf_sample_data *sample)
6651 if (event->attr.sample_id_all)
6652 __perf_event__output_id_sample(handle, sample);
6655 static void perf_output_read_one(struct perf_output_handle *handle,
6656 struct perf_event *event,
6657 u64 enabled, u64 running)
6659 u64 read_format = event->attr.read_format;
6663 values[n++] = perf_event_count(event);
6664 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
6665 values[n++] = enabled +
6666 atomic64_read(&event->child_total_time_enabled);
6668 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
6669 values[n++] = running +
6670 atomic64_read(&event->child_total_time_running);
6672 if (read_format & PERF_FORMAT_ID)
6673 values[n++] = primary_event_id(event);
6675 __output_copy(handle, values, n * sizeof(u64));
6678 static void perf_output_read_group(struct perf_output_handle *handle,
6679 struct perf_event *event,
6680 u64 enabled, u64 running)
6682 struct perf_event *leader = event->group_leader, *sub;
6683 u64 read_format = event->attr.read_format;
6687 values[n++] = 1 + leader->nr_siblings;
6689 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6690 values[n++] = enabled;
6692 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6693 values[n++] = running;
6695 if ((leader != event) &&
6696 (leader->state == PERF_EVENT_STATE_ACTIVE))
6697 leader->pmu->read(leader);
6699 values[n++] = perf_event_count(leader);
6700 if (read_format & PERF_FORMAT_ID)
6701 values[n++] = primary_event_id(leader);
6703 __output_copy(handle, values, n * sizeof(u64));
6705 for_each_sibling_event(sub, leader) {
6708 if ((sub != event) &&
6709 (sub->state == PERF_EVENT_STATE_ACTIVE))
6710 sub->pmu->read(sub);
6712 values[n++] = perf_event_count(sub);
6713 if (read_format & PERF_FORMAT_ID)
6714 values[n++] = primary_event_id(sub);
6716 __output_copy(handle, values, n * sizeof(u64));
6720 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
6721 PERF_FORMAT_TOTAL_TIME_RUNNING)
6724 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
6726 * The problem is that its both hard and excessively expensive to iterate the
6727 * child list, not to mention that its impossible to IPI the children running
6728 * on another CPU, from interrupt/NMI context.
6730 static void perf_output_read(struct perf_output_handle *handle,
6731 struct perf_event *event)
6733 u64 enabled = 0, running = 0, now;
6734 u64 read_format = event->attr.read_format;
6737 * compute total_time_enabled, total_time_running
6738 * based on snapshot values taken when the event
6739 * was last scheduled in.
6741 * we cannot simply called update_context_time()
6742 * because of locking issue as we are called in
6745 if (read_format & PERF_FORMAT_TOTAL_TIMES)
6746 calc_timer_values(event, &now, &enabled, &running);
6748 if (event->attr.read_format & PERF_FORMAT_GROUP)
6749 perf_output_read_group(handle, event, enabled, running);
6751 perf_output_read_one(handle, event, enabled, running);
6754 static inline bool perf_sample_save_hw_index(struct perf_event *event)
6756 return event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX;
6759 void perf_output_sample(struct perf_output_handle *handle,
6760 struct perf_event_header *header,
6761 struct perf_sample_data *data,
6762 struct perf_event *event)
6764 u64 sample_type = data->type;
6766 perf_output_put(handle, *header);
6768 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6769 perf_output_put(handle, data->id);
6771 if (sample_type & PERF_SAMPLE_IP)
6772 perf_output_put(handle, data->ip);
6774 if (sample_type & PERF_SAMPLE_TID)
6775 perf_output_put(handle, data->tid_entry);
6777 if (sample_type & PERF_SAMPLE_TIME)
6778 perf_output_put(handle, data->time);
6780 if (sample_type & PERF_SAMPLE_ADDR)
6781 perf_output_put(handle, data->addr);
6783 if (sample_type & PERF_SAMPLE_ID)
6784 perf_output_put(handle, data->id);
6786 if (sample_type & PERF_SAMPLE_STREAM_ID)
6787 perf_output_put(handle, data->stream_id);
6789 if (sample_type & PERF_SAMPLE_CPU)
6790 perf_output_put(handle, data->cpu_entry);
6792 if (sample_type & PERF_SAMPLE_PERIOD)
6793 perf_output_put(handle, data->period);
6795 if (sample_type & PERF_SAMPLE_READ)
6796 perf_output_read(handle, event);
6798 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
6801 size += data->callchain->nr;
6802 size *= sizeof(u64);
6803 __output_copy(handle, data->callchain, size);
6806 if (sample_type & PERF_SAMPLE_RAW) {
6807 struct perf_raw_record *raw = data->raw;
6810 struct perf_raw_frag *frag = &raw->frag;
6812 perf_output_put(handle, raw->size);
6815 __output_custom(handle, frag->copy,
6816 frag->data, frag->size);
6818 __output_copy(handle, frag->data,
6821 if (perf_raw_frag_last(frag))
6826 __output_skip(handle, NULL, frag->pad);
6832 .size = sizeof(u32),
6835 perf_output_put(handle, raw);
6839 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
6840 if (data->br_stack) {
6843 size = data->br_stack->nr
6844 * sizeof(struct perf_branch_entry);
6846 perf_output_put(handle, data->br_stack->nr);
6847 if (perf_sample_save_hw_index(event))
6848 perf_output_put(handle, data->br_stack->hw_idx);
6849 perf_output_copy(handle, data->br_stack->entries, size);
6852 * we always store at least the value of nr
6855 perf_output_put(handle, nr);
6859 if (sample_type & PERF_SAMPLE_REGS_USER) {
6860 u64 abi = data->regs_user.abi;
6863 * If there are no regs to dump, notice it through
6864 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6866 perf_output_put(handle, abi);
6869 u64 mask = event->attr.sample_regs_user;
6870 perf_output_sample_regs(handle,
6871 data->regs_user.regs,
6876 if (sample_type & PERF_SAMPLE_STACK_USER) {
6877 perf_output_sample_ustack(handle,
6878 data->stack_user_size,
6879 data->regs_user.regs);
6882 if (sample_type & PERF_SAMPLE_WEIGHT)
6883 perf_output_put(handle, data->weight);
6885 if (sample_type & PERF_SAMPLE_DATA_SRC)
6886 perf_output_put(handle, data->data_src.val);
6888 if (sample_type & PERF_SAMPLE_TRANSACTION)
6889 perf_output_put(handle, data->txn);
6891 if (sample_type & PERF_SAMPLE_REGS_INTR) {
6892 u64 abi = data->regs_intr.abi;
6894 * If there are no regs to dump, notice it through
6895 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6897 perf_output_put(handle, abi);
6900 u64 mask = event->attr.sample_regs_intr;
6902 perf_output_sample_regs(handle,
6903 data->regs_intr.regs,
6908 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
6909 perf_output_put(handle, data->phys_addr);
6911 if (sample_type & PERF_SAMPLE_CGROUP)
6912 perf_output_put(handle, data->cgroup);
6914 if (sample_type & PERF_SAMPLE_AUX) {
6915 perf_output_put(handle, data->aux_size);
6918 perf_aux_sample_output(event, handle, data);
6921 if (!event->attr.watermark) {
6922 int wakeup_events = event->attr.wakeup_events;
6924 if (wakeup_events) {
6925 struct perf_buffer *rb = handle->rb;
6926 int events = local_inc_return(&rb->events);
6928 if (events >= wakeup_events) {
6929 local_sub(wakeup_events, &rb->events);
6930 local_inc(&rb->wakeup);
6936 static u64 perf_virt_to_phys(u64 virt)
6939 struct page *p = NULL;
6944 if (virt >= TASK_SIZE) {
6945 /* If it's vmalloc()d memory, leave phys_addr as 0 */
6946 if (virt_addr_valid((void *)(uintptr_t)virt) &&
6947 !(virt >= VMALLOC_START && virt < VMALLOC_END))
6948 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
6951 * Walking the pages tables for user address.
6952 * Interrupts are disabled, so it prevents any tear down
6953 * of the page tables.
6954 * Try IRQ-safe get_user_page_fast_only first.
6955 * If failed, leave phys_addr as 0.
6957 if (current->mm != NULL) {
6958 pagefault_disable();
6959 if (get_user_page_fast_only(virt, 0, &p))
6960 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
6971 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
6973 struct perf_callchain_entry *
6974 perf_callchain(struct perf_event *event, struct pt_regs *regs)
6976 bool kernel = !event->attr.exclude_callchain_kernel;
6977 bool user = !event->attr.exclude_callchain_user;
6978 /* Disallow cross-task user callchains. */
6979 bool crosstask = event->ctx->task && event->ctx->task != current;
6980 const u32 max_stack = event->attr.sample_max_stack;
6981 struct perf_callchain_entry *callchain;
6983 if (!kernel && !user)
6984 return &__empty_callchain;
6986 callchain = get_perf_callchain(regs, 0, kernel, user,
6987 max_stack, crosstask, true);
6988 return callchain ?: &__empty_callchain;
6991 void perf_prepare_sample(struct perf_event_header *header,
6992 struct perf_sample_data *data,
6993 struct perf_event *event,
6994 struct pt_regs *regs)
6996 u64 sample_type = event->attr.sample_type;
6998 header->type = PERF_RECORD_SAMPLE;
6999 header->size = sizeof(*header) + event->header_size;
7002 header->misc |= perf_misc_flags(regs);
7004 __perf_event_header__init_id(header, data, event);
7006 if (sample_type & PERF_SAMPLE_IP)
7007 data->ip = perf_instruction_pointer(regs);
7009 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7012 if (!(sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
7013 data->callchain = perf_callchain(event, regs);
7015 size += data->callchain->nr;
7017 header->size += size * sizeof(u64);
7020 if (sample_type & PERF_SAMPLE_RAW) {
7021 struct perf_raw_record *raw = data->raw;
7025 struct perf_raw_frag *frag = &raw->frag;
7030 if (perf_raw_frag_last(frag))
7035 size = round_up(sum + sizeof(u32), sizeof(u64));
7036 raw->size = size - sizeof(u32);
7037 frag->pad = raw->size - sum;
7042 header->size += size;
7045 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7046 int size = sizeof(u64); /* nr */
7047 if (data->br_stack) {
7048 if (perf_sample_save_hw_index(event))
7049 size += sizeof(u64);
7051 size += data->br_stack->nr
7052 * sizeof(struct perf_branch_entry);
7054 header->size += size;
7057 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
7058 perf_sample_regs_user(&data->regs_user, regs,
7059 &data->regs_user_copy);
7061 if (sample_type & PERF_SAMPLE_REGS_USER) {
7062 /* regs dump ABI info */
7063 int size = sizeof(u64);
7065 if (data->regs_user.regs) {
7066 u64 mask = event->attr.sample_regs_user;
7067 size += hweight64(mask) * sizeof(u64);
7070 header->size += size;
7073 if (sample_type & PERF_SAMPLE_STACK_USER) {
7075 * Either we need PERF_SAMPLE_STACK_USER bit to be always
7076 * processed as the last one or have additional check added
7077 * in case new sample type is added, because we could eat
7078 * up the rest of the sample size.
7080 u16 stack_size = event->attr.sample_stack_user;
7081 u16 size = sizeof(u64);
7083 stack_size = perf_sample_ustack_size(stack_size, header->size,
7084 data->regs_user.regs);
7087 * If there is something to dump, add space for the dump
7088 * itself and for the field that tells the dynamic size,
7089 * which is how many have been actually dumped.
7092 size += sizeof(u64) + stack_size;
7094 data->stack_user_size = stack_size;
7095 header->size += size;
7098 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7099 /* regs dump ABI info */
7100 int size = sizeof(u64);
7102 perf_sample_regs_intr(&data->regs_intr, regs);
7104 if (data->regs_intr.regs) {
7105 u64 mask = event->attr.sample_regs_intr;
7107 size += hweight64(mask) * sizeof(u64);
7110 header->size += size;
7113 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7114 data->phys_addr = perf_virt_to_phys(data->addr);
7116 #ifdef CONFIG_CGROUP_PERF
7117 if (sample_type & PERF_SAMPLE_CGROUP) {
7118 struct cgroup *cgrp;
7120 /* protected by RCU */
7121 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
7122 data->cgroup = cgroup_id(cgrp);
7126 if (sample_type & PERF_SAMPLE_AUX) {
7129 header->size += sizeof(u64); /* size */
7132 * Given the 16bit nature of header::size, an AUX sample can
7133 * easily overflow it, what with all the preceding sample bits.
7134 * Make sure this doesn't happen by using up to U16_MAX bytes
7135 * per sample in total (rounded down to 8 byte boundary).
7137 size = min_t(size_t, U16_MAX - header->size,
7138 event->attr.aux_sample_size);
7139 size = rounddown(size, 8);
7140 size = perf_prepare_sample_aux(event, data, size);
7142 WARN_ON_ONCE(size + header->size > U16_MAX);
7143 header->size += size;
7146 * If you're adding more sample types here, you likely need to do
7147 * something about the overflowing header::size, like repurpose the
7148 * lowest 3 bits of size, which should be always zero at the moment.
7149 * This raises a more important question, do we really need 512k sized
7150 * samples and why, so good argumentation is in order for whatever you
7153 WARN_ON_ONCE(header->size & 7);
7156 static __always_inline int
7157 __perf_event_output(struct perf_event *event,
7158 struct perf_sample_data *data,
7159 struct pt_regs *regs,
7160 int (*output_begin)(struct perf_output_handle *,
7161 struct perf_event *,
7164 struct perf_output_handle handle;
7165 struct perf_event_header header;
7168 /* protect the callchain buffers */
7171 perf_prepare_sample(&header, data, event, regs);
7173 err = output_begin(&handle, event, header.size);
7177 perf_output_sample(&handle, &header, data, event);
7179 perf_output_end(&handle);
7187 perf_event_output_forward(struct perf_event *event,
7188 struct perf_sample_data *data,
7189 struct pt_regs *regs)
7191 __perf_event_output(event, data, regs, perf_output_begin_forward);
7195 perf_event_output_backward(struct perf_event *event,
7196 struct perf_sample_data *data,
7197 struct pt_regs *regs)
7199 __perf_event_output(event, data, regs, perf_output_begin_backward);
7203 perf_event_output(struct perf_event *event,
7204 struct perf_sample_data *data,
7205 struct pt_regs *regs)
7207 return __perf_event_output(event, data, regs, perf_output_begin);
7214 struct perf_read_event {
7215 struct perf_event_header header;
7222 perf_event_read_event(struct perf_event *event,
7223 struct task_struct *task)
7225 struct perf_output_handle handle;
7226 struct perf_sample_data sample;
7227 struct perf_read_event read_event = {
7229 .type = PERF_RECORD_READ,
7231 .size = sizeof(read_event) + event->read_size,
7233 .pid = perf_event_pid(event, task),
7234 .tid = perf_event_tid(event, task),
7238 perf_event_header__init_id(&read_event.header, &sample, event);
7239 ret = perf_output_begin(&handle, event, read_event.header.size);
7243 perf_output_put(&handle, read_event);
7244 perf_output_read(&handle, event);
7245 perf_event__output_id_sample(event, &handle, &sample);
7247 perf_output_end(&handle);
7250 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
7253 perf_iterate_ctx(struct perf_event_context *ctx,
7254 perf_iterate_f output,
7255 void *data, bool all)
7257 struct perf_event *event;
7259 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7261 if (event->state < PERF_EVENT_STATE_INACTIVE)
7263 if (!event_filter_match(event))
7267 output(event, data);
7271 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
7273 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
7274 struct perf_event *event;
7276 list_for_each_entry_rcu(event, &pel->list, sb_list) {
7278 * Skip events that are not fully formed yet; ensure that
7279 * if we observe event->ctx, both event and ctx will be
7280 * complete enough. See perf_install_in_context().
7282 if (!smp_load_acquire(&event->ctx))
7285 if (event->state < PERF_EVENT_STATE_INACTIVE)
7287 if (!event_filter_match(event))
7289 output(event, data);
7294 * Iterate all events that need to receive side-band events.
7296 * For new callers; ensure that account_pmu_sb_event() includes
7297 * your event, otherwise it might not get delivered.
7300 perf_iterate_sb(perf_iterate_f output, void *data,
7301 struct perf_event_context *task_ctx)
7303 struct perf_event_context *ctx;
7310 * If we have task_ctx != NULL we only notify the task context itself.
7311 * The task_ctx is set only for EXIT events before releasing task
7315 perf_iterate_ctx(task_ctx, output, data, false);
7319 perf_iterate_sb_cpu(output, data);
7321 for_each_task_context_nr(ctxn) {
7322 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7324 perf_iterate_ctx(ctx, output, data, false);
7332 * Clear all file-based filters at exec, they'll have to be
7333 * re-instated when/if these objects are mmapped again.
7335 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
7337 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7338 struct perf_addr_filter *filter;
7339 unsigned int restart = 0, count = 0;
7340 unsigned long flags;
7342 if (!has_addr_filter(event))
7345 raw_spin_lock_irqsave(&ifh->lock, flags);
7346 list_for_each_entry(filter, &ifh->list, entry) {
7347 if (filter->path.dentry) {
7348 event->addr_filter_ranges[count].start = 0;
7349 event->addr_filter_ranges[count].size = 0;
7357 event->addr_filters_gen++;
7358 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7361 perf_event_stop(event, 1);
7364 void perf_event_exec(void)
7366 struct perf_event_context *ctx;
7370 for_each_task_context_nr(ctxn) {
7371 ctx = current->perf_event_ctxp[ctxn];
7375 perf_event_enable_on_exec(ctxn);
7377 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
7383 struct remote_output {
7384 struct perf_buffer *rb;
7388 static void __perf_event_output_stop(struct perf_event *event, void *data)
7390 struct perf_event *parent = event->parent;
7391 struct remote_output *ro = data;
7392 struct perf_buffer *rb = ro->rb;
7393 struct stop_event_data sd = {
7397 if (!has_aux(event))
7404 * In case of inheritance, it will be the parent that links to the
7405 * ring-buffer, but it will be the child that's actually using it.
7407 * We are using event::rb to determine if the event should be stopped,
7408 * however this may race with ring_buffer_attach() (through set_output),
7409 * which will make us skip the event that actually needs to be stopped.
7410 * So ring_buffer_attach() has to stop an aux event before re-assigning
7413 if (rcu_dereference(parent->rb) == rb)
7414 ro->err = __perf_event_stop(&sd);
7417 static int __perf_pmu_output_stop(void *info)
7419 struct perf_event *event = info;
7420 struct pmu *pmu = event->ctx->pmu;
7421 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7422 struct remote_output ro = {
7427 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
7428 if (cpuctx->task_ctx)
7429 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
7436 static void perf_pmu_output_stop(struct perf_event *event)
7438 struct perf_event *iter;
7443 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
7445 * For per-CPU events, we need to make sure that neither they
7446 * nor their children are running; for cpu==-1 events it's
7447 * sufficient to stop the event itself if it's active, since
7448 * it can't have children.
7452 cpu = READ_ONCE(iter->oncpu);
7457 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
7458 if (err == -EAGAIN) {
7467 * task tracking -- fork/exit
7469 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
7472 struct perf_task_event {
7473 struct task_struct *task;
7474 struct perf_event_context *task_ctx;
7477 struct perf_event_header header;
7487 static int perf_event_task_match(struct perf_event *event)
7489 return event->attr.comm || event->attr.mmap ||
7490 event->attr.mmap2 || event->attr.mmap_data ||
7494 static void perf_event_task_output(struct perf_event *event,
7497 struct perf_task_event *task_event = data;
7498 struct perf_output_handle handle;
7499 struct perf_sample_data sample;
7500 struct task_struct *task = task_event->task;
7501 int ret, size = task_event->event_id.header.size;
7503 if (!perf_event_task_match(event))
7506 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
7508 ret = perf_output_begin(&handle, event,
7509 task_event->event_id.header.size);
7513 task_event->event_id.pid = perf_event_pid(event, task);
7514 task_event->event_id.tid = perf_event_tid(event, task);
7516 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
7517 task_event->event_id.ppid = perf_event_pid(event,
7519 task_event->event_id.ptid = perf_event_pid(event,
7521 } else { /* PERF_RECORD_FORK */
7522 task_event->event_id.ppid = perf_event_pid(event, current);
7523 task_event->event_id.ptid = perf_event_tid(event, current);
7526 task_event->event_id.time = perf_event_clock(event);
7528 perf_output_put(&handle, task_event->event_id);
7530 perf_event__output_id_sample(event, &handle, &sample);
7532 perf_output_end(&handle);
7534 task_event->event_id.header.size = size;
7537 static void perf_event_task(struct task_struct *task,
7538 struct perf_event_context *task_ctx,
7541 struct perf_task_event task_event;
7543 if (!atomic_read(&nr_comm_events) &&
7544 !atomic_read(&nr_mmap_events) &&
7545 !atomic_read(&nr_task_events))
7548 task_event = (struct perf_task_event){
7550 .task_ctx = task_ctx,
7553 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
7555 .size = sizeof(task_event.event_id),
7565 perf_iterate_sb(perf_event_task_output,
7570 void perf_event_fork(struct task_struct *task)
7572 perf_event_task(task, NULL, 1);
7573 perf_event_namespaces(task);
7580 struct perf_comm_event {
7581 struct task_struct *task;
7586 struct perf_event_header header;
7593 static int perf_event_comm_match(struct perf_event *event)
7595 return event->attr.comm;
7598 static void perf_event_comm_output(struct perf_event *event,
7601 struct perf_comm_event *comm_event = data;
7602 struct perf_output_handle handle;
7603 struct perf_sample_data sample;
7604 int size = comm_event->event_id.header.size;
7607 if (!perf_event_comm_match(event))
7610 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
7611 ret = perf_output_begin(&handle, event,
7612 comm_event->event_id.header.size);
7617 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
7618 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
7620 perf_output_put(&handle, comm_event->event_id);
7621 __output_copy(&handle, comm_event->comm,
7622 comm_event->comm_size);
7624 perf_event__output_id_sample(event, &handle, &sample);
7626 perf_output_end(&handle);
7628 comm_event->event_id.header.size = size;
7631 static void perf_event_comm_event(struct perf_comm_event *comm_event)
7633 char comm[TASK_COMM_LEN];
7636 memset(comm, 0, sizeof(comm));
7637 strlcpy(comm, comm_event->task->comm, sizeof(comm));
7638 size = ALIGN(strlen(comm)+1, sizeof(u64));
7640 comm_event->comm = comm;
7641 comm_event->comm_size = size;
7643 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
7645 perf_iterate_sb(perf_event_comm_output,
7650 void perf_event_comm(struct task_struct *task, bool exec)
7652 struct perf_comm_event comm_event;
7654 if (!atomic_read(&nr_comm_events))
7657 comm_event = (struct perf_comm_event){
7663 .type = PERF_RECORD_COMM,
7664 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
7672 perf_event_comm_event(&comm_event);
7676 * namespaces tracking
7679 struct perf_namespaces_event {
7680 struct task_struct *task;
7683 struct perf_event_header header;
7688 struct perf_ns_link_info link_info[NR_NAMESPACES];
7692 static int perf_event_namespaces_match(struct perf_event *event)
7694 return event->attr.namespaces;
7697 static void perf_event_namespaces_output(struct perf_event *event,
7700 struct perf_namespaces_event *namespaces_event = data;
7701 struct perf_output_handle handle;
7702 struct perf_sample_data sample;
7703 u16 header_size = namespaces_event->event_id.header.size;
7706 if (!perf_event_namespaces_match(event))
7709 perf_event_header__init_id(&namespaces_event->event_id.header,
7711 ret = perf_output_begin(&handle, event,
7712 namespaces_event->event_id.header.size);
7716 namespaces_event->event_id.pid = perf_event_pid(event,
7717 namespaces_event->task);
7718 namespaces_event->event_id.tid = perf_event_tid(event,
7719 namespaces_event->task);
7721 perf_output_put(&handle, namespaces_event->event_id);
7723 perf_event__output_id_sample(event, &handle, &sample);
7725 perf_output_end(&handle);
7727 namespaces_event->event_id.header.size = header_size;
7730 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
7731 struct task_struct *task,
7732 const struct proc_ns_operations *ns_ops)
7734 struct path ns_path;
7735 struct inode *ns_inode;
7738 error = ns_get_path(&ns_path, task, ns_ops);
7740 ns_inode = ns_path.dentry->d_inode;
7741 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
7742 ns_link_info->ino = ns_inode->i_ino;
7747 void perf_event_namespaces(struct task_struct *task)
7749 struct perf_namespaces_event namespaces_event;
7750 struct perf_ns_link_info *ns_link_info;
7752 if (!atomic_read(&nr_namespaces_events))
7755 namespaces_event = (struct perf_namespaces_event){
7759 .type = PERF_RECORD_NAMESPACES,
7761 .size = sizeof(namespaces_event.event_id),
7765 .nr_namespaces = NR_NAMESPACES,
7766 /* .link_info[NR_NAMESPACES] */
7770 ns_link_info = namespaces_event.event_id.link_info;
7772 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
7773 task, &mntns_operations);
7775 #ifdef CONFIG_USER_NS
7776 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
7777 task, &userns_operations);
7779 #ifdef CONFIG_NET_NS
7780 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
7781 task, &netns_operations);
7783 #ifdef CONFIG_UTS_NS
7784 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
7785 task, &utsns_operations);
7787 #ifdef CONFIG_IPC_NS
7788 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
7789 task, &ipcns_operations);
7791 #ifdef CONFIG_PID_NS
7792 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
7793 task, &pidns_operations);
7795 #ifdef CONFIG_CGROUPS
7796 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
7797 task, &cgroupns_operations);
7800 perf_iterate_sb(perf_event_namespaces_output,
7808 #ifdef CONFIG_CGROUP_PERF
7810 struct perf_cgroup_event {
7814 struct perf_event_header header;
7820 static int perf_event_cgroup_match(struct perf_event *event)
7822 return event->attr.cgroup;
7825 static void perf_event_cgroup_output(struct perf_event *event, void *data)
7827 struct perf_cgroup_event *cgroup_event = data;
7828 struct perf_output_handle handle;
7829 struct perf_sample_data sample;
7830 u16 header_size = cgroup_event->event_id.header.size;
7833 if (!perf_event_cgroup_match(event))
7836 perf_event_header__init_id(&cgroup_event->event_id.header,
7838 ret = perf_output_begin(&handle, event,
7839 cgroup_event->event_id.header.size);
7843 perf_output_put(&handle, cgroup_event->event_id);
7844 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
7846 perf_event__output_id_sample(event, &handle, &sample);
7848 perf_output_end(&handle);
7850 cgroup_event->event_id.header.size = header_size;
7853 static void perf_event_cgroup(struct cgroup *cgrp)
7855 struct perf_cgroup_event cgroup_event;
7856 char path_enomem[16] = "//enomem";
7860 if (!atomic_read(&nr_cgroup_events))
7863 cgroup_event = (struct perf_cgroup_event){
7866 .type = PERF_RECORD_CGROUP,
7868 .size = sizeof(cgroup_event.event_id),
7870 .id = cgroup_id(cgrp),
7874 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
7875 if (pathname == NULL) {
7876 cgroup_event.path = path_enomem;
7878 /* just to be sure to have enough space for alignment */
7879 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
7880 cgroup_event.path = pathname;
7884 * Since our buffer works in 8 byte units we need to align our string
7885 * size to a multiple of 8. However, we must guarantee the tail end is
7886 * zero'd out to avoid leaking random bits to userspace.
7888 size = strlen(cgroup_event.path) + 1;
7889 while (!IS_ALIGNED(size, sizeof(u64)))
7890 cgroup_event.path[size++] = '\0';
7892 cgroup_event.event_id.header.size += size;
7893 cgroup_event.path_size = size;
7895 perf_iterate_sb(perf_event_cgroup_output,
7908 struct perf_mmap_event {
7909 struct vm_area_struct *vma;
7911 const char *file_name;
7919 struct perf_event_header header;
7929 static int perf_event_mmap_match(struct perf_event *event,
7932 struct perf_mmap_event *mmap_event = data;
7933 struct vm_area_struct *vma = mmap_event->vma;
7934 int executable = vma->vm_flags & VM_EXEC;
7936 return (!executable && event->attr.mmap_data) ||
7937 (executable && (event->attr.mmap || event->attr.mmap2));
7940 static void perf_event_mmap_output(struct perf_event *event,
7943 struct perf_mmap_event *mmap_event = data;
7944 struct perf_output_handle handle;
7945 struct perf_sample_data sample;
7946 int size = mmap_event->event_id.header.size;
7947 u32 type = mmap_event->event_id.header.type;
7950 if (!perf_event_mmap_match(event, data))
7953 if (event->attr.mmap2) {
7954 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
7955 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
7956 mmap_event->event_id.header.size += sizeof(mmap_event->min);
7957 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
7958 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
7959 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
7960 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
7963 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
7964 ret = perf_output_begin(&handle, event,
7965 mmap_event->event_id.header.size);
7969 mmap_event->event_id.pid = perf_event_pid(event, current);
7970 mmap_event->event_id.tid = perf_event_tid(event, current);
7972 perf_output_put(&handle, mmap_event->event_id);
7974 if (event->attr.mmap2) {
7975 perf_output_put(&handle, mmap_event->maj);
7976 perf_output_put(&handle, mmap_event->min);
7977 perf_output_put(&handle, mmap_event->ino);
7978 perf_output_put(&handle, mmap_event->ino_generation);
7979 perf_output_put(&handle, mmap_event->prot);
7980 perf_output_put(&handle, mmap_event->flags);
7983 __output_copy(&handle, mmap_event->file_name,
7984 mmap_event->file_size);
7986 perf_event__output_id_sample(event, &handle, &sample);
7988 perf_output_end(&handle);
7990 mmap_event->event_id.header.size = size;
7991 mmap_event->event_id.header.type = type;
7994 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
7996 struct vm_area_struct *vma = mmap_event->vma;
7997 struct file *file = vma->vm_file;
7998 int maj = 0, min = 0;
7999 u64 ino = 0, gen = 0;
8000 u32 prot = 0, flags = 0;
8006 if (vma->vm_flags & VM_READ)
8008 if (vma->vm_flags & VM_WRITE)
8010 if (vma->vm_flags & VM_EXEC)
8013 if (vma->vm_flags & VM_MAYSHARE)
8016 flags = MAP_PRIVATE;
8018 if (vma->vm_flags & VM_DENYWRITE)
8019 flags |= MAP_DENYWRITE;
8020 if (vma->vm_flags & VM_MAYEXEC)
8021 flags |= MAP_EXECUTABLE;
8022 if (vma->vm_flags & VM_LOCKED)
8023 flags |= MAP_LOCKED;
8024 if (is_vm_hugetlb_page(vma))
8025 flags |= MAP_HUGETLB;
8028 struct inode *inode;
8031 buf = kmalloc(PATH_MAX, GFP_KERNEL);
8037 * d_path() works from the end of the rb backwards, so we
8038 * need to add enough zero bytes after the string to handle
8039 * the 64bit alignment we do later.
8041 name = file_path(file, buf, PATH_MAX - sizeof(u64));
8046 inode = file_inode(vma->vm_file);
8047 dev = inode->i_sb->s_dev;
8049 gen = inode->i_generation;
8055 if (vma->vm_ops && vma->vm_ops->name) {
8056 name = (char *) vma->vm_ops->name(vma);
8061 name = (char *)arch_vma_name(vma);
8065 if (vma->vm_start <= vma->vm_mm->start_brk &&
8066 vma->vm_end >= vma->vm_mm->brk) {
8070 if (vma->vm_start <= vma->vm_mm->start_stack &&
8071 vma->vm_end >= vma->vm_mm->start_stack) {
8081 strlcpy(tmp, name, sizeof(tmp));
8085 * Since our buffer works in 8 byte units we need to align our string
8086 * size to a multiple of 8. However, we must guarantee the tail end is
8087 * zero'd out to avoid leaking random bits to userspace.
8089 size = strlen(name)+1;
8090 while (!IS_ALIGNED(size, sizeof(u64)))
8091 name[size++] = '\0';
8093 mmap_event->file_name = name;
8094 mmap_event->file_size = size;
8095 mmap_event->maj = maj;
8096 mmap_event->min = min;
8097 mmap_event->ino = ino;
8098 mmap_event->ino_generation = gen;
8099 mmap_event->prot = prot;
8100 mmap_event->flags = flags;
8102 if (!(vma->vm_flags & VM_EXEC))
8103 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
8105 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
8107 perf_iterate_sb(perf_event_mmap_output,
8115 * Check whether inode and address range match filter criteria.
8117 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
8118 struct file *file, unsigned long offset,
8121 /* d_inode(NULL) won't be equal to any mapped user-space file */
8122 if (!filter->path.dentry)
8125 if (d_inode(filter->path.dentry) != file_inode(file))
8128 if (filter->offset > offset + size)
8131 if (filter->offset + filter->size < offset)
8137 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
8138 struct vm_area_struct *vma,
8139 struct perf_addr_filter_range *fr)
8141 unsigned long vma_size = vma->vm_end - vma->vm_start;
8142 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8143 struct file *file = vma->vm_file;
8145 if (!perf_addr_filter_match(filter, file, off, vma_size))
8148 if (filter->offset < off) {
8149 fr->start = vma->vm_start;
8150 fr->size = min(vma_size, filter->size - (off - filter->offset));
8152 fr->start = vma->vm_start + filter->offset - off;
8153 fr->size = min(vma->vm_end - fr->start, filter->size);
8159 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
8161 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8162 struct vm_area_struct *vma = data;
8163 struct perf_addr_filter *filter;
8164 unsigned int restart = 0, count = 0;
8165 unsigned long flags;
8167 if (!has_addr_filter(event))
8173 raw_spin_lock_irqsave(&ifh->lock, flags);
8174 list_for_each_entry(filter, &ifh->list, entry) {
8175 if (perf_addr_filter_vma_adjust(filter, vma,
8176 &event->addr_filter_ranges[count]))
8183 event->addr_filters_gen++;
8184 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8187 perf_event_stop(event, 1);
8191 * Adjust all task's events' filters to the new vma
8193 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
8195 struct perf_event_context *ctx;
8199 * Data tracing isn't supported yet and as such there is no need
8200 * to keep track of anything that isn't related to executable code:
8202 if (!(vma->vm_flags & VM_EXEC))
8206 for_each_task_context_nr(ctxn) {
8207 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
8211 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
8216 void perf_event_mmap(struct vm_area_struct *vma)
8218 struct perf_mmap_event mmap_event;
8220 if (!atomic_read(&nr_mmap_events))
8223 mmap_event = (struct perf_mmap_event){
8229 .type = PERF_RECORD_MMAP,
8230 .misc = PERF_RECORD_MISC_USER,
8235 .start = vma->vm_start,
8236 .len = vma->vm_end - vma->vm_start,
8237 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
8239 /* .maj (attr_mmap2 only) */
8240 /* .min (attr_mmap2 only) */
8241 /* .ino (attr_mmap2 only) */
8242 /* .ino_generation (attr_mmap2 only) */
8243 /* .prot (attr_mmap2 only) */
8244 /* .flags (attr_mmap2 only) */
8247 perf_addr_filters_adjust(vma);
8248 perf_event_mmap_event(&mmap_event);
8251 void perf_event_aux_event(struct perf_event *event, unsigned long head,
8252 unsigned long size, u64 flags)
8254 struct perf_output_handle handle;
8255 struct perf_sample_data sample;
8256 struct perf_aux_event {
8257 struct perf_event_header header;
8263 .type = PERF_RECORD_AUX,
8265 .size = sizeof(rec),
8273 perf_event_header__init_id(&rec.header, &sample, event);
8274 ret = perf_output_begin(&handle, event, rec.header.size);
8279 perf_output_put(&handle, rec);
8280 perf_event__output_id_sample(event, &handle, &sample);
8282 perf_output_end(&handle);
8286 * Lost/dropped samples logging
8288 void perf_log_lost_samples(struct perf_event *event, u64 lost)
8290 struct perf_output_handle handle;
8291 struct perf_sample_data sample;
8295 struct perf_event_header header;
8297 } lost_samples_event = {
8299 .type = PERF_RECORD_LOST_SAMPLES,
8301 .size = sizeof(lost_samples_event),
8306 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
8308 ret = perf_output_begin(&handle, event,
8309 lost_samples_event.header.size);
8313 perf_output_put(&handle, lost_samples_event);
8314 perf_event__output_id_sample(event, &handle, &sample);
8315 perf_output_end(&handle);
8319 * context_switch tracking
8322 struct perf_switch_event {
8323 struct task_struct *task;
8324 struct task_struct *next_prev;
8327 struct perf_event_header header;
8333 static int perf_event_switch_match(struct perf_event *event)
8335 return event->attr.context_switch;
8338 static void perf_event_switch_output(struct perf_event *event, void *data)
8340 struct perf_switch_event *se = data;
8341 struct perf_output_handle handle;
8342 struct perf_sample_data sample;
8345 if (!perf_event_switch_match(event))
8348 /* Only CPU-wide events are allowed to see next/prev pid/tid */
8349 if (event->ctx->task) {
8350 se->event_id.header.type = PERF_RECORD_SWITCH;
8351 se->event_id.header.size = sizeof(se->event_id.header);
8353 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
8354 se->event_id.header.size = sizeof(se->event_id);
8355 se->event_id.next_prev_pid =
8356 perf_event_pid(event, se->next_prev);
8357 se->event_id.next_prev_tid =
8358 perf_event_tid(event, se->next_prev);
8361 perf_event_header__init_id(&se->event_id.header, &sample, event);
8363 ret = perf_output_begin(&handle, event, se->event_id.header.size);
8367 if (event->ctx->task)
8368 perf_output_put(&handle, se->event_id.header);
8370 perf_output_put(&handle, se->event_id);
8372 perf_event__output_id_sample(event, &handle, &sample);
8374 perf_output_end(&handle);
8377 static void perf_event_switch(struct task_struct *task,
8378 struct task_struct *next_prev, bool sched_in)
8380 struct perf_switch_event switch_event;
8382 /* N.B. caller checks nr_switch_events != 0 */
8384 switch_event = (struct perf_switch_event){
8386 .next_prev = next_prev,
8390 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
8393 /* .next_prev_pid */
8394 /* .next_prev_tid */
8398 if (!sched_in && task->state == TASK_RUNNING)
8399 switch_event.event_id.header.misc |=
8400 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
8402 perf_iterate_sb(perf_event_switch_output,
8408 * IRQ throttle logging
8411 static void perf_log_throttle(struct perf_event *event, int enable)
8413 struct perf_output_handle handle;
8414 struct perf_sample_data sample;
8418 struct perf_event_header header;
8422 } throttle_event = {
8424 .type = PERF_RECORD_THROTTLE,
8426 .size = sizeof(throttle_event),
8428 .time = perf_event_clock(event),
8429 .id = primary_event_id(event),
8430 .stream_id = event->id,
8434 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
8436 perf_event_header__init_id(&throttle_event.header, &sample, event);
8438 ret = perf_output_begin(&handle, event,
8439 throttle_event.header.size);
8443 perf_output_put(&handle, throttle_event);
8444 perf_event__output_id_sample(event, &handle, &sample);
8445 perf_output_end(&handle);
8449 * ksymbol register/unregister tracking
8452 struct perf_ksymbol_event {
8456 struct perf_event_header header;
8464 static int perf_event_ksymbol_match(struct perf_event *event)
8466 return event->attr.ksymbol;
8469 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
8471 struct perf_ksymbol_event *ksymbol_event = data;
8472 struct perf_output_handle handle;
8473 struct perf_sample_data sample;
8476 if (!perf_event_ksymbol_match(event))
8479 perf_event_header__init_id(&ksymbol_event->event_id.header,
8481 ret = perf_output_begin(&handle, event,
8482 ksymbol_event->event_id.header.size);
8486 perf_output_put(&handle, ksymbol_event->event_id);
8487 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
8488 perf_event__output_id_sample(event, &handle, &sample);
8490 perf_output_end(&handle);
8493 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
8496 struct perf_ksymbol_event ksymbol_event;
8497 char name[KSYM_NAME_LEN];
8501 if (!atomic_read(&nr_ksymbol_events))
8504 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
8505 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
8508 strlcpy(name, sym, KSYM_NAME_LEN);
8509 name_len = strlen(name) + 1;
8510 while (!IS_ALIGNED(name_len, sizeof(u64)))
8511 name[name_len++] = '\0';
8512 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
8515 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
8517 ksymbol_event = (struct perf_ksymbol_event){
8519 .name_len = name_len,
8522 .type = PERF_RECORD_KSYMBOL,
8523 .size = sizeof(ksymbol_event.event_id) +
8528 .ksym_type = ksym_type,
8533 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
8536 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
8540 * bpf program load/unload tracking
8543 struct perf_bpf_event {
8544 struct bpf_prog *prog;
8546 struct perf_event_header header;
8550 u8 tag[BPF_TAG_SIZE];
8554 static int perf_event_bpf_match(struct perf_event *event)
8556 return event->attr.bpf_event;
8559 static void perf_event_bpf_output(struct perf_event *event, void *data)
8561 struct perf_bpf_event *bpf_event = data;
8562 struct perf_output_handle handle;
8563 struct perf_sample_data sample;
8566 if (!perf_event_bpf_match(event))
8569 perf_event_header__init_id(&bpf_event->event_id.header,
8571 ret = perf_output_begin(&handle, event,
8572 bpf_event->event_id.header.size);
8576 perf_output_put(&handle, bpf_event->event_id);
8577 perf_event__output_id_sample(event, &handle, &sample);
8579 perf_output_end(&handle);
8582 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
8583 enum perf_bpf_event_type type)
8585 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
8588 if (prog->aux->func_cnt == 0) {
8589 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
8590 (u64)(unsigned long)prog->bpf_func,
8591 prog->jited_len, unregister,
8592 prog->aux->ksym.name);
8594 for (i = 0; i < prog->aux->func_cnt; i++) {
8595 struct bpf_prog *subprog = prog->aux->func[i];
8598 PERF_RECORD_KSYMBOL_TYPE_BPF,
8599 (u64)(unsigned long)subprog->bpf_func,
8600 subprog->jited_len, unregister,
8601 prog->aux->ksym.name);
8606 void perf_event_bpf_event(struct bpf_prog *prog,
8607 enum perf_bpf_event_type type,
8610 struct perf_bpf_event bpf_event;
8612 if (type <= PERF_BPF_EVENT_UNKNOWN ||
8613 type >= PERF_BPF_EVENT_MAX)
8617 case PERF_BPF_EVENT_PROG_LOAD:
8618 case PERF_BPF_EVENT_PROG_UNLOAD:
8619 if (atomic_read(&nr_ksymbol_events))
8620 perf_event_bpf_emit_ksymbols(prog, type);
8626 if (!atomic_read(&nr_bpf_events))
8629 bpf_event = (struct perf_bpf_event){
8633 .type = PERF_RECORD_BPF_EVENT,
8634 .size = sizeof(bpf_event.event_id),
8638 .id = prog->aux->id,
8642 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
8644 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
8645 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
8648 struct perf_text_poke_event {
8649 const void *old_bytes;
8650 const void *new_bytes;
8656 struct perf_event_header header;
8662 static int perf_event_text_poke_match(struct perf_event *event)
8664 return event->attr.text_poke;
8667 static void perf_event_text_poke_output(struct perf_event *event, void *data)
8669 struct perf_text_poke_event *text_poke_event = data;
8670 struct perf_output_handle handle;
8671 struct perf_sample_data sample;
8675 if (!perf_event_text_poke_match(event))
8678 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
8680 ret = perf_output_begin(&handle, event, text_poke_event->event_id.header.size);
8684 perf_output_put(&handle, text_poke_event->event_id);
8685 perf_output_put(&handle, text_poke_event->old_len);
8686 perf_output_put(&handle, text_poke_event->new_len);
8688 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
8689 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
8691 if (text_poke_event->pad)
8692 __output_copy(&handle, &padding, text_poke_event->pad);
8694 perf_event__output_id_sample(event, &handle, &sample);
8696 perf_output_end(&handle);
8699 void perf_event_text_poke(const void *addr, const void *old_bytes,
8700 size_t old_len, const void *new_bytes, size_t new_len)
8702 struct perf_text_poke_event text_poke_event;
8705 if (!atomic_read(&nr_text_poke_events))
8708 tot = sizeof(text_poke_event.old_len) + old_len;
8709 tot += sizeof(text_poke_event.new_len) + new_len;
8710 pad = ALIGN(tot, sizeof(u64)) - tot;
8712 text_poke_event = (struct perf_text_poke_event){
8713 .old_bytes = old_bytes,
8714 .new_bytes = new_bytes,
8720 .type = PERF_RECORD_TEXT_POKE,
8721 .misc = PERF_RECORD_MISC_KERNEL,
8722 .size = sizeof(text_poke_event.event_id) + tot + pad,
8724 .addr = (unsigned long)addr,
8728 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
8731 void perf_event_itrace_started(struct perf_event *event)
8733 event->attach_state |= PERF_ATTACH_ITRACE;
8736 static void perf_log_itrace_start(struct perf_event *event)
8738 struct perf_output_handle handle;
8739 struct perf_sample_data sample;
8740 struct perf_aux_event {
8741 struct perf_event_header header;
8748 event = event->parent;
8750 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
8751 event->attach_state & PERF_ATTACH_ITRACE)
8754 rec.header.type = PERF_RECORD_ITRACE_START;
8755 rec.header.misc = 0;
8756 rec.header.size = sizeof(rec);
8757 rec.pid = perf_event_pid(event, current);
8758 rec.tid = perf_event_tid(event, current);
8760 perf_event_header__init_id(&rec.header, &sample, event);
8761 ret = perf_output_begin(&handle, event, rec.header.size);
8766 perf_output_put(&handle, rec);
8767 perf_event__output_id_sample(event, &handle, &sample);
8769 perf_output_end(&handle);
8773 __perf_event_account_interrupt(struct perf_event *event, int throttle)
8775 struct hw_perf_event *hwc = &event->hw;
8779 seq = __this_cpu_read(perf_throttled_seq);
8780 if (seq != hwc->interrupts_seq) {
8781 hwc->interrupts_seq = seq;
8782 hwc->interrupts = 1;
8785 if (unlikely(throttle
8786 && hwc->interrupts >= max_samples_per_tick)) {
8787 __this_cpu_inc(perf_throttled_count);
8788 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
8789 hwc->interrupts = MAX_INTERRUPTS;
8790 perf_log_throttle(event, 0);
8795 if (event->attr.freq) {
8796 u64 now = perf_clock();
8797 s64 delta = now - hwc->freq_time_stamp;
8799 hwc->freq_time_stamp = now;
8801 if (delta > 0 && delta < 2*TICK_NSEC)
8802 perf_adjust_period(event, delta, hwc->last_period, true);
8808 int perf_event_account_interrupt(struct perf_event *event)
8810 return __perf_event_account_interrupt(event, 1);
8814 * Generic event overflow handling, sampling.
8817 static int __perf_event_overflow(struct perf_event *event,
8818 int throttle, struct perf_sample_data *data,
8819 struct pt_regs *regs)
8821 int events = atomic_read(&event->event_limit);
8825 * Non-sampling counters might still use the PMI to fold short
8826 * hardware counters, ignore those.
8828 if (unlikely(!is_sampling_event(event)))
8831 ret = __perf_event_account_interrupt(event, throttle);
8834 * XXX event_limit might not quite work as expected on inherited
8838 event->pending_kill = POLL_IN;
8839 if (events && atomic_dec_and_test(&event->event_limit)) {
8841 event->pending_kill = POLL_HUP;
8843 perf_event_disable_inatomic(event);
8846 READ_ONCE(event->overflow_handler)(event, data, regs);
8848 if (*perf_event_fasync(event) && event->pending_kill) {
8849 event->pending_wakeup = 1;
8850 irq_work_queue(&event->pending);
8856 int perf_event_overflow(struct perf_event *event,
8857 struct perf_sample_data *data,
8858 struct pt_regs *regs)
8860 return __perf_event_overflow(event, 1, data, regs);
8864 * Generic software event infrastructure
8867 struct swevent_htable {
8868 struct swevent_hlist *swevent_hlist;
8869 struct mutex hlist_mutex;
8872 /* Recursion avoidance in each contexts */
8873 int recursion[PERF_NR_CONTEXTS];
8876 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
8879 * We directly increment event->count and keep a second value in
8880 * event->hw.period_left to count intervals. This period event
8881 * is kept in the range [-sample_period, 0] so that we can use the
8885 u64 perf_swevent_set_period(struct perf_event *event)
8887 struct hw_perf_event *hwc = &event->hw;
8888 u64 period = hwc->last_period;
8892 hwc->last_period = hwc->sample_period;
8895 old = val = local64_read(&hwc->period_left);
8899 nr = div64_u64(period + val, period);
8900 offset = nr * period;
8902 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
8908 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
8909 struct perf_sample_data *data,
8910 struct pt_regs *regs)
8912 struct hw_perf_event *hwc = &event->hw;
8916 overflow = perf_swevent_set_period(event);
8918 if (hwc->interrupts == MAX_INTERRUPTS)
8921 for (; overflow; overflow--) {
8922 if (__perf_event_overflow(event, throttle,
8925 * We inhibit the overflow from happening when
8926 * hwc->interrupts == MAX_INTERRUPTS.
8934 static void perf_swevent_event(struct perf_event *event, u64 nr,
8935 struct perf_sample_data *data,
8936 struct pt_regs *regs)
8938 struct hw_perf_event *hwc = &event->hw;
8940 local64_add(nr, &event->count);
8945 if (!is_sampling_event(event))
8948 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
8950 return perf_swevent_overflow(event, 1, data, regs);
8952 data->period = event->hw.last_period;
8954 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
8955 return perf_swevent_overflow(event, 1, data, regs);
8957 if (local64_add_negative(nr, &hwc->period_left))
8960 perf_swevent_overflow(event, 0, data, regs);
8963 static int perf_exclude_event(struct perf_event *event,
8964 struct pt_regs *regs)
8966 if (event->hw.state & PERF_HES_STOPPED)
8970 if (event->attr.exclude_user && user_mode(regs))
8973 if (event->attr.exclude_kernel && !user_mode(regs))
8980 static int perf_swevent_match(struct perf_event *event,
8981 enum perf_type_id type,
8983 struct perf_sample_data *data,
8984 struct pt_regs *regs)
8986 if (event->attr.type != type)
8989 if (event->attr.config != event_id)
8992 if (perf_exclude_event(event, regs))
8998 static inline u64 swevent_hash(u64 type, u32 event_id)
9000 u64 val = event_id | (type << 32);
9002 return hash_64(val, SWEVENT_HLIST_BITS);
9005 static inline struct hlist_head *
9006 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
9008 u64 hash = swevent_hash(type, event_id);
9010 return &hlist->heads[hash];
9013 /* For the read side: events when they trigger */
9014 static inline struct hlist_head *
9015 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
9017 struct swevent_hlist *hlist;
9019 hlist = rcu_dereference(swhash->swevent_hlist);
9023 return __find_swevent_head(hlist, type, event_id);
9026 /* For the event head insertion and removal in the hlist */
9027 static inline struct hlist_head *
9028 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
9030 struct swevent_hlist *hlist;
9031 u32 event_id = event->attr.config;
9032 u64 type = event->attr.type;
9035 * Event scheduling is always serialized against hlist allocation
9036 * and release. Which makes the protected version suitable here.
9037 * The context lock guarantees that.
9039 hlist = rcu_dereference_protected(swhash->swevent_hlist,
9040 lockdep_is_held(&event->ctx->lock));
9044 return __find_swevent_head(hlist, type, event_id);
9047 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
9049 struct perf_sample_data *data,
9050 struct pt_regs *regs)
9052 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9053 struct perf_event *event;
9054 struct hlist_head *head;
9057 head = find_swevent_head_rcu(swhash, type, event_id);
9061 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9062 if (perf_swevent_match(event, type, event_id, data, regs))
9063 perf_swevent_event(event, nr, data, regs);
9069 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
9071 int perf_swevent_get_recursion_context(void)
9073 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9075 return get_recursion_context(swhash->recursion);
9077 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
9079 void perf_swevent_put_recursion_context(int rctx)
9081 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9083 put_recursion_context(swhash->recursion, rctx);
9086 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9088 struct perf_sample_data data;
9090 if (WARN_ON_ONCE(!regs))
9093 perf_sample_data_init(&data, addr, 0);
9094 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
9097 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9101 preempt_disable_notrace();
9102 rctx = perf_swevent_get_recursion_context();
9103 if (unlikely(rctx < 0))
9106 ___perf_sw_event(event_id, nr, regs, addr);
9108 perf_swevent_put_recursion_context(rctx);
9110 preempt_enable_notrace();
9113 static void perf_swevent_read(struct perf_event *event)
9117 static int perf_swevent_add(struct perf_event *event, int flags)
9119 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9120 struct hw_perf_event *hwc = &event->hw;
9121 struct hlist_head *head;
9123 if (is_sampling_event(event)) {
9124 hwc->last_period = hwc->sample_period;
9125 perf_swevent_set_period(event);
9128 hwc->state = !(flags & PERF_EF_START);
9130 head = find_swevent_head(swhash, event);
9131 if (WARN_ON_ONCE(!head))
9134 hlist_add_head_rcu(&event->hlist_entry, head);
9135 perf_event_update_userpage(event);
9140 static void perf_swevent_del(struct perf_event *event, int flags)
9142 hlist_del_rcu(&event->hlist_entry);
9145 static void perf_swevent_start(struct perf_event *event, int flags)
9147 event->hw.state = 0;
9150 static void perf_swevent_stop(struct perf_event *event, int flags)
9152 event->hw.state = PERF_HES_STOPPED;
9155 /* Deref the hlist from the update side */
9156 static inline struct swevent_hlist *
9157 swevent_hlist_deref(struct swevent_htable *swhash)
9159 return rcu_dereference_protected(swhash->swevent_hlist,
9160 lockdep_is_held(&swhash->hlist_mutex));
9163 static void swevent_hlist_release(struct swevent_htable *swhash)
9165 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
9170 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
9171 kfree_rcu(hlist, rcu_head);
9174 static void swevent_hlist_put_cpu(int cpu)
9176 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9178 mutex_lock(&swhash->hlist_mutex);
9180 if (!--swhash->hlist_refcount)
9181 swevent_hlist_release(swhash);
9183 mutex_unlock(&swhash->hlist_mutex);
9186 static void swevent_hlist_put(void)
9190 for_each_possible_cpu(cpu)
9191 swevent_hlist_put_cpu(cpu);
9194 static int swevent_hlist_get_cpu(int cpu)
9196 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9199 mutex_lock(&swhash->hlist_mutex);
9200 if (!swevent_hlist_deref(swhash) &&
9201 cpumask_test_cpu(cpu, perf_online_mask)) {
9202 struct swevent_hlist *hlist;
9204 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
9209 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9211 swhash->hlist_refcount++;
9213 mutex_unlock(&swhash->hlist_mutex);
9218 static int swevent_hlist_get(void)
9220 int err, cpu, failed_cpu;
9222 mutex_lock(&pmus_lock);
9223 for_each_possible_cpu(cpu) {
9224 err = swevent_hlist_get_cpu(cpu);
9230 mutex_unlock(&pmus_lock);
9233 for_each_possible_cpu(cpu) {
9234 if (cpu == failed_cpu)
9236 swevent_hlist_put_cpu(cpu);
9238 mutex_unlock(&pmus_lock);
9242 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
9244 static void sw_perf_event_destroy(struct perf_event *event)
9246 u64 event_id = event->attr.config;
9248 WARN_ON(event->parent);
9250 static_key_slow_dec(&perf_swevent_enabled[event_id]);
9251 swevent_hlist_put();
9254 static int perf_swevent_init(struct perf_event *event)
9256 u64 event_id = event->attr.config;
9258 if (event->attr.type != PERF_TYPE_SOFTWARE)
9262 * no branch sampling for software events
9264 if (has_branch_stack(event))
9268 case PERF_COUNT_SW_CPU_CLOCK:
9269 case PERF_COUNT_SW_TASK_CLOCK:
9276 if (event_id >= PERF_COUNT_SW_MAX)
9279 if (!event->parent) {
9282 err = swevent_hlist_get();
9286 static_key_slow_inc(&perf_swevent_enabled[event_id]);
9287 event->destroy = sw_perf_event_destroy;
9293 static struct pmu perf_swevent = {
9294 .task_ctx_nr = perf_sw_context,
9296 .capabilities = PERF_PMU_CAP_NO_NMI,
9298 .event_init = perf_swevent_init,
9299 .add = perf_swevent_add,
9300 .del = perf_swevent_del,
9301 .start = perf_swevent_start,
9302 .stop = perf_swevent_stop,
9303 .read = perf_swevent_read,
9306 #ifdef CONFIG_EVENT_TRACING
9308 static int perf_tp_filter_match(struct perf_event *event,
9309 struct perf_sample_data *data)
9311 void *record = data->raw->frag.data;
9313 /* only top level events have filters set */
9315 event = event->parent;
9317 if (likely(!event->filter) || filter_match_preds(event->filter, record))
9322 static int perf_tp_event_match(struct perf_event *event,
9323 struct perf_sample_data *data,
9324 struct pt_regs *regs)
9326 if (event->hw.state & PERF_HES_STOPPED)
9329 * If exclude_kernel, only trace user-space tracepoints (uprobes)
9331 if (event->attr.exclude_kernel && !user_mode(regs))
9334 if (!perf_tp_filter_match(event, data))
9340 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
9341 struct trace_event_call *call, u64 count,
9342 struct pt_regs *regs, struct hlist_head *head,
9343 struct task_struct *task)
9345 if (bpf_prog_array_valid(call)) {
9346 *(struct pt_regs **)raw_data = regs;
9347 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
9348 perf_swevent_put_recursion_context(rctx);
9352 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
9355 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
9357 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
9358 struct pt_regs *regs, struct hlist_head *head, int rctx,
9359 struct task_struct *task)
9361 struct perf_sample_data data;
9362 struct perf_event *event;
9364 struct perf_raw_record raw = {
9371 perf_sample_data_init(&data, 0, 0);
9374 perf_trace_buf_update(record, event_type);
9376 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9377 if (perf_tp_event_match(event, &data, regs))
9378 perf_swevent_event(event, count, &data, regs);
9382 * If we got specified a target task, also iterate its context and
9383 * deliver this event there too.
9385 if (task && task != current) {
9386 struct perf_event_context *ctx;
9387 struct trace_entry *entry = record;
9390 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
9394 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
9395 if (event->cpu != smp_processor_id())
9397 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9399 if (event->attr.config != entry->type)
9401 if (perf_tp_event_match(event, &data, regs))
9402 perf_swevent_event(event, count, &data, regs);
9408 perf_swevent_put_recursion_context(rctx);
9410 EXPORT_SYMBOL_GPL(perf_tp_event);
9412 static void tp_perf_event_destroy(struct perf_event *event)
9414 perf_trace_destroy(event);
9417 static int perf_tp_event_init(struct perf_event *event)
9421 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9425 * no branch sampling for tracepoint events
9427 if (has_branch_stack(event))
9430 err = perf_trace_init(event);
9434 event->destroy = tp_perf_event_destroy;
9439 static struct pmu perf_tracepoint = {
9440 .task_ctx_nr = perf_sw_context,
9442 .event_init = perf_tp_event_init,
9443 .add = perf_trace_add,
9444 .del = perf_trace_del,
9445 .start = perf_swevent_start,
9446 .stop = perf_swevent_stop,
9447 .read = perf_swevent_read,
9450 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
9452 * Flags in config, used by dynamic PMU kprobe and uprobe
9453 * The flags should match following PMU_FORMAT_ATTR().
9455 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
9456 * if not set, create kprobe/uprobe
9458 * The following values specify a reference counter (or semaphore in the
9459 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
9460 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
9462 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
9463 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
9465 enum perf_probe_config {
9466 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
9467 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
9468 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
9471 PMU_FORMAT_ATTR(retprobe, "config:0");
9474 #ifdef CONFIG_KPROBE_EVENTS
9475 static struct attribute *kprobe_attrs[] = {
9476 &format_attr_retprobe.attr,
9480 static struct attribute_group kprobe_format_group = {
9482 .attrs = kprobe_attrs,
9485 static const struct attribute_group *kprobe_attr_groups[] = {
9486 &kprobe_format_group,
9490 static int perf_kprobe_event_init(struct perf_event *event);
9491 static struct pmu perf_kprobe = {
9492 .task_ctx_nr = perf_sw_context,
9493 .event_init = perf_kprobe_event_init,
9494 .add = perf_trace_add,
9495 .del = perf_trace_del,
9496 .start = perf_swevent_start,
9497 .stop = perf_swevent_stop,
9498 .read = perf_swevent_read,
9499 .attr_groups = kprobe_attr_groups,
9502 static int perf_kprobe_event_init(struct perf_event *event)
9507 if (event->attr.type != perf_kprobe.type)
9510 if (!perfmon_capable())
9514 * no branch sampling for probe events
9516 if (has_branch_stack(event))
9519 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9520 err = perf_kprobe_init(event, is_retprobe);
9524 event->destroy = perf_kprobe_destroy;
9528 #endif /* CONFIG_KPROBE_EVENTS */
9530 #ifdef CONFIG_UPROBE_EVENTS
9531 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
9533 static struct attribute *uprobe_attrs[] = {
9534 &format_attr_retprobe.attr,
9535 &format_attr_ref_ctr_offset.attr,
9539 static struct attribute_group uprobe_format_group = {
9541 .attrs = uprobe_attrs,
9544 static const struct attribute_group *uprobe_attr_groups[] = {
9545 &uprobe_format_group,
9549 static int perf_uprobe_event_init(struct perf_event *event);
9550 static struct pmu perf_uprobe = {
9551 .task_ctx_nr = perf_sw_context,
9552 .event_init = perf_uprobe_event_init,
9553 .add = perf_trace_add,
9554 .del = perf_trace_del,
9555 .start = perf_swevent_start,
9556 .stop = perf_swevent_stop,
9557 .read = perf_swevent_read,
9558 .attr_groups = uprobe_attr_groups,
9561 static int perf_uprobe_event_init(struct perf_event *event)
9564 unsigned long ref_ctr_offset;
9567 if (event->attr.type != perf_uprobe.type)
9570 if (!perfmon_capable())
9574 * no branch sampling for probe events
9576 if (has_branch_stack(event))
9579 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9580 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9581 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
9585 event->destroy = perf_uprobe_destroy;
9589 #endif /* CONFIG_UPROBE_EVENTS */
9591 static inline void perf_tp_register(void)
9593 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
9594 #ifdef CONFIG_KPROBE_EVENTS
9595 perf_pmu_register(&perf_kprobe, "kprobe", -1);
9597 #ifdef CONFIG_UPROBE_EVENTS
9598 perf_pmu_register(&perf_uprobe, "uprobe", -1);
9602 static void perf_event_free_filter(struct perf_event *event)
9604 ftrace_profile_free_filter(event);
9607 #ifdef CONFIG_BPF_SYSCALL
9608 static void bpf_overflow_handler(struct perf_event *event,
9609 struct perf_sample_data *data,
9610 struct pt_regs *regs)
9612 struct bpf_perf_event_data_kern ctx = {
9618 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
9619 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
9622 ret = BPF_PROG_RUN(event->prog, &ctx);
9625 __this_cpu_dec(bpf_prog_active);
9629 event->orig_overflow_handler(event, data, regs);
9632 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9634 struct bpf_prog *prog;
9636 if (event->overflow_handler_context)
9637 /* hw breakpoint or kernel counter */
9643 prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
9645 return PTR_ERR(prog);
9647 if (event->attr.precise_ip &&
9648 prog->call_get_stack &&
9649 (!(event->attr.sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY) ||
9650 event->attr.exclude_callchain_kernel ||
9651 event->attr.exclude_callchain_user)) {
9653 * On perf_event with precise_ip, calling bpf_get_stack()
9654 * may trigger unwinder warnings and occasional crashes.
9655 * bpf_get_[stack|stackid] works around this issue by using
9656 * callchain attached to perf_sample_data. If the
9657 * perf_event does not full (kernel and user) callchain
9658 * attached to perf_sample_data, do not allow attaching BPF
9659 * program that calls bpf_get_[stack|stackid].
9666 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
9667 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
9671 static void perf_event_free_bpf_handler(struct perf_event *event)
9673 struct bpf_prog *prog = event->prog;
9678 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
9683 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9687 static void perf_event_free_bpf_handler(struct perf_event *event)
9693 * returns true if the event is a tracepoint, or a kprobe/upprobe created
9694 * with perf_event_open()
9696 static inline bool perf_event_is_tracing(struct perf_event *event)
9698 if (event->pmu == &perf_tracepoint)
9700 #ifdef CONFIG_KPROBE_EVENTS
9701 if (event->pmu == &perf_kprobe)
9704 #ifdef CONFIG_UPROBE_EVENTS
9705 if (event->pmu == &perf_uprobe)
9711 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9713 bool is_kprobe, is_tracepoint, is_syscall_tp;
9714 struct bpf_prog *prog;
9717 if (!perf_event_is_tracing(event))
9718 return perf_event_set_bpf_handler(event, prog_fd);
9720 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
9721 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
9722 is_syscall_tp = is_syscall_trace_event(event->tp_event);
9723 if (!is_kprobe && !is_tracepoint && !is_syscall_tp)
9724 /* bpf programs can only be attached to u/kprobe or tracepoint */
9727 prog = bpf_prog_get(prog_fd);
9729 return PTR_ERR(prog);
9731 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
9732 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
9733 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
9734 /* valid fd, but invalid bpf program type */
9739 /* Kprobe override only works for kprobes, not uprobes. */
9740 if (prog->kprobe_override &&
9741 !(event->tp_event->flags & TRACE_EVENT_FL_KPROBE)) {
9746 if (is_tracepoint || is_syscall_tp) {
9747 int off = trace_event_get_offsets(event->tp_event);
9749 if (prog->aux->max_ctx_offset > off) {
9755 ret = perf_event_attach_bpf_prog(event, prog);
9761 static void perf_event_free_bpf_prog(struct perf_event *event)
9763 if (!perf_event_is_tracing(event)) {
9764 perf_event_free_bpf_handler(event);
9767 perf_event_detach_bpf_prog(event);
9772 static inline void perf_tp_register(void)
9776 static void perf_event_free_filter(struct perf_event *event)
9780 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9785 static void perf_event_free_bpf_prog(struct perf_event *event)
9788 #endif /* CONFIG_EVENT_TRACING */
9790 #ifdef CONFIG_HAVE_HW_BREAKPOINT
9791 void perf_bp_event(struct perf_event *bp, void *data)
9793 struct perf_sample_data sample;
9794 struct pt_regs *regs = data;
9796 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
9798 if (!bp->hw.state && !perf_exclude_event(bp, regs))
9799 perf_swevent_event(bp, 1, &sample, regs);
9804 * Allocate a new address filter
9806 static struct perf_addr_filter *
9807 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
9809 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
9810 struct perf_addr_filter *filter;
9812 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
9816 INIT_LIST_HEAD(&filter->entry);
9817 list_add_tail(&filter->entry, filters);
9822 static void free_filters_list(struct list_head *filters)
9824 struct perf_addr_filter *filter, *iter;
9826 list_for_each_entry_safe(filter, iter, filters, entry) {
9827 path_put(&filter->path);
9828 list_del(&filter->entry);
9834 * Free existing address filters and optionally install new ones
9836 static void perf_addr_filters_splice(struct perf_event *event,
9837 struct list_head *head)
9839 unsigned long flags;
9842 if (!has_addr_filter(event))
9845 /* don't bother with children, they don't have their own filters */
9849 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
9851 list_splice_init(&event->addr_filters.list, &list);
9853 list_splice(head, &event->addr_filters.list);
9855 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
9857 free_filters_list(&list);
9861 * Scan through mm's vmas and see if one of them matches the
9862 * @filter; if so, adjust filter's address range.
9863 * Called with mm::mmap_lock down for reading.
9865 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
9866 struct mm_struct *mm,
9867 struct perf_addr_filter_range *fr)
9869 struct vm_area_struct *vma;
9871 for (vma = mm->mmap; vma; vma = vma->vm_next) {
9875 if (perf_addr_filter_vma_adjust(filter, vma, fr))
9881 * Update event's address range filters based on the
9882 * task's existing mappings, if any.
9884 static void perf_event_addr_filters_apply(struct perf_event *event)
9886 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
9887 struct task_struct *task = READ_ONCE(event->ctx->task);
9888 struct perf_addr_filter *filter;
9889 struct mm_struct *mm = NULL;
9890 unsigned int count = 0;
9891 unsigned long flags;
9894 * We may observe TASK_TOMBSTONE, which means that the event tear-down
9895 * will stop on the parent's child_mutex that our caller is also holding
9897 if (task == TASK_TOMBSTONE)
9900 if (ifh->nr_file_filters) {
9901 mm = get_task_mm(event->ctx->task);
9908 raw_spin_lock_irqsave(&ifh->lock, flags);
9909 list_for_each_entry(filter, &ifh->list, entry) {
9910 if (filter->path.dentry) {
9912 * Adjust base offset if the filter is associated to a
9913 * binary that needs to be mapped:
9915 event->addr_filter_ranges[count].start = 0;
9916 event->addr_filter_ranges[count].size = 0;
9918 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
9920 event->addr_filter_ranges[count].start = filter->offset;
9921 event->addr_filter_ranges[count].size = filter->size;
9927 event->addr_filters_gen++;
9928 raw_spin_unlock_irqrestore(&ifh->lock, flags);
9930 if (ifh->nr_file_filters) {
9931 mmap_read_unlock(mm);
9937 perf_event_stop(event, 1);
9941 * Address range filtering: limiting the data to certain
9942 * instruction address ranges. Filters are ioctl()ed to us from
9943 * userspace as ascii strings.
9945 * Filter string format:
9948 * where ACTION is one of the
9949 * * "filter": limit the trace to this region
9950 * * "start": start tracing from this address
9951 * * "stop": stop tracing at this address/region;
9953 * * for kernel addresses: <start address>[/<size>]
9954 * * for object files: <start address>[/<size>]@</path/to/object/file>
9956 * if <size> is not specified or is zero, the range is treated as a single
9957 * address; not valid for ACTION=="filter".
9971 IF_STATE_ACTION = 0,
9976 static const match_table_t if_tokens = {
9977 { IF_ACT_FILTER, "filter" },
9978 { IF_ACT_START, "start" },
9979 { IF_ACT_STOP, "stop" },
9980 { IF_SRC_FILE, "%u/%u@%s" },
9981 { IF_SRC_KERNEL, "%u/%u" },
9982 { IF_SRC_FILEADDR, "%u@%s" },
9983 { IF_SRC_KERNELADDR, "%u" },
9984 { IF_ACT_NONE, NULL },
9988 * Address filter string parser
9991 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
9992 struct list_head *filters)
9994 struct perf_addr_filter *filter = NULL;
9995 char *start, *orig, *filename = NULL;
9996 substring_t args[MAX_OPT_ARGS];
9997 int state = IF_STATE_ACTION, token;
9998 unsigned int kernel = 0;
10001 orig = fstr = kstrdup(fstr, GFP_KERNEL);
10005 while ((start = strsep(&fstr, " ,\n")) != NULL) {
10006 static const enum perf_addr_filter_action_t actions[] = {
10007 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
10008 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
10009 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
10016 /* filter definition begins */
10017 if (state == IF_STATE_ACTION) {
10018 filter = perf_addr_filter_new(event, filters);
10023 token = match_token(start, if_tokens, args);
10025 case IF_ACT_FILTER:
10028 if (state != IF_STATE_ACTION)
10031 filter->action = actions[token];
10032 state = IF_STATE_SOURCE;
10035 case IF_SRC_KERNELADDR:
10036 case IF_SRC_KERNEL:
10040 case IF_SRC_FILEADDR:
10042 if (state != IF_STATE_SOURCE)
10046 ret = kstrtoul(args[0].from, 0, &filter->offset);
10050 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
10052 ret = kstrtoul(args[1].from, 0, &filter->size);
10057 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
10058 int fpos = token == IF_SRC_FILE ? 2 : 1;
10060 filename = match_strdup(&args[fpos]);
10067 state = IF_STATE_END;
10075 * Filter definition is fully parsed, validate and install it.
10076 * Make sure that it doesn't contradict itself or the event's
10079 if (state == IF_STATE_END) {
10081 if (kernel && event->attr.exclude_kernel)
10085 * ACTION "filter" must have a non-zero length region
10088 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
10097 * For now, we only support file-based filters
10098 * in per-task events; doing so for CPU-wide
10099 * events requires additional context switching
10100 * trickery, since same object code will be
10101 * mapped at different virtual addresses in
10102 * different processes.
10105 if (!event->ctx->task)
10106 goto fail_free_name;
10108 /* look up the path and grab its inode */
10109 ret = kern_path(filename, LOOKUP_FOLLOW,
10112 goto fail_free_name;
10118 if (!filter->path.dentry ||
10119 !S_ISREG(d_inode(filter->path.dentry)
10123 event->addr_filters.nr_file_filters++;
10126 /* ready to consume more filters */
10127 state = IF_STATE_ACTION;
10132 if (state != IF_STATE_ACTION)
10142 free_filters_list(filters);
10149 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
10151 LIST_HEAD(filters);
10155 * Since this is called in perf_ioctl() path, we're already holding
10158 lockdep_assert_held(&event->ctx->mutex);
10160 if (WARN_ON_ONCE(event->parent))
10163 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
10165 goto fail_clear_files;
10167 ret = event->pmu->addr_filters_validate(&filters);
10169 goto fail_free_filters;
10171 /* remove existing filters, if any */
10172 perf_addr_filters_splice(event, &filters);
10174 /* install new filters */
10175 perf_event_for_each_child(event, perf_event_addr_filters_apply);
10180 free_filters_list(&filters);
10183 event->addr_filters.nr_file_filters = 0;
10188 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
10193 filter_str = strndup_user(arg, PAGE_SIZE);
10194 if (IS_ERR(filter_str))
10195 return PTR_ERR(filter_str);
10197 #ifdef CONFIG_EVENT_TRACING
10198 if (perf_event_is_tracing(event)) {
10199 struct perf_event_context *ctx = event->ctx;
10202 * Beware, here be dragons!!
10204 * the tracepoint muck will deadlock against ctx->mutex, but
10205 * the tracepoint stuff does not actually need it. So
10206 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
10207 * already have a reference on ctx.
10209 * This can result in event getting moved to a different ctx,
10210 * but that does not affect the tracepoint state.
10212 mutex_unlock(&ctx->mutex);
10213 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
10214 mutex_lock(&ctx->mutex);
10217 if (has_addr_filter(event))
10218 ret = perf_event_set_addr_filter(event, filter_str);
10225 * hrtimer based swevent callback
10228 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
10230 enum hrtimer_restart ret = HRTIMER_RESTART;
10231 struct perf_sample_data data;
10232 struct pt_regs *regs;
10233 struct perf_event *event;
10236 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
10238 if (event->state != PERF_EVENT_STATE_ACTIVE)
10239 return HRTIMER_NORESTART;
10241 event->pmu->read(event);
10243 perf_sample_data_init(&data, 0, event->hw.last_period);
10244 regs = get_irq_regs();
10246 if (regs && !perf_exclude_event(event, regs)) {
10247 if (!(event->attr.exclude_idle && is_idle_task(current)))
10248 if (__perf_event_overflow(event, 1, &data, regs))
10249 ret = HRTIMER_NORESTART;
10252 period = max_t(u64, 10000, event->hw.sample_period);
10253 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
10258 static void perf_swevent_start_hrtimer(struct perf_event *event)
10260 struct hw_perf_event *hwc = &event->hw;
10263 if (!is_sampling_event(event))
10266 period = local64_read(&hwc->period_left);
10271 local64_set(&hwc->period_left, 0);
10273 period = max_t(u64, 10000, hwc->sample_period);
10275 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
10276 HRTIMER_MODE_REL_PINNED_HARD);
10279 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
10281 struct hw_perf_event *hwc = &event->hw;
10283 if (is_sampling_event(event)) {
10284 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
10285 local64_set(&hwc->period_left, ktime_to_ns(remaining));
10287 hrtimer_cancel(&hwc->hrtimer);
10291 static void perf_swevent_init_hrtimer(struct perf_event *event)
10293 struct hw_perf_event *hwc = &event->hw;
10295 if (!is_sampling_event(event))
10298 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
10299 hwc->hrtimer.function = perf_swevent_hrtimer;
10302 * Since hrtimers have a fixed rate, we can do a static freq->period
10303 * mapping and avoid the whole period adjust feedback stuff.
10305 if (event->attr.freq) {
10306 long freq = event->attr.sample_freq;
10308 event->attr.sample_period = NSEC_PER_SEC / freq;
10309 hwc->sample_period = event->attr.sample_period;
10310 local64_set(&hwc->period_left, hwc->sample_period);
10311 hwc->last_period = hwc->sample_period;
10312 event->attr.freq = 0;
10317 * Software event: cpu wall time clock
10320 static void cpu_clock_event_update(struct perf_event *event)
10325 now = local_clock();
10326 prev = local64_xchg(&event->hw.prev_count, now);
10327 local64_add(now - prev, &event->count);
10330 static void cpu_clock_event_start(struct perf_event *event, int flags)
10332 local64_set(&event->hw.prev_count, local_clock());
10333 perf_swevent_start_hrtimer(event);
10336 static void cpu_clock_event_stop(struct perf_event *event, int flags)
10338 perf_swevent_cancel_hrtimer(event);
10339 cpu_clock_event_update(event);
10342 static int cpu_clock_event_add(struct perf_event *event, int flags)
10344 if (flags & PERF_EF_START)
10345 cpu_clock_event_start(event, flags);
10346 perf_event_update_userpage(event);
10351 static void cpu_clock_event_del(struct perf_event *event, int flags)
10353 cpu_clock_event_stop(event, flags);
10356 static void cpu_clock_event_read(struct perf_event *event)
10358 cpu_clock_event_update(event);
10361 static int cpu_clock_event_init(struct perf_event *event)
10363 if (event->attr.type != PERF_TYPE_SOFTWARE)
10366 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
10370 * no branch sampling for software events
10372 if (has_branch_stack(event))
10373 return -EOPNOTSUPP;
10375 perf_swevent_init_hrtimer(event);
10380 static struct pmu perf_cpu_clock = {
10381 .task_ctx_nr = perf_sw_context,
10383 .capabilities = PERF_PMU_CAP_NO_NMI,
10385 .event_init = cpu_clock_event_init,
10386 .add = cpu_clock_event_add,
10387 .del = cpu_clock_event_del,
10388 .start = cpu_clock_event_start,
10389 .stop = cpu_clock_event_stop,
10390 .read = cpu_clock_event_read,
10394 * Software event: task time clock
10397 static void task_clock_event_update(struct perf_event *event, u64 now)
10402 prev = local64_xchg(&event->hw.prev_count, now);
10403 delta = now - prev;
10404 local64_add(delta, &event->count);
10407 static void task_clock_event_start(struct perf_event *event, int flags)
10409 local64_set(&event->hw.prev_count, event->ctx->time);
10410 perf_swevent_start_hrtimer(event);
10413 static void task_clock_event_stop(struct perf_event *event, int flags)
10415 perf_swevent_cancel_hrtimer(event);
10416 task_clock_event_update(event, event->ctx->time);
10419 static int task_clock_event_add(struct perf_event *event, int flags)
10421 if (flags & PERF_EF_START)
10422 task_clock_event_start(event, flags);
10423 perf_event_update_userpage(event);
10428 static void task_clock_event_del(struct perf_event *event, int flags)
10430 task_clock_event_stop(event, PERF_EF_UPDATE);
10433 static void task_clock_event_read(struct perf_event *event)
10435 u64 now = perf_clock();
10436 u64 delta = now - event->ctx->timestamp;
10437 u64 time = event->ctx->time + delta;
10439 task_clock_event_update(event, time);
10442 static int task_clock_event_init(struct perf_event *event)
10444 if (event->attr.type != PERF_TYPE_SOFTWARE)
10447 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
10451 * no branch sampling for software events
10453 if (has_branch_stack(event))
10454 return -EOPNOTSUPP;
10456 perf_swevent_init_hrtimer(event);
10461 static struct pmu perf_task_clock = {
10462 .task_ctx_nr = perf_sw_context,
10464 .capabilities = PERF_PMU_CAP_NO_NMI,
10466 .event_init = task_clock_event_init,
10467 .add = task_clock_event_add,
10468 .del = task_clock_event_del,
10469 .start = task_clock_event_start,
10470 .stop = task_clock_event_stop,
10471 .read = task_clock_event_read,
10474 static void perf_pmu_nop_void(struct pmu *pmu)
10478 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
10482 static int perf_pmu_nop_int(struct pmu *pmu)
10487 static int perf_event_nop_int(struct perf_event *event, u64 value)
10492 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
10494 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
10496 __this_cpu_write(nop_txn_flags, flags);
10498 if (flags & ~PERF_PMU_TXN_ADD)
10501 perf_pmu_disable(pmu);
10504 static int perf_pmu_commit_txn(struct pmu *pmu)
10506 unsigned int flags = __this_cpu_read(nop_txn_flags);
10508 __this_cpu_write(nop_txn_flags, 0);
10510 if (flags & ~PERF_PMU_TXN_ADD)
10513 perf_pmu_enable(pmu);
10517 static void perf_pmu_cancel_txn(struct pmu *pmu)
10519 unsigned int flags = __this_cpu_read(nop_txn_flags);
10521 __this_cpu_write(nop_txn_flags, 0);
10523 if (flags & ~PERF_PMU_TXN_ADD)
10526 perf_pmu_enable(pmu);
10529 static int perf_event_idx_default(struct perf_event *event)
10535 * Ensures all contexts with the same task_ctx_nr have the same
10536 * pmu_cpu_context too.
10538 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
10545 list_for_each_entry(pmu, &pmus, entry) {
10546 if (pmu->task_ctx_nr == ctxn)
10547 return pmu->pmu_cpu_context;
10553 static void free_pmu_context(struct pmu *pmu)
10556 * Static contexts such as perf_sw_context have a global lifetime
10557 * and may be shared between different PMUs. Avoid freeing them
10558 * when a single PMU is going away.
10560 if (pmu->task_ctx_nr > perf_invalid_context)
10563 free_percpu(pmu->pmu_cpu_context);
10567 * Let userspace know that this PMU supports address range filtering:
10569 static ssize_t nr_addr_filters_show(struct device *dev,
10570 struct device_attribute *attr,
10573 struct pmu *pmu = dev_get_drvdata(dev);
10575 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
10577 DEVICE_ATTR_RO(nr_addr_filters);
10579 static struct idr pmu_idr;
10582 type_show(struct device *dev, struct device_attribute *attr, char *page)
10584 struct pmu *pmu = dev_get_drvdata(dev);
10586 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
10588 static DEVICE_ATTR_RO(type);
10591 perf_event_mux_interval_ms_show(struct device *dev,
10592 struct device_attribute *attr,
10595 struct pmu *pmu = dev_get_drvdata(dev);
10597 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
10600 static DEFINE_MUTEX(mux_interval_mutex);
10603 perf_event_mux_interval_ms_store(struct device *dev,
10604 struct device_attribute *attr,
10605 const char *buf, size_t count)
10607 struct pmu *pmu = dev_get_drvdata(dev);
10608 int timer, cpu, ret;
10610 ret = kstrtoint(buf, 0, &timer);
10617 /* same value, noting to do */
10618 if (timer == pmu->hrtimer_interval_ms)
10621 mutex_lock(&mux_interval_mutex);
10622 pmu->hrtimer_interval_ms = timer;
10624 /* update all cpuctx for this PMU */
10626 for_each_online_cpu(cpu) {
10627 struct perf_cpu_context *cpuctx;
10628 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10629 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
10631 cpu_function_call(cpu,
10632 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
10634 cpus_read_unlock();
10635 mutex_unlock(&mux_interval_mutex);
10639 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
10641 static struct attribute *pmu_dev_attrs[] = {
10642 &dev_attr_type.attr,
10643 &dev_attr_perf_event_mux_interval_ms.attr,
10646 ATTRIBUTE_GROUPS(pmu_dev);
10648 static int pmu_bus_running;
10649 static struct bus_type pmu_bus = {
10650 .name = "event_source",
10651 .dev_groups = pmu_dev_groups,
10654 static void pmu_dev_release(struct device *dev)
10659 static int pmu_dev_alloc(struct pmu *pmu)
10663 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
10667 pmu->dev->groups = pmu->attr_groups;
10668 device_initialize(pmu->dev);
10669 ret = dev_set_name(pmu->dev, "%s", pmu->name);
10673 dev_set_drvdata(pmu->dev, pmu);
10674 pmu->dev->bus = &pmu_bus;
10675 pmu->dev->release = pmu_dev_release;
10676 ret = device_add(pmu->dev);
10680 /* For PMUs with address filters, throw in an extra attribute: */
10681 if (pmu->nr_addr_filters)
10682 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
10687 if (pmu->attr_update)
10688 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
10697 device_del(pmu->dev);
10700 put_device(pmu->dev);
10704 static struct lock_class_key cpuctx_mutex;
10705 static struct lock_class_key cpuctx_lock;
10707 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
10709 int cpu, ret, max = PERF_TYPE_MAX;
10711 mutex_lock(&pmus_lock);
10713 pmu->pmu_disable_count = alloc_percpu(int);
10714 if (!pmu->pmu_disable_count)
10722 if (type != PERF_TYPE_SOFTWARE) {
10726 ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL);
10730 WARN_ON(type >= 0 && ret != type);
10736 if (pmu_bus_running) {
10737 ret = pmu_dev_alloc(pmu);
10743 if (pmu->task_ctx_nr == perf_hw_context) {
10744 static int hw_context_taken = 0;
10747 * Other than systems with heterogeneous CPUs, it never makes
10748 * sense for two PMUs to share perf_hw_context. PMUs which are
10749 * uncore must use perf_invalid_context.
10751 if (WARN_ON_ONCE(hw_context_taken &&
10752 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
10753 pmu->task_ctx_nr = perf_invalid_context;
10755 hw_context_taken = 1;
10758 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
10759 if (pmu->pmu_cpu_context)
10760 goto got_cpu_context;
10763 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
10764 if (!pmu->pmu_cpu_context)
10767 for_each_possible_cpu(cpu) {
10768 struct perf_cpu_context *cpuctx;
10770 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10771 __perf_event_init_context(&cpuctx->ctx);
10772 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
10773 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
10774 cpuctx->ctx.pmu = pmu;
10775 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
10777 __perf_mux_hrtimer_init(cpuctx, cpu);
10779 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
10780 cpuctx->heap = cpuctx->heap_default;
10784 if (!pmu->start_txn) {
10785 if (pmu->pmu_enable) {
10787 * If we have pmu_enable/pmu_disable calls, install
10788 * transaction stubs that use that to try and batch
10789 * hardware accesses.
10791 pmu->start_txn = perf_pmu_start_txn;
10792 pmu->commit_txn = perf_pmu_commit_txn;
10793 pmu->cancel_txn = perf_pmu_cancel_txn;
10795 pmu->start_txn = perf_pmu_nop_txn;
10796 pmu->commit_txn = perf_pmu_nop_int;
10797 pmu->cancel_txn = perf_pmu_nop_void;
10801 if (!pmu->pmu_enable) {
10802 pmu->pmu_enable = perf_pmu_nop_void;
10803 pmu->pmu_disable = perf_pmu_nop_void;
10806 if (!pmu->check_period)
10807 pmu->check_period = perf_event_nop_int;
10809 if (!pmu->event_idx)
10810 pmu->event_idx = perf_event_idx_default;
10813 * Ensure the TYPE_SOFTWARE PMUs are at the head of the list,
10814 * since these cannot be in the IDR. This way the linear search
10815 * is fast, provided a valid software event is provided.
10817 if (type == PERF_TYPE_SOFTWARE || !name)
10818 list_add_rcu(&pmu->entry, &pmus);
10820 list_add_tail_rcu(&pmu->entry, &pmus);
10822 atomic_set(&pmu->exclusive_cnt, 0);
10825 mutex_unlock(&pmus_lock);
10830 device_del(pmu->dev);
10831 put_device(pmu->dev);
10834 if (pmu->type != PERF_TYPE_SOFTWARE)
10835 idr_remove(&pmu_idr, pmu->type);
10838 free_percpu(pmu->pmu_disable_count);
10841 EXPORT_SYMBOL_GPL(perf_pmu_register);
10843 void perf_pmu_unregister(struct pmu *pmu)
10845 mutex_lock(&pmus_lock);
10846 list_del_rcu(&pmu->entry);
10849 * We dereference the pmu list under both SRCU and regular RCU, so
10850 * synchronize against both of those.
10852 synchronize_srcu(&pmus_srcu);
10855 free_percpu(pmu->pmu_disable_count);
10856 if (pmu->type != PERF_TYPE_SOFTWARE)
10857 idr_remove(&pmu_idr, pmu->type);
10858 if (pmu_bus_running) {
10859 if (pmu->nr_addr_filters)
10860 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
10861 device_del(pmu->dev);
10862 put_device(pmu->dev);
10864 free_pmu_context(pmu);
10865 mutex_unlock(&pmus_lock);
10867 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
10869 static inline bool has_extended_regs(struct perf_event *event)
10871 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
10872 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
10875 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
10877 struct perf_event_context *ctx = NULL;
10880 if (!try_module_get(pmu->module))
10884 * A number of pmu->event_init() methods iterate the sibling_list to,
10885 * for example, validate if the group fits on the PMU. Therefore,
10886 * if this is a sibling event, acquire the ctx->mutex to protect
10887 * the sibling_list.
10889 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
10891 * This ctx->mutex can nest when we're called through
10892 * inheritance. See the perf_event_ctx_lock_nested() comment.
10894 ctx = perf_event_ctx_lock_nested(event->group_leader,
10895 SINGLE_DEPTH_NESTING);
10900 ret = pmu->event_init(event);
10903 perf_event_ctx_unlock(event->group_leader, ctx);
10906 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
10907 has_extended_regs(event))
10910 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
10911 event_has_any_exclude_flag(event))
10914 if (ret && event->destroy)
10915 event->destroy(event);
10919 module_put(pmu->module);
10924 static struct pmu *perf_init_event(struct perf_event *event)
10926 int idx, type, ret;
10929 idx = srcu_read_lock(&pmus_srcu);
10931 /* Try parent's PMU first: */
10932 if (event->parent && event->parent->pmu) {
10933 pmu = event->parent->pmu;
10934 ret = perf_try_init_event(pmu, event);
10940 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
10941 * are often aliases for PERF_TYPE_RAW.
10943 type = event->attr.type;
10944 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE)
10945 type = PERF_TYPE_RAW;
10949 pmu = idr_find(&pmu_idr, type);
10952 ret = perf_try_init_event(pmu, event);
10953 if (ret == -ENOENT && event->attr.type != type) {
10954 type = event->attr.type;
10959 pmu = ERR_PTR(ret);
10964 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
10965 ret = perf_try_init_event(pmu, event);
10969 if (ret != -ENOENT) {
10970 pmu = ERR_PTR(ret);
10974 pmu = ERR_PTR(-ENOENT);
10976 srcu_read_unlock(&pmus_srcu, idx);
10981 static void attach_sb_event(struct perf_event *event)
10983 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
10985 raw_spin_lock(&pel->lock);
10986 list_add_rcu(&event->sb_list, &pel->list);
10987 raw_spin_unlock(&pel->lock);
10991 * We keep a list of all !task (and therefore per-cpu) events
10992 * that need to receive side-band records.
10994 * This avoids having to scan all the various PMU per-cpu contexts
10995 * looking for them.
10997 static void account_pmu_sb_event(struct perf_event *event)
10999 if (is_sb_event(event))
11000 attach_sb_event(event);
11003 static void account_event_cpu(struct perf_event *event, int cpu)
11008 if (is_cgroup_event(event))
11009 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
11012 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
11013 static void account_freq_event_nohz(void)
11015 #ifdef CONFIG_NO_HZ_FULL
11016 /* Lock so we don't race with concurrent unaccount */
11017 spin_lock(&nr_freq_lock);
11018 if (atomic_inc_return(&nr_freq_events) == 1)
11019 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
11020 spin_unlock(&nr_freq_lock);
11024 static void account_freq_event(void)
11026 if (tick_nohz_full_enabled())
11027 account_freq_event_nohz();
11029 atomic_inc(&nr_freq_events);
11033 static void account_event(struct perf_event *event)
11040 if (event->attach_state & PERF_ATTACH_TASK)
11042 if (event->attr.mmap || event->attr.mmap_data)
11043 atomic_inc(&nr_mmap_events);
11044 if (event->attr.comm)
11045 atomic_inc(&nr_comm_events);
11046 if (event->attr.namespaces)
11047 atomic_inc(&nr_namespaces_events);
11048 if (event->attr.cgroup)
11049 atomic_inc(&nr_cgroup_events);
11050 if (event->attr.task)
11051 atomic_inc(&nr_task_events);
11052 if (event->attr.freq)
11053 account_freq_event();
11054 if (event->attr.context_switch) {
11055 atomic_inc(&nr_switch_events);
11058 if (has_branch_stack(event))
11060 if (is_cgroup_event(event))
11062 if (event->attr.ksymbol)
11063 atomic_inc(&nr_ksymbol_events);
11064 if (event->attr.bpf_event)
11065 atomic_inc(&nr_bpf_events);
11066 if (event->attr.text_poke)
11067 atomic_inc(&nr_text_poke_events);
11071 * We need the mutex here because static_branch_enable()
11072 * must complete *before* the perf_sched_count increment
11075 if (atomic_inc_not_zero(&perf_sched_count))
11078 mutex_lock(&perf_sched_mutex);
11079 if (!atomic_read(&perf_sched_count)) {
11080 static_branch_enable(&perf_sched_events);
11082 * Guarantee that all CPUs observe they key change and
11083 * call the perf scheduling hooks before proceeding to
11084 * install events that need them.
11089 * Now that we have waited for the sync_sched(), allow further
11090 * increments to by-pass the mutex.
11092 atomic_inc(&perf_sched_count);
11093 mutex_unlock(&perf_sched_mutex);
11097 account_event_cpu(event, event->cpu);
11099 account_pmu_sb_event(event);
11103 * Allocate and initialize an event structure
11105 static struct perf_event *
11106 perf_event_alloc(struct perf_event_attr *attr, int cpu,
11107 struct task_struct *task,
11108 struct perf_event *group_leader,
11109 struct perf_event *parent_event,
11110 perf_overflow_handler_t overflow_handler,
11111 void *context, int cgroup_fd)
11114 struct perf_event *event;
11115 struct hw_perf_event *hwc;
11116 long err = -EINVAL;
11118 if ((unsigned)cpu >= nr_cpu_ids) {
11119 if (!task || cpu != -1)
11120 return ERR_PTR(-EINVAL);
11123 event = kzalloc(sizeof(*event), GFP_KERNEL);
11125 return ERR_PTR(-ENOMEM);
11128 * Single events are their own group leaders, with an
11129 * empty sibling list:
11132 group_leader = event;
11134 mutex_init(&event->child_mutex);
11135 INIT_LIST_HEAD(&event->child_list);
11137 INIT_LIST_HEAD(&event->event_entry);
11138 INIT_LIST_HEAD(&event->sibling_list);
11139 INIT_LIST_HEAD(&event->active_list);
11140 init_event_group(event);
11141 INIT_LIST_HEAD(&event->rb_entry);
11142 INIT_LIST_HEAD(&event->active_entry);
11143 INIT_LIST_HEAD(&event->addr_filters.list);
11144 INIT_HLIST_NODE(&event->hlist_entry);
11147 init_waitqueue_head(&event->waitq);
11148 event->pending_disable = -1;
11149 init_irq_work(&event->pending, perf_pending_event);
11151 mutex_init(&event->mmap_mutex);
11152 raw_spin_lock_init(&event->addr_filters.lock);
11154 atomic_long_set(&event->refcount, 1);
11156 event->attr = *attr;
11157 event->group_leader = group_leader;
11161 event->parent = parent_event;
11163 event->ns = get_pid_ns(task_active_pid_ns(current));
11164 event->id = atomic64_inc_return(&perf_event_id);
11166 event->state = PERF_EVENT_STATE_INACTIVE;
11169 event->attach_state = PERF_ATTACH_TASK;
11171 * XXX pmu::event_init needs to know what task to account to
11172 * and we cannot use the ctx information because we need the
11173 * pmu before we get a ctx.
11175 event->hw.target = get_task_struct(task);
11178 event->clock = &local_clock;
11180 event->clock = parent_event->clock;
11182 if (!overflow_handler && parent_event) {
11183 overflow_handler = parent_event->overflow_handler;
11184 context = parent_event->overflow_handler_context;
11185 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
11186 if (overflow_handler == bpf_overflow_handler) {
11187 struct bpf_prog *prog = parent_event->prog;
11189 bpf_prog_inc(prog);
11190 event->prog = prog;
11191 event->orig_overflow_handler =
11192 parent_event->orig_overflow_handler;
11197 if (overflow_handler) {
11198 event->overflow_handler = overflow_handler;
11199 event->overflow_handler_context = context;
11200 } else if (is_write_backward(event)){
11201 event->overflow_handler = perf_event_output_backward;
11202 event->overflow_handler_context = NULL;
11204 event->overflow_handler = perf_event_output_forward;
11205 event->overflow_handler_context = NULL;
11208 perf_event__state_init(event);
11213 hwc->sample_period = attr->sample_period;
11214 if (attr->freq && attr->sample_freq)
11215 hwc->sample_period = 1;
11216 hwc->last_period = hwc->sample_period;
11218 local64_set(&hwc->period_left, hwc->sample_period);
11221 * We currently do not support PERF_SAMPLE_READ on inherited events.
11222 * See perf_output_read().
11224 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
11227 if (!has_branch_stack(event))
11228 event->attr.branch_sample_type = 0;
11230 pmu = perf_init_event(event);
11232 err = PTR_ERR(pmu);
11237 * Disallow uncore-cgroup events, they don't make sense as the cgroup will
11238 * be different on other CPUs in the uncore mask.
11240 if (pmu->task_ctx_nr == perf_invalid_context && cgroup_fd != -1) {
11245 if (event->attr.aux_output &&
11246 !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
11251 if (cgroup_fd != -1) {
11252 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
11257 err = exclusive_event_init(event);
11261 if (has_addr_filter(event)) {
11262 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
11263 sizeof(struct perf_addr_filter_range),
11265 if (!event->addr_filter_ranges) {
11271 * Clone the parent's vma offsets: they are valid until exec()
11272 * even if the mm is not shared with the parent.
11274 if (event->parent) {
11275 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11277 raw_spin_lock_irq(&ifh->lock);
11278 memcpy(event->addr_filter_ranges,
11279 event->parent->addr_filter_ranges,
11280 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
11281 raw_spin_unlock_irq(&ifh->lock);
11284 /* force hw sync on the address filters */
11285 event->addr_filters_gen = 1;
11288 if (!event->parent) {
11289 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
11290 err = get_callchain_buffers(attr->sample_max_stack);
11292 goto err_addr_filters;
11296 err = security_perf_event_alloc(event);
11298 goto err_callchain_buffer;
11300 /* symmetric to unaccount_event() in _free_event() */
11301 account_event(event);
11305 err_callchain_buffer:
11306 if (!event->parent) {
11307 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
11308 put_callchain_buffers();
11311 kfree(event->addr_filter_ranges);
11314 exclusive_event_destroy(event);
11317 if (is_cgroup_event(event))
11318 perf_detach_cgroup(event);
11319 if (event->destroy)
11320 event->destroy(event);
11321 module_put(pmu->module);
11324 put_pid_ns(event->ns);
11325 if (event->hw.target)
11326 put_task_struct(event->hw.target);
11329 return ERR_PTR(err);
11332 static int perf_copy_attr(struct perf_event_attr __user *uattr,
11333 struct perf_event_attr *attr)
11338 /* Zero the full structure, so that a short copy will be nice. */
11339 memset(attr, 0, sizeof(*attr));
11341 ret = get_user(size, &uattr->size);
11345 /* ABI compatibility quirk: */
11347 size = PERF_ATTR_SIZE_VER0;
11348 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
11351 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
11360 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
11363 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
11366 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
11369 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
11370 u64 mask = attr->branch_sample_type;
11372 /* only using defined bits */
11373 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
11376 /* at least one branch bit must be set */
11377 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
11380 /* propagate priv level, when not set for branch */
11381 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
11383 /* exclude_kernel checked on syscall entry */
11384 if (!attr->exclude_kernel)
11385 mask |= PERF_SAMPLE_BRANCH_KERNEL;
11387 if (!attr->exclude_user)
11388 mask |= PERF_SAMPLE_BRANCH_USER;
11390 if (!attr->exclude_hv)
11391 mask |= PERF_SAMPLE_BRANCH_HV;
11393 * adjust user setting (for HW filter setup)
11395 attr->branch_sample_type = mask;
11397 /* privileged levels capture (kernel, hv): check permissions */
11398 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
11399 ret = perf_allow_kernel(attr);
11405 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
11406 ret = perf_reg_validate(attr->sample_regs_user);
11411 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
11412 if (!arch_perf_have_user_stack_dump())
11416 * We have __u32 type for the size, but so far
11417 * we can only use __u16 as maximum due to the
11418 * __u16 sample size limit.
11420 if (attr->sample_stack_user >= USHRT_MAX)
11422 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
11426 if (!attr->sample_max_stack)
11427 attr->sample_max_stack = sysctl_perf_event_max_stack;
11429 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
11430 ret = perf_reg_validate(attr->sample_regs_intr);
11432 #ifndef CONFIG_CGROUP_PERF
11433 if (attr->sample_type & PERF_SAMPLE_CGROUP)
11441 put_user(sizeof(*attr), &uattr->size);
11447 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
11449 struct perf_buffer *rb = NULL;
11455 /* don't allow circular references */
11456 if (event == output_event)
11460 * Don't allow cross-cpu buffers
11462 if (output_event->cpu != event->cpu)
11466 * If its not a per-cpu rb, it must be the same task.
11468 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
11472 * Mixing clocks in the same buffer is trouble you don't need.
11474 if (output_event->clock != event->clock)
11478 * Either writing ring buffer from beginning or from end.
11479 * Mixing is not allowed.
11481 if (is_write_backward(output_event) != is_write_backward(event))
11485 * If both events generate aux data, they must be on the same PMU
11487 if (has_aux(event) && has_aux(output_event) &&
11488 event->pmu != output_event->pmu)
11492 mutex_lock(&event->mmap_mutex);
11493 /* Can't redirect output if we've got an active mmap() */
11494 if (atomic_read(&event->mmap_count))
11497 if (output_event) {
11498 /* get the rb we want to redirect to */
11499 rb = ring_buffer_get(output_event);
11504 ring_buffer_attach(event, rb);
11508 mutex_unlock(&event->mmap_mutex);
11514 static void mutex_lock_double(struct mutex *a, struct mutex *b)
11520 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
11523 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
11525 bool nmi_safe = false;
11528 case CLOCK_MONOTONIC:
11529 event->clock = &ktime_get_mono_fast_ns;
11533 case CLOCK_MONOTONIC_RAW:
11534 event->clock = &ktime_get_raw_fast_ns;
11538 case CLOCK_REALTIME:
11539 event->clock = &ktime_get_real_ns;
11542 case CLOCK_BOOTTIME:
11543 event->clock = &ktime_get_boottime_ns;
11547 event->clock = &ktime_get_clocktai_ns;
11554 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
11561 * Variation on perf_event_ctx_lock_nested(), except we take two context
11564 static struct perf_event_context *
11565 __perf_event_ctx_lock_double(struct perf_event *group_leader,
11566 struct perf_event_context *ctx)
11568 struct perf_event_context *gctx;
11572 gctx = READ_ONCE(group_leader->ctx);
11573 if (!refcount_inc_not_zero(&gctx->refcount)) {
11579 mutex_lock_double(&gctx->mutex, &ctx->mutex);
11581 if (group_leader->ctx != gctx) {
11582 mutex_unlock(&ctx->mutex);
11583 mutex_unlock(&gctx->mutex);
11592 * sys_perf_event_open - open a performance event, associate it to a task/cpu
11594 * @attr_uptr: event_id type attributes for monitoring/sampling
11597 * @group_fd: group leader event fd
11599 SYSCALL_DEFINE5(perf_event_open,
11600 struct perf_event_attr __user *, attr_uptr,
11601 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
11603 struct perf_event *group_leader = NULL, *output_event = NULL;
11604 struct perf_event *event, *sibling;
11605 struct perf_event_attr attr;
11606 struct perf_event_context *ctx, *gctx;
11607 struct file *event_file = NULL;
11608 struct fd group = {NULL, 0};
11609 struct task_struct *task = NULL;
11612 int move_group = 0;
11614 int f_flags = O_RDWR;
11615 int cgroup_fd = -1;
11617 /* for future expandability... */
11618 if (flags & ~PERF_FLAG_ALL)
11621 /* Do we allow access to perf_event_open(2) ? */
11622 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
11626 err = perf_copy_attr(attr_uptr, &attr);
11630 if (!attr.exclude_kernel) {
11631 err = perf_allow_kernel(&attr);
11636 if (attr.namespaces) {
11637 if (!perfmon_capable())
11642 if (attr.sample_freq > sysctl_perf_event_sample_rate)
11645 if (attr.sample_period & (1ULL << 63))
11649 /* Only privileged users can get physical addresses */
11650 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
11651 err = perf_allow_kernel(&attr);
11656 err = security_locked_down(LOCKDOWN_PERF);
11657 if (err && (attr.sample_type & PERF_SAMPLE_REGS_INTR))
11658 /* REGS_INTR can leak data, lockdown must prevent this */
11664 * In cgroup mode, the pid argument is used to pass the fd
11665 * opened to the cgroup directory in cgroupfs. The cpu argument
11666 * designates the cpu on which to monitor threads from that
11669 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
11672 if (flags & PERF_FLAG_FD_CLOEXEC)
11673 f_flags |= O_CLOEXEC;
11675 event_fd = get_unused_fd_flags(f_flags);
11679 if (group_fd != -1) {
11680 err = perf_fget_light(group_fd, &group);
11683 group_leader = group.file->private_data;
11684 if (flags & PERF_FLAG_FD_OUTPUT)
11685 output_event = group_leader;
11686 if (flags & PERF_FLAG_FD_NO_GROUP)
11687 group_leader = NULL;
11690 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
11691 task = find_lively_task_by_vpid(pid);
11692 if (IS_ERR(task)) {
11693 err = PTR_ERR(task);
11698 if (task && group_leader &&
11699 group_leader->attr.inherit != attr.inherit) {
11705 err = mutex_lock_interruptible(&task->signal->exec_update_mutex);
11710 * Reuse ptrace permission checks for now.
11712 * We must hold exec_update_mutex across this and any potential
11713 * perf_install_in_context() call for this new event to
11714 * serialize against exec() altering our credentials (and the
11715 * perf_event_exit_task() that could imply).
11718 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
11722 if (flags & PERF_FLAG_PID_CGROUP)
11725 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
11726 NULL, NULL, cgroup_fd);
11727 if (IS_ERR(event)) {
11728 err = PTR_ERR(event);
11732 if (is_sampling_event(event)) {
11733 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
11740 * Special case software events and allow them to be part of
11741 * any hardware group.
11745 if (attr.use_clockid) {
11746 err = perf_event_set_clock(event, attr.clockid);
11751 if (pmu->task_ctx_nr == perf_sw_context)
11752 event->event_caps |= PERF_EV_CAP_SOFTWARE;
11754 if (group_leader) {
11755 if (is_software_event(event) &&
11756 !in_software_context(group_leader)) {
11758 * If the event is a sw event, but the group_leader
11759 * is on hw context.
11761 * Allow the addition of software events to hw
11762 * groups, this is safe because software events
11763 * never fail to schedule.
11765 pmu = group_leader->ctx->pmu;
11766 } else if (!is_software_event(event) &&
11767 is_software_event(group_leader) &&
11768 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11770 * In case the group is a pure software group, and we
11771 * try to add a hardware event, move the whole group to
11772 * the hardware context.
11779 * Get the target context (task or percpu):
11781 ctx = find_get_context(pmu, task, event);
11783 err = PTR_ERR(ctx);
11788 * Look up the group leader (we will attach this event to it):
11790 if (group_leader) {
11794 * Do not allow a recursive hierarchy (this new sibling
11795 * becoming part of another group-sibling):
11797 if (group_leader->group_leader != group_leader)
11800 /* All events in a group should have the same clock */
11801 if (group_leader->clock != event->clock)
11805 * Make sure we're both events for the same CPU;
11806 * grouping events for different CPUs is broken; since
11807 * you can never concurrently schedule them anyhow.
11809 if (group_leader->cpu != event->cpu)
11813 * Make sure we're both on the same task, or both
11816 if (group_leader->ctx->task != ctx->task)
11820 * Do not allow to attach to a group in a different task
11821 * or CPU context. If we're moving SW events, we'll fix
11822 * this up later, so allow that.
11824 if (!move_group && group_leader->ctx != ctx)
11828 * Only a group leader can be exclusive or pinned
11830 if (attr.exclusive || attr.pinned)
11834 if (output_event) {
11835 err = perf_event_set_output(event, output_event);
11840 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
11842 if (IS_ERR(event_file)) {
11843 err = PTR_ERR(event_file);
11849 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
11851 if (gctx->task == TASK_TOMBSTONE) {
11857 * Check if we raced against another sys_perf_event_open() call
11858 * moving the software group underneath us.
11860 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11862 * If someone moved the group out from under us, check
11863 * if this new event wound up on the same ctx, if so
11864 * its the regular !move_group case, otherwise fail.
11870 perf_event_ctx_unlock(group_leader, gctx);
11876 * Failure to create exclusive events returns -EBUSY.
11879 if (!exclusive_event_installable(group_leader, ctx))
11882 for_each_sibling_event(sibling, group_leader) {
11883 if (!exclusive_event_installable(sibling, ctx))
11887 mutex_lock(&ctx->mutex);
11890 if (ctx->task == TASK_TOMBSTONE) {
11895 if (!perf_event_validate_size(event)) {
11902 * Check if the @cpu we're creating an event for is online.
11904 * We use the perf_cpu_context::ctx::mutex to serialize against
11905 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
11907 struct perf_cpu_context *cpuctx =
11908 container_of(ctx, struct perf_cpu_context, ctx);
11910 if (!cpuctx->online) {
11916 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
11922 * Must be under the same ctx::mutex as perf_install_in_context(),
11923 * because we need to serialize with concurrent event creation.
11925 if (!exclusive_event_installable(event, ctx)) {
11930 WARN_ON_ONCE(ctx->parent_ctx);
11933 * This is the point on no return; we cannot fail hereafter. This is
11934 * where we start modifying current state.
11939 * See perf_event_ctx_lock() for comments on the details
11940 * of swizzling perf_event::ctx.
11942 perf_remove_from_context(group_leader, 0);
11945 for_each_sibling_event(sibling, group_leader) {
11946 perf_remove_from_context(sibling, 0);
11951 * Wait for everybody to stop referencing the events through
11952 * the old lists, before installing it on new lists.
11957 * Install the group siblings before the group leader.
11959 * Because a group leader will try and install the entire group
11960 * (through the sibling list, which is still in-tact), we can
11961 * end up with siblings installed in the wrong context.
11963 * By installing siblings first we NO-OP because they're not
11964 * reachable through the group lists.
11966 for_each_sibling_event(sibling, group_leader) {
11967 perf_event__state_init(sibling);
11968 perf_install_in_context(ctx, sibling, sibling->cpu);
11973 * Removing from the context ends up with disabled
11974 * event. What we want here is event in the initial
11975 * startup state, ready to be add into new context.
11977 perf_event__state_init(group_leader);
11978 perf_install_in_context(ctx, group_leader, group_leader->cpu);
11983 * Precalculate sample_data sizes; do while holding ctx::mutex such
11984 * that we're serialized against further additions and before
11985 * perf_install_in_context() which is the point the event is active and
11986 * can use these values.
11988 perf_event__header_size(event);
11989 perf_event__id_header_size(event);
11991 event->owner = current;
11993 perf_install_in_context(ctx, event, event->cpu);
11994 perf_unpin_context(ctx);
11997 perf_event_ctx_unlock(group_leader, gctx);
11998 mutex_unlock(&ctx->mutex);
12001 mutex_unlock(&task->signal->exec_update_mutex);
12002 put_task_struct(task);
12005 mutex_lock(¤t->perf_event_mutex);
12006 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
12007 mutex_unlock(¤t->perf_event_mutex);
12010 * Drop the reference on the group_event after placing the
12011 * new event on the sibling_list. This ensures destruction
12012 * of the group leader will find the pointer to itself in
12013 * perf_group_detach().
12016 fd_install(event_fd, event_file);
12021 perf_event_ctx_unlock(group_leader, gctx);
12022 mutex_unlock(&ctx->mutex);
12026 perf_unpin_context(ctx);
12030 * If event_file is set, the fput() above will have called ->release()
12031 * and that will take care of freeing the event.
12037 mutex_unlock(&task->signal->exec_update_mutex);
12040 put_task_struct(task);
12044 put_unused_fd(event_fd);
12049 * perf_event_create_kernel_counter
12051 * @attr: attributes of the counter to create
12052 * @cpu: cpu in which the counter is bound
12053 * @task: task to profile (NULL for percpu)
12055 struct perf_event *
12056 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
12057 struct task_struct *task,
12058 perf_overflow_handler_t overflow_handler,
12061 struct perf_event_context *ctx;
12062 struct perf_event *event;
12066 * Grouping is not supported for kernel events, neither is 'AUX',
12067 * make sure the caller's intentions are adjusted.
12069 if (attr->aux_output)
12070 return ERR_PTR(-EINVAL);
12072 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
12073 overflow_handler, context, -1);
12074 if (IS_ERR(event)) {
12075 err = PTR_ERR(event);
12079 /* Mark owner so we could distinguish it from user events. */
12080 event->owner = TASK_TOMBSTONE;
12083 * Get the target context (task or percpu):
12085 ctx = find_get_context(event->pmu, task, event);
12087 err = PTR_ERR(ctx);
12091 WARN_ON_ONCE(ctx->parent_ctx);
12092 mutex_lock(&ctx->mutex);
12093 if (ctx->task == TASK_TOMBSTONE) {
12100 * Check if the @cpu we're creating an event for is online.
12102 * We use the perf_cpu_context::ctx::mutex to serialize against
12103 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12105 struct perf_cpu_context *cpuctx =
12106 container_of(ctx, struct perf_cpu_context, ctx);
12107 if (!cpuctx->online) {
12113 if (!exclusive_event_installable(event, ctx)) {
12118 perf_install_in_context(ctx, event, event->cpu);
12119 perf_unpin_context(ctx);
12120 mutex_unlock(&ctx->mutex);
12125 mutex_unlock(&ctx->mutex);
12126 perf_unpin_context(ctx);
12131 return ERR_PTR(err);
12133 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
12135 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
12137 struct perf_event_context *src_ctx;
12138 struct perf_event_context *dst_ctx;
12139 struct perf_event *event, *tmp;
12142 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
12143 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
12146 * See perf_event_ctx_lock() for comments on the details
12147 * of swizzling perf_event::ctx.
12149 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
12150 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
12152 perf_remove_from_context(event, 0);
12153 unaccount_event_cpu(event, src_cpu);
12155 list_add(&event->migrate_entry, &events);
12159 * Wait for the events to quiesce before re-instating them.
12164 * Re-instate events in 2 passes.
12166 * Skip over group leaders and only install siblings on this first
12167 * pass, siblings will not get enabled without a leader, however a
12168 * leader will enable its siblings, even if those are still on the old
12171 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12172 if (event->group_leader == event)
12175 list_del(&event->migrate_entry);
12176 if (event->state >= PERF_EVENT_STATE_OFF)
12177 event->state = PERF_EVENT_STATE_INACTIVE;
12178 account_event_cpu(event, dst_cpu);
12179 perf_install_in_context(dst_ctx, event, dst_cpu);
12184 * Once all the siblings are setup properly, install the group leaders
12187 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12188 list_del(&event->migrate_entry);
12189 if (event->state >= PERF_EVENT_STATE_OFF)
12190 event->state = PERF_EVENT_STATE_INACTIVE;
12191 account_event_cpu(event, dst_cpu);
12192 perf_install_in_context(dst_ctx, event, dst_cpu);
12195 mutex_unlock(&dst_ctx->mutex);
12196 mutex_unlock(&src_ctx->mutex);
12198 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
12200 static void sync_child_event(struct perf_event *child_event,
12201 struct task_struct *child)
12203 struct perf_event *parent_event = child_event->parent;
12206 if (child_event->attr.inherit_stat)
12207 perf_event_read_event(child_event, child);
12209 child_val = perf_event_count(child_event);
12212 * Add back the child's count to the parent's count:
12214 atomic64_add(child_val, &parent_event->child_count);
12215 atomic64_add(child_event->total_time_enabled,
12216 &parent_event->child_total_time_enabled);
12217 atomic64_add(child_event->total_time_running,
12218 &parent_event->child_total_time_running);
12222 perf_event_exit_event(struct perf_event *child_event,
12223 struct perf_event_context *child_ctx,
12224 struct task_struct *child)
12226 struct perf_event *parent_event = child_event->parent;
12229 * Do not destroy the 'original' grouping; because of the context
12230 * switch optimization the original events could've ended up in a
12231 * random child task.
12233 * If we were to destroy the original group, all group related
12234 * operations would cease to function properly after this random
12237 * Do destroy all inherited groups, we don't care about those
12238 * and being thorough is better.
12240 raw_spin_lock_irq(&child_ctx->lock);
12241 WARN_ON_ONCE(child_ctx->is_active);
12244 perf_group_detach(child_event);
12245 list_del_event(child_event, child_ctx);
12246 perf_event_set_state(child_event, PERF_EVENT_STATE_EXIT); /* is_event_hup() */
12247 raw_spin_unlock_irq(&child_ctx->lock);
12250 * Parent events are governed by their filedesc, retain them.
12252 if (!parent_event) {
12253 perf_event_wakeup(child_event);
12257 * Child events can be cleaned up.
12260 sync_child_event(child_event, child);
12263 * Remove this event from the parent's list
12265 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
12266 mutex_lock(&parent_event->child_mutex);
12267 list_del_init(&child_event->child_list);
12268 mutex_unlock(&parent_event->child_mutex);
12271 * Kick perf_poll() for is_event_hup().
12273 perf_event_wakeup(parent_event);
12274 free_event(child_event);
12275 put_event(parent_event);
12278 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
12280 struct perf_event_context *child_ctx, *clone_ctx = NULL;
12281 struct perf_event *child_event, *next;
12283 WARN_ON_ONCE(child != current);
12285 child_ctx = perf_pin_task_context(child, ctxn);
12290 * In order to reduce the amount of tricky in ctx tear-down, we hold
12291 * ctx::mutex over the entire thing. This serializes against almost
12292 * everything that wants to access the ctx.
12294 * The exception is sys_perf_event_open() /
12295 * perf_event_create_kernel_count() which does find_get_context()
12296 * without ctx::mutex (it cannot because of the move_group double mutex
12297 * lock thing). See the comments in perf_install_in_context().
12299 mutex_lock(&child_ctx->mutex);
12302 * In a single ctx::lock section, de-schedule the events and detach the
12303 * context from the task such that we cannot ever get it scheduled back
12306 raw_spin_lock_irq(&child_ctx->lock);
12307 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL);
12310 * Now that the context is inactive, destroy the task <-> ctx relation
12311 * and mark the context dead.
12313 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
12314 put_ctx(child_ctx); /* cannot be last */
12315 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
12316 put_task_struct(current); /* cannot be last */
12318 clone_ctx = unclone_ctx(child_ctx);
12319 raw_spin_unlock_irq(&child_ctx->lock);
12322 put_ctx(clone_ctx);
12325 * Report the task dead after unscheduling the events so that we
12326 * won't get any samples after PERF_RECORD_EXIT. We can however still
12327 * get a few PERF_RECORD_READ events.
12329 perf_event_task(child, child_ctx, 0);
12331 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
12332 perf_event_exit_event(child_event, child_ctx, child);
12334 mutex_unlock(&child_ctx->mutex);
12336 put_ctx(child_ctx);
12340 * When a child task exits, feed back event values to parent events.
12342 * Can be called with exec_update_mutex held when called from
12343 * setup_new_exec().
12345 void perf_event_exit_task(struct task_struct *child)
12347 struct perf_event *event, *tmp;
12350 mutex_lock(&child->perf_event_mutex);
12351 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
12353 list_del_init(&event->owner_entry);
12356 * Ensure the list deletion is visible before we clear
12357 * the owner, closes a race against perf_release() where
12358 * we need to serialize on the owner->perf_event_mutex.
12360 smp_store_release(&event->owner, NULL);
12362 mutex_unlock(&child->perf_event_mutex);
12364 for_each_task_context_nr(ctxn)
12365 perf_event_exit_task_context(child, ctxn);
12368 * The perf_event_exit_task_context calls perf_event_task
12369 * with child's task_ctx, which generates EXIT events for
12370 * child contexts and sets child->perf_event_ctxp[] to NULL.
12371 * At this point we need to send EXIT events to cpu contexts.
12373 perf_event_task(child, NULL, 0);
12376 static void perf_free_event(struct perf_event *event,
12377 struct perf_event_context *ctx)
12379 struct perf_event *parent = event->parent;
12381 if (WARN_ON_ONCE(!parent))
12384 mutex_lock(&parent->child_mutex);
12385 list_del_init(&event->child_list);
12386 mutex_unlock(&parent->child_mutex);
12390 raw_spin_lock_irq(&ctx->lock);
12391 perf_group_detach(event);
12392 list_del_event(event, ctx);
12393 raw_spin_unlock_irq(&ctx->lock);
12398 * Free a context as created by inheritance by perf_event_init_task() below,
12399 * used by fork() in case of fail.
12401 * Even though the task has never lived, the context and events have been
12402 * exposed through the child_list, so we must take care tearing it all down.
12404 void perf_event_free_task(struct task_struct *task)
12406 struct perf_event_context *ctx;
12407 struct perf_event *event, *tmp;
12410 for_each_task_context_nr(ctxn) {
12411 ctx = task->perf_event_ctxp[ctxn];
12415 mutex_lock(&ctx->mutex);
12416 raw_spin_lock_irq(&ctx->lock);
12418 * Destroy the task <-> ctx relation and mark the context dead.
12420 * This is important because even though the task hasn't been
12421 * exposed yet the context has been (through child_list).
12423 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
12424 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
12425 put_task_struct(task); /* cannot be last */
12426 raw_spin_unlock_irq(&ctx->lock);
12428 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
12429 perf_free_event(event, ctx);
12431 mutex_unlock(&ctx->mutex);
12434 * perf_event_release_kernel() could've stolen some of our
12435 * child events and still have them on its free_list. In that
12436 * case we must wait for these events to have been freed (in
12437 * particular all their references to this task must've been
12440 * Without this copy_process() will unconditionally free this
12441 * task (irrespective of its reference count) and
12442 * _free_event()'s put_task_struct(event->hw.target) will be a
12445 * Wait for all events to drop their context reference.
12447 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
12448 put_ctx(ctx); /* must be last */
12452 void perf_event_delayed_put(struct task_struct *task)
12456 for_each_task_context_nr(ctxn)
12457 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
12460 struct file *perf_event_get(unsigned int fd)
12462 struct file *file = fget(fd);
12464 return ERR_PTR(-EBADF);
12466 if (file->f_op != &perf_fops) {
12468 return ERR_PTR(-EBADF);
12474 const struct perf_event *perf_get_event(struct file *file)
12476 if (file->f_op != &perf_fops)
12477 return ERR_PTR(-EINVAL);
12479 return file->private_data;
12482 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
12485 return ERR_PTR(-EINVAL);
12487 return &event->attr;
12491 * Inherit an event from parent task to child task.
12494 * - valid pointer on success
12495 * - NULL for orphaned events
12496 * - IS_ERR() on error
12498 static struct perf_event *
12499 inherit_event(struct perf_event *parent_event,
12500 struct task_struct *parent,
12501 struct perf_event_context *parent_ctx,
12502 struct task_struct *child,
12503 struct perf_event *group_leader,
12504 struct perf_event_context *child_ctx)
12506 enum perf_event_state parent_state = parent_event->state;
12507 struct perf_event *child_event;
12508 unsigned long flags;
12511 * Instead of creating recursive hierarchies of events,
12512 * we link inherited events back to the original parent,
12513 * which has a filp for sure, which we use as the reference
12516 if (parent_event->parent)
12517 parent_event = parent_event->parent;
12519 child_event = perf_event_alloc(&parent_event->attr,
12522 group_leader, parent_event,
12524 if (IS_ERR(child_event))
12525 return child_event;
12528 if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) &&
12529 !child_ctx->task_ctx_data) {
12530 struct pmu *pmu = child_event->pmu;
12532 child_ctx->task_ctx_data = alloc_task_ctx_data(pmu);
12533 if (!child_ctx->task_ctx_data) {
12534 free_event(child_event);
12535 return ERR_PTR(-ENOMEM);
12540 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
12541 * must be under the same lock in order to serialize against
12542 * perf_event_release_kernel(), such that either we must observe
12543 * is_orphaned_event() or they will observe us on the child_list.
12545 mutex_lock(&parent_event->child_mutex);
12546 if (is_orphaned_event(parent_event) ||
12547 !atomic_long_inc_not_zero(&parent_event->refcount)) {
12548 mutex_unlock(&parent_event->child_mutex);
12549 /* task_ctx_data is freed with child_ctx */
12550 free_event(child_event);
12554 get_ctx(child_ctx);
12557 * Make the child state follow the state of the parent event,
12558 * not its attr.disabled bit. We hold the parent's mutex,
12559 * so we won't race with perf_event_{en, dis}able_family.
12561 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
12562 child_event->state = PERF_EVENT_STATE_INACTIVE;
12564 child_event->state = PERF_EVENT_STATE_OFF;
12566 if (parent_event->attr.freq) {
12567 u64 sample_period = parent_event->hw.sample_period;
12568 struct hw_perf_event *hwc = &child_event->hw;
12570 hwc->sample_period = sample_period;
12571 hwc->last_period = sample_period;
12573 local64_set(&hwc->period_left, sample_period);
12576 child_event->ctx = child_ctx;
12577 child_event->overflow_handler = parent_event->overflow_handler;
12578 child_event->overflow_handler_context
12579 = parent_event->overflow_handler_context;
12582 * Precalculate sample_data sizes
12584 perf_event__header_size(child_event);
12585 perf_event__id_header_size(child_event);
12588 * Link it up in the child's context:
12590 raw_spin_lock_irqsave(&child_ctx->lock, flags);
12591 add_event_to_ctx(child_event, child_ctx);
12592 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
12595 * Link this into the parent event's child list
12597 list_add_tail(&child_event->child_list, &parent_event->child_list);
12598 mutex_unlock(&parent_event->child_mutex);
12600 return child_event;
12604 * Inherits an event group.
12606 * This will quietly suppress orphaned events; !inherit_event() is not an error.
12607 * This matches with perf_event_release_kernel() removing all child events.
12613 static int inherit_group(struct perf_event *parent_event,
12614 struct task_struct *parent,
12615 struct perf_event_context *parent_ctx,
12616 struct task_struct *child,
12617 struct perf_event_context *child_ctx)
12619 struct perf_event *leader;
12620 struct perf_event *sub;
12621 struct perf_event *child_ctr;
12623 leader = inherit_event(parent_event, parent, parent_ctx,
12624 child, NULL, child_ctx);
12625 if (IS_ERR(leader))
12626 return PTR_ERR(leader);
12628 * @leader can be NULL here because of is_orphaned_event(). In this
12629 * case inherit_event() will create individual events, similar to what
12630 * perf_group_detach() would do anyway.
12632 for_each_sibling_event(sub, parent_event) {
12633 child_ctr = inherit_event(sub, parent, parent_ctx,
12634 child, leader, child_ctx);
12635 if (IS_ERR(child_ctr))
12636 return PTR_ERR(child_ctr);
12638 if (sub->aux_event == parent_event && child_ctr &&
12639 !perf_get_aux_event(child_ctr, leader))
12646 * Creates the child task context and tries to inherit the event-group.
12648 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
12649 * inherited_all set when we 'fail' to inherit an orphaned event; this is
12650 * consistent with perf_event_release_kernel() removing all child events.
12657 inherit_task_group(struct perf_event *event, struct task_struct *parent,
12658 struct perf_event_context *parent_ctx,
12659 struct task_struct *child, int ctxn,
12660 int *inherited_all)
12663 struct perf_event_context *child_ctx;
12665 if (!event->attr.inherit) {
12666 *inherited_all = 0;
12670 child_ctx = child->perf_event_ctxp[ctxn];
12673 * This is executed from the parent task context, so
12674 * inherit events that have been marked for cloning.
12675 * First allocate and initialize a context for the
12678 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
12682 child->perf_event_ctxp[ctxn] = child_ctx;
12685 ret = inherit_group(event, parent, parent_ctx,
12689 *inherited_all = 0;
12695 * Initialize the perf_event context in task_struct
12697 static int perf_event_init_context(struct task_struct *child, int ctxn)
12699 struct perf_event_context *child_ctx, *parent_ctx;
12700 struct perf_event_context *cloned_ctx;
12701 struct perf_event *event;
12702 struct task_struct *parent = current;
12703 int inherited_all = 1;
12704 unsigned long flags;
12707 if (likely(!parent->perf_event_ctxp[ctxn]))
12711 * If the parent's context is a clone, pin it so it won't get
12712 * swapped under us.
12714 parent_ctx = perf_pin_task_context(parent, ctxn);
12719 * No need to check if parent_ctx != NULL here; since we saw
12720 * it non-NULL earlier, the only reason for it to become NULL
12721 * is if we exit, and since we're currently in the middle of
12722 * a fork we can't be exiting at the same time.
12726 * Lock the parent list. No need to lock the child - not PID
12727 * hashed yet and not running, so nobody can access it.
12729 mutex_lock(&parent_ctx->mutex);
12732 * We dont have to disable NMIs - we are only looking at
12733 * the list, not manipulating it:
12735 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
12736 ret = inherit_task_group(event, parent, parent_ctx,
12737 child, ctxn, &inherited_all);
12743 * We can't hold ctx->lock when iterating the ->flexible_group list due
12744 * to allocations, but we need to prevent rotation because
12745 * rotate_ctx() will change the list from interrupt context.
12747 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12748 parent_ctx->rotate_disable = 1;
12749 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12751 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
12752 ret = inherit_task_group(event, parent, parent_ctx,
12753 child, ctxn, &inherited_all);
12758 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12759 parent_ctx->rotate_disable = 0;
12761 child_ctx = child->perf_event_ctxp[ctxn];
12763 if (child_ctx && inherited_all) {
12765 * Mark the child context as a clone of the parent
12766 * context, or of whatever the parent is a clone of.
12768 * Note that if the parent is a clone, the holding of
12769 * parent_ctx->lock avoids it from being uncloned.
12771 cloned_ctx = parent_ctx->parent_ctx;
12773 child_ctx->parent_ctx = cloned_ctx;
12774 child_ctx->parent_gen = parent_ctx->parent_gen;
12776 child_ctx->parent_ctx = parent_ctx;
12777 child_ctx->parent_gen = parent_ctx->generation;
12779 get_ctx(child_ctx->parent_ctx);
12782 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12784 mutex_unlock(&parent_ctx->mutex);
12786 perf_unpin_context(parent_ctx);
12787 put_ctx(parent_ctx);
12793 * Initialize the perf_event context in task_struct
12795 int perf_event_init_task(struct task_struct *child)
12799 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
12800 mutex_init(&child->perf_event_mutex);
12801 INIT_LIST_HEAD(&child->perf_event_list);
12803 for_each_task_context_nr(ctxn) {
12804 ret = perf_event_init_context(child, ctxn);
12806 perf_event_free_task(child);
12814 static void __init perf_event_init_all_cpus(void)
12816 struct swevent_htable *swhash;
12819 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
12821 for_each_possible_cpu(cpu) {
12822 swhash = &per_cpu(swevent_htable, cpu);
12823 mutex_init(&swhash->hlist_mutex);
12824 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
12826 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
12827 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
12829 #ifdef CONFIG_CGROUP_PERF
12830 INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu));
12832 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
12836 static void perf_swevent_init_cpu(unsigned int cpu)
12838 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
12840 mutex_lock(&swhash->hlist_mutex);
12841 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
12842 struct swevent_hlist *hlist;
12844 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
12846 rcu_assign_pointer(swhash->swevent_hlist, hlist);
12848 mutex_unlock(&swhash->hlist_mutex);
12851 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
12852 static void __perf_event_exit_context(void *__info)
12854 struct perf_event_context *ctx = __info;
12855 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
12856 struct perf_event *event;
12858 raw_spin_lock(&ctx->lock);
12859 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
12860 list_for_each_entry(event, &ctx->event_list, event_entry)
12861 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
12862 raw_spin_unlock(&ctx->lock);
12865 static void perf_event_exit_cpu_context(int cpu)
12867 struct perf_cpu_context *cpuctx;
12868 struct perf_event_context *ctx;
12871 mutex_lock(&pmus_lock);
12872 list_for_each_entry(pmu, &pmus, entry) {
12873 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
12874 ctx = &cpuctx->ctx;
12876 mutex_lock(&ctx->mutex);
12877 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
12878 cpuctx->online = 0;
12879 mutex_unlock(&ctx->mutex);
12881 cpumask_clear_cpu(cpu, perf_online_mask);
12882 mutex_unlock(&pmus_lock);
12886 static void perf_event_exit_cpu_context(int cpu) { }
12890 int perf_event_init_cpu(unsigned int cpu)
12892 struct perf_cpu_context *cpuctx;
12893 struct perf_event_context *ctx;
12896 perf_swevent_init_cpu(cpu);
12898 mutex_lock(&pmus_lock);
12899 cpumask_set_cpu(cpu, perf_online_mask);
12900 list_for_each_entry(pmu, &pmus, entry) {
12901 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
12902 ctx = &cpuctx->ctx;
12904 mutex_lock(&ctx->mutex);
12905 cpuctx->online = 1;
12906 mutex_unlock(&ctx->mutex);
12908 mutex_unlock(&pmus_lock);
12913 int perf_event_exit_cpu(unsigned int cpu)
12915 perf_event_exit_cpu_context(cpu);
12920 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
12924 for_each_online_cpu(cpu)
12925 perf_event_exit_cpu(cpu);
12931 * Run the perf reboot notifier at the very last possible moment so that
12932 * the generic watchdog code runs as long as possible.
12934 static struct notifier_block perf_reboot_notifier = {
12935 .notifier_call = perf_reboot,
12936 .priority = INT_MIN,
12939 void __init perf_event_init(void)
12943 idr_init(&pmu_idr);
12945 perf_event_init_all_cpus();
12946 init_srcu_struct(&pmus_srcu);
12947 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
12948 perf_pmu_register(&perf_cpu_clock, NULL, -1);
12949 perf_pmu_register(&perf_task_clock, NULL, -1);
12950 perf_tp_register();
12951 perf_event_init_cpu(smp_processor_id());
12952 register_reboot_notifier(&perf_reboot_notifier);
12954 ret = init_hw_breakpoint();
12955 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
12958 * Build time assertion that we keep the data_head at the intended
12959 * location. IOW, validation we got the __reserved[] size right.
12961 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
12965 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
12968 struct perf_pmu_events_attr *pmu_attr =
12969 container_of(attr, struct perf_pmu_events_attr, attr);
12971 if (pmu_attr->event_str)
12972 return sprintf(page, "%s\n", pmu_attr->event_str);
12976 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
12978 static int __init perf_event_sysfs_init(void)
12983 mutex_lock(&pmus_lock);
12985 ret = bus_register(&pmu_bus);
12989 list_for_each_entry(pmu, &pmus, entry) {
12990 if (!pmu->name || pmu->type < 0)
12993 ret = pmu_dev_alloc(pmu);
12994 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
12996 pmu_bus_running = 1;
13000 mutex_unlock(&pmus_lock);
13004 device_initcall(perf_event_sysfs_init);
13006 #ifdef CONFIG_CGROUP_PERF
13007 static struct cgroup_subsys_state *
13008 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
13010 struct perf_cgroup *jc;
13012 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
13014 return ERR_PTR(-ENOMEM);
13016 jc->info = alloc_percpu(struct perf_cgroup_info);
13019 return ERR_PTR(-ENOMEM);
13025 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
13027 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
13029 free_percpu(jc->info);
13033 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
13035 perf_event_cgroup(css->cgroup);
13039 static int __perf_cgroup_move(void *info)
13041 struct task_struct *task = info;
13043 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
13048 static void perf_cgroup_attach(struct cgroup_taskset *tset)
13050 struct task_struct *task;
13051 struct cgroup_subsys_state *css;
13053 cgroup_taskset_for_each(task, css, tset)
13054 task_function_call(task, __perf_cgroup_move, task);
13057 struct cgroup_subsys perf_event_cgrp_subsys = {
13058 .css_alloc = perf_cgroup_css_alloc,
13059 .css_free = perf_cgroup_css_free,
13060 .css_online = perf_cgroup_css_online,
13061 .attach = perf_cgroup_attach,
13063 * Implicitly enable on dfl hierarchy so that perf events can
13064 * always be filtered by cgroup2 path as long as perf_event
13065 * controller is not mounted on a legacy hierarchy.
13067 .implicit_on_dfl = true,
13070 #endif /* CONFIG_CGROUP_PERF */