1 // SPDX-License-Identifier: GPL-2.0
3 * Performance events core code:
5 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
6 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
7 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
8 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
13 #include <linux/cpu.h>
14 #include <linux/smp.h>
15 #include <linux/idr.h>
16 #include <linux/file.h>
17 #include <linux/poll.h>
18 #include <linux/slab.h>
19 #include <linux/hash.h>
20 #include <linux/tick.h>
21 #include <linux/sysfs.h>
22 #include <linux/dcache.h>
23 #include <linux/percpu.h>
24 #include <linux/ptrace.h>
25 #include <linux/reboot.h>
26 #include <linux/vmstat.h>
27 #include <linux/device.h>
28 #include <linux/export.h>
29 #include <linux/vmalloc.h>
30 #include <linux/hardirq.h>
31 #include <linux/hugetlb.h>
32 #include <linux/rculist.h>
33 #include <linux/uaccess.h>
34 #include <linux/syscalls.h>
35 #include <linux/anon_inodes.h>
36 #include <linux/kernel_stat.h>
37 #include <linux/cgroup.h>
38 #include <linux/perf_event.h>
39 #include <linux/trace_events.h>
40 #include <linux/hw_breakpoint.h>
41 #include <linux/mm_types.h>
42 #include <linux/module.h>
43 #include <linux/mman.h>
44 #include <linux/compat.h>
45 #include <linux/bpf.h>
46 #include <linux/filter.h>
47 #include <linux/namei.h>
48 #include <linux/parser.h>
49 #include <linux/sched/clock.h>
50 #include <linux/sched/mm.h>
51 #include <linux/proc_ns.h>
52 #include <linux/mount.h>
53 #include <linux/min_heap.h>
54 #include <linux/highmem.h>
55 #include <linux/pgtable.h>
56 #include <linux/buildid.h>
57 #include <linux/task_work.h>
61 #include <asm/irq_regs.h>
63 typedef int (*remote_function_f
)(void *);
65 struct remote_function_call
{
66 struct task_struct
*p
;
67 remote_function_f func
;
72 static void remote_function(void *data
)
74 struct remote_function_call
*tfc
= data
;
75 struct task_struct
*p
= tfc
->p
;
79 if (task_cpu(p
) != smp_processor_id())
83 * Now that we're on right CPU with IRQs disabled, we can test
84 * if we hit the right task without races.
87 tfc
->ret
= -ESRCH
; /* No such (running) process */
92 tfc
->ret
= tfc
->func(tfc
->info
);
96 * task_function_call - call a function on the cpu on which a task runs
97 * @p: the task to evaluate
98 * @func: the function to be called
99 * @info: the function call argument
101 * Calls the function @func when the task is currently running. This might
102 * be on the current CPU, which just calls the function directly. This will
103 * retry due to any failures in smp_call_function_single(), such as if the
104 * task_cpu() goes offline concurrently.
106 * returns @func return value or -ESRCH or -ENXIO when the process isn't running
109 task_function_call(struct task_struct
*p
, remote_function_f func
, void *info
)
111 struct remote_function_call data
= {
120 ret
= smp_call_function_single(task_cpu(p
), remote_function
,
135 * cpu_function_call - call a function on the cpu
136 * @cpu: target cpu to queue this function
137 * @func: the function to be called
138 * @info: the function call argument
140 * Calls the function @func on the remote cpu.
142 * returns: @func return value or -ENXIO when the cpu is offline
144 static int cpu_function_call(int cpu
, remote_function_f func
, void *info
)
146 struct remote_function_call data
= {
150 .ret
= -ENXIO
, /* No such CPU */
153 smp_call_function_single(cpu
, remote_function
, &data
, 1);
159 EVENT_FLEXIBLE
= 0x01,
163 /* see ctx_resched() for details */
167 /* compound helpers */
168 EVENT_ALL
= EVENT_FLEXIBLE
| EVENT_PINNED
,
169 EVENT_TIME_FROZEN
= EVENT_TIME
| EVENT_FROZEN
,
172 static inline void __perf_ctx_lock(struct perf_event_context
*ctx
)
174 raw_spin_lock(&ctx
->lock
);
175 WARN_ON_ONCE(ctx
->is_active
& EVENT_FROZEN
);
178 static void perf_ctx_lock(struct perf_cpu_context
*cpuctx
,
179 struct perf_event_context
*ctx
)
181 __perf_ctx_lock(&cpuctx
->ctx
);
183 __perf_ctx_lock(ctx
);
186 static inline void __perf_ctx_unlock(struct perf_event_context
*ctx
)
189 * If ctx_sched_in() didn't again set any ALL flags, clean up
190 * after ctx_sched_out() by clearing is_active.
192 if (ctx
->is_active
& EVENT_FROZEN
) {
193 if (!(ctx
->is_active
& EVENT_ALL
))
196 ctx
->is_active
&= ~EVENT_FROZEN
;
198 raw_spin_unlock(&ctx
->lock
);
201 static void perf_ctx_unlock(struct perf_cpu_context
*cpuctx
,
202 struct perf_event_context
*ctx
)
205 __perf_ctx_unlock(ctx
);
206 __perf_ctx_unlock(&cpuctx
->ctx
);
209 #define TASK_TOMBSTONE ((void *)-1L)
211 static bool is_kernel_event(struct perf_event
*event
)
213 return READ_ONCE(event
->owner
) == TASK_TOMBSTONE
;
216 static DEFINE_PER_CPU(struct perf_cpu_context
, perf_cpu_context
);
218 struct perf_event_context
*perf_cpu_task_ctx(void)
220 lockdep_assert_irqs_disabled();
221 return this_cpu_ptr(&perf_cpu_context
)->task_ctx
;
225 * On task ctx scheduling...
227 * When !ctx->nr_events a task context will not be scheduled. This means
228 * we can disable the scheduler hooks (for performance) without leaving
229 * pending task ctx state.
231 * This however results in two special cases:
233 * - removing the last event from a task ctx; this is relatively straight
234 * forward and is done in __perf_remove_from_context.
236 * - adding the first event to a task ctx; this is tricky because we cannot
237 * rely on ctx->is_active and therefore cannot use event_function_call().
238 * See perf_install_in_context().
240 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
243 typedef void (*event_f
)(struct perf_event
*, struct perf_cpu_context
*,
244 struct perf_event_context
*, void *);
246 struct event_function_struct
{
247 struct perf_event
*event
;
252 static int event_function(void *info
)
254 struct event_function_struct
*efs
= info
;
255 struct perf_event
*event
= efs
->event
;
256 struct perf_event_context
*ctx
= event
->ctx
;
257 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
258 struct perf_event_context
*task_ctx
= cpuctx
->task_ctx
;
261 lockdep_assert_irqs_disabled();
263 perf_ctx_lock(cpuctx
, task_ctx
);
265 * Since we do the IPI call without holding ctx->lock things can have
266 * changed, double check we hit the task we set out to hit.
269 if (ctx
->task
!= current
) {
275 * We only use event_function_call() on established contexts,
276 * and event_function() is only ever called when active (or
277 * rather, we'll have bailed in task_function_call() or the
278 * above ctx->task != current test), therefore we must have
279 * ctx->is_active here.
281 WARN_ON_ONCE(!ctx
->is_active
);
283 * And since we have ctx->is_active, cpuctx->task_ctx must
286 WARN_ON_ONCE(task_ctx
!= ctx
);
288 WARN_ON_ONCE(&cpuctx
->ctx
!= ctx
);
291 efs
->func(event
, cpuctx
, ctx
, efs
->data
);
293 perf_ctx_unlock(cpuctx
, task_ctx
);
298 static void event_function_call(struct perf_event
*event
, event_f func
, void *data
)
300 struct perf_event_context
*ctx
= event
->ctx
;
301 struct task_struct
*task
= READ_ONCE(ctx
->task
); /* verified in event_function */
302 struct perf_cpu_context
*cpuctx
;
303 struct event_function_struct efs
= {
309 if (!event
->parent
) {
311 * If this is a !child event, we must hold ctx::mutex to
312 * stabilize the event->ctx relation. See
313 * perf_event_ctx_lock().
315 lockdep_assert_held(&ctx
->mutex
);
319 cpu_function_call(event
->cpu
, event_function
, &efs
);
323 if (task
== TASK_TOMBSTONE
)
327 if (!task_function_call(task
, event_function
, &efs
))
331 cpuctx
= this_cpu_ptr(&perf_cpu_context
);
332 perf_ctx_lock(cpuctx
, ctx
);
334 * Reload the task pointer, it might have been changed by
335 * a concurrent perf_event_context_sched_out().
338 if (task
== TASK_TOMBSTONE
)
340 if (ctx
->is_active
) {
341 perf_ctx_unlock(cpuctx
, ctx
);
345 func(event
, NULL
, ctx
, data
);
347 perf_ctx_unlock(cpuctx
, ctx
);
352 * Similar to event_function_call() + event_function(), but hard assumes IRQs
353 * are already disabled and we're on the right CPU.
355 static void event_function_local(struct perf_event
*event
, event_f func
, void *data
)
357 struct perf_event_context
*ctx
= event
->ctx
;
358 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
359 struct task_struct
*task
= READ_ONCE(ctx
->task
);
360 struct perf_event_context
*task_ctx
= NULL
;
362 lockdep_assert_irqs_disabled();
365 if (task
== TASK_TOMBSTONE
)
371 perf_ctx_lock(cpuctx
, task_ctx
);
374 if (task
== TASK_TOMBSTONE
)
379 * We must be either inactive or active and the right task,
380 * otherwise we're screwed, since we cannot IPI to somewhere
383 if (ctx
->is_active
) {
384 if (WARN_ON_ONCE(task
!= current
))
387 if (WARN_ON_ONCE(cpuctx
->task_ctx
!= ctx
))
391 WARN_ON_ONCE(&cpuctx
->ctx
!= ctx
);
394 func(event
, cpuctx
, ctx
, data
);
396 perf_ctx_unlock(cpuctx
, task_ctx
);
399 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
400 PERF_FLAG_FD_OUTPUT |\
401 PERF_FLAG_PID_CGROUP |\
402 PERF_FLAG_FD_CLOEXEC)
405 * branch priv levels that need permission checks
407 #define PERF_SAMPLE_BRANCH_PERM_PLM \
408 (PERF_SAMPLE_BRANCH_KERNEL |\
409 PERF_SAMPLE_BRANCH_HV)
412 * perf_sched_events : >0 events exist
415 static void perf_sched_delayed(struct work_struct
*work
);
416 DEFINE_STATIC_KEY_FALSE(perf_sched_events
);
417 static DECLARE_DELAYED_WORK(perf_sched_work
, perf_sched_delayed
);
418 static DEFINE_MUTEX(perf_sched_mutex
);
419 static atomic_t perf_sched_count
;
421 static DEFINE_PER_CPU(struct pmu_event_list
, pmu_sb_events
);
423 static atomic_t nr_mmap_events __read_mostly
;
424 static atomic_t nr_comm_events __read_mostly
;
425 static atomic_t nr_namespaces_events __read_mostly
;
426 static atomic_t nr_task_events __read_mostly
;
427 static atomic_t nr_freq_events __read_mostly
;
428 static atomic_t nr_switch_events __read_mostly
;
429 static atomic_t nr_ksymbol_events __read_mostly
;
430 static atomic_t nr_bpf_events __read_mostly
;
431 static atomic_t nr_cgroup_events __read_mostly
;
432 static atomic_t nr_text_poke_events __read_mostly
;
433 static atomic_t nr_build_id_events __read_mostly
;
435 static LIST_HEAD(pmus
);
436 static DEFINE_MUTEX(pmus_lock
);
437 static struct srcu_struct pmus_srcu
;
438 static cpumask_var_t perf_online_mask
;
439 static cpumask_var_t perf_online_core_mask
;
440 static cpumask_var_t perf_online_die_mask
;
441 static cpumask_var_t perf_online_cluster_mask
;
442 static cpumask_var_t perf_online_pkg_mask
;
443 static cpumask_var_t perf_online_sys_mask
;
444 static struct kmem_cache
*perf_event_cache
;
447 * perf event paranoia level:
448 * -1 - not paranoid at all
449 * 0 - disallow raw tracepoint access for unpriv
450 * 1 - disallow cpu events for unpriv
451 * 2 - disallow kernel profiling for unpriv
453 int sysctl_perf_event_paranoid __read_mostly
= 2;
455 /* Minimum for 512 kiB + 1 user control page */
456 int sysctl_perf_event_mlock __read_mostly
= 512 + (PAGE_SIZE
/ 1024); /* 'free' kiB per user */
459 * max perf event sample rate
461 #define DEFAULT_MAX_SAMPLE_RATE 100000
462 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
463 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
465 int sysctl_perf_event_sample_rate __read_mostly
= DEFAULT_MAX_SAMPLE_RATE
;
467 static int max_samples_per_tick __read_mostly
= DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE
, HZ
);
468 static int perf_sample_period_ns __read_mostly
= DEFAULT_SAMPLE_PERIOD_NS
;
470 static int perf_sample_allowed_ns __read_mostly
=
471 DEFAULT_SAMPLE_PERIOD_NS
* DEFAULT_CPU_TIME_MAX_PERCENT
/ 100;
473 static void update_perf_cpu_limits(void)
475 u64 tmp
= perf_sample_period_ns
;
477 tmp
*= sysctl_perf_cpu_time_max_percent
;
478 tmp
= div_u64(tmp
, 100);
482 WRITE_ONCE(perf_sample_allowed_ns
, tmp
);
485 static bool perf_rotate_context(struct perf_cpu_pmu_context
*cpc
);
487 int perf_event_max_sample_rate_handler(const struct ctl_table
*table
, int write
,
488 void *buffer
, size_t *lenp
, loff_t
*ppos
)
491 int perf_cpu
= sysctl_perf_cpu_time_max_percent
;
493 * If throttling is disabled don't allow the write:
495 if (write
&& (perf_cpu
== 100 || perf_cpu
== 0))
498 ret
= proc_dointvec_minmax(table
, write
, buffer
, lenp
, ppos
);
502 max_samples_per_tick
= DIV_ROUND_UP(sysctl_perf_event_sample_rate
, HZ
);
503 perf_sample_period_ns
= NSEC_PER_SEC
/ sysctl_perf_event_sample_rate
;
504 update_perf_cpu_limits();
509 int sysctl_perf_cpu_time_max_percent __read_mostly
= DEFAULT_CPU_TIME_MAX_PERCENT
;
511 int perf_cpu_time_max_percent_handler(const struct ctl_table
*table
, int write
,
512 void *buffer
, size_t *lenp
, loff_t
*ppos
)
514 int ret
= proc_dointvec_minmax(table
, write
, buffer
, lenp
, ppos
);
519 if (sysctl_perf_cpu_time_max_percent
== 100 ||
520 sysctl_perf_cpu_time_max_percent
== 0) {
522 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
523 WRITE_ONCE(perf_sample_allowed_ns
, 0);
525 update_perf_cpu_limits();
532 * perf samples are done in some very critical code paths (NMIs).
533 * If they take too much CPU time, the system can lock up and not
534 * get any real work done. This will drop the sample rate when
535 * we detect that events are taking too long.
537 #define NR_ACCUMULATED_SAMPLES 128
538 static DEFINE_PER_CPU(u64
, running_sample_length
);
540 static u64 __report_avg
;
541 static u64 __report_allowed
;
543 static void perf_duration_warn(struct irq_work
*w
)
545 printk_ratelimited(KERN_INFO
546 "perf: interrupt took too long (%lld > %lld), lowering "
547 "kernel.perf_event_max_sample_rate to %d\n",
548 __report_avg
, __report_allowed
,
549 sysctl_perf_event_sample_rate
);
552 static DEFINE_IRQ_WORK(perf_duration_work
, perf_duration_warn
);
554 void perf_sample_event_took(u64 sample_len_ns
)
556 u64 max_len
= READ_ONCE(perf_sample_allowed_ns
);
564 /* Decay the counter by 1 average sample. */
565 running_len
= __this_cpu_read(running_sample_length
);
566 running_len
-= running_len
/NR_ACCUMULATED_SAMPLES
;
567 running_len
+= sample_len_ns
;
568 __this_cpu_write(running_sample_length
, running_len
);
571 * Note: this will be biased artificially low until we have
572 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
573 * from having to maintain a count.
575 avg_len
= running_len
/NR_ACCUMULATED_SAMPLES
;
576 if (avg_len
<= max_len
)
579 __report_avg
= avg_len
;
580 __report_allowed
= max_len
;
583 * Compute a throttle threshold 25% below the current duration.
585 avg_len
+= avg_len
/ 4;
586 max
= (TICK_NSEC
/ 100) * sysctl_perf_cpu_time_max_percent
;
592 WRITE_ONCE(perf_sample_allowed_ns
, avg_len
);
593 WRITE_ONCE(max_samples_per_tick
, max
);
595 sysctl_perf_event_sample_rate
= max
* HZ
;
596 perf_sample_period_ns
= NSEC_PER_SEC
/ sysctl_perf_event_sample_rate
;
598 if (!irq_work_queue(&perf_duration_work
)) {
599 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
600 "kernel.perf_event_max_sample_rate to %d\n",
601 __report_avg
, __report_allowed
,
602 sysctl_perf_event_sample_rate
);
606 static atomic64_t perf_event_id
;
608 static void update_context_time(struct perf_event_context
*ctx
);
609 static u64
perf_event_time(struct perf_event
*event
);
611 void __weak
perf_event_print_debug(void) { }
613 static inline u64
perf_clock(void)
615 return local_clock();
618 static inline u64
perf_event_clock(struct perf_event
*event
)
620 return event
->clock();
624 * State based event timekeeping...
626 * The basic idea is to use event->state to determine which (if any) time
627 * fields to increment with the current delta. This means we only need to
628 * update timestamps when we change state or when they are explicitly requested
631 * Event groups make things a little more complicated, but not terribly so. The
632 * rules for a group are that if the group leader is OFF the entire group is
633 * OFF, irrespective of what the group member states are. This results in
634 * __perf_effective_state().
636 * A further ramification is that when a group leader flips between OFF and
637 * !OFF, we need to update all group member times.
640 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
641 * need to make sure the relevant context time is updated before we try and
642 * update our timestamps.
645 static __always_inline
enum perf_event_state
646 __perf_effective_state(struct perf_event
*event
)
648 struct perf_event
*leader
= event
->group_leader
;
650 if (leader
->state
<= PERF_EVENT_STATE_OFF
)
651 return leader
->state
;
656 static __always_inline
void
657 __perf_update_times(struct perf_event
*event
, u64 now
, u64
*enabled
, u64
*running
)
659 enum perf_event_state state
= __perf_effective_state(event
);
660 u64 delta
= now
- event
->tstamp
;
662 *enabled
= event
->total_time_enabled
;
663 if (state
>= PERF_EVENT_STATE_INACTIVE
)
666 *running
= event
->total_time_running
;
667 if (state
>= PERF_EVENT_STATE_ACTIVE
)
671 static void perf_event_update_time(struct perf_event
*event
)
673 u64 now
= perf_event_time(event
);
675 __perf_update_times(event
, now
, &event
->total_time_enabled
,
676 &event
->total_time_running
);
680 static void perf_event_update_sibling_time(struct perf_event
*leader
)
682 struct perf_event
*sibling
;
684 for_each_sibling_event(sibling
, leader
)
685 perf_event_update_time(sibling
);
689 perf_event_set_state(struct perf_event
*event
, enum perf_event_state state
)
691 if (event
->state
== state
)
694 perf_event_update_time(event
);
696 * If a group leader gets enabled/disabled all its siblings
699 if ((event
->state
< 0) ^ (state
< 0))
700 perf_event_update_sibling_time(event
);
702 WRITE_ONCE(event
->state
, state
);
706 * UP store-release, load-acquire
709 #define __store_release(ptr, val) \
712 WRITE_ONCE(*(ptr), (val)); \
715 #define __load_acquire(ptr) \
717 __unqual_scalar_typeof(*(ptr)) ___p = READ_ONCE(*(ptr)); \
722 #define for_each_epc(_epc, _ctx, _pmu, _cgroup) \
723 list_for_each_entry(_epc, &((_ctx)->pmu_ctx_list), pmu_ctx_entry) \
724 if (_cgroup && !_epc->nr_cgroups) \
726 else if (_pmu && _epc->pmu != _pmu) \
730 static void perf_ctx_disable(struct perf_event_context
*ctx
, bool cgroup
)
732 struct perf_event_pmu_context
*pmu_ctx
;
734 for_each_epc(pmu_ctx
, ctx
, NULL
, cgroup
)
735 perf_pmu_disable(pmu_ctx
->pmu
);
738 static void perf_ctx_enable(struct perf_event_context
*ctx
, bool cgroup
)
740 struct perf_event_pmu_context
*pmu_ctx
;
742 for_each_epc(pmu_ctx
, ctx
, NULL
, cgroup
)
743 perf_pmu_enable(pmu_ctx
->pmu
);
746 static void ctx_sched_out(struct perf_event_context
*ctx
, struct pmu
*pmu
, enum event_type_t event_type
);
747 static void ctx_sched_in(struct perf_event_context
*ctx
, struct pmu
*pmu
, enum event_type_t event_type
);
749 #ifdef CONFIG_CGROUP_PERF
752 perf_cgroup_match(struct perf_event
*event
)
754 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
756 /* @event doesn't care about cgroup */
760 /* wants specific cgroup scope but @cpuctx isn't associated with any */
765 * Cgroup scoping is recursive. An event enabled for a cgroup is
766 * also enabled for all its descendant cgroups. If @cpuctx's
767 * cgroup is a descendant of @event's (the test covers identity
768 * case), it's a match.
770 return cgroup_is_descendant(cpuctx
->cgrp
->css
.cgroup
,
771 event
->cgrp
->css
.cgroup
);
774 static inline void perf_detach_cgroup(struct perf_event
*event
)
776 css_put(&event
->cgrp
->css
);
780 static inline int is_cgroup_event(struct perf_event
*event
)
782 return event
->cgrp
!= NULL
;
785 static inline u64
perf_cgroup_event_time(struct perf_event
*event
)
787 struct perf_cgroup_info
*t
;
789 t
= per_cpu_ptr(event
->cgrp
->info
, event
->cpu
);
793 static inline u64
perf_cgroup_event_time_now(struct perf_event
*event
, u64 now
)
795 struct perf_cgroup_info
*t
;
797 t
= per_cpu_ptr(event
->cgrp
->info
, event
->cpu
);
798 if (!__load_acquire(&t
->active
))
800 now
+= READ_ONCE(t
->timeoffset
);
804 static inline void __update_cgrp_time(struct perf_cgroup_info
*info
, u64 now
, bool adv
)
807 info
->time
+= now
- info
->timestamp
;
808 info
->timestamp
= now
;
810 * see update_context_time()
812 WRITE_ONCE(info
->timeoffset
, info
->time
- info
->timestamp
);
815 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context
*cpuctx
, bool final
)
817 struct perf_cgroup
*cgrp
= cpuctx
->cgrp
;
818 struct cgroup_subsys_state
*css
;
819 struct perf_cgroup_info
*info
;
822 u64 now
= perf_clock();
824 for (css
= &cgrp
->css
; css
; css
= css
->parent
) {
825 cgrp
= container_of(css
, struct perf_cgroup
, css
);
826 info
= this_cpu_ptr(cgrp
->info
);
828 __update_cgrp_time(info
, now
, true);
830 __store_release(&info
->active
, 0);
835 static inline void update_cgrp_time_from_event(struct perf_event
*event
)
837 struct perf_cgroup_info
*info
;
840 * ensure we access cgroup data only when needed and
841 * when we know the cgroup is pinned (css_get)
843 if (!is_cgroup_event(event
))
846 info
= this_cpu_ptr(event
->cgrp
->info
);
848 * Do not update time when cgroup is not active
851 __update_cgrp_time(info
, perf_clock(), true);
855 perf_cgroup_set_timestamp(struct perf_cpu_context
*cpuctx
)
857 struct perf_event_context
*ctx
= &cpuctx
->ctx
;
858 struct perf_cgroup
*cgrp
= cpuctx
->cgrp
;
859 struct perf_cgroup_info
*info
;
860 struct cgroup_subsys_state
*css
;
863 * ctx->lock held by caller
864 * ensure we do not access cgroup data
865 * unless we have the cgroup pinned (css_get)
870 WARN_ON_ONCE(!ctx
->nr_cgroups
);
872 for (css
= &cgrp
->css
; css
; css
= css
->parent
) {
873 cgrp
= container_of(css
, struct perf_cgroup
, css
);
874 info
= this_cpu_ptr(cgrp
->info
);
875 __update_cgrp_time(info
, ctx
->timestamp
, false);
876 __store_release(&info
->active
, 1);
881 * reschedule events based on the cgroup constraint of task.
883 static void perf_cgroup_switch(struct task_struct
*task
)
885 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
886 struct perf_cgroup
*cgrp
;
889 * cpuctx->cgrp is set when the first cgroup event enabled,
890 * and is cleared when the last cgroup event disabled.
892 if (READ_ONCE(cpuctx
->cgrp
) == NULL
)
895 WARN_ON_ONCE(cpuctx
->ctx
.nr_cgroups
== 0);
897 cgrp
= perf_cgroup_from_task(task
, NULL
);
898 if (READ_ONCE(cpuctx
->cgrp
) == cgrp
)
901 perf_ctx_lock(cpuctx
, cpuctx
->task_ctx
);
902 perf_ctx_disable(&cpuctx
->ctx
, true);
904 ctx_sched_out(&cpuctx
->ctx
, NULL
, EVENT_ALL
|EVENT_CGROUP
);
906 * must not be done before ctxswout due
907 * to update_cgrp_time_from_cpuctx() in
912 * set cgrp before ctxsw in to allow
913 * perf_cgroup_set_timestamp() in ctx_sched_in()
914 * to not have to pass task around
916 ctx_sched_in(&cpuctx
->ctx
, NULL
, EVENT_ALL
|EVENT_CGROUP
);
918 perf_ctx_enable(&cpuctx
->ctx
, true);
919 perf_ctx_unlock(cpuctx
, cpuctx
->task_ctx
);
922 static int perf_cgroup_ensure_storage(struct perf_event
*event
,
923 struct cgroup_subsys_state
*css
)
925 struct perf_cpu_context
*cpuctx
;
926 struct perf_event
**storage
;
927 int cpu
, heap_size
, ret
= 0;
930 * Allow storage to have sufficient space for an iterator for each
931 * possibly nested cgroup plus an iterator for events with no cgroup.
933 for (heap_size
= 1; css
; css
= css
->parent
)
936 for_each_possible_cpu(cpu
) {
937 cpuctx
= per_cpu_ptr(&perf_cpu_context
, cpu
);
938 if (heap_size
<= cpuctx
->heap_size
)
941 storage
= kmalloc_node(heap_size
* sizeof(struct perf_event
*),
942 GFP_KERNEL
, cpu_to_node(cpu
));
948 raw_spin_lock_irq(&cpuctx
->ctx
.lock
);
949 if (cpuctx
->heap_size
< heap_size
) {
950 swap(cpuctx
->heap
, storage
);
951 if (storage
== cpuctx
->heap_default
)
953 cpuctx
->heap_size
= heap_size
;
955 raw_spin_unlock_irq(&cpuctx
->ctx
.lock
);
963 static inline int perf_cgroup_connect(int fd
, struct perf_event
*event
,
964 struct perf_event_attr
*attr
,
965 struct perf_event
*group_leader
)
967 struct perf_cgroup
*cgrp
;
968 struct cgroup_subsys_state
*css
;
969 struct fd f
= fdget(fd
);
975 css
= css_tryget_online_from_dir(fd_file(f
)->f_path
.dentry
,
976 &perf_event_cgrp_subsys
);
982 ret
= perf_cgroup_ensure_storage(event
, css
);
986 cgrp
= container_of(css
, struct perf_cgroup
, css
);
990 * all events in a group must monitor
991 * the same cgroup because a task belongs
992 * to only one perf cgroup at a time
994 if (group_leader
&& group_leader
->cgrp
!= cgrp
) {
995 perf_detach_cgroup(event
);
1004 perf_cgroup_event_enable(struct perf_event
*event
, struct perf_event_context
*ctx
)
1006 struct perf_cpu_context
*cpuctx
;
1008 if (!is_cgroup_event(event
))
1011 event
->pmu_ctx
->nr_cgroups
++;
1014 * Because cgroup events are always per-cpu events,
1015 * @ctx == &cpuctx->ctx.
1017 cpuctx
= container_of(ctx
, struct perf_cpu_context
, ctx
);
1019 if (ctx
->nr_cgroups
++)
1022 cpuctx
->cgrp
= perf_cgroup_from_task(current
, ctx
);
1026 perf_cgroup_event_disable(struct perf_event
*event
, struct perf_event_context
*ctx
)
1028 struct perf_cpu_context
*cpuctx
;
1030 if (!is_cgroup_event(event
))
1033 event
->pmu_ctx
->nr_cgroups
--;
1036 * Because cgroup events are always per-cpu events,
1037 * @ctx == &cpuctx->ctx.
1039 cpuctx
= container_of(ctx
, struct perf_cpu_context
, ctx
);
1041 if (--ctx
->nr_cgroups
)
1044 cpuctx
->cgrp
= NULL
;
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
,
1072 static inline int perf_cgroup_connect(pid_t pid
, struct perf_event
*event
,
1073 struct perf_event_attr
*attr
,
1074 struct perf_event
*group_leader
)
1080 perf_cgroup_set_timestamp(struct perf_cpu_context
*cpuctx
)
1084 static inline u64
perf_cgroup_event_time(struct perf_event
*event
)
1089 static inline u64
perf_cgroup_event_time_now(struct perf_event
*event
, u64 now
)
1095 perf_cgroup_event_enable(struct perf_event
*event
, struct perf_event_context
*ctx
)
1100 perf_cgroup_event_disable(struct perf_event
*event
, struct perf_event_context
*ctx
)
1104 static void perf_cgroup_switch(struct task_struct
*task
)
1110 * set default to be dependent on timer tick just
1111 * like original code
1113 #define PERF_CPU_HRTIMER (1000 / HZ)
1115 * function must be called with interrupts disabled
1117 static enum hrtimer_restart
perf_mux_hrtimer_handler(struct hrtimer
*hr
)
1119 struct perf_cpu_pmu_context
*cpc
;
1122 lockdep_assert_irqs_disabled();
1124 cpc
= container_of(hr
, struct perf_cpu_pmu_context
, hrtimer
);
1125 rotations
= perf_rotate_context(cpc
);
1127 raw_spin_lock(&cpc
->hrtimer_lock
);
1129 hrtimer_forward_now(hr
, cpc
->hrtimer_interval
);
1131 cpc
->hrtimer_active
= 0;
1132 raw_spin_unlock(&cpc
->hrtimer_lock
);
1134 return rotations
? HRTIMER_RESTART
: HRTIMER_NORESTART
;
1137 static void __perf_mux_hrtimer_init(struct perf_cpu_pmu_context
*cpc
, int cpu
)
1139 struct hrtimer
*timer
= &cpc
->hrtimer
;
1140 struct pmu
*pmu
= cpc
->epc
.pmu
;
1144 * check default is sane, if not set then force to
1145 * default interval (1/tick)
1147 interval
= pmu
->hrtimer_interval_ms
;
1149 interval
= pmu
->hrtimer_interval_ms
= PERF_CPU_HRTIMER
;
1151 cpc
->hrtimer_interval
= ns_to_ktime(NSEC_PER_MSEC
* interval
);
1153 raw_spin_lock_init(&cpc
->hrtimer_lock
);
1154 hrtimer_init(timer
, CLOCK_MONOTONIC
, HRTIMER_MODE_ABS_PINNED_HARD
);
1155 timer
->function
= perf_mux_hrtimer_handler
;
1158 static int perf_mux_hrtimer_restart(struct perf_cpu_pmu_context
*cpc
)
1160 struct hrtimer
*timer
= &cpc
->hrtimer
;
1161 unsigned long flags
;
1163 raw_spin_lock_irqsave(&cpc
->hrtimer_lock
, flags
);
1164 if (!cpc
->hrtimer_active
) {
1165 cpc
->hrtimer_active
= 1;
1166 hrtimer_forward_now(timer
, cpc
->hrtimer_interval
);
1167 hrtimer_start_expires(timer
, HRTIMER_MODE_ABS_PINNED_HARD
);
1169 raw_spin_unlock_irqrestore(&cpc
->hrtimer_lock
, flags
);
1174 static int perf_mux_hrtimer_restart_ipi(void *arg
)
1176 return perf_mux_hrtimer_restart(arg
);
1179 void perf_pmu_disable(struct pmu
*pmu
)
1181 int *count
= this_cpu_ptr(pmu
->pmu_disable_count
);
1183 pmu
->pmu_disable(pmu
);
1186 void perf_pmu_enable(struct pmu
*pmu
)
1188 int *count
= this_cpu_ptr(pmu
->pmu_disable_count
);
1190 pmu
->pmu_enable(pmu
);
1193 static void perf_assert_pmu_disabled(struct pmu
*pmu
)
1195 WARN_ON_ONCE(*this_cpu_ptr(pmu
->pmu_disable_count
) == 0);
1198 static void get_ctx(struct perf_event_context
*ctx
)
1200 refcount_inc(&ctx
->refcount
);
1203 static void *alloc_task_ctx_data(struct pmu
*pmu
)
1205 if (pmu
->task_ctx_cache
)
1206 return kmem_cache_zalloc(pmu
->task_ctx_cache
, GFP_KERNEL
);
1211 static void free_task_ctx_data(struct pmu
*pmu
, void *task_ctx_data
)
1213 if (pmu
->task_ctx_cache
&& task_ctx_data
)
1214 kmem_cache_free(pmu
->task_ctx_cache
, task_ctx_data
);
1217 static void free_ctx(struct rcu_head
*head
)
1219 struct perf_event_context
*ctx
;
1221 ctx
= container_of(head
, struct perf_event_context
, rcu_head
);
1225 static void put_ctx(struct perf_event_context
*ctx
)
1227 if (refcount_dec_and_test(&ctx
->refcount
)) {
1228 if (ctx
->parent_ctx
)
1229 put_ctx(ctx
->parent_ctx
);
1230 if (ctx
->task
&& ctx
->task
!= TASK_TOMBSTONE
)
1231 put_task_struct(ctx
->task
);
1232 call_rcu(&ctx
->rcu_head
, free_ctx
);
1237 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1238 * perf_pmu_migrate_context() we need some magic.
1240 * Those places that change perf_event::ctx will hold both
1241 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1243 * Lock ordering is by mutex address. There are two other sites where
1244 * perf_event_context::mutex nests and those are:
1246 * - perf_event_exit_task_context() [ child , 0 ]
1247 * perf_event_exit_event()
1248 * put_event() [ parent, 1 ]
1250 * - perf_event_init_context() [ parent, 0 ]
1251 * inherit_task_group()
1254 * perf_event_alloc()
1256 * perf_try_init_event() [ child , 1 ]
1258 * While it appears there is an obvious deadlock here -- the parent and child
1259 * nesting levels are inverted between the two. This is in fact safe because
1260 * life-time rules separate them. That is an exiting task cannot fork, and a
1261 * spawning task cannot (yet) exit.
1263 * But remember that these are parent<->child context relations, and
1264 * migration does not affect children, therefore these two orderings should not
1267 * The change in perf_event::ctx does not affect children (as claimed above)
1268 * because the sys_perf_event_open() case will install a new event and break
1269 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1270 * concerned with cpuctx and that doesn't have children.
1272 * The places that change perf_event::ctx will issue:
1274 * perf_remove_from_context();
1275 * synchronize_rcu();
1276 * perf_install_in_context();
1278 * to affect the change. The remove_from_context() + synchronize_rcu() should
1279 * quiesce the event, after which we can install it in the new location. This
1280 * means that only external vectors (perf_fops, prctl) can perturb the event
1281 * while in transit. Therefore all such accessors should also acquire
1282 * perf_event_context::mutex to serialize against this.
1284 * However; because event->ctx can change while we're waiting to acquire
1285 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1290 * task_struct::perf_event_mutex
1291 * perf_event_context::mutex
1292 * perf_event::child_mutex;
1293 * perf_event_context::lock
1295 * perf_event::mmap_mutex
1296 * perf_buffer::aux_mutex
1297 * perf_addr_filters_head::lock
1301 * cpuctx->mutex / perf_event_context::mutex
1303 static struct perf_event_context
*
1304 perf_event_ctx_lock_nested(struct perf_event
*event
, int nesting
)
1306 struct perf_event_context
*ctx
;
1310 ctx
= READ_ONCE(event
->ctx
);
1311 if (!refcount_inc_not_zero(&ctx
->refcount
)) {
1317 mutex_lock_nested(&ctx
->mutex
, nesting
);
1318 if (event
->ctx
!= ctx
) {
1319 mutex_unlock(&ctx
->mutex
);
1327 static inline struct perf_event_context
*
1328 perf_event_ctx_lock(struct perf_event
*event
)
1330 return perf_event_ctx_lock_nested(event
, 0);
1333 static void perf_event_ctx_unlock(struct perf_event
*event
,
1334 struct perf_event_context
*ctx
)
1336 mutex_unlock(&ctx
->mutex
);
1341 * This must be done under the ctx->lock, such as to serialize against
1342 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1343 * calling scheduler related locks and ctx->lock nests inside those.
1345 static __must_check
struct perf_event_context
*
1346 unclone_ctx(struct perf_event_context
*ctx
)
1348 struct perf_event_context
*parent_ctx
= ctx
->parent_ctx
;
1350 lockdep_assert_held(&ctx
->lock
);
1353 ctx
->parent_ctx
= NULL
;
1359 static u32
perf_event_pid_type(struct perf_event
*event
, struct task_struct
*p
,
1364 * only top level events have the pid namespace they were created in
1367 event
= event
->parent
;
1369 nr
= __task_pid_nr_ns(p
, type
, event
->ns
);
1370 /* avoid -1 if it is idle thread or runs in another ns */
1371 if (!nr
&& !pid_alive(p
))
1376 static u32
perf_event_pid(struct perf_event
*event
, struct task_struct
*p
)
1378 return perf_event_pid_type(event
, p
, PIDTYPE_TGID
);
1381 static u32
perf_event_tid(struct perf_event
*event
, struct task_struct
*p
)
1383 return perf_event_pid_type(event
, p
, PIDTYPE_PID
);
1387 * If we inherit events we want to return the parent event id
1390 static u64
primary_event_id(struct perf_event
*event
)
1395 id
= event
->parent
->id
;
1401 * Get the perf_event_context for a task and lock it.
1403 * This has to cope with the fact that until it is locked,
1404 * the context could get moved to another task.
1406 static struct perf_event_context
*
1407 perf_lock_task_context(struct task_struct
*task
, unsigned long *flags
)
1409 struct perf_event_context
*ctx
;
1413 * One of the few rules of preemptible RCU is that one cannot do
1414 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1415 * part of the read side critical section was irqs-enabled -- see
1416 * rcu_read_unlock_special().
1418 * Since ctx->lock nests under rq->lock we must ensure the entire read
1419 * side critical section has interrupts disabled.
1421 local_irq_save(*flags
);
1423 ctx
= rcu_dereference(task
->perf_event_ctxp
);
1426 * If this context is a clone of another, it might
1427 * get swapped for another underneath us by
1428 * perf_event_task_sched_out, though the
1429 * rcu_read_lock() protects us from any context
1430 * getting freed. Lock the context and check if it
1431 * got swapped before we could get the lock, and retry
1432 * if so. If we locked the right context, then it
1433 * can't get swapped on us any more.
1435 raw_spin_lock(&ctx
->lock
);
1436 if (ctx
!= rcu_dereference(task
->perf_event_ctxp
)) {
1437 raw_spin_unlock(&ctx
->lock
);
1439 local_irq_restore(*flags
);
1443 if (ctx
->task
== TASK_TOMBSTONE
||
1444 !refcount_inc_not_zero(&ctx
->refcount
)) {
1445 raw_spin_unlock(&ctx
->lock
);
1448 WARN_ON_ONCE(ctx
->task
!= task
);
1453 local_irq_restore(*flags
);
1458 * Get the context for a task and increment its pin_count so it
1459 * can't get swapped to another task. This also increments its
1460 * reference count so that the context can't get freed.
1462 static struct perf_event_context
*
1463 perf_pin_task_context(struct task_struct
*task
)
1465 struct perf_event_context
*ctx
;
1466 unsigned long flags
;
1468 ctx
= perf_lock_task_context(task
, &flags
);
1471 raw_spin_unlock_irqrestore(&ctx
->lock
, flags
);
1476 static void perf_unpin_context(struct perf_event_context
*ctx
)
1478 unsigned long flags
;
1480 raw_spin_lock_irqsave(&ctx
->lock
, flags
);
1482 raw_spin_unlock_irqrestore(&ctx
->lock
, flags
);
1486 * Update the record of the current time in a context.
1488 static void __update_context_time(struct perf_event_context
*ctx
, bool adv
)
1490 u64 now
= perf_clock();
1492 lockdep_assert_held(&ctx
->lock
);
1495 ctx
->time
+= now
- ctx
->timestamp
;
1496 ctx
->timestamp
= now
;
1499 * The above: time' = time + (now - timestamp), can be re-arranged
1500 * into: time` = now + (time - timestamp), which gives a single value
1501 * offset to compute future time without locks on.
1503 * See perf_event_time_now(), which can be used from NMI context where
1504 * it's (obviously) not possible to acquire ctx->lock in order to read
1505 * both the above values in a consistent manner.
1507 WRITE_ONCE(ctx
->timeoffset
, ctx
->time
- ctx
->timestamp
);
1510 static void update_context_time(struct perf_event_context
*ctx
)
1512 __update_context_time(ctx
, true);
1515 static u64
perf_event_time(struct perf_event
*event
)
1517 struct perf_event_context
*ctx
= event
->ctx
;
1522 if (is_cgroup_event(event
))
1523 return perf_cgroup_event_time(event
);
1528 static u64
perf_event_time_now(struct perf_event
*event
, u64 now
)
1530 struct perf_event_context
*ctx
= event
->ctx
;
1535 if (is_cgroup_event(event
))
1536 return perf_cgroup_event_time_now(event
, now
);
1538 if (!(__load_acquire(&ctx
->is_active
) & EVENT_TIME
))
1541 now
+= READ_ONCE(ctx
->timeoffset
);
1545 static enum event_type_t
get_event_type(struct perf_event
*event
)
1547 struct perf_event_context
*ctx
= event
->ctx
;
1548 enum event_type_t event_type
;
1550 lockdep_assert_held(&ctx
->lock
);
1553 * It's 'group type', really, because if our group leader is
1554 * pinned, so are we.
1556 if (event
->group_leader
!= event
)
1557 event
= event
->group_leader
;
1559 event_type
= event
->attr
.pinned
? EVENT_PINNED
: EVENT_FLEXIBLE
;
1561 event_type
|= EVENT_CPU
;
1567 * Helper function to initialize event group nodes.
1569 static void init_event_group(struct perf_event
*event
)
1571 RB_CLEAR_NODE(&event
->group_node
);
1572 event
->group_index
= 0;
1576 * Extract pinned or flexible groups from the context
1577 * based on event attrs bits.
1579 static struct perf_event_groups
*
1580 get_event_groups(struct perf_event
*event
, struct perf_event_context
*ctx
)
1582 if (event
->attr
.pinned
)
1583 return &ctx
->pinned_groups
;
1585 return &ctx
->flexible_groups
;
1589 * Helper function to initializes perf_event_group trees.
1591 static void perf_event_groups_init(struct perf_event_groups
*groups
)
1593 groups
->tree
= RB_ROOT
;
1597 static inline struct cgroup
*event_cgroup(const struct perf_event
*event
)
1599 struct cgroup
*cgroup
= NULL
;
1601 #ifdef CONFIG_CGROUP_PERF
1603 cgroup
= event
->cgrp
->css
.cgroup
;
1610 * Compare function for event groups;
1612 * Implements complex key that first sorts by CPU and then by virtual index
1613 * which provides ordering when rotating groups for the same CPU.
1615 static __always_inline
int
1616 perf_event_groups_cmp(const int left_cpu
, const struct pmu
*left_pmu
,
1617 const struct cgroup
*left_cgroup
, const u64 left_group_index
,
1618 const struct perf_event
*right
)
1620 if (left_cpu
< right
->cpu
)
1622 if (left_cpu
> right
->cpu
)
1626 if (left_pmu
< right
->pmu_ctx
->pmu
)
1628 if (left_pmu
> right
->pmu_ctx
->pmu
)
1632 #ifdef CONFIG_CGROUP_PERF
1634 const struct cgroup
*right_cgroup
= event_cgroup(right
);
1636 if (left_cgroup
!= right_cgroup
) {
1639 * Left has no cgroup but right does, no
1640 * cgroups come first.
1644 if (!right_cgroup
) {
1646 * Right has no cgroup but left does, no
1647 * cgroups come first.
1651 /* Two dissimilar cgroups, order by id. */
1652 if (cgroup_id(left_cgroup
) < cgroup_id(right_cgroup
))
1660 if (left_group_index
< right
->group_index
)
1662 if (left_group_index
> right
->group_index
)
1668 #define __node_2_pe(node) \
1669 rb_entry((node), struct perf_event, group_node)
1671 static inline bool __group_less(struct rb_node
*a
, const struct rb_node
*b
)
1673 struct perf_event
*e
= __node_2_pe(a
);
1674 return perf_event_groups_cmp(e
->cpu
, e
->pmu_ctx
->pmu
, event_cgroup(e
),
1675 e
->group_index
, __node_2_pe(b
)) < 0;
1678 struct __group_key
{
1681 struct cgroup
*cgroup
;
1684 static inline int __group_cmp(const void *key
, const struct rb_node
*node
)
1686 const struct __group_key
*a
= key
;
1687 const struct perf_event
*b
= __node_2_pe(node
);
1689 /* partial/subtree match: @cpu, @pmu, @cgroup; ignore: @group_index */
1690 return perf_event_groups_cmp(a
->cpu
, a
->pmu
, a
->cgroup
, b
->group_index
, b
);
1694 __group_cmp_ignore_cgroup(const void *key
, const struct rb_node
*node
)
1696 const struct __group_key
*a
= key
;
1697 const struct perf_event
*b
= __node_2_pe(node
);
1699 /* partial/subtree match: @cpu, @pmu, ignore: @cgroup, @group_index */
1700 return perf_event_groups_cmp(a
->cpu
, a
->pmu
, event_cgroup(b
),
1705 * Insert @event into @groups' tree; using
1706 * {@event->cpu, @event->pmu_ctx->pmu, event_cgroup(@event), ++@groups->index}
1707 * as key. This places it last inside the {cpu,pmu,cgroup} subtree.
1710 perf_event_groups_insert(struct perf_event_groups
*groups
,
1711 struct perf_event
*event
)
1713 event
->group_index
= ++groups
->index
;
1715 rb_add(&event
->group_node
, &groups
->tree
, __group_less
);
1719 * Helper function to insert event into the pinned or flexible groups.
1722 add_event_to_groups(struct perf_event
*event
, struct perf_event_context
*ctx
)
1724 struct perf_event_groups
*groups
;
1726 groups
= get_event_groups(event
, ctx
);
1727 perf_event_groups_insert(groups
, event
);
1731 * Delete a group from a tree.
1734 perf_event_groups_delete(struct perf_event_groups
*groups
,
1735 struct perf_event
*event
)
1737 WARN_ON_ONCE(RB_EMPTY_NODE(&event
->group_node
) ||
1738 RB_EMPTY_ROOT(&groups
->tree
));
1740 rb_erase(&event
->group_node
, &groups
->tree
);
1741 init_event_group(event
);
1745 * Helper function to delete event from its groups.
1748 del_event_from_groups(struct perf_event
*event
, struct perf_event_context
*ctx
)
1750 struct perf_event_groups
*groups
;
1752 groups
= get_event_groups(event
, ctx
);
1753 perf_event_groups_delete(groups
, event
);
1757 * Get the leftmost event in the {cpu,pmu,cgroup} subtree.
1759 static struct perf_event
*
1760 perf_event_groups_first(struct perf_event_groups
*groups
, int cpu
,
1761 struct pmu
*pmu
, struct cgroup
*cgrp
)
1763 struct __group_key key
= {
1768 struct rb_node
*node
;
1770 node
= rb_find_first(&key
, &groups
->tree
, __group_cmp
);
1772 return __node_2_pe(node
);
1777 static struct perf_event
*
1778 perf_event_groups_next(struct perf_event
*event
, struct pmu
*pmu
)
1780 struct __group_key key
= {
1783 .cgroup
= event_cgroup(event
),
1785 struct rb_node
*next
;
1787 next
= rb_next_match(&key
, &event
->group_node
, __group_cmp
);
1789 return __node_2_pe(next
);
1794 #define perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) \
1795 for (event = perf_event_groups_first(groups, cpu, pmu, NULL); \
1796 event; event = perf_event_groups_next(event, pmu))
1799 * Iterate through the whole groups tree.
1801 #define perf_event_groups_for_each(event, groups) \
1802 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1803 typeof(*event), group_node); event; \
1804 event = rb_entry_safe(rb_next(&event->group_node), \
1805 typeof(*event), group_node))
1808 * Does the event attribute request inherit with PERF_SAMPLE_READ
1810 static inline bool has_inherit_and_sample_read(struct perf_event_attr
*attr
)
1812 return attr
->inherit
&& (attr
->sample_type
& PERF_SAMPLE_READ
);
1816 * Add an event from the lists for its context.
1817 * Must be called with ctx->mutex and ctx->lock held.
1820 list_add_event(struct perf_event
*event
, struct perf_event_context
*ctx
)
1822 lockdep_assert_held(&ctx
->lock
);
1824 WARN_ON_ONCE(event
->attach_state
& PERF_ATTACH_CONTEXT
);
1825 event
->attach_state
|= PERF_ATTACH_CONTEXT
;
1827 event
->tstamp
= perf_event_time(event
);
1830 * If we're a stand alone event or group leader, we go to the context
1831 * list, group events are kept attached to the group so that
1832 * perf_group_detach can, at all times, locate all siblings.
1834 if (event
->group_leader
== event
) {
1835 event
->group_caps
= event
->event_caps
;
1836 add_event_to_groups(event
, ctx
);
1839 list_add_rcu(&event
->event_entry
, &ctx
->event_list
);
1841 if (event
->hw
.flags
& PERF_EVENT_FLAG_USER_READ_CNT
)
1843 if (event
->attr
.inherit_stat
)
1845 if (has_inherit_and_sample_read(&event
->attr
))
1846 local_inc(&ctx
->nr_no_switch_fast
);
1848 if (event
->state
> PERF_EVENT_STATE_OFF
)
1849 perf_cgroup_event_enable(event
, ctx
);
1852 event
->pmu_ctx
->nr_events
++;
1856 * Initialize event state based on the perf_event_attr::disabled.
1858 static inline void perf_event__state_init(struct perf_event
*event
)
1860 event
->state
= event
->attr
.disabled
? PERF_EVENT_STATE_OFF
:
1861 PERF_EVENT_STATE_INACTIVE
;
1864 static int __perf_event_read_size(u64 read_format
, int nr_siblings
)
1866 int entry
= sizeof(u64
); /* value */
1870 if (read_format
& PERF_FORMAT_TOTAL_TIME_ENABLED
)
1871 size
+= sizeof(u64
);
1873 if (read_format
& PERF_FORMAT_TOTAL_TIME_RUNNING
)
1874 size
+= sizeof(u64
);
1876 if (read_format
& PERF_FORMAT_ID
)
1877 entry
+= sizeof(u64
);
1879 if (read_format
& PERF_FORMAT_LOST
)
1880 entry
+= sizeof(u64
);
1882 if (read_format
& PERF_FORMAT_GROUP
) {
1884 size
+= sizeof(u64
);
1888 * Since perf_event_validate_size() limits this to 16k and inhibits
1889 * adding more siblings, this will never overflow.
1891 return size
+ nr
* entry
;
1894 static void __perf_event_header_size(struct perf_event
*event
, u64 sample_type
)
1896 struct perf_sample_data
*data
;
1899 if (sample_type
& PERF_SAMPLE_IP
)
1900 size
+= sizeof(data
->ip
);
1902 if (sample_type
& PERF_SAMPLE_ADDR
)
1903 size
+= sizeof(data
->addr
);
1905 if (sample_type
& PERF_SAMPLE_PERIOD
)
1906 size
+= sizeof(data
->period
);
1908 if (sample_type
& PERF_SAMPLE_WEIGHT_TYPE
)
1909 size
+= sizeof(data
->weight
.full
);
1911 if (sample_type
& PERF_SAMPLE_READ
)
1912 size
+= event
->read_size
;
1914 if (sample_type
& PERF_SAMPLE_DATA_SRC
)
1915 size
+= sizeof(data
->data_src
.val
);
1917 if (sample_type
& PERF_SAMPLE_TRANSACTION
)
1918 size
+= sizeof(data
->txn
);
1920 if (sample_type
& PERF_SAMPLE_PHYS_ADDR
)
1921 size
+= sizeof(data
->phys_addr
);
1923 if (sample_type
& PERF_SAMPLE_CGROUP
)
1924 size
+= sizeof(data
->cgroup
);
1926 if (sample_type
& PERF_SAMPLE_DATA_PAGE_SIZE
)
1927 size
+= sizeof(data
->data_page_size
);
1929 if (sample_type
& PERF_SAMPLE_CODE_PAGE_SIZE
)
1930 size
+= sizeof(data
->code_page_size
);
1932 event
->header_size
= size
;
1936 * Called at perf_event creation and when events are attached/detached from a
1939 static void perf_event__header_size(struct perf_event
*event
)
1942 __perf_event_read_size(event
->attr
.read_format
,
1943 event
->group_leader
->nr_siblings
);
1944 __perf_event_header_size(event
, event
->attr
.sample_type
);
1947 static void perf_event__id_header_size(struct perf_event
*event
)
1949 struct perf_sample_data
*data
;
1950 u64 sample_type
= event
->attr
.sample_type
;
1953 if (sample_type
& PERF_SAMPLE_TID
)
1954 size
+= sizeof(data
->tid_entry
);
1956 if (sample_type
& PERF_SAMPLE_TIME
)
1957 size
+= sizeof(data
->time
);
1959 if (sample_type
& PERF_SAMPLE_IDENTIFIER
)
1960 size
+= sizeof(data
->id
);
1962 if (sample_type
& PERF_SAMPLE_ID
)
1963 size
+= sizeof(data
->id
);
1965 if (sample_type
& PERF_SAMPLE_STREAM_ID
)
1966 size
+= sizeof(data
->stream_id
);
1968 if (sample_type
& PERF_SAMPLE_CPU
)
1969 size
+= sizeof(data
->cpu_entry
);
1971 event
->id_header_size
= size
;
1975 * Check that adding an event to the group does not result in anybody
1976 * overflowing the 64k event limit imposed by the output buffer.
1978 * Specifically, check that the read_size for the event does not exceed 16k,
1979 * read_size being the one term that grows with groups size. Since read_size
1980 * depends on per-event read_format, also (re)check the existing events.
1982 * This leaves 48k for the constant size fields and things like callchains,
1983 * branch stacks and register sets.
1985 static bool perf_event_validate_size(struct perf_event
*event
)
1987 struct perf_event
*sibling
, *group_leader
= event
->group_leader
;
1989 if (__perf_event_read_size(event
->attr
.read_format
,
1990 group_leader
->nr_siblings
+ 1) > 16*1024)
1993 if (__perf_event_read_size(group_leader
->attr
.read_format
,
1994 group_leader
->nr_siblings
+ 1) > 16*1024)
1998 * When creating a new group leader, group_leader->ctx is initialized
1999 * after the size has been validated, but we cannot safely use
2000 * for_each_sibling_event() until group_leader->ctx is set. A new group
2001 * leader cannot have any siblings yet, so we can safely skip checking
2002 * the non-existent siblings.
2004 if (event
== group_leader
)
2007 for_each_sibling_event(sibling
, group_leader
) {
2008 if (__perf_event_read_size(sibling
->attr
.read_format
,
2009 group_leader
->nr_siblings
+ 1) > 16*1024)
2016 static void perf_group_attach(struct perf_event
*event
)
2018 struct perf_event
*group_leader
= event
->group_leader
, *pos
;
2020 lockdep_assert_held(&event
->ctx
->lock
);
2023 * We can have double attach due to group movement (move_group) in
2024 * perf_event_open().
2026 if (event
->attach_state
& PERF_ATTACH_GROUP
)
2029 event
->attach_state
|= PERF_ATTACH_GROUP
;
2031 if (group_leader
== event
)
2034 WARN_ON_ONCE(group_leader
->ctx
!= event
->ctx
);
2036 group_leader
->group_caps
&= event
->event_caps
;
2038 list_add_tail(&event
->sibling_list
, &group_leader
->sibling_list
);
2039 group_leader
->nr_siblings
++;
2040 group_leader
->group_generation
++;
2042 perf_event__header_size(group_leader
);
2044 for_each_sibling_event(pos
, group_leader
)
2045 perf_event__header_size(pos
);
2049 * Remove an event from the lists for its context.
2050 * Must be called with ctx->mutex and ctx->lock held.
2053 list_del_event(struct perf_event
*event
, struct perf_event_context
*ctx
)
2055 WARN_ON_ONCE(event
->ctx
!= ctx
);
2056 lockdep_assert_held(&ctx
->lock
);
2059 * We can have double detach due to exit/hot-unplug + close.
2061 if (!(event
->attach_state
& PERF_ATTACH_CONTEXT
))
2064 event
->attach_state
&= ~PERF_ATTACH_CONTEXT
;
2067 if (event
->hw
.flags
& PERF_EVENT_FLAG_USER_READ_CNT
)
2069 if (event
->attr
.inherit_stat
)
2071 if (has_inherit_and_sample_read(&event
->attr
))
2072 local_dec(&ctx
->nr_no_switch_fast
);
2074 list_del_rcu(&event
->event_entry
);
2076 if (event
->group_leader
== event
)
2077 del_event_from_groups(event
, ctx
);
2080 * If event was in error state, then keep it
2081 * that way, otherwise bogus counts will be
2082 * returned on read(). The only way to get out
2083 * of error state is by explicit re-enabling
2086 if (event
->state
> PERF_EVENT_STATE_OFF
) {
2087 perf_cgroup_event_disable(event
, ctx
);
2088 perf_event_set_state(event
, PERF_EVENT_STATE_OFF
);
2092 event
->pmu_ctx
->nr_events
--;
2096 perf_aux_output_match(struct perf_event
*event
, struct perf_event
*aux_event
)
2098 if (!has_aux(aux_event
))
2101 if (!event
->pmu
->aux_output_match
)
2104 return event
->pmu
->aux_output_match(aux_event
);
2107 static void put_event(struct perf_event
*event
);
2108 static void event_sched_out(struct perf_event
*event
,
2109 struct perf_event_context
*ctx
);
2111 static void perf_put_aux_event(struct perf_event
*event
)
2113 struct perf_event_context
*ctx
= event
->ctx
;
2114 struct perf_event
*iter
;
2117 * If event uses aux_event tear down the link
2119 if (event
->aux_event
) {
2120 iter
= event
->aux_event
;
2121 event
->aux_event
= NULL
;
2127 * If the event is an aux_event, tear down all links to
2128 * it from other events.
2130 for_each_sibling_event(iter
, event
->group_leader
) {
2131 if (iter
->aux_event
!= event
)
2134 iter
->aux_event
= NULL
;
2138 * If it's ACTIVE, schedule it out and put it into ERROR
2139 * state so that we don't try to schedule it again. Note
2140 * that perf_event_enable() will clear the ERROR status.
2142 event_sched_out(iter
, ctx
);
2143 perf_event_set_state(event
, PERF_EVENT_STATE_ERROR
);
2147 static bool perf_need_aux_event(struct perf_event
*event
)
2149 return !!event
->attr
.aux_output
|| !!event
->attr
.aux_sample_size
;
2152 static int perf_get_aux_event(struct perf_event
*event
,
2153 struct perf_event
*group_leader
)
2156 * Our group leader must be an aux event if we want to be
2157 * an aux_output. This way, the aux event will precede its
2158 * aux_output events in the group, and therefore will always
2165 * aux_output and aux_sample_size are mutually exclusive.
2167 if (event
->attr
.aux_output
&& event
->attr
.aux_sample_size
)
2170 if (event
->attr
.aux_output
&&
2171 !perf_aux_output_match(event
, group_leader
))
2174 if (event
->attr
.aux_sample_size
&& !group_leader
->pmu
->snapshot_aux
)
2177 if (!atomic_long_inc_not_zero(&group_leader
->refcount
))
2181 * Link aux_outputs to their aux event; this is undone in
2182 * perf_group_detach() by perf_put_aux_event(). When the
2183 * group in torn down, the aux_output events loose their
2184 * link to the aux_event and can't schedule any more.
2186 event
->aux_event
= group_leader
;
2191 static inline struct list_head
*get_event_list(struct perf_event
*event
)
2193 return event
->attr
.pinned
? &event
->pmu_ctx
->pinned_active
:
2194 &event
->pmu_ctx
->flexible_active
;
2198 * Events that have PERF_EV_CAP_SIBLING require being part of a group and
2199 * cannot exist on their own, schedule them out and move them into the ERROR
2200 * state. Also see _perf_event_enable(), it will not be able to recover
2203 static inline void perf_remove_sibling_event(struct perf_event
*event
)
2205 event_sched_out(event
, event
->ctx
);
2206 perf_event_set_state(event
, PERF_EVENT_STATE_ERROR
);
2209 static void perf_group_detach(struct perf_event
*event
)
2211 struct perf_event
*leader
= event
->group_leader
;
2212 struct perf_event
*sibling
, *tmp
;
2213 struct perf_event_context
*ctx
= event
->ctx
;
2215 lockdep_assert_held(&ctx
->lock
);
2218 * We can have double detach due to exit/hot-unplug + close.
2220 if (!(event
->attach_state
& PERF_ATTACH_GROUP
))
2223 event
->attach_state
&= ~PERF_ATTACH_GROUP
;
2225 perf_put_aux_event(event
);
2228 * If this is a sibling, remove it from its group.
2230 if (leader
!= event
) {
2231 list_del_init(&event
->sibling_list
);
2232 event
->group_leader
->nr_siblings
--;
2233 event
->group_leader
->group_generation
++;
2238 * If this was a group event with sibling events then
2239 * upgrade the siblings to singleton events by adding them
2240 * to whatever list we are on.
2242 list_for_each_entry_safe(sibling
, tmp
, &event
->sibling_list
, sibling_list
) {
2244 if (sibling
->event_caps
& PERF_EV_CAP_SIBLING
)
2245 perf_remove_sibling_event(sibling
);
2247 sibling
->group_leader
= sibling
;
2248 list_del_init(&sibling
->sibling_list
);
2250 /* Inherit group flags from the previous leader */
2251 sibling
->group_caps
= event
->group_caps
;
2253 if (sibling
->attach_state
& PERF_ATTACH_CONTEXT
) {
2254 add_event_to_groups(sibling
, event
->ctx
);
2256 if (sibling
->state
== PERF_EVENT_STATE_ACTIVE
)
2257 list_add_tail(&sibling
->active_list
, get_event_list(sibling
));
2260 WARN_ON_ONCE(sibling
->ctx
!= event
->ctx
);
2264 for_each_sibling_event(tmp
, leader
)
2265 perf_event__header_size(tmp
);
2267 perf_event__header_size(leader
);
2270 static void sync_child_event(struct perf_event
*child_event
);
2272 static void perf_child_detach(struct perf_event
*event
)
2274 struct perf_event
*parent_event
= event
->parent
;
2276 if (!(event
->attach_state
& PERF_ATTACH_CHILD
))
2279 event
->attach_state
&= ~PERF_ATTACH_CHILD
;
2281 if (WARN_ON_ONCE(!parent_event
))
2284 lockdep_assert_held(&parent_event
->child_mutex
);
2286 sync_child_event(event
);
2287 list_del_init(&event
->child_list
);
2290 static bool is_orphaned_event(struct perf_event
*event
)
2292 return event
->state
== PERF_EVENT_STATE_DEAD
;
2296 event_filter_match(struct perf_event
*event
)
2298 return (event
->cpu
== -1 || event
->cpu
== smp_processor_id()) &&
2299 perf_cgroup_match(event
);
2303 event_sched_out(struct perf_event
*event
, struct perf_event_context
*ctx
)
2305 struct perf_event_pmu_context
*epc
= event
->pmu_ctx
;
2306 struct perf_cpu_pmu_context
*cpc
= this_cpu_ptr(epc
->pmu
->cpu_pmu_context
);
2307 enum perf_event_state state
= PERF_EVENT_STATE_INACTIVE
;
2309 // XXX cpc serialization, probably per-cpu IRQ disabled
2311 WARN_ON_ONCE(event
->ctx
!= ctx
);
2312 lockdep_assert_held(&ctx
->lock
);
2314 if (event
->state
!= PERF_EVENT_STATE_ACTIVE
)
2318 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2319 * we can schedule events _OUT_ individually through things like
2320 * __perf_remove_from_context().
2322 list_del_init(&event
->active_list
);
2324 perf_pmu_disable(event
->pmu
);
2326 event
->pmu
->del(event
, 0);
2329 if (event
->pending_disable
) {
2330 event
->pending_disable
= 0;
2331 perf_cgroup_event_disable(event
, ctx
);
2332 state
= PERF_EVENT_STATE_OFF
;
2335 perf_event_set_state(event
, state
);
2337 if (!is_software_event(event
))
2338 cpc
->active_oncpu
--;
2339 if (event
->attr
.freq
&& event
->attr
.sample_freq
) {
2343 if (event
->attr
.exclusive
|| !cpc
->active_oncpu
)
2346 perf_pmu_enable(event
->pmu
);
2350 group_sched_out(struct perf_event
*group_event
, struct perf_event_context
*ctx
)
2352 struct perf_event
*event
;
2354 if (group_event
->state
!= PERF_EVENT_STATE_ACTIVE
)
2357 perf_assert_pmu_disabled(group_event
->pmu_ctx
->pmu
);
2359 event_sched_out(group_event
, ctx
);
2362 * Schedule out siblings (if any):
2364 for_each_sibling_event(event
, group_event
)
2365 event_sched_out(event
, ctx
);
2369 __ctx_time_update(struct perf_cpu_context
*cpuctx
, struct perf_event_context
*ctx
, bool final
)
2371 if (ctx
->is_active
& EVENT_TIME
) {
2372 if (ctx
->is_active
& EVENT_FROZEN
)
2374 update_context_time(ctx
);
2375 update_cgrp_time_from_cpuctx(cpuctx
, final
);
2380 ctx_time_update(struct perf_cpu_context
*cpuctx
, struct perf_event_context
*ctx
)
2382 __ctx_time_update(cpuctx
, ctx
, false);
2386 * To be used inside perf_ctx_lock() / perf_ctx_unlock(). Lasts until perf_ctx_unlock().
2389 ctx_time_freeze(struct perf_cpu_context
*cpuctx
, struct perf_event_context
*ctx
)
2391 ctx_time_update(cpuctx
, ctx
);
2392 if (ctx
->is_active
& EVENT_TIME
)
2393 ctx
->is_active
|= EVENT_FROZEN
;
2397 ctx_time_update_event(struct perf_event_context
*ctx
, struct perf_event
*event
)
2399 if (ctx
->is_active
& EVENT_TIME
) {
2400 if (ctx
->is_active
& EVENT_FROZEN
)
2402 update_context_time(ctx
);
2403 update_cgrp_time_from_event(event
);
2407 #define DETACH_GROUP 0x01UL
2408 #define DETACH_CHILD 0x02UL
2409 #define DETACH_DEAD 0x04UL
2412 * Cross CPU call to remove a performance event
2414 * We disable the event on the hardware level first. After that we
2415 * remove it from the context list.
2418 __perf_remove_from_context(struct perf_event
*event
,
2419 struct perf_cpu_context
*cpuctx
,
2420 struct perf_event_context
*ctx
,
2423 struct perf_event_pmu_context
*pmu_ctx
= event
->pmu_ctx
;
2424 unsigned long flags
= (unsigned long)info
;
2426 ctx_time_update(cpuctx
, ctx
);
2429 * Ensure event_sched_out() switches to OFF, at the very least
2430 * this avoids raising perf_pending_task() at this time.
2432 if (flags
& DETACH_DEAD
)
2433 event
->pending_disable
= 1;
2434 event_sched_out(event
, ctx
);
2435 if (flags
& DETACH_GROUP
)
2436 perf_group_detach(event
);
2437 if (flags
& DETACH_CHILD
)
2438 perf_child_detach(event
);
2439 list_del_event(event
, ctx
);
2440 if (flags
& DETACH_DEAD
)
2441 event
->state
= PERF_EVENT_STATE_DEAD
;
2443 if (!pmu_ctx
->nr_events
) {
2444 pmu_ctx
->rotate_necessary
= 0;
2446 if (ctx
->task
&& ctx
->is_active
) {
2447 struct perf_cpu_pmu_context
*cpc
;
2449 cpc
= this_cpu_ptr(pmu_ctx
->pmu
->cpu_pmu_context
);
2450 WARN_ON_ONCE(cpc
->task_epc
&& cpc
->task_epc
!= pmu_ctx
);
2451 cpc
->task_epc
= NULL
;
2455 if (!ctx
->nr_events
&& ctx
->is_active
) {
2456 if (ctx
== &cpuctx
->ctx
)
2457 update_cgrp_time_from_cpuctx(cpuctx
, true);
2461 WARN_ON_ONCE(cpuctx
->task_ctx
!= ctx
);
2462 cpuctx
->task_ctx
= NULL
;
2468 * Remove the event from a task's (or a CPU's) list of events.
2470 * If event->ctx is a cloned context, callers must make sure that
2471 * every task struct that event->ctx->task could possibly point to
2472 * remains valid. This is OK when called from perf_release since
2473 * that only calls us on the top-level context, which can't be a clone.
2474 * When called from perf_event_exit_task, it's OK because the
2475 * context has been detached from its task.
2477 static void perf_remove_from_context(struct perf_event
*event
, unsigned long flags
)
2479 struct perf_event_context
*ctx
= event
->ctx
;
2481 lockdep_assert_held(&ctx
->mutex
);
2484 * Because of perf_event_exit_task(), perf_remove_from_context() ought
2485 * to work in the face of TASK_TOMBSTONE, unlike every other
2486 * event_function_call() user.
2488 raw_spin_lock_irq(&ctx
->lock
);
2489 if (!ctx
->is_active
) {
2490 __perf_remove_from_context(event
, this_cpu_ptr(&perf_cpu_context
),
2491 ctx
, (void *)flags
);
2492 raw_spin_unlock_irq(&ctx
->lock
);
2495 raw_spin_unlock_irq(&ctx
->lock
);
2497 event_function_call(event
, __perf_remove_from_context
, (void *)flags
);
2501 * Cross CPU call to disable a performance event
2503 static void __perf_event_disable(struct perf_event
*event
,
2504 struct perf_cpu_context
*cpuctx
,
2505 struct perf_event_context
*ctx
,
2508 if (event
->state
< PERF_EVENT_STATE_INACTIVE
)
2511 perf_pmu_disable(event
->pmu_ctx
->pmu
);
2512 ctx_time_update_event(ctx
, event
);
2514 if (event
== event
->group_leader
)
2515 group_sched_out(event
, ctx
);
2517 event_sched_out(event
, ctx
);
2519 perf_event_set_state(event
, PERF_EVENT_STATE_OFF
);
2520 perf_cgroup_event_disable(event
, ctx
);
2522 perf_pmu_enable(event
->pmu_ctx
->pmu
);
2528 * If event->ctx is a cloned context, callers must make sure that
2529 * every task struct that event->ctx->task could possibly point to
2530 * remains valid. This condition is satisfied when called through
2531 * perf_event_for_each_child or perf_event_for_each because they
2532 * hold the top-level event's child_mutex, so any descendant that
2533 * goes to exit will block in perf_event_exit_event().
2535 * When called from perf_pending_disable it's OK because event->ctx
2536 * is the current context on this CPU and preemption is disabled,
2537 * hence we can't get into perf_event_task_sched_out for this context.
2539 static void _perf_event_disable(struct perf_event
*event
)
2541 struct perf_event_context
*ctx
= event
->ctx
;
2543 raw_spin_lock_irq(&ctx
->lock
);
2544 if (event
->state
<= PERF_EVENT_STATE_OFF
) {
2545 raw_spin_unlock_irq(&ctx
->lock
);
2548 raw_spin_unlock_irq(&ctx
->lock
);
2550 event_function_call(event
, __perf_event_disable
, NULL
);
2553 void perf_event_disable_local(struct perf_event
*event
)
2555 event_function_local(event
, __perf_event_disable
, NULL
);
2559 * Strictly speaking kernel users cannot create groups and therefore this
2560 * interface does not need the perf_event_ctx_lock() magic.
2562 void perf_event_disable(struct perf_event
*event
)
2564 struct perf_event_context
*ctx
;
2566 ctx
= perf_event_ctx_lock(event
);
2567 _perf_event_disable(event
);
2568 perf_event_ctx_unlock(event
, ctx
);
2570 EXPORT_SYMBOL_GPL(perf_event_disable
);
2572 void perf_event_disable_inatomic(struct perf_event
*event
)
2574 event
->pending_disable
= 1;
2575 irq_work_queue(&event
->pending_disable_irq
);
2578 #define MAX_INTERRUPTS (~0ULL)
2580 static void perf_log_throttle(struct perf_event
*event
, int enable
);
2581 static void perf_log_itrace_start(struct perf_event
*event
);
2584 event_sched_in(struct perf_event
*event
, struct perf_event_context
*ctx
)
2586 struct perf_event_pmu_context
*epc
= event
->pmu_ctx
;
2587 struct perf_cpu_pmu_context
*cpc
= this_cpu_ptr(epc
->pmu
->cpu_pmu_context
);
2590 WARN_ON_ONCE(event
->ctx
!= ctx
);
2592 lockdep_assert_held(&ctx
->lock
);
2594 if (event
->state
<= PERF_EVENT_STATE_OFF
)
2597 WRITE_ONCE(event
->oncpu
, smp_processor_id());
2599 * Order event::oncpu write to happen before the ACTIVE state is
2600 * visible. This allows perf_event_{stop,read}() to observe the correct
2601 * ->oncpu if it sees ACTIVE.
2604 perf_event_set_state(event
, PERF_EVENT_STATE_ACTIVE
);
2607 * Unthrottle events, since we scheduled we might have missed several
2608 * ticks already, also for a heavily scheduling task there is little
2609 * guarantee it'll get a tick in a timely manner.
2611 if (unlikely(event
->hw
.interrupts
== MAX_INTERRUPTS
)) {
2612 perf_log_throttle(event
, 1);
2613 event
->hw
.interrupts
= 0;
2616 perf_pmu_disable(event
->pmu
);
2618 perf_log_itrace_start(event
);
2620 if (event
->pmu
->add(event
, PERF_EF_START
)) {
2621 perf_event_set_state(event
, PERF_EVENT_STATE_INACTIVE
);
2627 if (!is_software_event(event
))
2628 cpc
->active_oncpu
++;
2629 if (event
->attr
.freq
&& event
->attr
.sample_freq
) {
2633 if (event
->attr
.exclusive
)
2637 perf_pmu_enable(event
->pmu
);
2643 group_sched_in(struct perf_event
*group_event
, struct perf_event_context
*ctx
)
2645 struct perf_event
*event
, *partial_group
= NULL
;
2646 struct pmu
*pmu
= group_event
->pmu_ctx
->pmu
;
2648 if (group_event
->state
== PERF_EVENT_STATE_OFF
)
2651 pmu
->start_txn(pmu
, PERF_PMU_TXN_ADD
);
2653 if (event_sched_in(group_event
, ctx
))
2657 * Schedule in siblings as one group (if any):
2659 for_each_sibling_event(event
, group_event
) {
2660 if (event_sched_in(event
, ctx
)) {
2661 partial_group
= event
;
2666 if (!pmu
->commit_txn(pmu
))
2671 * Groups can be scheduled in as one unit only, so undo any
2672 * partial group before returning:
2673 * The events up to the failed event are scheduled out normally.
2675 for_each_sibling_event(event
, group_event
) {
2676 if (event
== partial_group
)
2679 event_sched_out(event
, ctx
);
2681 event_sched_out(group_event
, ctx
);
2684 pmu
->cancel_txn(pmu
);
2689 * Work out whether we can put this event group on the CPU now.
2691 static int group_can_go_on(struct perf_event
*event
, int can_add_hw
)
2693 struct perf_event_pmu_context
*epc
= event
->pmu_ctx
;
2694 struct perf_cpu_pmu_context
*cpc
= this_cpu_ptr(epc
->pmu
->cpu_pmu_context
);
2697 * Groups consisting entirely of software events can always go on.
2699 if (event
->group_caps
& PERF_EV_CAP_SOFTWARE
)
2702 * If an exclusive group is already on, no other hardware
2708 * If this group is exclusive and there are already
2709 * events on the CPU, it can't go on.
2711 if (event
->attr
.exclusive
&& !list_empty(get_event_list(event
)))
2714 * Otherwise, try to add it if all previous groups were able
2720 static void add_event_to_ctx(struct perf_event
*event
,
2721 struct perf_event_context
*ctx
)
2723 list_add_event(event
, ctx
);
2724 perf_group_attach(event
);
2727 static void task_ctx_sched_out(struct perf_event_context
*ctx
,
2729 enum event_type_t event_type
)
2731 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
2733 if (!cpuctx
->task_ctx
)
2736 if (WARN_ON_ONCE(ctx
!= cpuctx
->task_ctx
))
2739 ctx_sched_out(ctx
, pmu
, event_type
);
2742 static void perf_event_sched_in(struct perf_cpu_context
*cpuctx
,
2743 struct perf_event_context
*ctx
,
2746 ctx_sched_in(&cpuctx
->ctx
, pmu
, EVENT_PINNED
);
2748 ctx_sched_in(ctx
, pmu
, EVENT_PINNED
);
2749 ctx_sched_in(&cpuctx
->ctx
, pmu
, EVENT_FLEXIBLE
);
2751 ctx_sched_in(ctx
, pmu
, EVENT_FLEXIBLE
);
2755 * We want to maintain the following priority of scheduling:
2756 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2757 * - task pinned (EVENT_PINNED)
2758 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2759 * - task flexible (EVENT_FLEXIBLE).
2761 * In order to avoid unscheduling and scheduling back in everything every
2762 * time an event is added, only do it for the groups of equal priority and
2765 * This can be called after a batch operation on task events, in which case
2766 * event_type is a bit mask of the types of events involved. For CPU events,
2767 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2769 static void ctx_resched(struct perf_cpu_context
*cpuctx
,
2770 struct perf_event_context
*task_ctx
,
2771 struct pmu
*pmu
, enum event_type_t event_type
)
2773 bool cpu_event
= !!(event_type
& EVENT_CPU
);
2774 struct perf_event_pmu_context
*epc
;
2777 * If pinned groups are involved, flexible groups also need to be
2780 if (event_type
& EVENT_PINNED
)
2781 event_type
|= EVENT_FLEXIBLE
;
2783 event_type
&= EVENT_ALL
;
2785 for_each_epc(epc
, &cpuctx
->ctx
, pmu
, false)
2786 perf_pmu_disable(epc
->pmu
);
2789 for_each_epc(epc
, task_ctx
, pmu
, false)
2790 perf_pmu_disable(epc
->pmu
);
2792 task_ctx_sched_out(task_ctx
, pmu
, event_type
);
2796 * Decide which cpu ctx groups to schedule out based on the types
2797 * of events that caused rescheduling:
2798 * - EVENT_CPU: schedule out corresponding groups;
2799 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2800 * - otherwise, do nothing more.
2803 ctx_sched_out(&cpuctx
->ctx
, pmu
, event_type
);
2804 else if (event_type
& EVENT_PINNED
)
2805 ctx_sched_out(&cpuctx
->ctx
, pmu
, EVENT_FLEXIBLE
);
2807 perf_event_sched_in(cpuctx
, task_ctx
, pmu
);
2809 for_each_epc(epc
, &cpuctx
->ctx
, pmu
, false)
2810 perf_pmu_enable(epc
->pmu
);
2813 for_each_epc(epc
, task_ctx
, pmu
, false)
2814 perf_pmu_enable(epc
->pmu
);
2818 void perf_pmu_resched(struct pmu
*pmu
)
2820 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
2821 struct perf_event_context
*task_ctx
= cpuctx
->task_ctx
;
2823 perf_ctx_lock(cpuctx
, task_ctx
);
2824 ctx_resched(cpuctx
, task_ctx
, pmu
, EVENT_ALL
|EVENT_CPU
);
2825 perf_ctx_unlock(cpuctx
, task_ctx
);
2829 * Cross CPU call to install and enable a performance event
2831 * Very similar to remote_function() + event_function() but cannot assume that
2832 * things like ctx->is_active and cpuctx->task_ctx are set.
2834 static int __perf_install_in_context(void *info
)
2836 struct perf_event
*event
= info
;
2837 struct perf_event_context
*ctx
= event
->ctx
;
2838 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
2839 struct perf_event_context
*task_ctx
= cpuctx
->task_ctx
;
2840 bool reprogram
= true;
2843 raw_spin_lock(&cpuctx
->ctx
.lock
);
2845 raw_spin_lock(&ctx
->lock
);
2848 reprogram
= (ctx
->task
== current
);
2851 * If the task is running, it must be running on this CPU,
2852 * otherwise we cannot reprogram things.
2854 * If its not running, we don't care, ctx->lock will
2855 * serialize against it becoming runnable.
2857 if (task_curr(ctx
->task
) && !reprogram
) {
2862 WARN_ON_ONCE(reprogram
&& cpuctx
->task_ctx
&& cpuctx
->task_ctx
!= ctx
);
2863 } else if (task_ctx
) {
2864 raw_spin_lock(&task_ctx
->lock
);
2867 #ifdef CONFIG_CGROUP_PERF
2868 if (event
->state
> PERF_EVENT_STATE_OFF
&& is_cgroup_event(event
)) {
2870 * If the current cgroup doesn't match the event's
2871 * cgroup, we should not try to schedule it.
2873 struct perf_cgroup
*cgrp
= perf_cgroup_from_task(current
, ctx
);
2874 reprogram
= cgroup_is_descendant(cgrp
->css
.cgroup
,
2875 event
->cgrp
->css
.cgroup
);
2880 ctx_time_freeze(cpuctx
, ctx
);
2881 add_event_to_ctx(event
, ctx
);
2882 ctx_resched(cpuctx
, task_ctx
, event
->pmu_ctx
->pmu
,
2883 get_event_type(event
));
2885 add_event_to_ctx(event
, ctx
);
2889 perf_ctx_unlock(cpuctx
, task_ctx
);
2894 static bool exclusive_event_installable(struct perf_event
*event
,
2895 struct perf_event_context
*ctx
);
2898 * Attach a performance event to a context.
2900 * Very similar to event_function_call, see comment there.
2903 perf_install_in_context(struct perf_event_context
*ctx
,
2904 struct perf_event
*event
,
2907 struct task_struct
*task
= READ_ONCE(ctx
->task
);
2909 lockdep_assert_held(&ctx
->mutex
);
2911 WARN_ON_ONCE(!exclusive_event_installable(event
, ctx
));
2913 if (event
->cpu
!= -1)
2914 WARN_ON_ONCE(event
->cpu
!= cpu
);
2917 * Ensures that if we can observe event->ctx, both the event and ctx
2918 * will be 'complete'. See perf_iterate_sb_cpu().
2920 smp_store_release(&event
->ctx
, ctx
);
2923 * perf_event_attr::disabled events will not run and can be initialized
2924 * without IPI. Except when this is the first event for the context, in
2925 * that case we need the magic of the IPI to set ctx->is_active.
2927 * The IOC_ENABLE that is sure to follow the creation of a disabled
2928 * event will issue the IPI and reprogram the hardware.
2930 if (__perf_effective_state(event
) == PERF_EVENT_STATE_OFF
&&
2931 ctx
->nr_events
&& !is_cgroup_event(event
)) {
2932 raw_spin_lock_irq(&ctx
->lock
);
2933 if (ctx
->task
== TASK_TOMBSTONE
) {
2934 raw_spin_unlock_irq(&ctx
->lock
);
2937 add_event_to_ctx(event
, ctx
);
2938 raw_spin_unlock_irq(&ctx
->lock
);
2943 cpu_function_call(cpu
, __perf_install_in_context
, event
);
2948 * Should not happen, we validate the ctx is still alive before calling.
2950 if (WARN_ON_ONCE(task
== TASK_TOMBSTONE
))
2954 * Installing events is tricky because we cannot rely on ctx->is_active
2955 * to be set in case this is the nr_events 0 -> 1 transition.
2957 * Instead we use task_curr(), which tells us if the task is running.
2958 * However, since we use task_curr() outside of rq::lock, we can race
2959 * against the actual state. This means the result can be wrong.
2961 * If we get a false positive, we retry, this is harmless.
2963 * If we get a false negative, things are complicated. If we are after
2964 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2965 * value must be correct. If we're before, it doesn't matter since
2966 * perf_event_context_sched_in() will program the counter.
2968 * However, this hinges on the remote context switch having observed
2969 * our task->perf_event_ctxp[] store, such that it will in fact take
2970 * ctx::lock in perf_event_context_sched_in().
2972 * We do this by task_function_call(), if the IPI fails to hit the task
2973 * we know any future context switch of task must see the
2974 * perf_event_ctpx[] store.
2978 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2979 * task_cpu() load, such that if the IPI then does not find the task
2980 * running, a future context switch of that task must observe the
2985 if (!task_function_call(task
, __perf_install_in_context
, event
))
2988 raw_spin_lock_irq(&ctx
->lock
);
2990 if (WARN_ON_ONCE(task
== TASK_TOMBSTONE
)) {
2992 * Cannot happen because we already checked above (which also
2993 * cannot happen), and we hold ctx->mutex, which serializes us
2994 * against perf_event_exit_task_context().
2996 raw_spin_unlock_irq(&ctx
->lock
);
3000 * If the task is not running, ctx->lock will avoid it becoming so,
3001 * thus we can safely install the event.
3003 if (task_curr(task
)) {
3004 raw_spin_unlock_irq(&ctx
->lock
);
3007 add_event_to_ctx(event
, ctx
);
3008 raw_spin_unlock_irq(&ctx
->lock
);
3012 * Cross CPU call to enable a performance event
3014 static void __perf_event_enable(struct perf_event
*event
,
3015 struct perf_cpu_context
*cpuctx
,
3016 struct perf_event_context
*ctx
,
3019 struct perf_event
*leader
= event
->group_leader
;
3020 struct perf_event_context
*task_ctx
;
3022 if (event
->state
>= PERF_EVENT_STATE_INACTIVE
||
3023 event
->state
<= PERF_EVENT_STATE_ERROR
)
3026 ctx_time_freeze(cpuctx
, ctx
);
3028 perf_event_set_state(event
, PERF_EVENT_STATE_INACTIVE
);
3029 perf_cgroup_event_enable(event
, ctx
);
3031 if (!ctx
->is_active
)
3034 if (!event_filter_match(event
))
3038 * If the event is in a group and isn't the group leader,
3039 * then don't put it on unless the group is on.
3041 if (leader
!= event
&& leader
->state
!= PERF_EVENT_STATE_ACTIVE
)
3044 task_ctx
= cpuctx
->task_ctx
;
3046 WARN_ON_ONCE(task_ctx
!= ctx
);
3048 ctx_resched(cpuctx
, task_ctx
, event
->pmu_ctx
->pmu
, get_event_type(event
));
3054 * If event->ctx is a cloned context, callers must make sure that
3055 * every task struct that event->ctx->task could possibly point to
3056 * remains valid. This condition is satisfied when called through
3057 * perf_event_for_each_child or perf_event_for_each as described
3058 * for perf_event_disable.
3060 static void _perf_event_enable(struct perf_event
*event
)
3062 struct perf_event_context
*ctx
= event
->ctx
;
3064 raw_spin_lock_irq(&ctx
->lock
);
3065 if (event
->state
>= PERF_EVENT_STATE_INACTIVE
||
3066 event
->state
< PERF_EVENT_STATE_ERROR
) {
3068 raw_spin_unlock_irq(&ctx
->lock
);
3073 * If the event is in error state, clear that first.
3075 * That way, if we see the event in error state below, we know that it
3076 * has gone back into error state, as distinct from the task having
3077 * been scheduled away before the cross-call arrived.
3079 if (event
->state
== PERF_EVENT_STATE_ERROR
) {
3081 * Detached SIBLING events cannot leave ERROR state.
3083 if (event
->event_caps
& PERF_EV_CAP_SIBLING
&&
3084 event
->group_leader
== event
)
3087 event
->state
= PERF_EVENT_STATE_OFF
;
3089 raw_spin_unlock_irq(&ctx
->lock
);
3091 event_function_call(event
, __perf_event_enable
, NULL
);
3095 * See perf_event_disable();
3097 void perf_event_enable(struct perf_event
*event
)
3099 struct perf_event_context
*ctx
;
3101 ctx
= perf_event_ctx_lock(event
);
3102 _perf_event_enable(event
);
3103 perf_event_ctx_unlock(event
, ctx
);
3105 EXPORT_SYMBOL_GPL(perf_event_enable
);
3107 struct stop_event_data
{
3108 struct perf_event
*event
;
3109 unsigned int restart
;
3112 static int __perf_event_stop(void *info
)
3114 struct stop_event_data
*sd
= info
;
3115 struct perf_event
*event
= sd
->event
;
3117 /* if it's already INACTIVE, do nothing */
3118 if (READ_ONCE(event
->state
) != PERF_EVENT_STATE_ACTIVE
)
3121 /* matches smp_wmb() in event_sched_in() */
3125 * There is a window with interrupts enabled before we get here,
3126 * so we need to check again lest we try to stop another CPU's event.
3128 if (READ_ONCE(event
->oncpu
) != smp_processor_id())
3131 event
->pmu
->stop(event
, PERF_EF_UPDATE
);
3134 * May race with the actual stop (through perf_pmu_output_stop()),
3135 * but it is only used for events with AUX ring buffer, and such
3136 * events will refuse to restart because of rb::aux_mmap_count==0,
3137 * see comments in perf_aux_output_begin().
3139 * Since this is happening on an event-local CPU, no trace is lost
3143 event
->pmu
->start(event
, 0);
3148 static int perf_event_stop(struct perf_event
*event
, int restart
)
3150 struct stop_event_data sd
= {
3157 if (READ_ONCE(event
->state
) != PERF_EVENT_STATE_ACTIVE
)
3160 /* matches smp_wmb() in event_sched_in() */
3164 * We only want to restart ACTIVE events, so if the event goes
3165 * inactive here (event->oncpu==-1), there's nothing more to do;
3166 * fall through with ret==-ENXIO.
3168 ret
= cpu_function_call(READ_ONCE(event
->oncpu
),
3169 __perf_event_stop
, &sd
);
3170 } while (ret
== -EAGAIN
);
3176 * In order to contain the amount of racy and tricky in the address filter
3177 * configuration management, it is a two part process:
3179 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3180 * we update the addresses of corresponding vmas in
3181 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3182 * (p2) when an event is scheduled in (pmu::add), it calls
3183 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3184 * if the generation has changed since the previous call.
3186 * If (p1) happens while the event is active, we restart it to force (p2).
3188 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3189 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3191 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3192 * registered mapping, called for every new mmap(), with mm::mmap_lock down
3194 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3197 void perf_event_addr_filters_sync(struct perf_event
*event
)
3199 struct perf_addr_filters_head
*ifh
= perf_event_addr_filters(event
);
3201 if (!has_addr_filter(event
))
3204 raw_spin_lock(&ifh
->lock
);
3205 if (event
->addr_filters_gen
!= event
->hw
.addr_filters_gen
) {
3206 event
->pmu
->addr_filters_sync(event
);
3207 event
->hw
.addr_filters_gen
= event
->addr_filters_gen
;
3209 raw_spin_unlock(&ifh
->lock
);
3211 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync
);
3213 static int _perf_event_refresh(struct perf_event
*event
, int refresh
)
3216 * not supported on inherited events
3218 if (event
->attr
.inherit
|| !is_sampling_event(event
))
3221 atomic_add(refresh
, &event
->event_limit
);
3222 _perf_event_enable(event
);
3228 * See perf_event_disable()
3230 int perf_event_refresh(struct perf_event
*event
, int refresh
)
3232 struct perf_event_context
*ctx
;
3235 ctx
= perf_event_ctx_lock(event
);
3236 ret
= _perf_event_refresh(event
, refresh
);
3237 perf_event_ctx_unlock(event
, ctx
);
3241 EXPORT_SYMBOL_GPL(perf_event_refresh
);
3243 static int perf_event_modify_breakpoint(struct perf_event
*bp
,
3244 struct perf_event_attr
*attr
)
3248 _perf_event_disable(bp
);
3250 err
= modify_user_hw_breakpoint_check(bp
, attr
, true);
3252 if (!bp
->attr
.disabled
)
3253 _perf_event_enable(bp
);
3259 * Copy event-type-independent attributes that may be modified.
3261 static void perf_event_modify_copy_attr(struct perf_event_attr
*to
,
3262 const struct perf_event_attr
*from
)
3264 to
->sig_data
= from
->sig_data
;
3267 static int perf_event_modify_attr(struct perf_event
*event
,
3268 struct perf_event_attr
*attr
)
3270 int (*func
)(struct perf_event
*, struct perf_event_attr
*);
3271 struct perf_event
*child
;
3274 if (event
->attr
.type
!= attr
->type
)
3277 switch (event
->attr
.type
) {
3278 case PERF_TYPE_BREAKPOINT
:
3279 func
= perf_event_modify_breakpoint
;
3282 /* Place holder for future additions. */
3286 WARN_ON_ONCE(event
->ctx
->parent_ctx
);
3288 mutex_lock(&event
->child_mutex
);
3290 * Event-type-independent attributes must be copied before event-type
3291 * modification, which will validate that final attributes match the
3292 * source attributes after all relevant attributes have been copied.
3294 perf_event_modify_copy_attr(&event
->attr
, attr
);
3295 err
= func(event
, attr
);
3298 list_for_each_entry(child
, &event
->child_list
, child_list
) {
3299 perf_event_modify_copy_attr(&child
->attr
, attr
);
3300 err
= func(child
, attr
);
3305 mutex_unlock(&event
->child_mutex
);
3309 static void __pmu_ctx_sched_out(struct perf_event_pmu_context
*pmu_ctx
,
3310 enum event_type_t event_type
)
3312 struct perf_event_context
*ctx
= pmu_ctx
->ctx
;
3313 struct perf_event
*event
, *tmp
;
3314 struct pmu
*pmu
= pmu_ctx
->pmu
;
3316 if (ctx
->task
&& !(ctx
->is_active
& EVENT_ALL
)) {
3317 struct perf_cpu_pmu_context
*cpc
;
3319 cpc
= this_cpu_ptr(pmu
->cpu_pmu_context
);
3320 WARN_ON_ONCE(cpc
->task_epc
&& cpc
->task_epc
!= pmu_ctx
);
3321 cpc
->task_epc
= NULL
;
3324 if (!(event_type
& EVENT_ALL
))
3327 perf_pmu_disable(pmu
);
3328 if (event_type
& EVENT_PINNED
) {
3329 list_for_each_entry_safe(event
, tmp
,
3330 &pmu_ctx
->pinned_active
,
3332 group_sched_out(event
, ctx
);
3335 if (event_type
& EVENT_FLEXIBLE
) {
3336 list_for_each_entry_safe(event
, tmp
,
3337 &pmu_ctx
->flexible_active
,
3339 group_sched_out(event
, ctx
);
3341 * Since we cleared EVENT_FLEXIBLE, also clear
3342 * rotate_necessary, is will be reset by
3343 * ctx_flexible_sched_in() when needed.
3345 pmu_ctx
->rotate_necessary
= 0;
3347 perf_pmu_enable(pmu
);
3351 * Be very careful with the @pmu argument since this will change ctx state.
3352 * The @pmu argument works for ctx_resched(), because that is symmetric in
3353 * ctx_sched_out() / ctx_sched_in() usage and the ctx state ends up invariant.
3355 * However, if you were to be asymmetrical, you could end up with messed up
3356 * state, eg. ctx->is_active cleared even though most EPCs would still actually
3360 ctx_sched_out(struct perf_event_context
*ctx
, struct pmu
*pmu
, enum event_type_t event_type
)
3362 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
3363 struct perf_event_pmu_context
*pmu_ctx
;
3364 int is_active
= ctx
->is_active
;
3365 bool cgroup
= event_type
& EVENT_CGROUP
;
3367 event_type
&= ~EVENT_CGROUP
;
3369 lockdep_assert_held(&ctx
->lock
);
3371 if (likely(!ctx
->nr_events
)) {
3373 * See __perf_remove_from_context().
3375 WARN_ON_ONCE(ctx
->is_active
);
3377 WARN_ON_ONCE(cpuctx
->task_ctx
);
3382 * Always update time if it was set; not only when it changes.
3383 * Otherwise we can 'forget' to update time for any but the last
3384 * context we sched out. For example:
3386 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3387 * ctx_sched_out(.event_type = EVENT_PINNED)
3389 * would only update time for the pinned events.
3391 __ctx_time_update(cpuctx
, ctx
, ctx
== &cpuctx
->ctx
);
3394 * CPU-release for the below ->is_active store,
3395 * see __load_acquire() in perf_event_time_now()
3398 ctx
->is_active
&= ~event_type
;
3400 if (!(ctx
->is_active
& EVENT_ALL
)) {
3402 * For FROZEN, preserve TIME|FROZEN such that perf_event_time_now()
3403 * does not observe a hole. perf_ctx_unlock() will clean up.
3405 if (ctx
->is_active
& EVENT_FROZEN
)
3406 ctx
->is_active
&= EVENT_TIME_FROZEN
;
3412 WARN_ON_ONCE(cpuctx
->task_ctx
!= ctx
);
3413 if (!(ctx
->is_active
& EVENT_ALL
))
3414 cpuctx
->task_ctx
= NULL
;
3417 is_active
^= ctx
->is_active
; /* changed bits */
3419 for_each_epc(pmu_ctx
, ctx
, pmu
, cgroup
)
3420 __pmu_ctx_sched_out(pmu_ctx
, is_active
);
3424 * Test whether two contexts are equivalent, i.e. whether they have both been
3425 * cloned from the same version of the same context.
3427 * Equivalence is measured using a generation number in the context that is
3428 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3429 * and list_del_event().
3431 static int context_equiv(struct perf_event_context
*ctx1
,
3432 struct perf_event_context
*ctx2
)
3434 lockdep_assert_held(&ctx1
->lock
);
3435 lockdep_assert_held(&ctx2
->lock
);
3437 /* Pinning disables the swap optimization */
3438 if (ctx1
->pin_count
|| ctx2
->pin_count
)
3441 /* If ctx1 is the parent of ctx2 */
3442 if (ctx1
== ctx2
->parent_ctx
&& ctx1
->generation
== ctx2
->parent_gen
)
3445 /* If ctx2 is the parent of ctx1 */
3446 if (ctx1
->parent_ctx
== ctx2
&& ctx1
->parent_gen
== ctx2
->generation
)
3450 * If ctx1 and ctx2 have the same parent; we flatten the parent
3451 * hierarchy, see perf_event_init_context().
3453 if (ctx1
->parent_ctx
&& ctx1
->parent_ctx
== ctx2
->parent_ctx
&&
3454 ctx1
->parent_gen
== ctx2
->parent_gen
)
3461 static void __perf_event_sync_stat(struct perf_event
*event
,
3462 struct perf_event
*next_event
)
3466 if (!event
->attr
.inherit_stat
)
3470 * Update the event value, we cannot use perf_event_read()
3471 * because we're in the middle of a context switch and have IRQs
3472 * disabled, which upsets smp_call_function_single(), however
3473 * we know the event must be on the current CPU, therefore we
3474 * don't need to use it.
3476 if (event
->state
== PERF_EVENT_STATE_ACTIVE
)
3477 event
->pmu
->read(event
);
3479 perf_event_update_time(event
);
3482 * In order to keep per-task stats reliable we need to flip the event
3483 * values when we flip the contexts.
3485 value
= local64_read(&next_event
->count
);
3486 value
= local64_xchg(&event
->count
, value
);
3487 local64_set(&next_event
->count
, value
);
3489 swap(event
->total_time_enabled
, next_event
->total_time_enabled
);
3490 swap(event
->total_time_running
, next_event
->total_time_running
);
3493 * Since we swizzled the values, update the user visible data too.
3495 perf_event_update_userpage(event
);
3496 perf_event_update_userpage(next_event
);
3499 static void perf_event_sync_stat(struct perf_event_context
*ctx
,
3500 struct perf_event_context
*next_ctx
)
3502 struct perf_event
*event
, *next_event
;
3507 update_context_time(ctx
);
3509 event
= list_first_entry(&ctx
->event_list
,
3510 struct perf_event
, event_entry
);
3512 next_event
= list_first_entry(&next_ctx
->event_list
,
3513 struct perf_event
, event_entry
);
3515 while (&event
->event_entry
!= &ctx
->event_list
&&
3516 &next_event
->event_entry
!= &next_ctx
->event_list
) {
3518 __perf_event_sync_stat(event
, next_event
);
3520 event
= list_next_entry(event
, event_entry
);
3521 next_event
= list_next_entry(next_event
, event_entry
);
3525 #define double_list_for_each_entry(pos1, pos2, head1, head2, member) \
3526 for (pos1 = list_first_entry(head1, typeof(*pos1), member), \
3527 pos2 = list_first_entry(head2, typeof(*pos2), member); \
3528 !list_entry_is_head(pos1, head1, member) && \
3529 !list_entry_is_head(pos2, head2, member); \
3530 pos1 = list_next_entry(pos1, member), \
3531 pos2 = list_next_entry(pos2, member))
3533 static void perf_event_swap_task_ctx_data(struct perf_event_context
*prev_ctx
,
3534 struct perf_event_context
*next_ctx
)
3536 struct perf_event_pmu_context
*prev_epc
, *next_epc
;
3538 if (!prev_ctx
->nr_task_data
)
3541 double_list_for_each_entry(prev_epc
, next_epc
,
3542 &prev_ctx
->pmu_ctx_list
, &next_ctx
->pmu_ctx_list
,
3545 if (WARN_ON_ONCE(prev_epc
->pmu
!= next_epc
->pmu
))
3549 * PMU specific parts of task perf context can require
3550 * additional synchronization. As an example of such
3551 * synchronization see implementation details of Intel
3552 * LBR call stack data profiling;
3554 if (prev_epc
->pmu
->swap_task_ctx
)
3555 prev_epc
->pmu
->swap_task_ctx(prev_epc
, next_epc
);
3557 swap(prev_epc
->task_ctx_data
, next_epc
->task_ctx_data
);
3561 static void perf_ctx_sched_task_cb(struct perf_event_context
*ctx
, bool sched_in
)
3563 struct perf_event_pmu_context
*pmu_ctx
;
3564 struct perf_cpu_pmu_context
*cpc
;
3566 list_for_each_entry(pmu_ctx
, &ctx
->pmu_ctx_list
, pmu_ctx_entry
) {
3567 cpc
= this_cpu_ptr(pmu_ctx
->pmu
->cpu_pmu_context
);
3569 if (cpc
->sched_cb_usage
&& pmu_ctx
->pmu
->sched_task
)
3570 pmu_ctx
->pmu
->sched_task(pmu_ctx
, sched_in
);
3575 perf_event_context_sched_out(struct task_struct
*task
, struct task_struct
*next
)
3577 struct perf_event_context
*ctx
= task
->perf_event_ctxp
;
3578 struct perf_event_context
*next_ctx
;
3579 struct perf_event_context
*parent
, *next_parent
;
3586 next_ctx
= rcu_dereference(next
->perf_event_ctxp
);
3590 parent
= rcu_dereference(ctx
->parent_ctx
);
3591 next_parent
= rcu_dereference(next_ctx
->parent_ctx
);
3593 /* If neither context have a parent context; they cannot be clones. */
3594 if (!parent
&& !next_parent
)
3597 if (next_parent
== ctx
|| next_ctx
== parent
|| next_parent
== parent
) {
3599 * Looks like the two contexts are clones, so we might be
3600 * able to optimize the context switch. We lock both
3601 * contexts and check that they are clones under the
3602 * lock (including re-checking that neither has been
3603 * uncloned in the meantime). It doesn't matter which
3604 * order we take the locks because no other cpu could
3605 * be trying to lock both of these tasks.
3607 raw_spin_lock(&ctx
->lock
);
3608 raw_spin_lock_nested(&next_ctx
->lock
, SINGLE_DEPTH_NESTING
);
3609 if (context_equiv(ctx
, next_ctx
)) {
3611 perf_ctx_disable(ctx
, false);
3613 /* PMIs are disabled; ctx->nr_no_switch_fast is stable. */
3614 if (local_read(&ctx
->nr_no_switch_fast
) ||
3615 local_read(&next_ctx
->nr_no_switch_fast
)) {
3617 * Must not swap out ctx when there's pending
3618 * events that rely on the ctx->task relation.
3620 * Likewise, when a context contains inherit +
3621 * SAMPLE_READ events they should be switched
3622 * out using the slow path so that they are
3623 * treated as if they were distinct contexts.
3625 raw_spin_unlock(&next_ctx
->lock
);
3630 WRITE_ONCE(ctx
->task
, next
);
3631 WRITE_ONCE(next_ctx
->task
, task
);
3633 perf_ctx_sched_task_cb(ctx
, false);
3634 perf_event_swap_task_ctx_data(ctx
, next_ctx
);
3636 perf_ctx_enable(ctx
, false);
3639 * RCU_INIT_POINTER here is safe because we've not
3640 * modified the ctx and the above modification of
3641 * ctx->task and ctx->task_ctx_data are immaterial
3642 * since those values are always verified under
3643 * ctx->lock which we're now holding.
3645 RCU_INIT_POINTER(task
->perf_event_ctxp
, next_ctx
);
3646 RCU_INIT_POINTER(next
->perf_event_ctxp
, ctx
);
3650 perf_event_sync_stat(ctx
, next_ctx
);
3652 raw_spin_unlock(&next_ctx
->lock
);
3653 raw_spin_unlock(&ctx
->lock
);
3659 raw_spin_lock(&ctx
->lock
);
3660 perf_ctx_disable(ctx
, false);
3663 perf_ctx_sched_task_cb(ctx
, false);
3664 task_ctx_sched_out(ctx
, NULL
, EVENT_ALL
);
3666 perf_ctx_enable(ctx
, false);
3667 raw_spin_unlock(&ctx
->lock
);
3671 static DEFINE_PER_CPU(struct list_head
, sched_cb_list
);
3672 static DEFINE_PER_CPU(int, perf_sched_cb_usages
);
3674 void perf_sched_cb_dec(struct pmu
*pmu
)
3676 struct perf_cpu_pmu_context
*cpc
= this_cpu_ptr(pmu
->cpu_pmu_context
);
3678 this_cpu_dec(perf_sched_cb_usages
);
3681 if (!--cpc
->sched_cb_usage
)
3682 list_del(&cpc
->sched_cb_entry
);
3686 void perf_sched_cb_inc(struct pmu
*pmu
)
3688 struct perf_cpu_pmu_context
*cpc
= this_cpu_ptr(pmu
->cpu_pmu_context
);
3690 if (!cpc
->sched_cb_usage
++)
3691 list_add(&cpc
->sched_cb_entry
, this_cpu_ptr(&sched_cb_list
));
3694 this_cpu_inc(perf_sched_cb_usages
);
3698 * This function provides the context switch callback to the lower code
3699 * layer. It is invoked ONLY when the context switch callback is enabled.
3701 * This callback is relevant even to per-cpu events; for example multi event
3702 * PEBS requires this to provide PID/TID information. This requires we flush
3703 * all queued PEBS records before we context switch to a new task.
3705 static void __perf_pmu_sched_task(struct perf_cpu_pmu_context
*cpc
, bool sched_in
)
3707 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
3712 /* software PMUs will not have sched_task */
3713 if (WARN_ON_ONCE(!pmu
->sched_task
))
3716 perf_ctx_lock(cpuctx
, cpuctx
->task_ctx
);
3717 perf_pmu_disable(pmu
);
3719 pmu
->sched_task(cpc
->task_epc
, sched_in
);
3721 perf_pmu_enable(pmu
);
3722 perf_ctx_unlock(cpuctx
, cpuctx
->task_ctx
);
3725 static void perf_pmu_sched_task(struct task_struct
*prev
,
3726 struct task_struct
*next
,
3729 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
3730 struct perf_cpu_pmu_context
*cpc
;
3732 /* cpuctx->task_ctx will be handled in perf_event_context_sched_in/out */
3733 if (prev
== next
|| cpuctx
->task_ctx
)
3736 list_for_each_entry(cpc
, this_cpu_ptr(&sched_cb_list
), sched_cb_entry
)
3737 __perf_pmu_sched_task(cpc
, sched_in
);
3740 static void perf_event_switch(struct task_struct
*task
,
3741 struct task_struct
*next_prev
, bool sched_in
);
3744 * Called from scheduler to remove the events of the current task,
3745 * with interrupts disabled.
3747 * We stop each event and update the event value in event->count.
3749 * This does not protect us against NMI, but disable()
3750 * sets the disabled bit in the control field of event _before_
3751 * accessing the event control register. If a NMI hits, then it will
3752 * not restart the event.
3754 void __perf_event_task_sched_out(struct task_struct
*task
,
3755 struct task_struct
*next
)
3757 if (__this_cpu_read(perf_sched_cb_usages
))
3758 perf_pmu_sched_task(task
, next
, false);
3760 if (atomic_read(&nr_switch_events
))
3761 perf_event_switch(task
, next
, false);
3763 perf_event_context_sched_out(task
, next
);
3766 * if cgroup events exist on this CPU, then we need
3767 * to check if we have to switch out PMU state.
3768 * cgroup event are system-wide mode only
3770 perf_cgroup_switch(next
);
3773 static bool perf_less_group_idx(const void *l
, const void *r
, void __always_unused
*args
)
3775 const struct perf_event
*le
= *(const struct perf_event
**)l
;
3776 const struct perf_event
*re
= *(const struct perf_event
**)r
;
3778 return le
->group_index
< re
->group_index
;
3781 static void swap_ptr(void *l
, void *r
, void __always_unused
*args
)
3783 void **lp
= l
, **rp
= r
;
3788 DEFINE_MIN_HEAP(struct perf_event
*, perf_event_min_heap
);
3790 static const struct min_heap_callbacks perf_min_heap
= {
3791 .less
= perf_less_group_idx
,
3795 static void __heap_add(struct perf_event_min_heap
*heap
, struct perf_event
*event
)
3797 struct perf_event
**itrs
= heap
->data
;
3800 itrs
[heap
->nr
] = event
;
3805 static void __link_epc(struct perf_event_pmu_context
*pmu_ctx
)
3807 struct perf_cpu_pmu_context
*cpc
;
3809 if (!pmu_ctx
->ctx
->task
)
3812 cpc
= this_cpu_ptr(pmu_ctx
->pmu
->cpu_pmu_context
);
3813 WARN_ON_ONCE(cpc
->task_epc
&& cpc
->task_epc
!= pmu_ctx
);
3814 cpc
->task_epc
= pmu_ctx
;
3817 static noinline
int visit_groups_merge(struct perf_event_context
*ctx
,
3818 struct perf_event_groups
*groups
, int cpu
,
3820 int (*func
)(struct perf_event
*, void *),
3823 #ifdef CONFIG_CGROUP_PERF
3824 struct cgroup_subsys_state
*css
= NULL
;
3826 struct perf_cpu_context
*cpuctx
= NULL
;
3827 /* Space for per CPU and/or any CPU event iterators. */
3828 struct perf_event
*itrs
[2];
3829 struct perf_event_min_heap event_heap
;
3830 struct perf_event
**evt
;
3833 if (pmu
->filter
&& pmu
->filter(pmu
, cpu
))
3837 cpuctx
= this_cpu_ptr(&perf_cpu_context
);
3838 event_heap
= (struct perf_event_min_heap
){
3839 .data
= cpuctx
->heap
,
3841 .size
= cpuctx
->heap_size
,
3844 lockdep_assert_held(&cpuctx
->ctx
.lock
);
3846 #ifdef CONFIG_CGROUP_PERF
3848 css
= &cpuctx
->cgrp
->css
;
3851 event_heap
= (struct perf_event_min_heap
){
3854 .size
= ARRAY_SIZE(itrs
),
3856 /* Events not within a CPU context may be on any CPU. */
3857 __heap_add(&event_heap
, perf_event_groups_first(groups
, -1, pmu
, NULL
));
3859 evt
= event_heap
.data
;
3861 __heap_add(&event_heap
, perf_event_groups_first(groups
, cpu
, pmu
, NULL
));
3863 #ifdef CONFIG_CGROUP_PERF
3864 for (; css
; css
= css
->parent
)
3865 __heap_add(&event_heap
, perf_event_groups_first(groups
, cpu
, pmu
, css
->cgroup
));
3868 if (event_heap
.nr
) {
3869 __link_epc((*evt
)->pmu_ctx
);
3870 perf_assert_pmu_disabled((*evt
)->pmu_ctx
->pmu
);
3873 min_heapify_all(&event_heap
, &perf_min_heap
, NULL
);
3875 while (event_heap
.nr
) {
3876 ret
= func(*evt
, data
);
3880 *evt
= perf_event_groups_next(*evt
, pmu
);
3882 min_heap_sift_down(&event_heap
, 0, &perf_min_heap
, NULL
);
3884 min_heap_pop(&event_heap
, &perf_min_heap
, NULL
);
3891 * Because the userpage is strictly per-event (there is no concept of context,
3892 * so there cannot be a context indirection), every userpage must be updated
3893 * when context time starts :-(
3895 * IOW, we must not miss EVENT_TIME edges.
3897 static inline bool event_update_userpage(struct perf_event
*event
)
3899 if (likely(!atomic_read(&event
->mmap_count
)))
3902 perf_event_update_time(event
);
3903 perf_event_update_userpage(event
);
3908 static inline void group_update_userpage(struct perf_event
*group_event
)
3910 struct perf_event
*event
;
3912 if (!event_update_userpage(group_event
))
3915 for_each_sibling_event(event
, group_event
)
3916 event_update_userpage(event
);
3919 static int merge_sched_in(struct perf_event
*event
, void *data
)
3921 struct perf_event_context
*ctx
= event
->ctx
;
3922 int *can_add_hw
= data
;
3924 if (event
->state
<= PERF_EVENT_STATE_OFF
)
3927 if (!event_filter_match(event
))
3930 if (group_can_go_on(event
, *can_add_hw
)) {
3931 if (!group_sched_in(event
, ctx
))
3932 list_add_tail(&event
->active_list
, get_event_list(event
));
3935 if (event
->state
== PERF_EVENT_STATE_INACTIVE
) {
3937 if (event
->attr
.pinned
) {
3938 perf_cgroup_event_disable(event
, ctx
);
3939 perf_event_set_state(event
, PERF_EVENT_STATE_ERROR
);
3941 struct perf_cpu_pmu_context
*cpc
;
3943 event
->pmu_ctx
->rotate_necessary
= 1;
3944 cpc
= this_cpu_ptr(event
->pmu_ctx
->pmu
->cpu_pmu_context
);
3945 perf_mux_hrtimer_restart(cpc
);
3946 group_update_userpage(event
);
3953 static void pmu_groups_sched_in(struct perf_event_context
*ctx
,
3954 struct perf_event_groups
*groups
,
3958 visit_groups_merge(ctx
, groups
, smp_processor_id(), pmu
,
3959 merge_sched_in
, &can_add_hw
);
3962 static void __pmu_ctx_sched_in(struct perf_event_pmu_context
*pmu_ctx
,
3963 enum event_type_t event_type
)
3965 struct perf_event_context
*ctx
= pmu_ctx
->ctx
;
3967 if (event_type
& EVENT_PINNED
)
3968 pmu_groups_sched_in(ctx
, &ctx
->pinned_groups
, pmu_ctx
->pmu
);
3969 if (event_type
& EVENT_FLEXIBLE
)
3970 pmu_groups_sched_in(ctx
, &ctx
->flexible_groups
, pmu_ctx
->pmu
);
3974 ctx_sched_in(struct perf_event_context
*ctx
, struct pmu
*pmu
, enum event_type_t event_type
)
3976 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
3977 struct perf_event_pmu_context
*pmu_ctx
;
3978 int is_active
= ctx
->is_active
;
3979 bool cgroup
= event_type
& EVENT_CGROUP
;
3981 event_type
&= ~EVENT_CGROUP
;
3983 lockdep_assert_held(&ctx
->lock
);
3985 if (likely(!ctx
->nr_events
))
3988 if (!(is_active
& EVENT_TIME
)) {
3989 /* start ctx time */
3990 __update_context_time(ctx
, false);
3991 perf_cgroup_set_timestamp(cpuctx
);
3993 * CPU-release for the below ->is_active store,
3994 * see __load_acquire() in perf_event_time_now()
3999 ctx
->is_active
|= (event_type
| EVENT_TIME
);
4001 if (!(is_active
& EVENT_ALL
))
4002 cpuctx
->task_ctx
= ctx
;
4004 WARN_ON_ONCE(cpuctx
->task_ctx
!= ctx
);
4007 is_active
^= ctx
->is_active
; /* changed bits */
4010 * First go through the list and put on any pinned groups
4011 * in order to give them the best chance of going on.
4013 if (is_active
& EVENT_PINNED
) {
4014 for_each_epc(pmu_ctx
, ctx
, pmu
, cgroup
)
4015 __pmu_ctx_sched_in(pmu_ctx
, EVENT_PINNED
);
4018 /* Then walk through the lower prio flexible groups */
4019 if (is_active
& EVENT_FLEXIBLE
) {
4020 for_each_epc(pmu_ctx
, ctx
, pmu
, cgroup
)
4021 __pmu_ctx_sched_in(pmu_ctx
, EVENT_FLEXIBLE
);
4025 static void perf_event_context_sched_in(struct task_struct
*task
)
4027 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
4028 struct perf_event_context
*ctx
;
4031 ctx
= rcu_dereference(task
->perf_event_ctxp
);
4035 if (cpuctx
->task_ctx
== ctx
) {
4036 perf_ctx_lock(cpuctx
, ctx
);
4037 perf_ctx_disable(ctx
, false);
4039 perf_ctx_sched_task_cb(ctx
, true);
4041 perf_ctx_enable(ctx
, false);
4042 perf_ctx_unlock(cpuctx
, ctx
);
4046 perf_ctx_lock(cpuctx
, ctx
);
4048 * We must check ctx->nr_events while holding ctx->lock, such
4049 * that we serialize against perf_install_in_context().
4051 if (!ctx
->nr_events
)
4054 perf_ctx_disable(ctx
, false);
4056 * We want to keep the following priority order:
4057 * cpu pinned (that don't need to move), task pinned,
4058 * cpu flexible, task flexible.
4060 * However, if task's ctx is not carrying any pinned
4061 * events, no need to flip the cpuctx's events around.
4063 if (!RB_EMPTY_ROOT(&ctx
->pinned_groups
.tree
)) {
4064 perf_ctx_disable(&cpuctx
->ctx
, false);
4065 ctx_sched_out(&cpuctx
->ctx
, NULL
, EVENT_FLEXIBLE
);
4068 perf_event_sched_in(cpuctx
, ctx
, NULL
);
4070 perf_ctx_sched_task_cb(cpuctx
->task_ctx
, true);
4072 if (!RB_EMPTY_ROOT(&ctx
->pinned_groups
.tree
))
4073 perf_ctx_enable(&cpuctx
->ctx
, false);
4075 perf_ctx_enable(ctx
, false);
4078 perf_ctx_unlock(cpuctx
, ctx
);
4084 * Called from scheduler to add the events of the current task
4085 * with interrupts disabled.
4087 * We restore the event value and then enable it.
4089 * This does not protect us against NMI, but enable()
4090 * sets the enabled bit in the control field of event _before_
4091 * accessing the event control register. If a NMI hits, then it will
4092 * keep the event running.
4094 void __perf_event_task_sched_in(struct task_struct
*prev
,
4095 struct task_struct
*task
)
4097 perf_event_context_sched_in(task
);
4099 if (atomic_read(&nr_switch_events
))
4100 perf_event_switch(task
, prev
, true);
4102 if (__this_cpu_read(perf_sched_cb_usages
))
4103 perf_pmu_sched_task(prev
, task
, true);
4106 static u64
perf_calculate_period(struct perf_event
*event
, u64 nsec
, u64 count
)
4108 u64 frequency
= event
->attr
.sample_freq
;
4109 u64 sec
= NSEC_PER_SEC
;
4110 u64 divisor
, dividend
;
4112 int count_fls
, nsec_fls
, frequency_fls
, sec_fls
;
4114 count_fls
= fls64(count
);
4115 nsec_fls
= fls64(nsec
);
4116 frequency_fls
= fls64(frequency
);
4120 * We got @count in @nsec, with a target of sample_freq HZ
4121 * the target period becomes:
4124 * period = -------------------
4125 * @nsec * sample_freq
4130 * Reduce accuracy by one bit such that @a and @b converge
4131 * to a similar magnitude.
4133 #define REDUCE_FLS(a, b) \
4135 if (a##_fls > b##_fls) { \
4145 * Reduce accuracy until either term fits in a u64, then proceed with
4146 * the other, so that finally we can do a u64/u64 division.
4148 while (count_fls
+ sec_fls
> 64 && nsec_fls
+ frequency_fls
> 64) {
4149 REDUCE_FLS(nsec
, frequency
);
4150 REDUCE_FLS(sec
, count
);
4153 if (count_fls
+ sec_fls
> 64) {
4154 divisor
= nsec
* frequency
;
4156 while (count_fls
+ sec_fls
> 64) {
4157 REDUCE_FLS(count
, sec
);
4161 dividend
= count
* sec
;
4163 dividend
= count
* sec
;
4165 while (nsec_fls
+ frequency_fls
> 64) {
4166 REDUCE_FLS(nsec
, frequency
);
4170 divisor
= nsec
* frequency
;
4176 return div64_u64(dividend
, divisor
);
4179 static DEFINE_PER_CPU(int, perf_throttled_count
);
4180 static DEFINE_PER_CPU(u64
, perf_throttled_seq
);
4182 static void perf_adjust_period(struct perf_event
*event
, u64 nsec
, u64 count
, bool disable
)
4184 struct hw_perf_event
*hwc
= &event
->hw
;
4185 s64 period
, sample_period
;
4188 period
= perf_calculate_period(event
, nsec
, count
);
4190 delta
= (s64
)(period
- hwc
->sample_period
);
4195 delta
/= 8; /* low pass filter */
4197 sample_period
= hwc
->sample_period
+ delta
;
4202 hwc
->sample_period
= sample_period
;
4204 if (local64_read(&hwc
->period_left
) > 8*sample_period
) {
4206 event
->pmu
->stop(event
, PERF_EF_UPDATE
);
4208 local64_set(&hwc
->period_left
, 0);
4211 event
->pmu
->start(event
, PERF_EF_RELOAD
);
4215 static void perf_adjust_freq_unthr_events(struct list_head
*event_list
)
4217 struct perf_event
*event
;
4218 struct hw_perf_event
*hwc
;
4219 u64 now
, period
= TICK_NSEC
;
4222 list_for_each_entry(event
, event_list
, active_list
) {
4223 if (event
->state
!= PERF_EVENT_STATE_ACTIVE
)
4226 // XXX use visit thingy to avoid the -1,cpu match
4227 if (!event_filter_match(event
))
4232 if (hwc
->interrupts
== MAX_INTERRUPTS
) {
4233 hwc
->interrupts
= 0;
4234 perf_log_throttle(event
, 1);
4235 if (!event
->attr
.freq
|| !event
->attr
.sample_freq
)
4236 event
->pmu
->start(event
, 0);
4239 if (!event
->attr
.freq
|| !event
->attr
.sample_freq
)
4243 * stop the event and update event->count
4245 event
->pmu
->stop(event
, PERF_EF_UPDATE
);
4247 now
= local64_read(&event
->count
);
4248 delta
= now
- hwc
->freq_count_stamp
;
4249 hwc
->freq_count_stamp
= now
;
4253 * reload only if value has changed
4254 * we have stopped the event so tell that
4255 * to perf_adjust_period() to avoid stopping it
4259 perf_adjust_period(event
, period
, delta
, false);
4261 event
->pmu
->start(event
, delta
> 0 ? PERF_EF_RELOAD
: 0);
4266 * combine freq adjustment with unthrottling to avoid two passes over the
4267 * events. At the same time, make sure, having freq events does not change
4268 * the rate of unthrottling as that would introduce bias.
4271 perf_adjust_freq_unthr_context(struct perf_event_context
*ctx
, bool unthrottle
)
4273 struct perf_event_pmu_context
*pmu_ctx
;
4276 * only need to iterate over all events iff:
4277 * - context have events in frequency mode (needs freq adjust)
4278 * - there are events to unthrottle on this cpu
4280 if (!(ctx
->nr_freq
|| unthrottle
))
4283 raw_spin_lock(&ctx
->lock
);
4285 list_for_each_entry(pmu_ctx
, &ctx
->pmu_ctx_list
, pmu_ctx_entry
) {
4286 if (!(pmu_ctx
->nr_freq
|| unthrottle
))
4288 if (!perf_pmu_ctx_is_active(pmu_ctx
))
4290 if (pmu_ctx
->pmu
->capabilities
& PERF_PMU_CAP_NO_INTERRUPT
)
4293 perf_pmu_disable(pmu_ctx
->pmu
);
4294 perf_adjust_freq_unthr_events(&pmu_ctx
->pinned_active
);
4295 perf_adjust_freq_unthr_events(&pmu_ctx
->flexible_active
);
4296 perf_pmu_enable(pmu_ctx
->pmu
);
4299 raw_spin_unlock(&ctx
->lock
);
4303 * Move @event to the tail of the @ctx's elegible events.
4305 static void rotate_ctx(struct perf_event_context
*ctx
, struct perf_event
*event
)
4308 * Rotate the first entry last of non-pinned groups. Rotation might be
4309 * disabled by the inheritance code.
4311 if (ctx
->rotate_disable
)
4314 perf_event_groups_delete(&ctx
->flexible_groups
, event
);
4315 perf_event_groups_insert(&ctx
->flexible_groups
, event
);
4318 /* pick an event from the flexible_groups to rotate */
4319 static inline struct perf_event
*
4320 ctx_event_to_rotate(struct perf_event_pmu_context
*pmu_ctx
)
4322 struct perf_event
*event
;
4323 struct rb_node
*node
;
4324 struct rb_root
*tree
;
4325 struct __group_key key
= {
4326 .pmu
= pmu_ctx
->pmu
,
4329 /* pick the first active flexible event */
4330 event
= list_first_entry_or_null(&pmu_ctx
->flexible_active
,
4331 struct perf_event
, active_list
);
4335 /* if no active flexible event, pick the first event */
4336 tree
= &pmu_ctx
->ctx
->flexible_groups
.tree
;
4338 if (!pmu_ctx
->ctx
->task
) {
4339 key
.cpu
= smp_processor_id();
4341 node
= rb_find_first(&key
, tree
, __group_cmp_ignore_cgroup
);
4343 event
= __node_2_pe(node
);
4348 node
= rb_find_first(&key
, tree
, __group_cmp_ignore_cgroup
);
4350 event
= __node_2_pe(node
);
4354 key
.cpu
= smp_processor_id();
4355 node
= rb_find_first(&key
, tree
, __group_cmp_ignore_cgroup
);
4357 event
= __node_2_pe(node
);
4361 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4362 * finds there are unschedulable events, it will set it again.
4364 pmu_ctx
->rotate_necessary
= 0;
4369 static bool perf_rotate_context(struct perf_cpu_pmu_context
*cpc
)
4371 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
4372 struct perf_event_pmu_context
*cpu_epc
, *task_epc
= NULL
;
4373 struct perf_event
*cpu_event
= NULL
, *task_event
= NULL
;
4374 int cpu_rotate
, task_rotate
;
4378 * Since we run this from IRQ context, nobody can install new
4379 * events, thus the event count values are stable.
4382 cpu_epc
= &cpc
->epc
;
4384 task_epc
= cpc
->task_epc
;
4386 cpu_rotate
= cpu_epc
->rotate_necessary
;
4387 task_rotate
= task_epc
? task_epc
->rotate_necessary
: 0;
4389 if (!(cpu_rotate
|| task_rotate
))
4392 perf_ctx_lock(cpuctx
, cpuctx
->task_ctx
);
4393 perf_pmu_disable(pmu
);
4396 task_event
= ctx_event_to_rotate(task_epc
);
4398 cpu_event
= ctx_event_to_rotate(cpu_epc
);
4401 * As per the order given at ctx_resched() first 'pop' task flexible
4402 * and then, if needed CPU flexible.
4404 if (task_event
|| (task_epc
&& cpu_event
)) {
4405 update_context_time(task_epc
->ctx
);
4406 __pmu_ctx_sched_out(task_epc
, EVENT_FLEXIBLE
);
4410 update_context_time(&cpuctx
->ctx
);
4411 __pmu_ctx_sched_out(cpu_epc
, EVENT_FLEXIBLE
);
4412 rotate_ctx(&cpuctx
->ctx
, cpu_event
);
4413 __pmu_ctx_sched_in(cpu_epc
, EVENT_FLEXIBLE
);
4417 rotate_ctx(task_epc
->ctx
, task_event
);
4419 if (task_event
|| (task_epc
&& cpu_event
))
4420 __pmu_ctx_sched_in(task_epc
, EVENT_FLEXIBLE
);
4422 perf_pmu_enable(pmu
);
4423 perf_ctx_unlock(cpuctx
, cpuctx
->task_ctx
);
4428 void perf_event_task_tick(void)
4430 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
4431 struct perf_event_context
*ctx
;
4434 lockdep_assert_irqs_disabled();
4436 __this_cpu_inc(perf_throttled_seq
);
4437 throttled
= __this_cpu_xchg(perf_throttled_count
, 0);
4438 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS
);
4440 perf_adjust_freq_unthr_context(&cpuctx
->ctx
, !!throttled
);
4443 ctx
= rcu_dereference(current
->perf_event_ctxp
);
4445 perf_adjust_freq_unthr_context(ctx
, !!throttled
);
4449 static int event_enable_on_exec(struct perf_event
*event
,
4450 struct perf_event_context
*ctx
)
4452 if (!event
->attr
.enable_on_exec
)
4455 event
->attr
.enable_on_exec
= 0;
4456 if (event
->state
>= PERF_EVENT_STATE_INACTIVE
)
4459 perf_event_set_state(event
, PERF_EVENT_STATE_INACTIVE
);
4465 * Enable all of a task's events that have been marked enable-on-exec.
4466 * This expects task == current.
4468 static void perf_event_enable_on_exec(struct perf_event_context
*ctx
)
4470 struct perf_event_context
*clone_ctx
= NULL
;
4471 enum event_type_t event_type
= 0;
4472 struct perf_cpu_context
*cpuctx
;
4473 struct perf_event
*event
;
4474 unsigned long flags
;
4477 local_irq_save(flags
);
4478 if (WARN_ON_ONCE(current
->perf_event_ctxp
!= ctx
))
4481 if (!ctx
->nr_events
)
4484 cpuctx
= this_cpu_ptr(&perf_cpu_context
);
4485 perf_ctx_lock(cpuctx
, ctx
);
4486 ctx_time_freeze(cpuctx
, ctx
);
4488 list_for_each_entry(event
, &ctx
->event_list
, event_entry
) {
4489 enabled
|= event_enable_on_exec(event
, ctx
);
4490 event_type
|= get_event_type(event
);
4494 * Unclone and reschedule this context if we enabled any event.
4497 clone_ctx
= unclone_ctx(ctx
);
4498 ctx_resched(cpuctx
, ctx
, NULL
, event_type
);
4500 perf_ctx_unlock(cpuctx
, ctx
);
4503 local_irq_restore(flags
);
4509 static void perf_remove_from_owner(struct perf_event
*event
);
4510 static void perf_event_exit_event(struct perf_event
*event
,
4511 struct perf_event_context
*ctx
);
4514 * Removes all events from the current task that have been marked
4515 * remove-on-exec, and feeds their values back to parent events.
4517 static void perf_event_remove_on_exec(struct perf_event_context
*ctx
)
4519 struct perf_event_context
*clone_ctx
= NULL
;
4520 struct perf_event
*event
, *next
;
4521 unsigned long flags
;
4522 bool modified
= false;
4524 mutex_lock(&ctx
->mutex
);
4526 if (WARN_ON_ONCE(ctx
->task
!= current
))
4529 list_for_each_entry_safe(event
, next
, &ctx
->event_list
, event_entry
) {
4530 if (!event
->attr
.remove_on_exec
)
4533 if (!is_kernel_event(event
))
4534 perf_remove_from_owner(event
);
4538 perf_event_exit_event(event
, ctx
);
4541 raw_spin_lock_irqsave(&ctx
->lock
, flags
);
4543 clone_ctx
= unclone_ctx(ctx
);
4544 raw_spin_unlock_irqrestore(&ctx
->lock
, flags
);
4547 mutex_unlock(&ctx
->mutex
);
4553 struct perf_read_data
{
4554 struct perf_event
*event
;
4559 static inline const struct cpumask
*perf_scope_cpu_topology_cpumask(unsigned int scope
, int cpu
);
4561 static int __perf_event_read_cpu(struct perf_event
*event
, int event_cpu
)
4563 int local_cpu
= smp_processor_id();
4564 u16 local_pkg
, event_pkg
;
4566 if ((unsigned)event_cpu
>= nr_cpu_ids
)
4569 if (event
->group_caps
& PERF_EV_CAP_READ_SCOPE
) {
4570 const struct cpumask
*cpumask
= perf_scope_cpu_topology_cpumask(event
->pmu
->scope
, event_cpu
);
4572 if (cpumask
&& cpumask_test_cpu(local_cpu
, cpumask
))
4576 if (event
->group_caps
& PERF_EV_CAP_READ_ACTIVE_PKG
) {
4577 event_pkg
= topology_physical_package_id(event_cpu
);
4578 local_pkg
= topology_physical_package_id(local_cpu
);
4580 if (event_pkg
== local_pkg
)
4588 * Cross CPU call to read the hardware event
4590 static void __perf_event_read(void *info
)
4592 struct perf_read_data
*data
= info
;
4593 struct perf_event
*sub
, *event
= data
->event
;
4594 struct perf_event_context
*ctx
= event
->ctx
;
4595 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
4596 struct pmu
*pmu
= event
->pmu
;
4599 * If this is a task context, we need to check whether it is
4600 * the current task context of this cpu. If not it has been
4601 * scheduled out before the smp call arrived. In that case
4602 * event->count would have been updated to a recent sample
4603 * when the event was scheduled out.
4605 if (ctx
->task
&& cpuctx
->task_ctx
!= ctx
)
4608 raw_spin_lock(&ctx
->lock
);
4609 ctx_time_update_event(ctx
, event
);
4611 perf_event_update_time(event
);
4613 perf_event_update_sibling_time(event
);
4615 if (event
->state
!= PERF_EVENT_STATE_ACTIVE
)
4624 pmu
->start_txn(pmu
, PERF_PMU_TXN_READ
);
4628 for_each_sibling_event(sub
, event
) {
4629 if (sub
->state
== PERF_EVENT_STATE_ACTIVE
) {
4631 * Use sibling's PMU rather than @event's since
4632 * sibling could be on different (eg: software) PMU.
4634 sub
->pmu
->read(sub
);
4638 data
->ret
= pmu
->commit_txn(pmu
);
4641 raw_spin_unlock(&ctx
->lock
);
4644 static inline u64
perf_event_count(struct perf_event
*event
, bool self
)
4647 return local64_read(&event
->count
);
4649 return local64_read(&event
->count
) + atomic64_read(&event
->child_count
);
4652 static void calc_timer_values(struct perf_event
*event
,
4659 *now
= perf_clock();
4660 ctx_time
= perf_event_time_now(event
, *now
);
4661 __perf_update_times(event
, ctx_time
, enabled
, running
);
4665 * NMI-safe method to read a local event, that is an event that
4667 * - either for the current task, or for this CPU
4668 * - does not have inherit set, for inherited task events
4669 * will not be local and we cannot read them atomically
4670 * - must not have a pmu::count method
4672 int perf_event_read_local(struct perf_event
*event
, u64
*value
,
4673 u64
*enabled
, u64
*running
)
4675 unsigned long flags
;
4681 * Disabling interrupts avoids all counter scheduling (context
4682 * switches, timer based rotation and IPIs).
4684 local_irq_save(flags
);
4687 * It must not be an event with inherit set, we cannot read
4688 * all child counters from atomic context.
4690 if (event
->attr
.inherit
) {
4695 /* If this is a per-task event, it must be for current */
4696 if ((event
->attach_state
& PERF_ATTACH_TASK
) &&
4697 event
->hw
.target
!= current
) {
4703 * Get the event CPU numbers, and adjust them to local if the event is
4704 * a per-package event that can be read locally
4706 event_oncpu
= __perf_event_read_cpu(event
, event
->oncpu
);
4707 event_cpu
= __perf_event_read_cpu(event
, event
->cpu
);
4709 /* If this is a per-CPU event, it must be for this CPU */
4710 if (!(event
->attach_state
& PERF_ATTACH_TASK
) &&
4711 event_cpu
!= smp_processor_id()) {
4716 /* If this is a pinned event it must be running on this CPU */
4717 if (event
->attr
.pinned
&& event_oncpu
!= smp_processor_id()) {
4723 * If the event is currently on this CPU, its either a per-task event,
4724 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4727 if (event_oncpu
== smp_processor_id())
4728 event
->pmu
->read(event
);
4730 *value
= local64_read(&event
->count
);
4731 if (enabled
|| running
) {
4732 u64 __enabled
, __running
, __now
;
4734 calc_timer_values(event
, &__now
, &__enabled
, &__running
);
4736 *enabled
= __enabled
;
4738 *running
= __running
;
4741 local_irq_restore(flags
);
4746 static int perf_event_read(struct perf_event
*event
, bool group
)
4748 enum perf_event_state state
= READ_ONCE(event
->state
);
4749 int event_cpu
, ret
= 0;
4752 * If event is enabled and currently active on a CPU, update the
4753 * value in the event structure:
4756 if (state
== PERF_EVENT_STATE_ACTIVE
) {
4757 struct perf_read_data data
;
4760 * Orders the ->state and ->oncpu loads such that if we see
4761 * ACTIVE we must also see the right ->oncpu.
4763 * Matches the smp_wmb() from event_sched_in().
4767 event_cpu
= READ_ONCE(event
->oncpu
);
4768 if ((unsigned)event_cpu
>= nr_cpu_ids
)
4771 data
= (struct perf_read_data
){
4778 event_cpu
= __perf_event_read_cpu(event
, event_cpu
);
4781 * Purposely ignore the smp_call_function_single() return
4784 * If event_cpu isn't a valid CPU it means the event got
4785 * scheduled out and that will have updated the event count.
4787 * Therefore, either way, we'll have an up-to-date event count
4790 (void)smp_call_function_single(event_cpu
, __perf_event_read
, &data
, 1);
4794 } else if (state
== PERF_EVENT_STATE_INACTIVE
) {
4795 struct perf_event_context
*ctx
= event
->ctx
;
4796 unsigned long flags
;
4798 raw_spin_lock_irqsave(&ctx
->lock
, flags
);
4799 state
= event
->state
;
4800 if (state
!= PERF_EVENT_STATE_INACTIVE
) {
4801 raw_spin_unlock_irqrestore(&ctx
->lock
, flags
);
4806 * May read while context is not active (e.g., thread is
4807 * blocked), in that case we cannot update context time
4809 ctx_time_update_event(ctx
, event
);
4811 perf_event_update_time(event
);
4813 perf_event_update_sibling_time(event
);
4814 raw_spin_unlock_irqrestore(&ctx
->lock
, flags
);
4821 * Initialize the perf_event context in a task_struct:
4823 static void __perf_event_init_context(struct perf_event_context
*ctx
)
4825 raw_spin_lock_init(&ctx
->lock
);
4826 mutex_init(&ctx
->mutex
);
4827 INIT_LIST_HEAD(&ctx
->pmu_ctx_list
);
4828 perf_event_groups_init(&ctx
->pinned_groups
);
4829 perf_event_groups_init(&ctx
->flexible_groups
);
4830 INIT_LIST_HEAD(&ctx
->event_list
);
4831 refcount_set(&ctx
->refcount
, 1);
4835 __perf_init_event_pmu_context(struct perf_event_pmu_context
*epc
, struct pmu
*pmu
)
4838 INIT_LIST_HEAD(&epc
->pmu_ctx_entry
);
4839 INIT_LIST_HEAD(&epc
->pinned_active
);
4840 INIT_LIST_HEAD(&epc
->flexible_active
);
4841 atomic_set(&epc
->refcount
, 1);
4844 static struct perf_event_context
*
4845 alloc_perf_context(struct task_struct
*task
)
4847 struct perf_event_context
*ctx
;
4849 ctx
= kzalloc(sizeof(struct perf_event_context
), GFP_KERNEL
);
4853 __perf_event_init_context(ctx
);
4855 ctx
->task
= get_task_struct(task
);
4860 static struct task_struct
*
4861 find_lively_task_by_vpid(pid_t vpid
)
4863 struct task_struct
*task
;
4869 task
= find_task_by_vpid(vpid
);
4871 get_task_struct(task
);
4875 return ERR_PTR(-ESRCH
);
4881 * Returns a matching context with refcount and pincount.
4883 static struct perf_event_context
*
4884 find_get_context(struct task_struct
*task
, struct perf_event
*event
)
4886 struct perf_event_context
*ctx
, *clone_ctx
= NULL
;
4887 struct perf_cpu_context
*cpuctx
;
4888 unsigned long flags
;
4892 /* Must be root to operate on a CPU event: */
4893 err
= perf_allow_cpu(&event
->attr
);
4895 return ERR_PTR(err
);
4897 cpuctx
= per_cpu_ptr(&perf_cpu_context
, event
->cpu
);
4900 raw_spin_lock_irqsave(&ctx
->lock
, flags
);
4902 raw_spin_unlock_irqrestore(&ctx
->lock
, flags
);
4909 ctx
= perf_lock_task_context(task
, &flags
);
4911 clone_ctx
= unclone_ctx(ctx
);
4914 raw_spin_unlock_irqrestore(&ctx
->lock
, flags
);
4919 ctx
= alloc_perf_context(task
);
4925 mutex_lock(&task
->perf_event_mutex
);
4927 * If it has already passed perf_event_exit_task().
4928 * we must see PF_EXITING, it takes this mutex too.
4930 if (task
->flags
& PF_EXITING
)
4932 else if (task
->perf_event_ctxp
)
4937 rcu_assign_pointer(task
->perf_event_ctxp
, ctx
);
4939 mutex_unlock(&task
->perf_event_mutex
);
4941 if (unlikely(err
)) {
4953 return ERR_PTR(err
);
4956 static struct perf_event_pmu_context
*
4957 find_get_pmu_context(struct pmu
*pmu
, struct perf_event_context
*ctx
,
4958 struct perf_event
*event
)
4960 struct perf_event_pmu_context
*new = NULL
, *epc
;
4961 void *task_ctx_data
= NULL
;
4965 * perf_pmu_migrate_context() / __perf_pmu_install_event()
4966 * relies on the fact that find_get_pmu_context() cannot fail
4969 struct perf_cpu_pmu_context
*cpc
;
4971 cpc
= per_cpu_ptr(pmu
->cpu_pmu_context
, event
->cpu
);
4973 raw_spin_lock_irq(&ctx
->lock
);
4975 atomic_set(&epc
->refcount
, 1);
4977 list_add(&epc
->pmu_ctx_entry
, &ctx
->pmu_ctx_list
);
4980 WARN_ON_ONCE(epc
->ctx
!= ctx
);
4981 atomic_inc(&epc
->refcount
);
4983 raw_spin_unlock_irq(&ctx
->lock
);
4987 new = kzalloc(sizeof(*epc
), GFP_KERNEL
);
4989 return ERR_PTR(-ENOMEM
);
4991 if (event
->attach_state
& PERF_ATTACH_TASK_DATA
) {
4992 task_ctx_data
= alloc_task_ctx_data(pmu
);
4993 if (!task_ctx_data
) {
4995 return ERR_PTR(-ENOMEM
);
4999 __perf_init_event_pmu_context(new, pmu
);
5004 * lockdep_assert_held(&ctx->mutex);
5006 * can't because perf_event_init_task() doesn't actually hold the
5010 raw_spin_lock_irq(&ctx
->lock
);
5011 list_for_each_entry(epc
, &ctx
->pmu_ctx_list
, pmu_ctx_entry
) {
5012 if (epc
->pmu
== pmu
) {
5013 WARN_ON_ONCE(epc
->ctx
!= ctx
);
5014 atomic_inc(&epc
->refcount
);
5022 list_add(&epc
->pmu_ctx_entry
, &ctx
->pmu_ctx_list
);
5026 if (task_ctx_data
&& !epc
->task_ctx_data
) {
5027 epc
->task_ctx_data
= task_ctx_data
;
5028 task_ctx_data
= NULL
;
5029 ctx
->nr_task_data
++;
5031 raw_spin_unlock_irq(&ctx
->lock
);
5033 free_task_ctx_data(pmu
, task_ctx_data
);
5039 static void get_pmu_ctx(struct perf_event_pmu_context
*epc
)
5041 WARN_ON_ONCE(!atomic_inc_not_zero(&epc
->refcount
));
5044 static void free_epc_rcu(struct rcu_head
*head
)
5046 struct perf_event_pmu_context
*epc
= container_of(head
, typeof(*epc
), rcu_head
);
5048 kfree(epc
->task_ctx_data
);
5052 static void put_pmu_ctx(struct perf_event_pmu_context
*epc
)
5054 struct perf_event_context
*ctx
= epc
->ctx
;
5055 unsigned long flags
;
5060 * lockdep_assert_held(&ctx->mutex);
5062 * can't because of the call-site in _free_event()/put_event()
5063 * which isn't always called under ctx->mutex.
5065 if (!atomic_dec_and_raw_lock_irqsave(&epc
->refcount
, &ctx
->lock
, flags
))
5068 WARN_ON_ONCE(list_empty(&epc
->pmu_ctx_entry
));
5070 list_del_init(&epc
->pmu_ctx_entry
);
5073 WARN_ON_ONCE(!list_empty(&epc
->pinned_active
));
5074 WARN_ON_ONCE(!list_empty(&epc
->flexible_active
));
5076 raw_spin_unlock_irqrestore(&ctx
->lock
, flags
);
5081 call_rcu(&epc
->rcu_head
, free_epc_rcu
);
5084 static void perf_event_free_filter(struct perf_event
*event
);
5086 static void free_event_rcu(struct rcu_head
*head
)
5088 struct perf_event
*event
= container_of(head
, typeof(*event
), rcu_head
);
5091 put_pid_ns(event
->ns
);
5092 perf_event_free_filter(event
);
5093 kmem_cache_free(perf_event_cache
, event
);
5096 static void ring_buffer_attach(struct perf_event
*event
,
5097 struct perf_buffer
*rb
);
5099 static void detach_sb_event(struct perf_event
*event
)
5101 struct pmu_event_list
*pel
= per_cpu_ptr(&pmu_sb_events
, event
->cpu
);
5103 raw_spin_lock(&pel
->lock
);
5104 list_del_rcu(&event
->sb_list
);
5105 raw_spin_unlock(&pel
->lock
);
5108 static bool is_sb_event(struct perf_event
*event
)
5110 struct perf_event_attr
*attr
= &event
->attr
;
5115 if (event
->attach_state
& PERF_ATTACH_TASK
)
5118 if (attr
->mmap
|| attr
->mmap_data
|| attr
->mmap2
||
5119 attr
->comm
|| attr
->comm_exec
||
5120 attr
->task
|| attr
->ksymbol
||
5121 attr
->context_switch
|| attr
->text_poke
||
5127 static void unaccount_pmu_sb_event(struct perf_event
*event
)
5129 if (is_sb_event(event
))
5130 detach_sb_event(event
);
5133 #ifdef CONFIG_NO_HZ_FULL
5134 static DEFINE_SPINLOCK(nr_freq_lock
);
5137 static void unaccount_freq_event_nohz(void)
5139 #ifdef CONFIG_NO_HZ_FULL
5140 spin_lock(&nr_freq_lock
);
5141 if (atomic_dec_and_test(&nr_freq_events
))
5142 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS
);
5143 spin_unlock(&nr_freq_lock
);
5147 static void unaccount_freq_event(void)
5149 if (tick_nohz_full_enabled())
5150 unaccount_freq_event_nohz();
5152 atomic_dec(&nr_freq_events
);
5155 static void unaccount_event(struct perf_event
*event
)
5162 if (event
->attach_state
& (PERF_ATTACH_TASK
| PERF_ATTACH_SCHED_CB
))
5164 if (event
->attr
.mmap
|| event
->attr
.mmap_data
)
5165 atomic_dec(&nr_mmap_events
);
5166 if (event
->attr
.build_id
)
5167 atomic_dec(&nr_build_id_events
);
5168 if (event
->attr
.comm
)
5169 atomic_dec(&nr_comm_events
);
5170 if (event
->attr
.namespaces
)
5171 atomic_dec(&nr_namespaces_events
);
5172 if (event
->attr
.cgroup
)
5173 atomic_dec(&nr_cgroup_events
);
5174 if (event
->attr
.task
)
5175 atomic_dec(&nr_task_events
);
5176 if (event
->attr
.freq
)
5177 unaccount_freq_event();
5178 if (event
->attr
.context_switch
) {
5180 atomic_dec(&nr_switch_events
);
5182 if (is_cgroup_event(event
))
5184 if (has_branch_stack(event
))
5186 if (event
->attr
.ksymbol
)
5187 atomic_dec(&nr_ksymbol_events
);
5188 if (event
->attr
.bpf_event
)
5189 atomic_dec(&nr_bpf_events
);
5190 if (event
->attr
.text_poke
)
5191 atomic_dec(&nr_text_poke_events
);
5194 if (!atomic_add_unless(&perf_sched_count
, -1, 1))
5195 schedule_delayed_work(&perf_sched_work
, HZ
);
5198 unaccount_pmu_sb_event(event
);
5201 static void perf_sched_delayed(struct work_struct
*work
)
5203 mutex_lock(&perf_sched_mutex
);
5204 if (atomic_dec_and_test(&perf_sched_count
))
5205 static_branch_disable(&perf_sched_events
);
5206 mutex_unlock(&perf_sched_mutex
);
5210 * The following implement mutual exclusion of events on "exclusive" pmus
5211 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
5212 * at a time, so we disallow creating events that might conflict, namely:
5214 * 1) cpu-wide events in the presence of per-task events,
5215 * 2) per-task events in the presence of cpu-wide events,
5216 * 3) two matching events on the same perf_event_context.
5218 * The former two cases are handled in the allocation path (perf_event_alloc(),
5219 * _free_event()), the latter -- before the first perf_install_in_context().
5221 static int exclusive_event_init(struct perf_event
*event
)
5223 struct pmu
*pmu
= event
->pmu
;
5225 if (!is_exclusive_pmu(pmu
))
5229 * Prevent co-existence of per-task and cpu-wide events on the
5230 * same exclusive pmu.
5232 * Negative pmu::exclusive_cnt means there are cpu-wide
5233 * events on this "exclusive" pmu, positive means there are
5236 * Since this is called in perf_event_alloc() path, event::ctx
5237 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
5238 * to mean "per-task event", because unlike other attach states it
5239 * never gets cleared.
5241 if (event
->attach_state
& PERF_ATTACH_TASK
) {
5242 if (!atomic_inc_unless_negative(&pmu
->exclusive_cnt
))
5245 if (!atomic_dec_unless_positive(&pmu
->exclusive_cnt
))
5252 static void exclusive_event_destroy(struct perf_event
*event
)
5254 struct pmu
*pmu
= event
->pmu
;
5256 if (!is_exclusive_pmu(pmu
))
5259 /* see comment in exclusive_event_init() */
5260 if (event
->attach_state
& PERF_ATTACH_TASK
)
5261 atomic_dec(&pmu
->exclusive_cnt
);
5263 atomic_inc(&pmu
->exclusive_cnt
);
5266 static bool exclusive_event_match(struct perf_event
*e1
, struct perf_event
*e2
)
5268 if ((e1
->pmu
== e2
->pmu
) &&
5269 (e1
->cpu
== e2
->cpu
||
5276 static bool exclusive_event_installable(struct perf_event
*event
,
5277 struct perf_event_context
*ctx
)
5279 struct perf_event
*iter_event
;
5280 struct pmu
*pmu
= event
->pmu
;
5282 lockdep_assert_held(&ctx
->mutex
);
5284 if (!is_exclusive_pmu(pmu
))
5287 list_for_each_entry(iter_event
, &ctx
->event_list
, event_entry
) {
5288 if (exclusive_event_match(iter_event
, event
))
5295 static void perf_addr_filters_splice(struct perf_event
*event
,
5296 struct list_head
*head
);
5298 static void perf_pending_task_sync(struct perf_event
*event
)
5300 struct callback_head
*head
= &event
->pending_task
;
5302 if (!event
->pending_work
)
5305 * If the task is queued to the current task's queue, we
5306 * obviously can't wait for it to complete. Simply cancel it.
5308 if (task_work_cancel(current
, head
)) {
5309 event
->pending_work
= 0;
5310 local_dec(&event
->ctx
->nr_no_switch_fast
);
5315 * All accesses related to the event are within the same RCU section in
5316 * perf_pending_task(). The RCU grace period before the event is freed
5317 * will make sure all those accesses are complete by then.
5319 rcuwait_wait_event(&event
->pending_work_wait
, !event
->pending_work
, TASK_UNINTERRUPTIBLE
);
5322 static void _free_event(struct perf_event
*event
)
5324 irq_work_sync(&event
->pending_irq
);
5325 irq_work_sync(&event
->pending_disable_irq
);
5326 perf_pending_task_sync(event
);
5328 unaccount_event(event
);
5330 security_perf_event_free(event
);
5334 * Can happen when we close an event with re-directed output.
5336 * Since we have a 0 refcount, perf_mmap_close() will skip
5337 * over us; possibly making our ring_buffer_put() the last.
5339 mutex_lock(&event
->mmap_mutex
);
5340 ring_buffer_attach(event
, NULL
);
5341 mutex_unlock(&event
->mmap_mutex
);
5344 if (is_cgroup_event(event
))
5345 perf_detach_cgroup(event
);
5347 if (!event
->parent
) {
5348 if (event
->attr
.sample_type
& PERF_SAMPLE_CALLCHAIN
)
5349 put_callchain_buffers();
5352 perf_event_free_bpf_prog(event
);
5353 perf_addr_filters_splice(event
, NULL
);
5354 kfree(event
->addr_filter_ranges
);
5357 event
->destroy(event
);
5360 * Must be after ->destroy(), due to uprobe_perf_close() using
5363 if (event
->hw
.target
)
5364 put_task_struct(event
->hw
.target
);
5367 put_pmu_ctx(event
->pmu_ctx
);
5370 * perf_event_free_task() relies on put_ctx() being 'last', in particular
5371 * all task references must be cleaned up.
5374 put_ctx(event
->ctx
);
5376 exclusive_event_destroy(event
);
5377 module_put(event
->pmu
->module
);
5379 call_rcu(&event
->rcu_head
, free_event_rcu
);
5383 * Used to free events which have a known refcount of 1, such as in error paths
5384 * where the event isn't exposed yet and inherited events.
5386 static void free_event(struct perf_event
*event
)
5388 if (WARN(atomic_long_cmpxchg(&event
->refcount
, 1, 0) != 1,
5389 "unexpected event refcount: %ld; ptr=%p\n",
5390 atomic_long_read(&event
->refcount
), event
)) {
5391 /* leak to avoid use-after-free */
5399 * Remove user event from the owner task.
5401 static void perf_remove_from_owner(struct perf_event
*event
)
5403 struct task_struct
*owner
;
5407 * Matches the smp_store_release() in perf_event_exit_task(). If we
5408 * observe !owner it means the list deletion is complete and we can
5409 * indeed free this event, otherwise we need to serialize on
5410 * owner->perf_event_mutex.
5412 owner
= READ_ONCE(event
->owner
);
5415 * Since delayed_put_task_struct() also drops the last
5416 * task reference we can safely take a new reference
5417 * while holding the rcu_read_lock().
5419 get_task_struct(owner
);
5425 * If we're here through perf_event_exit_task() we're already
5426 * holding ctx->mutex which would be an inversion wrt. the
5427 * normal lock order.
5429 * However we can safely take this lock because its the child
5432 mutex_lock_nested(&owner
->perf_event_mutex
, SINGLE_DEPTH_NESTING
);
5435 * We have to re-check the event->owner field, if it is cleared
5436 * we raced with perf_event_exit_task(), acquiring the mutex
5437 * ensured they're done, and we can proceed with freeing the
5441 list_del_init(&event
->owner_entry
);
5442 smp_store_release(&event
->owner
, NULL
);
5444 mutex_unlock(&owner
->perf_event_mutex
);
5445 put_task_struct(owner
);
5449 static void put_event(struct perf_event
*event
)
5451 if (!atomic_long_dec_and_test(&event
->refcount
))
5458 * Kill an event dead; while event:refcount will preserve the event
5459 * object, it will not preserve its functionality. Once the last 'user'
5460 * gives up the object, we'll destroy the thing.
5462 int perf_event_release_kernel(struct perf_event
*event
)
5464 struct perf_event_context
*ctx
= event
->ctx
;
5465 struct perf_event
*child
, *tmp
;
5466 LIST_HEAD(free_list
);
5469 * If we got here through err_alloc: free_event(event); we will not
5470 * have attached to a context yet.
5473 WARN_ON_ONCE(event
->attach_state
&
5474 (PERF_ATTACH_CONTEXT
|PERF_ATTACH_GROUP
));
5478 if (!is_kernel_event(event
))
5479 perf_remove_from_owner(event
);
5481 ctx
= perf_event_ctx_lock(event
);
5482 WARN_ON_ONCE(ctx
->parent_ctx
);
5485 * Mark this event as STATE_DEAD, there is no external reference to it
5488 * Anybody acquiring event->child_mutex after the below loop _must_
5489 * also see this, most importantly inherit_event() which will avoid
5490 * placing more children on the list.
5492 * Thus this guarantees that we will in fact observe and kill _ALL_
5495 perf_remove_from_context(event
, DETACH_GROUP
|DETACH_DEAD
);
5497 perf_event_ctx_unlock(event
, ctx
);
5500 mutex_lock(&event
->child_mutex
);
5501 list_for_each_entry(child
, &event
->child_list
, child_list
) {
5505 * Cannot change, child events are not migrated, see the
5506 * comment with perf_event_ctx_lock_nested().
5508 ctx
= READ_ONCE(child
->ctx
);
5510 * Since child_mutex nests inside ctx::mutex, we must jump
5511 * through hoops. We start by grabbing a reference on the ctx.
5513 * Since the event cannot get freed while we hold the
5514 * child_mutex, the context must also exist and have a !0
5520 * Now that we have a ctx ref, we can drop child_mutex, and
5521 * acquire ctx::mutex without fear of it going away. Then we
5522 * can re-acquire child_mutex.
5524 mutex_unlock(&event
->child_mutex
);
5525 mutex_lock(&ctx
->mutex
);
5526 mutex_lock(&event
->child_mutex
);
5529 * Now that we hold ctx::mutex and child_mutex, revalidate our
5530 * state, if child is still the first entry, it didn't get freed
5531 * and we can continue doing so.
5533 tmp
= list_first_entry_or_null(&event
->child_list
,
5534 struct perf_event
, child_list
);
5536 perf_remove_from_context(child
, DETACH_GROUP
);
5537 list_move(&child
->child_list
, &free_list
);
5539 * This matches the refcount bump in inherit_event();
5540 * this can't be the last reference.
5544 var
= &ctx
->refcount
;
5547 mutex_unlock(&event
->child_mutex
);
5548 mutex_unlock(&ctx
->mutex
);
5553 * If perf_event_free_task() has deleted all events from the
5554 * ctx while the child_mutex got released above, make sure to
5555 * notify about the preceding put_ctx().
5557 smp_mb(); /* pairs with wait_var_event() */
5562 mutex_unlock(&event
->child_mutex
);
5564 list_for_each_entry_safe(child
, tmp
, &free_list
, child_list
) {
5565 void *var
= &child
->ctx
->refcount
;
5567 list_del(&child
->child_list
);
5571 * Wake any perf_event_free_task() waiting for this event to be
5574 smp_mb(); /* pairs with wait_var_event() */
5579 put_event(event
); /* Must be the 'last' reference */
5582 EXPORT_SYMBOL_GPL(perf_event_release_kernel
);
5585 * Called when the last reference to the file is gone.
5587 static int perf_release(struct inode
*inode
, struct file
*file
)
5589 perf_event_release_kernel(file
->private_data
);
5593 static u64
__perf_event_read_value(struct perf_event
*event
, u64
*enabled
, u64
*running
)
5595 struct perf_event
*child
;
5601 mutex_lock(&event
->child_mutex
);
5603 (void)perf_event_read(event
, false);
5604 total
+= perf_event_count(event
, false);
5606 *enabled
+= event
->total_time_enabled
+
5607 atomic64_read(&event
->child_total_time_enabled
);
5608 *running
+= event
->total_time_running
+
5609 atomic64_read(&event
->child_total_time_running
);
5611 list_for_each_entry(child
, &event
->child_list
, child_list
) {
5612 (void)perf_event_read(child
, false);
5613 total
+= perf_event_count(child
, false);
5614 *enabled
+= child
->total_time_enabled
;
5615 *running
+= child
->total_time_running
;
5617 mutex_unlock(&event
->child_mutex
);
5622 u64
perf_event_read_value(struct perf_event
*event
, u64
*enabled
, u64
*running
)
5624 struct perf_event_context
*ctx
;
5627 ctx
= perf_event_ctx_lock(event
);
5628 count
= __perf_event_read_value(event
, enabled
, running
);
5629 perf_event_ctx_unlock(event
, ctx
);
5633 EXPORT_SYMBOL_GPL(perf_event_read_value
);
5635 static int __perf_read_group_add(struct perf_event
*leader
,
5636 u64 read_format
, u64
*values
)
5638 struct perf_event_context
*ctx
= leader
->ctx
;
5639 struct perf_event
*sub
, *parent
;
5640 unsigned long flags
;
5641 int n
= 1; /* skip @nr */
5644 ret
= perf_event_read(leader
, true);
5648 raw_spin_lock_irqsave(&ctx
->lock
, flags
);
5650 * Verify the grouping between the parent and child (inherited)
5651 * events is still in tact.
5654 * - leader->ctx->lock pins leader->sibling_list
5655 * - parent->child_mutex pins parent->child_list
5656 * - parent->ctx->mutex pins parent->sibling_list
5658 * Because parent->ctx != leader->ctx (and child_list nests inside
5659 * ctx->mutex), group destruction is not atomic between children, also
5660 * see perf_event_release_kernel(). Additionally, parent can grow the
5663 * Therefore it is possible to have parent and child groups in a
5664 * different configuration and summing over such a beast makes no sense
5669 parent
= leader
->parent
;
5671 (parent
->group_generation
!= leader
->group_generation
||
5672 parent
->nr_siblings
!= leader
->nr_siblings
)) {
5678 * Since we co-schedule groups, {enabled,running} times of siblings
5679 * will be identical to those of the leader, so we only publish one
5682 if (read_format
& PERF_FORMAT_TOTAL_TIME_ENABLED
) {
5683 values
[n
++] += leader
->total_time_enabled
+
5684 atomic64_read(&leader
->child_total_time_enabled
);
5687 if (read_format
& PERF_FORMAT_TOTAL_TIME_RUNNING
) {
5688 values
[n
++] += leader
->total_time_running
+
5689 atomic64_read(&leader
->child_total_time_running
);
5693 * Write {count,id} tuples for every sibling.
5695 values
[n
++] += perf_event_count(leader
, false);
5696 if (read_format
& PERF_FORMAT_ID
)
5697 values
[n
++] = primary_event_id(leader
);
5698 if (read_format
& PERF_FORMAT_LOST
)
5699 values
[n
++] = atomic64_read(&leader
->lost_samples
);
5701 for_each_sibling_event(sub
, leader
) {
5702 values
[n
++] += perf_event_count(sub
, false);
5703 if (read_format
& PERF_FORMAT_ID
)
5704 values
[n
++] = primary_event_id(sub
);
5705 if (read_format
& PERF_FORMAT_LOST
)
5706 values
[n
++] = atomic64_read(&sub
->lost_samples
);
5710 raw_spin_unlock_irqrestore(&ctx
->lock
, flags
);
5714 static int perf_read_group(struct perf_event
*event
,
5715 u64 read_format
, char __user
*buf
)
5717 struct perf_event
*leader
= event
->group_leader
, *child
;
5718 struct perf_event_context
*ctx
= leader
->ctx
;
5722 lockdep_assert_held(&ctx
->mutex
);
5724 values
= kzalloc(event
->read_size
, GFP_KERNEL
);
5728 values
[0] = 1 + leader
->nr_siblings
;
5730 mutex_lock(&leader
->child_mutex
);
5732 ret
= __perf_read_group_add(leader
, read_format
, values
);
5736 list_for_each_entry(child
, &leader
->child_list
, child_list
) {
5737 ret
= __perf_read_group_add(child
, read_format
, values
);
5742 mutex_unlock(&leader
->child_mutex
);
5744 ret
= event
->read_size
;
5745 if (copy_to_user(buf
, values
, event
->read_size
))
5750 mutex_unlock(&leader
->child_mutex
);
5756 static int perf_read_one(struct perf_event
*event
,
5757 u64 read_format
, char __user
*buf
)
5759 u64 enabled
, running
;
5763 values
[n
++] = __perf_event_read_value(event
, &enabled
, &running
);
5764 if (read_format
& PERF_FORMAT_TOTAL_TIME_ENABLED
)
5765 values
[n
++] = enabled
;
5766 if (read_format
& PERF_FORMAT_TOTAL_TIME_RUNNING
)
5767 values
[n
++] = running
;
5768 if (read_format
& PERF_FORMAT_ID
)
5769 values
[n
++] = primary_event_id(event
);
5770 if (read_format
& PERF_FORMAT_LOST
)
5771 values
[n
++] = atomic64_read(&event
->lost_samples
);
5773 if (copy_to_user(buf
, values
, n
* sizeof(u64
)))
5776 return n
* sizeof(u64
);
5779 static bool is_event_hup(struct perf_event
*event
)
5783 if (event
->state
> PERF_EVENT_STATE_EXIT
)
5786 mutex_lock(&event
->child_mutex
);
5787 no_children
= list_empty(&event
->child_list
);
5788 mutex_unlock(&event
->child_mutex
);
5793 * Read the performance event - simple non blocking version for now
5796 __perf_read(struct perf_event
*event
, char __user
*buf
, size_t count
)
5798 u64 read_format
= event
->attr
.read_format
;
5802 * Return end-of-file for a read on an event that is in
5803 * error state (i.e. because it was pinned but it couldn't be
5804 * scheduled on to the CPU at some point).
5806 if (event
->state
== PERF_EVENT_STATE_ERROR
)
5809 if (count
< event
->read_size
)
5812 WARN_ON_ONCE(event
->ctx
->parent_ctx
);
5813 if (read_format
& PERF_FORMAT_GROUP
)
5814 ret
= perf_read_group(event
, read_format
, buf
);
5816 ret
= perf_read_one(event
, read_format
, buf
);
5822 perf_read(struct file
*file
, char __user
*buf
, size_t count
, loff_t
*ppos
)
5824 struct perf_event
*event
= file
->private_data
;
5825 struct perf_event_context
*ctx
;
5828 ret
= security_perf_event_read(event
);
5832 ctx
= perf_event_ctx_lock(event
);
5833 ret
= __perf_read(event
, buf
, count
);
5834 perf_event_ctx_unlock(event
, ctx
);
5839 static __poll_t
perf_poll(struct file
*file
, poll_table
*wait
)
5841 struct perf_event
*event
= file
->private_data
;
5842 struct perf_buffer
*rb
;
5843 __poll_t events
= EPOLLHUP
;
5845 poll_wait(file
, &event
->waitq
, wait
);
5847 if (is_event_hup(event
))
5851 * Pin the event->rb by taking event->mmap_mutex; otherwise
5852 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5854 mutex_lock(&event
->mmap_mutex
);
5857 events
= atomic_xchg(&rb
->poll
, 0);
5858 mutex_unlock(&event
->mmap_mutex
);
5862 static void _perf_event_reset(struct perf_event
*event
)
5864 (void)perf_event_read(event
, false);
5865 local64_set(&event
->count
, 0);
5866 perf_event_update_userpage(event
);
5869 /* Assume it's not an event with inherit set. */
5870 u64
perf_event_pause(struct perf_event
*event
, bool reset
)
5872 struct perf_event_context
*ctx
;
5875 ctx
= perf_event_ctx_lock(event
);
5876 WARN_ON_ONCE(event
->attr
.inherit
);
5877 _perf_event_disable(event
);
5878 count
= local64_read(&event
->count
);
5880 local64_set(&event
->count
, 0);
5881 perf_event_ctx_unlock(event
, ctx
);
5885 EXPORT_SYMBOL_GPL(perf_event_pause
);
5888 * Holding the top-level event's child_mutex means that any
5889 * descendant process that has inherited this event will block
5890 * in perf_event_exit_event() if it goes to exit, thus satisfying the
5891 * task existence requirements of perf_event_enable/disable.
5893 static void perf_event_for_each_child(struct perf_event
*event
,
5894 void (*func
)(struct perf_event
*))
5896 struct perf_event
*child
;
5898 WARN_ON_ONCE(event
->ctx
->parent_ctx
);
5900 mutex_lock(&event
->child_mutex
);
5902 list_for_each_entry(child
, &event
->child_list
, child_list
)
5904 mutex_unlock(&event
->child_mutex
);
5907 static void perf_event_for_each(struct perf_event
*event
,
5908 void (*func
)(struct perf_event
*))
5910 struct perf_event_context
*ctx
= event
->ctx
;
5911 struct perf_event
*sibling
;
5913 lockdep_assert_held(&ctx
->mutex
);
5915 event
= event
->group_leader
;
5917 perf_event_for_each_child(event
, func
);
5918 for_each_sibling_event(sibling
, event
)
5919 perf_event_for_each_child(sibling
, func
);
5922 static void __perf_event_period(struct perf_event
*event
,
5923 struct perf_cpu_context
*cpuctx
,
5924 struct perf_event_context
*ctx
,
5927 u64 value
= *((u64
*)info
);
5930 if (event
->attr
.freq
) {
5931 event
->attr
.sample_freq
= value
;
5933 event
->attr
.sample_period
= value
;
5934 event
->hw
.sample_period
= value
;
5937 active
= (event
->state
== PERF_EVENT_STATE_ACTIVE
);
5939 perf_pmu_disable(event
->pmu
);
5941 * We could be throttled; unthrottle now to avoid the tick
5942 * trying to unthrottle while we already re-started the event.
5944 if (event
->hw
.interrupts
== MAX_INTERRUPTS
) {
5945 event
->hw
.interrupts
= 0;
5946 perf_log_throttle(event
, 1);
5948 event
->pmu
->stop(event
, PERF_EF_UPDATE
);
5951 local64_set(&event
->hw
.period_left
, 0);
5954 event
->pmu
->start(event
, PERF_EF_RELOAD
);
5955 perf_pmu_enable(event
->pmu
);
5959 static int perf_event_check_period(struct perf_event
*event
, u64 value
)
5961 return event
->pmu
->check_period(event
, value
);
5964 static int _perf_event_period(struct perf_event
*event
, u64 value
)
5966 if (!is_sampling_event(event
))
5972 if (event
->attr
.freq
&& value
> sysctl_perf_event_sample_rate
)
5975 if (perf_event_check_period(event
, value
))
5978 if (!event
->attr
.freq
&& (value
& (1ULL << 63)))
5981 event_function_call(event
, __perf_event_period
, &value
);
5986 int perf_event_period(struct perf_event
*event
, u64 value
)
5988 struct perf_event_context
*ctx
;
5991 ctx
= perf_event_ctx_lock(event
);
5992 ret
= _perf_event_period(event
, value
);
5993 perf_event_ctx_unlock(event
, ctx
);
5997 EXPORT_SYMBOL_GPL(perf_event_period
);
5999 static const struct file_operations perf_fops
;
6001 static inline int perf_fget_light(int fd
, struct fd
*p
)
6003 struct fd f
= fdget(fd
);
6007 if (fd_file(f
)->f_op
!= &perf_fops
) {
6015 static int perf_event_set_output(struct perf_event
*event
,
6016 struct perf_event
*output_event
);
6017 static int perf_event_set_filter(struct perf_event
*event
, void __user
*arg
);
6018 static int perf_copy_attr(struct perf_event_attr __user
*uattr
,
6019 struct perf_event_attr
*attr
);
6021 static long _perf_ioctl(struct perf_event
*event
, unsigned int cmd
, unsigned long arg
)
6023 void (*func
)(struct perf_event
*);
6027 case PERF_EVENT_IOC_ENABLE
:
6028 func
= _perf_event_enable
;
6030 case PERF_EVENT_IOC_DISABLE
:
6031 func
= _perf_event_disable
;
6033 case PERF_EVENT_IOC_RESET
:
6034 func
= _perf_event_reset
;
6037 case PERF_EVENT_IOC_REFRESH
:
6038 return _perf_event_refresh(event
, arg
);
6040 case PERF_EVENT_IOC_PERIOD
:
6044 if (copy_from_user(&value
, (u64 __user
*)arg
, sizeof(value
)))
6047 return _perf_event_period(event
, value
);
6049 case PERF_EVENT_IOC_ID
:
6051 u64 id
= primary_event_id(event
);
6053 if (copy_to_user((void __user
*)arg
, &id
, sizeof(id
)))
6058 case PERF_EVENT_IOC_SET_OUTPUT
:
6062 struct perf_event
*output_event
;
6064 ret
= perf_fget_light(arg
, &output
);
6067 output_event
= fd_file(output
)->private_data
;
6068 ret
= perf_event_set_output(event
, output_event
);
6071 ret
= perf_event_set_output(event
, NULL
);
6076 case PERF_EVENT_IOC_SET_FILTER
:
6077 return perf_event_set_filter(event
, (void __user
*)arg
);
6079 case PERF_EVENT_IOC_SET_BPF
:
6081 struct bpf_prog
*prog
;
6084 prog
= bpf_prog_get(arg
);
6086 return PTR_ERR(prog
);
6088 err
= perf_event_set_bpf_prog(event
, prog
, 0);
6097 case PERF_EVENT_IOC_PAUSE_OUTPUT
: {
6098 struct perf_buffer
*rb
;
6101 rb
= rcu_dereference(event
->rb
);
6102 if (!rb
|| !rb
->nr_pages
) {
6106 rb_toggle_paused(rb
, !!arg
);
6111 case PERF_EVENT_IOC_QUERY_BPF
:
6112 return perf_event_query_prog_array(event
, (void __user
*)arg
);
6114 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES
: {
6115 struct perf_event_attr new_attr
;
6116 int err
= perf_copy_attr((struct perf_event_attr __user
*)arg
,
6122 return perf_event_modify_attr(event
, &new_attr
);
6128 if (flags
& PERF_IOC_FLAG_GROUP
)
6129 perf_event_for_each(event
, func
);
6131 perf_event_for_each_child(event
, func
);
6136 static long perf_ioctl(struct file
*file
, unsigned int cmd
, unsigned long arg
)
6138 struct perf_event
*event
= file
->private_data
;
6139 struct perf_event_context
*ctx
;
6142 /* Treat ioctl like writes as it is likely a mutating operation. */
6143 ret
= security_perf_event_write(event
);
6147 ctx
= perf_event_ctx_lock(event
);
6148 ret
= _perf_ioctl(event
, cmd
, arg
);
6149 perf_event_ctx_unlock(event
, ctx
);
6154 #ifdef CONFIG_COMPAT
6155 static long perf_compat_ioctl(struct file
*file
, unsigned int cmd
,
6158 switch (_IOC_NR(cmd
)) {
6159 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER
):
6160 case _IOC_NR(PERF_EVENT_IOC_ID
):
6161 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF
):
6162 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES
):
6163 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
6164 if (_IOC_SIZE(cmd
) == sizeof(compat_uptr_t
)) {
6165 cmd
&= ~IOCSIZE_MASK
;
6166 cmd
|= sizeof(void *) << IOCSIZE_SHIFT
;
6170 return perf_ioctl(file
, cmd
, arg
);
6173 # define perf_compat_ioctl NULL
6176 int perf_event_task_enable(void)
6178 struct perf_event_context
*ctx
;
6179 struct perf_event
*event
;
6181 mutex_lock(¤t
->perf_event_mutex
);
6182 list_for_each_entry(event
, ¤t
->perf_event_list
, owner_entry
) {
6183 ctx
= perf_event_ctx_lock(event
);
6184 perf_event_for_each_child(event
, _perf_event_enable
);
6185 perf_event_ctx_unlock(event
, ctx
);
6187 mutex_unlock(¤t
->perf_event_mutex
);
6192 int perf_event_task_disable(void)
6194 struct perf_event_context
*ctx
;
6195 struct perf_event
*event
;
6197 mutex_lock(¤t
->perf_event_mutex
);
6198 list_for_each_entry(event
, ¤t
->perf_event_list
, owner_entry
) {
6199 ctx
= perf_event_ctx_lock(event
);
6200 perf_event_for_each_child(event
, _perf_event_disable
);
6201 perf_event_ctx_unlock(event
, ctx
);
6203 mutex_unlock(¤t
->perf_event_mutex
);
6208 static int perf_event_index(struct perf_event
*event
)
6210 if (event
->hw
.state
& PERF_HES_STOPPED
)
6213 if (event
->state
!= PERF_EVENT_STATE_ACTIVE
)
6216 return event
->pmu
->event_idx(event
);
6219 static void perf_event_init_userpage(struct perf_event
*event
)
6221 struct perf_event_mmap_page
*userpg
;
6222 struct perf_buffer
*rb
;
6225 rb
= rcu_dereference(event
->rb
);
6229 userpg
= rb
->user_page
;
6231 /* Allow new userspace to detect that bit 0 is deprecated */
6232 userpg
->cap_bit0_is_deprecated
= 1;
6233 userpg
->size
= offsetof(struct perf_event_mmap_page
, __reserved
);
6234 userpg
->data_offset
= PAGE_SIZE
;
6235 userpg
->data_size
= perf_data_size(rb
);
6241 void __weak
arch_perf_update_userpage(
6242 struct perf_event
*event
, struct perf_event_mmap_page
*userpg
, u64 now
)
6247 * Callers need to ensure there can be no nesting of this function, otherwise
6248 * the seqlock logic goes bad. We can not serialize this because the arch
6249 * code calls this from NMI context.
6251 void perf_event_update_userpage(struct perf_event
*event
)
6253 struct perf_event_mmap_page
*userpg
;
6254 struct perf_buffer
*rb
;
6255 u64 enabled
, running
, now
;
6258 rb
= rcu_dereference(event
->rb
);
6263 * compute total_time_enabled, total_time_running
6264 * based on snapshot values taken when the event
6265 * was last scheduled in.
6267 * we cannot simply called update_context_time()
6268 * because of locking issue as we can be called in
6271 calc_timer_values(event
, &now
, &enabled
, &running
);
6273 userpg
= rb
->user_page
;
6275 * Disable preemption to guarantee consistent time stamps are stored to
6281 userpg
->index
= perf_event_index(event
);
6282 userpg
->offset
= perf_event_count(event
, false);
6284 userpg
->offset
-= local64_read(&event
->hw
.prev_count
);
6286 userpg
->time_enabled
= enabled
+
6287 atomic64_read(&event
->child_total_time_enabled
);
6289 userpg
->time_running
= running
+
6290 atomic64_read(&event
->child_total_time_running
);
6292 arch_perf_update_userpage(event
, userpg
, now
);
6300 EXPORT_SYMBOL_GPL(perf_event_update_userpage
);
6302 static vm_fault_t
perf_mmap_fault(struct vm_fault
*vmf
)
6304 struct perf_event
*event
= vmf
->vma
->vm_file
->private_data
;
6305 struct perf_buffer
*rb
;
6306 vm_fault_t ret
= VM_FAULT_SIGBUS
;
6308 if (vmf
->flags
& FAULT_FLAG_MKWRITE
) {
6309 if (vmf
->pgoff
== 0)
6315 rb
= rcu_dereference(event
->rb
);
6319 if (vmf
->pgoff
&& (vmf
->flags
& FAULT_FLAG_WRITE
))
6322 vmf
->page
= perf_mmap_to_page(rb
, vmf
->pgoff
);
6326 get_page(vmf
->page
);
6327 vmf
->page
->mapping
= vmf
->vma
->vm_file
->f_mapping
;
6328 vmf
->page
->index
= vmf
->pgoff
;
6337 static void ring_buffer_attach(struct perf_event
*event
,
6338 struct perf_buffer
*rb
)
6340 struct perf_buffer
*old_rb
= NULL
;
6341 unsigned long flags
;
6343 WARN_ON_ONCE(event
->parent
);
6347 * Should be impossible, we set this when removing
6348 * event->rb_entry and wait/clear when adding event->rb_entry.
6350 WARN_ON_ONCE(event
->rcu_pending
);
6353 spin_lock_irqsave(&old_rb
->event_lock
, flags
);
6354 list_del_rcu(&event
->rb_entry
);
6355 spin_unlock_irqrestore(&old_rb
->event_lock
, flags
);
6357 event
->rcu_batches
= get_state_synchronize_rcu();
6358 event
->rcu_pending
= 1;
6362 if (event
->rcu_pending
) {
6363 cond_synchronize_rcu(event
->rcu_batches
);
6364 event
->rcu_pending
= 0;
6367 spin_lock_irqsave(&rb
->event_lock
, flags
);
6368 list_add_rcu(&event
->rb_entry
, &rb
->event_list
);
6369 spin_unlock_irqrestore(&rb
->event_lock
, flags
);
6373 * Avoid racing with perf_mmap_close(AUX): stop the event
6374 * before swizzling the event::rb pointer; if it's getting
6375 * unmapped, its aux_mmap_count will be 0 and it won't
6376 * restart. See the comment in __perf_pmu_output_stop().
6378 * Data will inevitably be lost when set_output is done in
6379 * mid-air, but then again, whoever does it like this is
6380 * not in for the data anyway.
6383 perf_event_stop(event
, 0);
6385 rcu_assign_pointer(event
->rb
, rb
);
6388 ring_buffer_put(old_rb
);
6390 * Since we detached before setting the new rb, so that we
6391 * could attach the new rb, we could have missed a wakeup.
6394 wake_up_all(&event
->waitq
);
6398 static void ring_buffer_wakeup(struct perf_event
*event
)
6400 struct perf_buffer
*rb
;
6403 event
= event
->parent
;
6406 rb
= rcu_dereference(event
->rb
);
6408 list_for_each_entry_rcu(event
, &rb
->event_list
, rb_entry
)
6409 wake_up_all(&event
->waitq
);
6414 struct perf_buffer
*ring_buffer_get(struct perf_event
*event
)
6416 struct perf_buffer
*rb
;
6419 event
= event
->parent
;
6422 rb
= rcu_dereference(event
->rb
);
6424 if (!refcount_inc_not_zero(&rb
->refcount
))
6432 void ring_buffer_put(struct perf_buffer
*rb
)
6434 if (!refcount_dec_and_test(&rb
->refcount
))
6437 WARN_ON_ONCE(!list_empty(&rb
->event_list
));
6439 call_rcu(&rb
->rcu_head
, rb_free_rcu
);
6442 static void perf_mmap_open(struct vm_area_struct
*vma
)
6444 struct perf_event
*event
= vma
->vm_file
->private_data
;
6446 atomic_inc(&event
->mmap_count
);
6447 atomic_inc(&event
->rb
->mmap_count
);
6450 atomic_inc(&event
->rb
->aux_mmap_count
);
6452 if (event
->pmu
->event_mapped
)
6453 event
->pmu
->event_mapped(event
, vma
->vm_mm
);
6456 static void perf_pmu_output_stop(struct perf_event
*event
);
6459 * A buffer can be mmap()ed multiple times; either directly through the same
6460 * event, or through other events by use of perf_event_set_output().
6462 * In order to undo the VM accounting done by perf_mmap() we need to destroy
6463 * the buffer here, where we still have a VM context. This means we need
6464 * to detach all events redirecting to us.
6466 static void perf_mmap_close(struct vm_area_struct
*vma
)
6468 struct perf_event
*event
= vma
->vm_file
->private_data
;
6469 struct perf_buffer
*rb
= ring_buffer_get(event
);
6470 struct user_struct
*mmap_user
= rb
->mmap_user
;
6471 int mmap_locked
= rb
->mmap_locked
;
6472 unsigned long size
= perf_data_size(rb
);
6473 bool detach_rest
= false;
6475 if (event
->pmu
->event_unmapped
)
6476 event
->pmu
->event_unmapped(event
, vma
->vm_mm
);
6479 * The AUX buffer is strictly a sub-buffer, serialize using aux_mutex
6480 * to avoid complications.
6482 if (rb_has_aux(rb
) && vma
->vm_pgoff
== rb
->aux_pgoff
&&
6483 atomic_dec_and_mutex_lock(&rb
->aux_mmap_count
, &rb
->aux_mutex
)) {
6485 * Stop all AUX events that are writing to this buffer,
6486 * so that we can free its AUX pages and corresponding PMU
6487 * data. Note that after rb::aux_mmap_count dropped to zero,
6488 * they won't start any more (see perf_aux_output_begin()).
6490 perf_pmu_output_stop(event
);
6492 /* now it's safe to free the pages */
6493 atomic_long_sub(rb
->aux_nr_pages
- rb
->aux_mmap_locked
, &mmap_user
->locked_vm
);
6494 atomic64_sub(rb
->aux_mmap_locked
, &vma
->vm_mm
->pinned_vm
);
6496 /* this has to be the last one */
6498 WARN_ON_ONCE(refcount_read(&rb
->aux_refcount
));
6500 mutex_unlock(&rb
->aux_mutex
);
6503 if (atomic_dec_and_test(&rb
->mmap_count
))
6506 if (!atomic_dec_and_mutex_lock(&event
->mmap_count
, &event
->mmap_mutex
))
6509 ring_buffer_attach(event
, NULL
);
6510 mutex_unlock(&event
->mmap_mutex
);
6512 /* If there's still other mmap()s of this buffer, we're done. */
6517 * No other mmap()s, detach from all other events that might redirect
6518 * into the now unreachable buffer. Somewhat complicated by the
6519 * fact that rb::event_lock otherwise nests inside mmap_mutex.
6523 list_for_each_entry_rcu(event
, &rb
->event_list
, rb_entry
) {
6524 if (!atomic_long_inc_not_zero(&event
->refcount
)) {
6526 * This event is en-route to free_event() which will
6527 * detach it and remove it from the list.
6533 mutex_lock(&event
->mmap_mutex
);
6535 * Check we didn't race with perf_event_set_output() which can
6536 * swizzle the rb from under us while we were waiting to
6537 * acquire mmap_mutex.
6539 * If we find a different rb; ignore this event, a next
6540 * iteration will no longer find it on the list. We have to
6541 * still restart the iteration to make sure we're not now
6542 * iterating the wrong list.
6544 if (event
->rb
== rb
)
6545 ring_buffer_attach(event
, NULL
);
6547 mutex_unlock(&event
->mmap_mutex
);
6551 * Restart the iteration; either we're on the wrong list or
6552 * destroyed its integrity by doing a deletion.
6559 * It could be there's still a few 0-ref events on the list; they'll
6560 * get cleaned up by free_event() -- they'll also still have their
6561 * ref on the rb and will free it whenever they are done with it.
6563 * Aside from that, this buffer is 'fully' detached and unmapped,
6564 * undo the VM accounting.
6567 atomic_long_sub((size
>> PAGE_SHIFT
) + 1 - mmap_locked
,
6568 &mmap_user
->locked_vm
);
6569 atomic64_sub(mmap_locked
, &vma
->vm_mm
->pinned_vm
);
6570 free_uid(mmap_user
);
6573 ring_buffer_put(rb
); /* could be last */
6576 static const struct vm_operations_struct perf_mmap_vmops
= {
6577 .open
= perf_mmap_open
,
6578 .close
= perf_mmap_close
, /* non mergeable */
6579 .fault
= perf_mmap_fault
,
6580 .page_mkwrite
= perf_mmap_fault
,
6583 static int perf_mmap(struct file
*file
, struct vm_area_struct
*vma
)
6585 struct perf_event
*event
= file
->private_data
;
6586 unsigned long user_locked
, user_lock_limit
;
6587 struct user_struct
*user
= current_user();
6588 struct mutex
*aux_mutex
= NULL
;
6589 struct perf_buffer
*rb
= NULL
;
6590 unsigned long locked
, lock_limit
;
6591 unsigned long vma_size
;
6592 unsigned long nr_pages
;
6593 long user_extra
= 0, extra
= 0;
6594 int ret
= 0, flags
= 0;
6597 * Don't allow mmap() of inherited per-task counters. This would
6598 * create a performance issue due to all children writing to the
6601 if (event
->cpu
== -1 && event
->attr
.inherit
)
6604 if (!(vma
->vm_flags
& VM_SHARED
))
6607 ret
= security_perf_event_read(event
);
6611 vma_size
= vma
->vm_end
- vma
->vm_start
;
6613 if (vma
->vm_pgoff
== 0) {
6614 nr_pages
= (vma_size
/ PAGE_SIZE
) - 1;
6617 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
6618 * mapped, all subsequent mappings should have the same size
6619 * and offset. Must be above the normal perf buffer.
6621 u64 aux_offset
, aux_size
;
6626 nr_pages
= vma_size
/ PAGE_SIZE
;
6627 if (nr_pages
> INT_MAX
)
6630 mutex_lock(&event
->mmap_mutex
);
6637 aux_mutex
= &rb
->aux_mutex
;
6638 mutex_lock(aux_mutex
);
6640 aux_offset
= READ_ONCE(rb
->user_page
->aux_offset
);
6641 aux_size
= READ_ONCE(rb
->user_page
->aux_size
);
6643 if (aux_offset
< perf_data_size(rb
) + PAGE_SIZE
)
6646 if (aux_offset
!= vma
->vm_pgoff
<< PAGE_SHIFT
)
6649 /* already mapped with a different offset */
6650 if (rb_has_aux(rb
) && rb
->aux_pgoff
!= vma
->vm_pgoff
)
6653 if (aux_size
!= vma_size
|| aux_size
!= nr_pages
* PAGE_SIZE
)
6656 /* already mapped with a different size */
6657 if (rb_has_aux(rb
) && rb
->aux_nr_pages
!= nr_pages
)
6660 if (!is_power_of_2(nr_pages
))
6663 if (!atomic_inc_not_zero(&rb
->mmap_count
))
6666 if (rb_has_aux(rb
)) {
6667 atomic_inc(&rb
->aux_mmap_count
);
6672 atomic_set(&rb
->aux_mmap_count
, 1);
6673 user_extra
= nr_pages
;
6679 * If we have rb pages ensure they're a power-of-two number, so we
6680 * can do bitmasks instead of modulo.
6682 if (nr_pages
!= 0 && !is_power_of_2(nr_pages
))
6685 if (vma_size
!= PAGE_SIZE
* (1 + nr_pages
))
6688 WARN_ON_ONCE(event
->ctx
->parent_ctx
);
6690 mutex_lock(&event
->mmap_mutex
);
6692 if (data_page_nr(event
->rb
) != nr_pages
) {
6697 if (!atomic_inc_not_zero(&event
->rb
->mmap_count
)) {
6699 * Raced against perf_mmap_close(); remove the
6700 * event and try again.
6702 ring_buffer_attach(event
, NULL
);
6703 mutex_unlock(&event
->mmap_mutex
);
6710 user_extra
= nr_pages
+ 1;
6713 user_lock_limit
= sysctl_perf_event_mlock
>> (PAGE_SHIFT
- 10);
6716 * Increase the limit linearly with more CPUs:
6718 user_lock_limit
*= num_online_cpus();
6720 user_locked
= atomic_long_read(&user
->locked_vm
);
6723 * sysctl_perf_event_mlock may have changed, so that
6724 * user->locked_vm > user_lock_limit
6726 if (user_locked
> user_lock_limit
)
6727 user_locked
= user_lock_limit
;
6728 user_locked
+= user_extra
;
6730 if (user_locked
> user_lock_limit
) {
6732 * charge locked_vm until it hits user_lock_limit;
6733 * charge the rest from pinned_vm
6735 extra
= user_locked
- user_lock_limit
;
6736 user_extra
-= extra
;
6739 lock_limit
= rlimit(RLIMIT_MEMLOCK
);
6740 lock_limit
>>= PAGE_SHIFT
;
6741 locked
= atomic64_read(&vma
->vm_mm
->pinned_vm
) + extra
;
6743 if ((locked
> lock_limit
) && perf_is_paranoid() &&
6744 !capable(CAP_IPC_LOCK
)) {
6749 WARN_ON(!rb
&& event
->rb
);
6751 if (vma
->vm_flags
& VM_WRITE
)
6752 flags
|= RING_BUFFER_WRITABLE
;
6755 rb
= rb_alloc(nr_pages
,
6756 event
->attr
.watermark
? event
->attr
.wakeup_watermark
: 0,
6764 atomic_set(&rb
->mmap_count
, 1);
6765 rb
->mmap_user
= get_current_user();
6766 rb
->mmap_locked
= extra
;
6768 ring_buffer_attach(event
, rb
);
6770 perf_event_update_time(event
);
6771 perf_event_init_userpage(event
);
6772 perf_event_update_userpage(event
);
6774 ret
= rb_alloc_aux(rb
, event
, vma
->vm_pgoff
, nr_pages
,
6775 event
->attr
.aux_watermark
, flags
);
6777 rb
->aux_mmap_locked
= extra
;
6782 atomic_long_add(user_extra
, &user
->locked_vm
);
6783 atomic64_add(extra
, &vma
->vm_mm
->pinned_vm
);
6785 atomic_inc(&event
->mmap_count
);
6787 atomic_dec(&rb
->mmap_count
);
6791 mutex_unlock(aux_mutex
);
6792 mutex_unlock(&event
->mmap_mutex
);
6795 * Since pinned accounting is per vm we cannot allow fork() to copy our
6798 vm_flags_set(vma
, VM_DONTCOPY
| VM_DONTEXPAND
| VM_DONTDUMP
);
6799 vma
->vm_ops
= &perf_mmap_vmops
;
6801 if (event
->pmu
->event_mapped
)
6802 event
->pmu
->event_mapped(event
, vma
->vm_mm
);
6807 static int perf_fasync(int fd
, struct file
*filp
, int on
)
6809 struct inode
*inode
= file_inode(filp
);
6810 struct perf_event
*event
= filp
->private_data
;
6814 retval
= fasync_helper(fd
, filp
, on
, &event
->fasync
);
6815 inode_unlock(inode
);
6823 static const struct file_operations perf_fops
= {
6824 .release
= perf_release
,
6827 .unlocked_ioctl
= perf_ioctl
,
6828 .compat_ioctl
= perf_compat_ioctl
,
6830 .fasync
= perf_fasync
,
6836 * If there's data, ensure we set the poll() state and publish everything
6837 * to user-space before waking everybody up.
6840 void perf_event_wakeup(struct perf_event
*event
)
6842 ring_buffer_wakeup(event
);
6844 if (event
->pending_kill
) {
6845 kill_fasync(perf_event_fasync(event
), SIGIO
, event
->pending_kill
);
6846 event
->pending_kill
= 0;
6850 static void perf_sigtrap(struct perf_event
*event
)
6853 * We'd expect this to only occur if the irq_work is delayed and either
6854 * ctx->task or current has changed in the meantime. This can be the
6855 * case on architectures that do not implement arch_irq_work_raise().
6857 if (WARN_ON_ONCE(event
->ctx
->task
!= current
))
6861 * Both perf_pending_task() and perf_pending_irq() can race with the
6864 if (current
->flags
& PF_EXITING
)
6867 send_sig_perf((void __user
*)event
->pending_addr
,
6868 event
->orig_type
, event
->attr
.sig_data
);
6872 * Deliver the pending work in-event-context or follow the context.
6874 static void __perf_pending_disable(struct perf_event
*event
)
6876 int cpu
= READ_ONCE(event
->oncpu
);
6879 * If the event isn't running; we done. event_sched_out() will have
6880 * taken care of things.
6886 * Yay, we hit home and are in the context of the event.
6888 if (cpu
== smp_processor_id()) {
6889 if (event
->pending_disable
) {
6890 event
->pending_disable
= 0;
6891 perf_event_disable_local(event
);
6899 * perf_event_disable_inatomic()
6900 * @pending_disable = CPU-A;
6904 * @pending_disable = -1;
6907 * perf_event_disable_inatomic()
6908 * @pending_disable = CPU-B;
6909 * irq_work_queue(); // FAILS
6912 * perf_pending_disable()
6914 * But the event runs on CPU-B and wants disabling there.
6916 irq_work_queue_on(&event
->pending_disable_irq
, cpu
);
6919 static void perf_pending_disable(struct irq_work
*entry
)
6921 struct perf_event
*event
= container_of(entry
, struct perf_event
, pending_disable_irq
);
6925 * If we 'fail' here, that's OK, it means recursion is already disabled
6926 * and we won't recurse 'further'.
6928 rctx
= perf_swevent_get_recursion_context();
6929 __perf_pending_disable(event
);
6931 perf_swevent_put_recursion_context(rctx
);
6934 static void perf_pending_irq(struct irq_work
*entry
)
6936 struct perf_event
*event
= container_of(entry
, struct perf_event
, pending_irq
);
6940 * If we 'fail' here, that's OK, it means recursion is already disabled
6941 * and we won't recurse 'further'.
6943 rctx
= perf_swevent_get_recursion_context();
6946 * The wakeup isn't bound to the context of the event -- it can happen
6947 * irrespective of where the event is.
6949 if (event
->pending_wakeup
) {
6950 event
->pending_wakeup
= 0;
6951 perf_event_wakeup(event
);
6955 perf_swevent_put_recursion_context(rctx
);
6958 static void perf_pending_task(struct callback_head
*head
)
6960 struct perf_event
*event
= container_of(head
, struct perf_event
, pending_task
);
6964 * All accesses to the event must belong to the same implicit RCU read-side
6965 * critical section as the ->pending_work reset. See comment in
6966 * perf_pending_task_sync().
6970 * If we 'fail' here, that's OK, it means recursion is already disabled
6971 * and we won't recurse 'further'.
6973 rctx
= perf_swevent_get_recursion_context();
6975 if (event
->pending_work
) {
6976 event
->pending_work
= 0;
6977 perf_sigtrap(event
);
6978 local_dec(&event
->ctx
->nr_no_switch_fast
);
6979 rcuwait_wake_up(&event
->pending_work_wait
);
6984 perf_swevent_put_recursion_context(rctx
);
6987 #ifdef CONFIG_GUEST_PERF_EVENTS
6988 struct perf_guest_info_callbacks __rcu
*perf_guest_cbs
;
6990 DEFINE_STATIC_CALL_RET0(__perf_guest_state
, *perf_guest_cbs
->state
);
6991 DEFINE_STATIC_CALL_RET0(__perf_guest_get_ip
, *perf_guest_cbs
->get_ip
);
6992 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_intel_pt_intr
, *perf_guest_cbs
->handle_intel_pt_intr
);
6994 void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks
*cbs
)
6996 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs
)))
6999 rcu_assign_pointer(perf_guest_cbs
, cbs
);
7000 static_call_update(__perf_guest_state
, cbs
->state
);
7001 static_call_update(__perf_guest_get_ip
, cbs
->get_ip
);
7003 /* Implementing ->handle_intel_pt_intr is optional. */
7004 if (cbs
->handle_intel_pt_intr
)
7005 static_call_update(__perf_guest_handle_intel_pt_intr
,
7006 cbs
->handle_intel_pt_intr
);
7008 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks
);
7010 void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks
*cbs
)
7012 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs
) != cbs
))
7015 rcu_assign_pointer(perf_guest_cbs
, NULL
);
7016 static_call_update(__perf_guest_state
, (void *)&__static_call_return0
);
7017 static_call_update(__perf_guest_get_ip
, (void *)&__static_call_return0
);
7018 static_call_update(__perf_guest_handle_intel_pt_intr
,
7019 (void *)&__static_call_return0
);
7022 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks
);
7026 perf_output_sample_regs(struct perf_output_handle
*handle
,
7027 struct pt_regs
*regs
, u64 mask
)
7030 DECLARE_BITMAP(_mask
, 64);
7032 bitmap_from_u64(_mask
, mask
);
7033 for_each_set_bit(bit
, _mask
, sizeof(mask
) * BITS_PER_BYTE
) {
7036 val
= perf_reg_value(regs
, bit
);
7037 perf_output_put(handle
, val
);
7041 static void perf_sample_regs_user(struct perf_regs
*regs_user
,
7042 struct pt_regs
*regs
)
7044 if (user_mode(regs
)) {
7045 regs_user
->abi
= perf_reg_abi(current
);
7046 regs_user
->regs
= regs
;
7047 } else if (!(current
->flags
& PF_KTHREAD
)) {
7048 perf_get_regs_user(regs_user
, regs
);
7050 regs_user
->abi
= PERF_SAMPLE_REGS_ABI_NONE
;
7051 regs_user
->regs
= NULL
;
7055 static void perf_sample_regs_intr(struct perf_regs
*regs_intr
,
7056 struct pt_regs
*regs
)
7058 regs_intr
->regs
= regs
;
7059 regs_intr
->abi
= perf_reg_abi(current
);
7064 * Get remaining task size from user stack pointer.
7066 * It'd be better to take stack vma map and limit this more
7067 * precisely, but there's no way to get it safely under interrupt,
7068 * so using TASK_SIZE as limit.
7070 static u64
perf_ustack_task_size(struct pt_regs
*regs
)
7072 unsigned long addr
= perf_user_stack_pointer(regs
);
7074 if (!addr
|| addr
>= TASK_SIZE
)
7077 return TASK_SIZE
- addr
;
7081 perf_sample_ustack_size(u16 stack_size
, u16 header_size
,
7082 struct pt_regs
*regs
)
7086 /* No regs, no stack pointer, no dump. */
7091 * Check if we fit in with the requested stack size into the:
7093 * If we don't, we limit the size to the TASK_SIZE.
7095 * - remaining sample size
7096 * If we don't, we customize the stack size to
7097 * fit in to the remaining sample size.
7100 task_size
= min((u64
) USHRT_MAX
, perf_ustack_task_size(regs
));
7101 stack_size
= min(stack_size
, (u16
) task_size
);
7103 /* Current header size plus static size and dynamic size. */
7104 header_size
+= 2 * sizeof(u64
);
7106 /* Do we fit in with the current stack dump size? */
7107 if ((u16
) (header_size
+ stack_size
) < header_size
) {
7109 * If we overflow the maximum size for the sample,
7110 * we customize the stack dump size to fit in.
7112 stack_size
= USHRT_MAX
- header_size
- sizeof(u64
);
7113 stack_size
= round_up(stack_size
, sizeof(u64
));
7120 perf_output_sample_ustack(struct perf_output_handle
*handle
, u64 dump_size
,
7121 struct pt_regs
*regs
)
7123 /* Case of a kernel thread, nothing to dump */
7126 perf_output_put(handle
, size
);
7135 * - the size requested by user or the best one we can fit
7136 * in to the sample max size
7138 * - user stack dump data
7140 * - the actual dumped size
7144 perf_output_put(handle
, dump_size
);
7147 sp
= perf_user_stack_pointer(regs
);
7148 rem
= __output_copy_user(handle
, (void *) sp
, dump_size
);
7149 dyn_size
= dump_size
- rem
;
7151 perf_output_skip(handle
, rem
);
7154 perf_output_put(handle
, dyn_size
);
7158 static unsigned long perf_prepare_sample_aux(struct perf_event
*event
,
7159 struct perf_sample_data
*data
,
7162 struct perf_event
*sampler
= event
->aux_event
;
7163 struct perf_buffer
*rb
;
7170 if (WARN_ON_ONCE(READ_ONCE(sampler
->state
) != PERF_EVENT_STATE_ACTIVE
))
7173 if (WARN_ON_ONCE(READ_ONCE(sampler
->oncpu
) != smp_processor_id()))
7176 rb
= ring_buffer_get(sampler
);
7181 * If this is an NMI hit inside sampling code, don't take
7182 * the sample. See also perf_aux_sample_output().
7184 if (READ_ONCE(rb
->aux_in_sampling
)) {
7187 size
= min_t(size_t, size
, perf_aux_size(rb
));
7188 data
->aux_size
= ALIGN(size
, sizeof(u64
));
7190 ring_buffer_put(rb
);
7193 return data
->aux_size
;
7196 static long perf_pmu_snapshot_aux(struct perf_buffer
*rb
,
7197 struct perf_event
*event
,
7198 struct perf_output_handle
*handle
,
7201 unsigned long flags
;
7205 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
7206 * paths. If we start calling them in NMI context, they may race with
7207 * the IRQ ones, that is, for example, re-starting an event that's just
7208 * been stopped, which is why we're using a separate callback that
7209 * doesn't change the event state.
7211 * IRQs need to be disabled to prevent IPIs from racing with us.
7213 local_irq_save(flags
);
7215 * Guard against NMI hits inside the critical section;
7216 * see also perf_prepare_sample_aux().
7218 WRITE_ONCE(rb
->aux_in_sampling
, 1);
7221 ret
= event
->pmu
->snapshot_aux(event
, handle
, size
);
7224 WRITE_ONCE(rb
->aux_in_sampling
, 0);
7225 local_irq_restore(flags
);
7230 static void perf_aux_sample_output(struct perf_event
*event
,
7231 struct perf_output_handle
*handle
,
7232 struct perf_sample_data
*data
)
7234 struct perf_event
*sampler
= event
->aux_event
;
7235 struct perf_buffer
*rb
;
7239 if (WARN_ON_ONCE(!sampler
|| !data
->aux_size
))
7242 rb
= ring_buffer_get(sampler
);
7246 size
= perf_pmu_snapshot_aux(rb
, sampler
, handle
, data
->aux_size
);
7249 * An error here means that perf_output_copy() failed (returned a
7250 * non-zero surplus that it didn't copy), which in its current
7251 * enlightened implementation is not possible. If that changes, we'd
7254 if (WARN_ON_ONCE(size
< 0))
7258 * The pad comes from ALIGN()ing data->aux_size up to u64 in
7259 * perf_prepare_sample_aux(), so should not be more than that.
7261 pad
= data
->aux_size
- size
;
7262 if (WARN_ON_ONCE(pad
>= sizeof(u64
)))
7267 perf_output_copy(handle
, &zero
, pad
);
7271 ring_buffer_put(rb
);
7275 * A set of common sample data types saved even for non-sample records
7276 * when event->attr.sample_id_all is set.
7278 #define PERF_SAMPLE_ID_ALL (PERF_SAMPLE_TID | PERF_SAMPLE_TIME | \
7279 PERF_SAMPLE_ID | PERF_SAMPLE_STREAM_ID | \
7280 PERF_SAMPLE_CPU | PERF_SAMPLE_IDENTIFIER)
7282 static void __perf_event_header__init_id(struct perf_sample_data
*data
,
7283 struct perf_event
*event
,
7286 data
->type
= event
->attr
.sample_type
;
7287 data
->sample_flags
|= data
->type
& PERF_SAMPLE_ID_ALL
;
7289 if (sample_type
& PERF_SAMPLE_TID
) {
7290 /* namespace issues */
7291 data
->tid_entry
.pid
= perf_event_pid(event
, current
);
7292 data
->tid_entry
.tid
= perf_event_tid(event
, current
);
7295 if (sample_type
& PERF_SAMPLE_TIME
)
7296 data
->time
= perf_event_clock(event
);
7298 if (sample_type
& (PERF_SAMPLE_ID
| PERF_SAMPLE_IDENTIFIER
))
7299 data
->id
= primary_event_id(event
);
7301 if (sample_type
& PERF_SAMPLE_STREAM_ID
)
7302 data
->stream_id
= event
->id
;
7304 if (sample_type
& PERF_SAMPLE_CPU
) {
7305 data
->cpu_entry
.cpu
= raw_smp_processor_id();
7306 data
->cpu_entry
.reserved
= 0;
7310 void perf_event_header__init_id(struct perf_event_header
*header
,
7311 struct perf_sample_data
*data
,
7312 struct perf_event
*event
)
7314 if (event
->attr
.sample_id_all
) {
7315 header
->size
+= event
->id_header_size
;
7316 __perf_event_header__init_id(data
, event
, event
->attr
.sample_type
);
7320 static void __perf_event__output_id_sample(struct perf_output_handle
*handle
,
7321 struct perf_sample_data
*data
)
7323 u64 sample_type
= data
->type
;
7325 if (sample_type
& PERF_SAMPLE_TID
)
7326 perf_output_put(handle
, data
->tid_entry
);
7328 if (sample_type
& PERF_SAMPLE_TIME
)
7329 perf_output_put(handle
, data
->time
);
7331 if (sample_type
& PERF_SAMPLE_ID
)
7332 perf_output_put(handle
, data
->id
);
7334 if (sample_type
& PERF_SAMPLE_STREAM_ID
)
7335 perf_output_put(handle
, data
->stream_id
);
7337 if (sample_type
& PERF_SAMPLE_CPU
)
7338 perf_output_put(handle
, data
->cpu_entry
);
7340 if (sample_type
& PERF_SAMPLE_IDENTIFIER
)
7341 perf_output_put(handle
, data
->id
);
7344 void perf_event__output_id_sample(struct perf_event
*event
,
7345 struct perf_output_handle
*handle
,
7346 struct perf_sample_data
*sample
)
7348 if (event
->attr
.sample_id_all
)
7349 __perf_event__output_id_sample(handle
, sample
);
7352 static void perf_output_read_one(struct perf_output_handle
*handle
,
7353 struct perf_event
*event
,
7354 u64 enabled
, u64 running
)
7356 u64 read_format
= event
->attr
.read_format
;
7360 values
[n
++] = perf_event_count(event
, has_inherit_and_sample_read(&event
->attr
));
7361 if (read_format
& PERF_FORMAT_TOTAL_TIME_ENABLED
) {
7362 values
[n
++] = enabled
+
7363 atomic64_read(&event
->child_total_time_enabled
);
7365 if (read_format
& PERF_FORMAT_TOTAL_TIME_RUNNING
) {
7366 values
[n
++] = running
+
7367 atomic64_read(&event
->child_total_time_running
);
7369 if (read_format
& PERF_FORMAT_ID
)
7370 values
[n
++] = primary_event_id(event
);
7371 if (read_format
& PERF_FORMAT_LOST
)
7372 values
[n
++] = atomic64_read(&event
->lost_samples
);
7374 __output_copy(handle
, values
, n
* sizeof(u64
));
7377 static void perf_output_read_group(struct perf_output_handle
*handle
,
7378 struct perf_event
*event
,
7379 u64 enabled
, u64 running
)
7381 struct perf_event
*leader
= event
->group_leader
, *sub
;
7382 u64 read_format
= event
->attr
.read_format
;
7383 unsigned long flags
;
7386 bool self
= has_inherit_and_sample_read(&event
->attr
);
7389 * Disabling interrupts avoids all counter scheduling
7390 * (context switches, timer based rotation and IPIs).
7392 local_irq_save(flags
);
7394 values
[n
++] = 1 + leader
->nr_siblings
;
7396 if (read_format
& PERF_FORMAT_TOTAL_TIME_ENABLED
)
7397 values
[n
++] = enabled
;
7399 if (read_format
& PERF_FORMAT_TOTAL_TIME_RUNNING
)
7400 values
[n
++] = running
;
7402 if ((leader
!= event
) &&
7403 (leader
->state
== PERF_EVENT_STATE_ACTIVE
))
7404 leader
->pmu
->read(leader
);
7406 values
[n
++] = perf_event_count(leader
, self
);
7407 if (read_format
& PERF_FORMAT_ID
)
7408 values
[n
++] = primary_event_id(leader
);
7409 if (read_format
& PERF_FORMAT_LOST
)
7410 values
[n
++] = atomic64_read(&leader
->lost_samples
);
7412 __output_copy(handle
, values
, n
* sizeof(u64
));
7414 for_each_sibling_event(sub
, leader
) {
7417 if ((sub
!= event
) &&
7418 (sub
->state
== PERF_EVENT_STATE_ACTIVE
))
7419 sub
->pmu
->read(sub
);
7421 values
[n
++] = perf_event_count(sub
, self
);
7422 if (read_format
& PERF_FORMAT_ID
)
7423 values
[n
++] = primary_event_id(sub
);
7424 if (read_format
& PERF_FORMAT_LOST
)
7425 values
[n
++] = atomic64_read(&sub
->lost_samples
);
7427 __output_copy(handle
, values
, n
* sizeof(u64
));
7430 local_irq_restore(flags
);
7433 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
7434 PERF_FORMAT_TOTAL_TIME_RUNNING)
7437 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
7439 * The problem is that its both hard and excessively expensive to iterate the
7440 * child list, not to mention that its impossible to IPI the children running
7441 * on another CPU, from interrupt/NMI context.
7443 * Instead the combination of PERF_SAMPLE_READ and inherit will track per-thread
7444 * counts rather than attempting to accumulate some value across all children on
7447 static void perf_output_read(struct perf_output_handle
*handle
,
7448 struct perf_event
*event
)
7450 u64 enabled
= 0, running
= 0, now
;
7451 u64 read_format
= event
->attr
.read_format
;
7454 * compute total_time_enabled, total_time_running
7455 * based on snapshot values taken when the event
7456 * was last scheduled in.
7458 * we cannot simply called update_context_time()
7459 * because of locking issue as we are called in
7462 if (read_format
& PERF_FORMAT_TOTAL_TIMES
)
7463 calc_timer_values(event
, &now
, &enabled
, &running
);
7465 if (event
->attr
.read_format
& PERF_FORMAT_GROUP
)
7466 perf_output_read_group(handle
, event
, enabled
, running
);
7468 perf_output_read_one(handle
, event
, enabled
, running
);
7471 void perf_output_sample(struct perf_output_handle
*handle
,
7472 struct perf_event_header
*header
,
7473 struct perf_sample_data
*data
,
7474 struct perf_event
*event
)
7476 u64 sample_type
= data
->type
;
7478 perf_output_put(handle
, *header
);
7480 if (sample_type
& PERF_SAMPLE_IDENTIFIER
)
7481 perf_output_put(handle
, data
->id
);
7483 if (sample_type
& PERF_SAMPLE_IP
)
7484 perf_output_put(handle
, data
->ip
);
7486 if (sample_type
& PERF_SAMPLE_TID
)
7487 perf_output_put(handle
, data
->tid_entry
);
7489 if (sample_type
& PERF_SAMPLE_TIME
)
7490 perf_output_put(handle
, data
->time
);
7492 if (sample_type
& PERF_SAMPLE_ADDR
)
7493 perf_output_put(handle
, data
->addr
);
7495 if (sample_type
& PERF_SAMPLE_ID
)
7496 perf_output_put(handle
, data
->id
);
7498 if (sample_type
& PERF_SAMPLE_STREAM_ID
)
7499 perf_output_put(handle
, data
->stream_id
);
7501 if (sample_type
& PERF_SAMPLE_CPU
)
7502 perf_output_put(handle
, data
->cpu_entry
);
7504 if (sample_type
& PERF_SAMPLE_PERIOD
)
7505 perf_output_put(handle
, data
->period
);
7507 if (sample_type
& PERF_SAMPLE_READ
)
7508 perf_output_read(handle
, event
);
7510 if (sample_type
& PERF_SAMPLE_CALLCHAIN
) {
7513 size
+= data
->callchain
->nr
;
7514 size
*= sizeof(u64
);
7515 __output_copy(handle
, data
->callchain
, size
);
7518 if (sample_type
& PERF_SAMPLE_RAW
) {
7519 struct perf_raw_record
*raw
= data
->raw
;
7522 struct perf_raw_frag
*frag
= &raw
->frag
;
7524 perf_output_put(handle
, raw
->size
);
7527 __output_custom(handle
, frag
->copy
,
7528 frag
->data
, frag
->size
);
7530 __output_copy(handle
, frag
->data
,
7533 if (perf_raw_frag_last(frag
))
7538 __output_skip(handle
, NULL
, frag
->pad
);
7544 .size
= sizeof(u32
),
7547 perf_output_put(handle
, raw
);
7551 if (sample_type
& PERF_SAMPLE_BRANCH_STACK
) {
7552 if (data
->br_stack
) {
7555 size
= data
->br_stack
->nr
7556 * sizeof(struct perf_branch_entry
);
7558 perf_output_put(handle
, data
->br_stack
->nr
);
7559 if (branch_sample_hw_index(event
))
7560 perf_output_put(handle
, data
->br_stack
->hw_idx
);
7561 perf_output_copy(handle
, data
->br_stack
->entries
, size
);
7563 * Add the extension space which is appended
7564 * right after the struct perf_branch_stack.
7566 if (data
->br_stack_cntr
) {
7567 size
= data
->br_stack
->nr
* sizeof(u64
);
7568 perf_output_copy(handle
, data
->br_stack_cntr
, size
);
7572 * we always store at least the value of nr
7575 perf_output_put(handle
, nr
);
7579 if (sample_type
& PERF_SAMPLE_REGS_USER
) {
7580 u64 abi
= data
->regs_user
.abi
;
7583 * If there are no regs to dump, notice it through
7584 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7586 perf_output_put(handle
, abi
);
7589 u64 mask
= event
->attr
.sample_regs_user
;
7590 perf_output_sample_regs(handle
,
7591 data
->regs_user
.regs
,
7596 if (sample_type
& PERF_SAMPLE_STACK_USER
) {
7597 perf_output_sample_ustack(handle
,
7598 data
->stack_user_size
,
7599 data
->regs_user
.regs
);
7602 if (sample_type
& PERF_SAMPLE_WEIGHT_TYPE
)
7603 perf_output_put(handle
, data
->weight
.full
);
7605 if (sample_type
& PERF_SAMPLE_DATA_SRC
)
7606 perf_output_put(handle
, data
->data_src
.val
);
7608 if (sample_type
& PERF_SAMPLE_TRANSACTION
)
7609 perf_output_put(handle
, data
->txn
);
7611 if (sample_type
& PERF_SAMPLE_REGS_INTR
) {
7612 u64 abi
= data
->regs_intr
.abi
;
7614 * If there are no regs to dump, notice it through
7615 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7617 perf_output_put(handle
, abi
);
7620 u64 mask
= event
->attr
.sample_regs_intr
;
7622 perf_output_sample_regs(handle
,
7623 data
->regs_intr
.regs
,
7628 if (sample_type
& PERF_SAMPLE_PHYS_ADDR
)
7629 perf_output_put(handle
, data
->phys_addr
);
7631 if (sample_type
& PERF_SAMPLE_CGROUP
)
7632 perf_output_put(handle
, data
->cgroup
);
7634 if (sample_type
& PERF_SAMPLE_DATA_PAGE_SIZE
)
7635 perf_output_put(handle
, data
->data_page_size
);
7637 if (sample_type
& PERF_SAMPLE_CODE_PAGE_SIZE
)
7638 perf_output_put(handle
, data
->code_page_size
);
7640 if (sample_type
& PERF_SAMPLE_AUX
) {
7641 perf_output_put(handle
, data
->aux_size
);
7644 perf_aux_sample_output(event
, handle
, data
);
7647 if (!event
->attr
.watermark
) {
7648 int wakeup_events
= event
->attr
.wakeup_events
;
7650 if (wakeup_events
) {
7651 struct perf_buffer
*rb
= handle
->rb
;
7652 int events
= local_inc_return(&rb
->events
);
7654 if (events
>= wakeup_events
) {
7655 local_sub(wakeup_events
, &rb
->events
);
7656 local_inc(&rb
->wakeup
);
7662 static u64
perf_virt_to_phys(u64 virt
)
7669 if (virt
>= TASK_SIZE
) {
7670 /* If it's vmalloc()d memory, leave phys_addr as 0 */
7671 if (virt_addr_valid((void *)(uintptr_t)virt
) &&
7672 !(virt
>= VMALLOC_START
&& virt
< VMALLOC_END
))
7673 phys_addr
= (u64
)virt_to_phys((void *)(uintptr_t)virt
);
7676 * Walking the pages tables for user address.
7677 * Interrupts are disabled, so it prevents any tear down
7678 * of the page tables.
7679 * Try IRQ-safe get_user_page_fast_only first.
7680 * If failed, leave phys_addr as 0.
7682 if (current
->mm
!= NULL
) {
7685 pagefault_disable();
7686 if (get_user_page_fast_only(virt
, 0, &p
)) {
7687 phys_addr
= page_to_phys(p
) + virt
% PAGE_SIZE
;
7698 * Return the pagetable size of a given virtual address.
7700 static u64
perf_get_pgtable_size(struct mm_struct
*mm
, unsigned long addr
)
7704 #ifdef CONFIG_HAVE_GUP_FAST
7711 pgdp
= pgd_offset(mm
, addr
);
7712 pgd
= READ_ONCE(*pgdp
);
7717 return pgd_leaf_size(pgd
);
7719 p4dp
= p4d_offset_lockless(pgdp
, pgd
, addr
);
7720 p4d
= READ_ONCE(*p4dp
);
7721 if (!p4d_present(p4d
))
7725 return p4d_leaf_size(p4d
);
7727 pudp
= pud_offset_lockless(p4dp
, p4d
, addr
);
7728 pud
= READ_ONCE(*pudp
);
7729 if (!pud_present(pud
))
7733 return pud_leaf_size(pud
);
7735 pmdp
= pmd_offset_lockless(pudp
, pud
, addr
);
7737 pmd
= pmdp_get_lockless(pmdp
);
7738 if (!pmd_present(pmd
))
7742 return pmd_leaf_size(pmd
);
7744 ptep
= pte_offset_map(&pmd
, addr
);
7748 pte
= ptep_get_lockless(ptep
);
7749 if (pte_present(pte
))
7750 size
= __pte_leaf_size(pmd
, pte
);
7752 #endif /* CONFIG_HAVE_GUP_FAST */
7757 static u64
perf_get_page_size(unsigned long addr
)
7759 struct mm_struct
*mm
;
7760 unsigned long flags
;
7767 * Software page-table walkers must disable IRQs,
7768 * which prevents any tear down of the page tables.
7770 local_irq_save(flags
);
7775 * For kernel threads and the like, use init_mm so that
7776 * we can find kernel memory.
7781 size
= perf_get_pgtable_size(mm
, addr
);
7783 local_irq_restore(flags
);
7788 static struct perf_callchain_entry __empty_callchain
= { .nr
= 0, };
7790 struct perf_callchain_entry
*
7791 perf_callchain(struct perf_event
*event
, struct pt_regs
*regs
)
7793 bool kernel
= !event
->attr
.exclude_callchain_kernel
;
7794 bool user
= !event
->attr
.exclude_callchain_user
;
7795 /* Disallow cross-task user callchains. */
7796 bool crosstask
= event
->ctx
->task
&& event
->ctx
->task
!= current
;
7797 const u32 max_stack
= event
->attr
.sample_max_stack
;
7798 struct perf_callchain_entry
*callchain
;
7800 if (!kernel
&& !user
)
7801 return &__empty_callchain
;
7803 callchain
= get_perf_callchain(regs
, 0, kernel
, user
,
7804 max_stack
, crosstask
, true);
7805 return callchain
?: &__empty_callchain
;
7808 static __always_inline u64
__cond_set(u64 flags
, u64 s
, u64 d
)
7810 return d
* !!(flags
& s
);
7813 void perf_prepare_sample(struct perf_sample_data
*data
,
7814 struct perf_event
*event
,
7815 struct pt_regs
*regs
)
7817 u64 sample_type
= event
->attr
.sample_type
;
7818 u64 filtered_sample_type
;
7821 * Add the sample flags that are dependent to others. And clear the
7822 * sample flags that have already been done by the PMU driver.
7824 filtered_sample_type
= sample_type
;
7825 filtered_sample_type
|= __cond_set(sample_type
, PERF_SAMPLE_CODE_PAGE_SIZE
,
7827 filtered_sample_type
|= __cond_set(sample_type
, PERF_SAMPLE_DATA_PAGE_SIZE
|
7828 PERF_SAMPLE_PHYS_ADDR
, PERF_SAMPLE_ADDR
);
7829 filtered_sample_type
|= __cond_set(sample_type
, PERF_SAMPLE_STACK_USER
,
7830 PERF_SAMPLE_REGS_USER
);
7831 filtered_sample_type
&= ~data
->sample_flags
;
7833 if (filtered_sample_type
== 0) {
7834 /* Make sure it has the correct data->type for output */
7835 data
->type
= event
->attr
.sample_type
;
7839 __perf_event_header__init_id(data
, event
, filtered_sample_type
);
7841 if (filtered_sample_type
& PERF_SAMPLE_IP
) {
7842 data
->ip
= perf_instruction_pointer(regs
);
7843 data
->sample_flags
|= PERF_SAMPLE_IP
;
7846 if (filtered_sample_type
& PERF_SAMPLE_CALLCHAIN
)
7847 perf_sample_save_callchain(data
, event
, regs
);
7849 if (filtered_sample_type
& PERF_SAMPLE_RAW
) {
7851 data
->dyn_size
+= sizeof(u64
);
7852 data
->sample_flags
|= PERF_SAMPLE_RAW
;
7855 if (filtered_sample_type
& PERF_SAMPLE_BRANCH_STACK
) {
7856 data
->br_stack
= NULL
;
7857 data
->dyn_size
+= sizeof(u64
);
7858 data
->sample_flags
|= PERF_SAMPLE_BRANCH_STACK
;
7861 if (filtered_sample_type
& PERF_SAMPLE_REGS_USER
)
7862 perf_sample_regs_user(&data
->regs_user
, regs
);
7865 * It cannot use the filtered_sample_type here as REGS_USER can be set
7866 * by STACK_USER (using __cond_set() above) and we don't want to update
7867 * the dyn_size if it's not requested by users.
7869 if ((sample_type
& ~data
->sample_flags
) & PERF_SAMPLE_REGS_USER
) {
7870 /* regs dump ABI info */
7871 int size
= sizeof(u64
);
7873 if (data
->regs_user
.regs
) {
7874 u64 mask
= event
->attr
.sample_regs_user
;
7875 size
+= hweight64(mask
) * sizeof(u64
);
7878 data
->dyn_size
+= size
;
7879 data
->sample_flags
|= PERF_SAMPLE_REGS_USER
;
7882 if (filtered_sample_type
& PERF_SAMPLE_STACK_USER
) {
7884 * Either we need PERF_SAMPLE_STACK_USER bit to be always
7885 * processed as the last one or have additional check added
7886 * in case new sample type is added, because we could eat
7887 * up the rest of the sample size.
7889 u16 stack_size
= event
->attr
.sample_stack_user
;
7890 u16 header_size
= perf_sample_data_size(data
, event
);
7891 u16 size
= sizeof(u64
);
7893 stack_size
= perf_sample_ustack_size(stack_size
, header_size
,
7894 data
->regs_user
.regs
);
7897 * If there is something to dump, add space for the dump
7898 * itself and for the field that tells the dynamic size,
7899 * which is how many have been actually dumped.
7902 size
+= sizeof(u64
) + stack_size
;
7904 data
->stack_user_size
= stack_size
;
7905 data
->dyn_size
+= size
;
7906 data
->sample_flags
|= PERF_SAMPLE_STACK_USER
;
7909 if (filtered_sample_type
& PERF_SAMPLE_WEIGHT_TYPE
) {
7910 data
->weight
.full
= 0;
7911 data
->sample_flags
|= PERF_SAMPLE_WEIGHT_TYPE
;
7914 if (filtered_sample_type
& PERF_SAMPLE_DATA_SRC
) {
7915 data
->data_src
.val
= PERF_MEM_NA
;
7916 data
->sample_flags
|= PERF_SAMPLE_DATA_SRC
;
7919 if (filtered_sample_type
& PERF_SAMPLE_TRANSACTION
) {
7921 data
->sample_flags
|= PERF_SAMPLE_TRANSACTION
;
7924 if (filtered_sample_type
& PERF_SAMPLE_ADDR
) {
7926 data
->sample_flags
|= PERF_SAMPLE_ADDR
;
7929 if (filtered_sample_type
& PERF_SAMPLE_REGS_INTR
) {
7930 /* regs dump ABI info */
7931 int size
= sizeof(u64
);
7933 perf_sample_regs_intr(&data
->regs_intr
, regs
);
7935 if (data
->regs_intr
.regs
) {
7936 u64 mask
= event
->attr
.sample_regs_intr
;
7938 size
+= hweight64(mask
) * sizeof(u64
);
7941 data
->dyn_size
+= size
;
7942 data
->sample_flags
|= PERF_SAMPLE_REGS_INTR
;
7945 if (filtered_sample_type
& PERF_SAMPLE_PHYS_ADDR
) {
7946 data
->phys_addr
= perf_virt_to_phys(data
->addr
);
7947 data
->sample_flags
|= PERF_SAMPLE_PHYS_ADDR
;
7950 #ifdef CONFIG_CGROUP_PERF
7951 if (filtered_sample_type
& PERF_SAMPLE_CGROUP
) {
7952 struct cgroup
*cgrp
;
7954 /* protected by RCU */
7955 cgrp
= task_css_check(current
, perf_event_cgrp_id
, 1)->cgroup
;
7956 data
->cgroup
= cgroup_id(cgrp
);
7957 data
->sample_flags
|= PERF_SAMPLE_CGROUP
;
7962 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't
7963 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr,
7964 * but the value will not dump to the userspace.
7966 if (filtered_sample_type
& PERF_SAMPLE_DATA_PAGE_SIZE
) {
7967 data
->data_page_size
= perf_get_page_size(data
->addr
);
7968 data
->sample_flags
|= PERF_SAMPLE_DATA_PAGE_SIZE
;
7971 if (filtered_sample_type
& PERF_SAMPLE_CODE_PAGE_SIZE
) {
7972 data
->code_page_size
= perf_get_page_size(data
->ip
);
7973 data
->sample_flags
|= PERF_SAMPLE_CODE_PAGE_SIZE
;
7976 if (filtered_sample_type
& PERF_SAMPLE_AUX
) {
7978 u16 header_size
= perf_sample_data_size(data
, event
);
7980 header_size
+= sizeof(u64
); /* size */
7983 * Given the 16bit nature of header::size, an AUX sample can
7984 * easily overflow it, what with all the preceding sample bits.
7985 * Make sure this doesn't happen by using up to U16_MAX bytes
7986 * per sample in total (rounded down to 8 byte boundary).
7988 size
= min_t(size_t, U16_MAX
- header_size
,
7989 event
->attr
.aux_sample_size
);
7990 size
= rounddown(size
, 8);
7991 size
= perf_prepare_sample_aux(event
, data
, size
);
7993 WARN_ON_ONCE(size
+ header_size
> U16_MAX
);
7994 data
->dyn_size
+= size
+ sizeof(u64
); /* size above */
7995 data
->sample_flags
|= PERF_SAMPLE_AUX
;
7999 void perf_prepare_header(struct perf_event_header
*header
,
8000 struct perf_sample_data
*data
,
8001 struct perf_event
*event
,
8002 struct pt_regs
*regs
)
8004 header
->type
= PERF_RECORD_SAMPLE
;
8005 header
->size
= perf_sample_data_size(data
, event
);
8006 header
->misc
= perf_misc_flags(regs
);
8009 * If you're adding more sample types here, you likely need to do
8010 * something about the overflowing header::size, like repurpose the
8011 * lowest 3 bits of size, which should be always zero at the moment.
8012 * This raises a more important question, do we really need 512k sized
8013 * samples and why, so good argumentation is in order for whatever you
8016 WARN_ON_ONCE(header
->size
& 7);
8019 static __always_inline
int
8020 __perf_event_output(struct perf_event
*event
,
8021 struct perf_sample_data
*data
,
8022 struct pt_regs
*regs
,
8023 int (*output_begin
)(struct perf_output_handle
*,
8024 struct perf_sample_data
*,
8025 struct perf_event
*,
8028 struct perf_output_handle handle
;
8029 struct perf_event_header header
;
8032 /* protect the callchain buffers */
8035 perf_prepare_sample(data
, event
, regs
);
8036 perf_prepare_header(&header
, data
, event
, regs
);
8038 err
= output_begin(&handle
, data
, event
, header
.size
);
8042 perf_output_sample(&handle
, &header
, data
, event
);
8044 perf_output_end(&handle
);
8052 perf_event_output_forward(struct perf_event
*event
,
8053 struct perf_sample_data
*data
,
8054 struct pt_regs
*regs
)
8056 __perf_event_output(event
, data
, regs
, perf_output_begin_forward
);
8060 perf_event_output_backward(struct perf_event
*event
,
8061 struct perf_sample_data
*data
,
8062 struct pt_regs
*regs
)
8064 __perf_event_output(event
, data
, regs
, perf_output_begin_backward
);
8068 perf_event_output(struct perf_event
*event
,
8069 struct perf_sample_data
*data
,
8070 struct pt_regs
*regs
)
8072 return __perf_event_output(event
, data
, regs
, perf_output_begin
);
8079 struct perf_read_event
{
8080 struct perf_event_header header
;
8087 perf_event_read_event(struct perf_event
*event
,
8088 struct task_struct
*task
)
8090 struct perf_output_handle handle
;
8091 struct perf_sample_data sample
;
8092 struct perf_read_event read_event
= {
8094 .type
= PERF_RECORD_READ
,
8096 .size
= sizeof(read_event
) + event
->read_size
,
8098 .pid
= perf_event_pid(event
, task
),
8099 .tid
= perf_event_tid(event
, task
),
8103 perf_event_header__init_id(&read_event
.header
, &sample
, event
);
8104 ret
= perf_output_begin(&handle
, &sample
, event
, read_event
.header
.size
);
8108 perf_output_put(&handle
, read_event
);
8109 perf_output_read(&handle
, event
);
8110 perf_event__output_id_sample(event
, &handle
, &sample
);
8112 perf_output_end(&handle
);
8115 typedef void (perf_iterate_f
)(struct perf_event
*event
, void *data
);
8118 perf_iterate_ctx(struct perf_event_context
*ctx
,
8119 perf_iterate_f output
,
8120 void *data
, bool all
)
8122 struct perf_event
*event
;
8124 list_for_each_entry_rcu(event
, &ctx
->event_list
, event_entry
) {
8126 if (event
->state
< PERF_EVENT_STATE_INACTIVE
)
8128 if (!event_filter_match(event
))
8132 output(event
, data
);
8136 static void perf_iterate_sb_cpu(perf_iterate_f output
, void *data
)
8138 struct pmu_event_list
*pel
= this_cpu_ptr(&pmu_sb_events
);
8139 struct perf_event
*event
;
8141 list_for_each_entry_rcu(event
, &pel
->list
, sb_list
) {
8143 * Skip events that are not fully formed yet; ensure that
8144 * if we observe event->ctx, both event and ctx will be
8145 * complete enough. See perf_install_in_context().
8147 if (!smp_load_acquire(&event
->ctx
))
8150 if (event
->state
< PERF_EVENT_STATE_INACTIVE
)
8152 if (!event_filter_match(event
))
8154 output(event
, data
);
8159 * Iterate all events that need to receive side-band events.
8161 * For new callers; ensure that account_pmu_sb_event() includes
8162 * your event, otherwise it might not get delivered.
8165 perf_iterate_sb(perf_iterate_f output
, void *data
,
8166 struct perf_event_context
*task_ctx
)
8168 struct perf_event_context
*ctx
;
8174 * If we have task_ctx != NULL we only notify the task context itself.
8175 * The task_ctx is set only for EXIT events before releasing task
8179 perf_iterate_ctx(task_ctx
, output
, data
, false);
8183 perf_iterate_sb_cpu(output
, data
);
8185 ctx
= rcu_dereference(current
->perf_event_ctxp
);
8187 perf_iterate_ctx(ctx
, output
, data
, false);
8194 * Clear all file-based filters at exec, they'll have to be
8195 * re-instated when/if these objects are mmapped again.
8197 static void perf_event_addr_filters_exec(struct perf_event
*event
, void *data
)
8199 struct perf_addr_filters_head
*ifh
= perf_event_addr_filters(event
);
8200 struct perf_addr_filter
*filter
;
8201 unsigned int restart
= 0, count
= 0;
8202 unsigned long flags
;
8204 if (!has_addr_filter(event
))
8207 raw_spin_lock_irqsave(&ifh
->lock
, flags
);
8208 list_for_each_entry(filter
, &ifh
->list
, entry
) {
8209 if (filter
->path
.dentry
) {
8210 event
->addr_filter_ranges
[count
].start
= 0;
8211 event
->addr_filter_ranges
[count
].size
= 0;
8219 event
->addr_filters_gen
++;
8220 raw_spin_unlock_irqrestore(&ifh
->lock
, flags
);
8223 perf_event_stop(event
, 1);
8226 void perf_event_exec(void)
8228 struct perf_event_context
*ctx
;
8230 ctx
= perf_pin_task_context(current
);
8234 perf_event_enable_on_exec(ctx
);
8235 perf_event_remove_on_exec(ctx
);
8236 perf_iterate_ctx(ctx
, perf_event_addr_filters_exec
, NULL
, true);
8238 perf_unpin_context(ctx
);
8242 struct remote_output
{
8243 struct perf_buffer
*rb
;
8247 static void __perf_event_output_stop(struct perf_event
*event
, void *data
)
8249 struct perf_event
*parent
= event
->parent
;
8250 struct remote_output
*ro
= data
;
8251 struct perf_buffer
*rb
= ro
->rb
;
8252 struct stop_event_data sd
= {
8256 if (!has_aux(event
))
8263 * In case of inheritance, it will be the parent that links to the
8264 * ring-buffer, but it will be the child that's actually using it.
8266 * We are using event::rb to determine if the event should be stopped,
8267 * however this may race with ring_buffer_attach() (through set_output),
8268 * which will make us skip the event that actually needs to be stopped.
8269 * So ring_buffer_attach() has to stop an aux event before re-assigning
8272 if (rcu_dereference(parent
->rb
) == rb
)
8273 ro
->err
= __perf_event_stop(&sd
);
8276 static int __perf_pmu_output_stop(void *info
)
8278 struct perf_event
*event
= info
;
8279 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
8280 struct remote_output ro
= {
8285 perf_iterate_ctx(&cpuctx
->ctx
, __perf_event_output_stop
, &ro
, false);
8286 if (cpuctx
->task_ctx
)
8287 perf_iterate_ctx(cpuctx
->task_ctx
, __perf_event_output_stop
,
8294 static void perf_pmu_output_stop(struct perf_event
*event
)
8296 struct perf_event
*iter
;
8301 list_for_each_entry_rcu(iter
, &event
->rb
->event_list
, rb_entry
) {
8303 * For per-CPU events, we need to make sure that neither they
8304 * nor their children are running; for cpu==-1 events it's
8305 * sufficient to stop the event itself if it's active, since
8306 * it can't have children.
8310 cpu
= READ_ONCE(iter
->oncpu
);
8315 err
= cpu_function_call(cpu
, __perf_pmu_output_stop
, event
);
8316 if (err
== -EAGAIN
) {
8325 * task tracking -- fork/exit
8327 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
8330 struct perf_task_event
{
8331 struct task_struct
*task
;
8332 struct perf_event_context
*task_ctx
;
8335 struct perf_event_header header
;
8345 static int perf_event_task_match(struct perf_event
*event
)
8347 return event
->attr
.comm
|| event
->attr
.mmap
||
8348 event
->attr
.mmap2
|| event
->attr
.mmap_data
||
8352 static void perf_event_task_output(struct perf_event
*event
,
8355 struct perf_task_event
*task_event
= data
;
8356 struct perf_output_handle handle
;
8357 struct perf_sample_data sample
;
8358 struct task_struct
*task
= task_event
->task
;
8359 int ret
, size
= task_event
->event_id
.header
.size
;
8361 if (!perf_event_task_match(event
))
8364 perf_event_header__init_id(&task_event
->event_id
.header
, &sample
, event
);
8366 ret
= perf_output_begin(&handle
, &sample
, event
,
8367 task_event
->event_id
.header
.size
);
8371 task_event
->event_id
.pid
= perf_event_pid(event
, task
);
8372 task_event
->event_id
.tid
= perf_event_tid(event
, task
);
8374 if (task_event
->event_id
.header
.type
== PERF_RECORD_EXIT
) {
8375 task_event
->event_id
.ppid
= perf_event_pid(event
,
8377 task_event
->event_id
.ptid
= perf_event_pid(event
,
8379 } else { /* PERF_RECORD_FORK */
8380 task_event
->event_id
.ppid
= perf_event_pid(event
, current
);
8381 task_event
->event_id
.ptid
= perf_event_tid(event
, current
);
8384 task_event
->event_id
.time
= perf_event_clock(event
);
8386 perf_output_put(&handle
, task_event
->event_id
);
8388 perf_event__output_id_sample(event
, &handle
, &sample
);
8390 perf_output_end(&handle
);
8392 task_event
->event_id
.header
.size
= size
;
8395 static void perf_event_task(struct task_struct
*task
,
8396 struct perf_event_context
*task_ctx
,
8399 struct perf_task_event task_event
;
8401 if (!atomic_read(&nr_comm_events
) &&
8402 !atomic_read(&nr_mmap_events
) &&
8403 !atomic_read(&nr_task_events
))
8406 task_event
= (struct perf_task_event
){
8408 .task_ctx
= task_ctx
,
8411 .type
= new ? PERF_RECORD_FORK
: PERF_RECORD_EXIT
,
8413 .size
= sizeof(task_event
.event_id
),
8423 perf_iterate_sb(perf_event_task_output
,
8428 void perf_event_fork(struct task_struct
*task
)
8430 perf_event_task(task
, NULL
, 1);
8431 perf_event_namespaces(task
);
8438 struct perf_comm_event
{
8439 struct task_struct
*task
;
8444 struct perf_event_header header
;
8451 static int perf_event_comm_match(struct perf_event
*event
)
8453 return event
->attr
.comm
;
8456 static void perf_event_comm_output(struct perf_event
*event
,
8459 struct perf_comm_event
*comm_event
= data
;
8460 struct perf_output_handle handle
;
8461 struct perf_sample_data sample
;
8462 int size
= comm_event
->event_id
.header
.size
;
8465 if (!perf_event_comm_match(event
))
8468 perf_event_header__init_id(&comm_event
->event_id
.header
, &sample
, event
);
8469 ret
= perf_output_begin(&handle
, &sample
, event
,
8470 comm_event
->event_id
.header
.size
);
8475 comm_event
->event_id
.pid
= perf_event_pid(event
, comm_event
->task
);
8476 comm_event
->event_id
.tid
= perf_event_tid(event
, comm_event
->task
);
8478 perf_output_put(&handle
, comm_event
->event_id
);
8479 __output_copy(&handle
, comm_event
->comm
,
8480 comm_event
->comm_size
);
8482 perf_event__output_id_sample(event
, &handle
, &sample
);
8484 perf_output_end(&handle
);
8486 comm_event
->event_id
.header
.size
= size
;
8489 static void perf_event_comm_event(struct perf_comm_event
*comm_event
)
8491 char comm
[TASK_COMM_LEN
];
8494 memset(comm
, 0, sizeof(comm
));
8495 strscpy(comm
, comm_event
->task
->comm
, sizeof(comm
));
8496 size
= ALIGN(strlen(comm
)+1, sizeof(u64
));
8498 comm_event
->comm
= comm
;
8499 comm_event
->comm_size
= size
;
8501 comm_event
->event_id
.header
.size
= sizeof(comm_event
->event_id
) + size
;
8503 perf_iterate_sb(perf_event_comm_output
,
8508 void perf_event_comm(struct task_struct
*task
, bool exec
)
8510 struct perf_comm_event comm_event
;
8512 if (!atomic_read(&nr_comm_events
))
8515 comm_event
= (struct perf_comm_event
){
8521 .type
= PERF_RECORD_COMM
,
8522 .misc
= exec
? PERF_RECORD_MISC_COMM_EXEC
: 0,
8530 perf_event_comm_event(&comm_event
);
8534 * namespaces tracking
8537 struct perf_namespaces_event
{
8538 struct task_struct
*task
;
8541 struct perf_event_header header
;
8546 struct perf_ns_link_info link_info
[NR_NAMESPACES
];
8550 static int perf_event_namespaces_match(struct perf_event
*event
)
8552 return event
->attr
.namespaces
;
8555 static void perf_event_namespaces_output(struct perf_event
*event
,
8558 struct perf_namespaces_event
*namespaces_event
= data
;
8559 struct perf_output_handle handle
;
8560 struct perf_sample_data sample
;
8561 u16 header_size
= namespaces_event
->event_id
.header
.size
;
8564 if (!perf_event_namespaces_match(event
))
8567 perf_event_header__init_id(&namespaces_event
->event_id
.header
,
8569 ret
= perf_output_begin(&handle
, &sample
, event
,
8570 namespaces_event
->event_id
.header
.size
);
8574 namespaces_event
->event_id
.pid
= perf_event_pid(event
,
8575 namespaces_event
->task
);
8576 namespaces_event
->event_id
.tid
= perf_event_tid(event
,
8577 namespaces_event
->task
);
8579 perf_output_put(&handle
, namespaces_event
->event_id
);
8581 perf_event__output_id_sample(event
, &handle
, &sample
);
8583 perf_output_end(&handle
);
8585 namespaces_event
->event_id
.header
.size
= header_size
;
8588 static void perf_fill_ns_link_info(struct perf_ns_link_info
*ns_link_info
,
8589 struct task_struct
*task
,
8590 const struct proc_ns_operations
*ns_ops
)
8592 struct path ns_path
;
8593 struct inode
*ns_inode
;
8596 error
= ns_get_path(&ns_path
, task
, ns_ops
);
8598 ns_inode
= ns_path
.dentry
->d_inode
;
8599 ns_link_info
->dev
= new_encode_dev(ns_inode
->i_sb
->s_dev
);
8600 ns_link_info
->ino
= ns_inode
->i_ino
;
8605 void perf_event_namespaces(struct task_struct
*task
)
8607 struct perf_namespaces_event namespaces_event
;
8608 struct perf_ns_link_info
*ns_link_info
;
8610 if (!atomic_read(&nr_namespaces_events
))
8613 namespaces_event
= (struct perf_namespaces_event
){
8617 .type
= PERF_RECORD_NAMESPACES
,
8619 .size
= sizeof(namespaces_event
.event_id
),
8623 .nr_namespaces
= NR_NAMESPACES
,
8624 /* .link_info[NR_NAMESPACES] */
8628 ns_link_info
= namespaces_event
.event_id
.link_info
;
8630 perf_fill_ns_link_info(&ns_link_info
[MNT_NS_INDEX
],
8631 task
, &mntns_operations
);
8633 #ifdef CONFIG_USER_NS
8634 perf_fill_ns_link_info(&ns_link_info
[USER_NS_INDEX
],
8635 task
, &userns_operations
);
8637 #ifdef CONFIG_NET_NS
8638 perf_fill_ns_link_info(&ns_link_info
[NET_NS_INDEX
],
8639 task
, &netns_operations
);
8641 #ifdef CONFIG_UTS_NS
8642 perf_fill_ns_link_info(&ns_link_info
[UTS_NS_INDEX
],
8643 task
, &utsns_operations
);
8645 #ifdef CONFIG_IPC_NS
8646 perf_fill_ns_link_info(&ns_link_info
[IPC_NS_INDEX
],
8647 task
, &ipcns_operations
);
8649 #ifdef CONFIG_PID_NS
8650 perf_fill_ns_link_info(&ns_link_info
[PID_NS_INDEX
],
8651 task
, &pidns_operations
);
8653 #ifdef CONFIG_CGROUPS
8654 perf_fill_ns_link_info(&ns_link_info
[CGROUP_NS_INDEX
],
8655 task
, &cgroupns_operations
);
8658 perf_iterate_sb(perf_event_namespaces_output
,
8666 #ifdef CONFIG_CGROUP_PERF
8668 struct perf_cgroup_event
{
8672 struct perf_event_header header
;
8678 static int perf_event_cgroup_match(struct perf_event
*event
)
8680 return event
->attr
.cgroup
;
8683 static void perf_event_cgroup_output(struct perf_event
*event
, void *data
)
8685 struct perf_cgroup_event
*cgroup_event
= data
;
8686 struct perf_output_handle handle
;
8687 struct perf_sample_data sample
;
8688 u16 header_size
= cgroup_event
->event_id
.header
.size
;
8691 if (!perf_event_cgroup_match(event
))
8694 perf_event_header__init_id(&cgroup_event
->event_id
.header
,
8696 ret
= perf_output_begin(&handle
, &sample
, event
,
8697 cgroup_event
->event_id
.header
.size
);
8701 perf_output_put(&handle
, cgroup_event
->event_id
);
8702 __output_copy(&handle
, cgroup_event
->path
, cgroup_event
->path_size
);
8704 perf_event__output_id_sample(event
, &handle
, &sample
);
8706 perf_output_end(&handle
);
8708 cgroup_event
->event_id
.header
.size
= header_size
;
8711 static void perf_event_cgroup(struct cgroup
*cgrp
)
8713 struct perf_cgroup_event cgroup_event
;
8714 char path_enomem
[16] = "//enomem";
8718 if (!atomic_read(&nr_cgroup_events
))
8721 cgroup_event
= (struct perf_cgroup_event
){
8724 .type
= PERF_RECORD_CGROUP
,
8726 .size
= sizeof(cgroup_event
.event_id
),
8728 .id
= cgroup_id(cgrp
),
8732 pathname
= kmalloc(PATH_MAX
, GFP_KERNEL
);
8733 if (pathname
== NULL
) {
8734 cgroup_event
.path
= path_enomem
;
8736 /* just to be sure to have enough space for alignment */
8737 cgroup_path(cgrp
, pathname
, PATH_MAX
- sizeof(u64
));
8738 cgroup_event
.path
= pathname
;
8742 * Since our buffer works in 8 byte units we need to align our string
8743 * size to a multiple of 8. However, we must guarantee the tail end is
8744 * zero'd out to avoid leaking random bits to userspace.
8746 size
= strlen(cgroup_event
.path
) + 1;
8747 while (!IS_ALIGNED(size
, sizeof(u64
)))
8748 cgroup_event
.path
[size
++] = '\0';
8750 cgroup_event
.event_id
.header
.size
+= size
;
8751 cgroup_event
.path_size
= size
;
8753 perf_iterate_sb(perf_event_cgroup_output
,
8766 struct perf_mmap_event
{
8767 struct vm_area_struct
*vma
;
8769 const char *file_name
;
8775 u8 build_id
[BUILD_ID_SIZE_MAX
];
8779 struct perf_event_header header
;
8789 static int perf_event_mmap_match(struct perf_event
*event
,
8792 struct perf_mmap_event
*mmap_event
= data
;
8793 struct vm_area_struct
*vma
= mmap_event
->vma
;
8794 int executable
= vma
->vm_flags
& VM_EXEC
;
8796 return (!executable
&& event
->attr
.mmap_data
) ||
8797 (executable
&& (event
->attr
.mmap
|| event
->attr
.mmap2
));
8800 static void perf_event_mmap_output(struct perf_event
*event
,
8803 struct perf_mmap_event
*mmap_event
= data
;
8804 struct perf_output_handle handle
;
8805 struct perf_sample_data sample
;
8806 int size
= mmap_event
->event_id
.header
.size
;
8807 u32 type
= mmap_event
->event_id
.header
.type
;
8811 if (!perf_event_mmap_match(event
, data
))
8814 if (event
->attr
.mmap2
) {
8815 mmap_event
->event_id
.header
.type
= PERF_RECORD_MMAP2
;
8816 mmap_event
->event_id
.header
.size
+= sizeof(mmap_event
->maj
);
8817 mmap_event
->event_id
.header
.size
+= sizeof(mmap_event
->min
);
8818 mmap_event
->event_id
.header
.size
+= sizeof(mmap_event
->ino
);
8819 mmap_event
->event_id
.header
.size
+= sizeof(mmap_event
->ino_generation
);
8820 mmap_event
->event_id
.header
.size
+= sizeof(mmap_event
->prot
);
8821 mmap_event
->event_id
.header
.size
+= sizeof(mmap_event
->flags
);
8824 perf_event_header__init_id(&mmap_event
->event_id
.header
, &sample
, event
);
8825 ret
= perf_output_begin(&handle
, &sample
, event
,
8826 mmap_event
->event_id
.header
.size
);
8830 mmap_event
->event_id
.pid
= perf_event_pid(event
, current
);
8831 mmap_event
->event_id
.tid
= perf_event_tid(event
, current
);
8833 use_build_id
= event
->attr
.build_id
&& mmap_event
->build_id_size
;
8835 if (event
->attr
.mmap2
&& use_build_id
)
8836 mmap_event
->event_id
.header
.misc
|= PERF_RECORD_MISC_MMAP_BUILD_ID
;
8838 perf_output_put(&handle
, mmap_event
->event_id
);
8840 if (event
->attr
.mmap2
) {
8842 u8 size
[4] = { (u8
) mmap_event
->build_id_size
, 0, 0, 0 };
8844 __output_copy(&handle
, size
, 4);
8845 __output_copy(&handle
, mmap_event
->build_id
, BUILD_ID_SIZE_MAX
);
8847 perf_output_put(&handle
, mmap_event
->maj
);
8848 perf_output_put(&handle
, mmap_event
->min
);
8849 perf_output_put(&handle
, mmap_event
->ino
);
8850 perf_output_put(&handle
, mmap_event
->ino_generation
);
8852 perf_output_put(&handle
, mmap_event
->prot
);
8853 perf_output_put(&handle
, mmap_event
->flags
);
8856 __output_copy(&handle
, mmap_event
->file_name
,
8857 mmap_event
->file_size
);
8859 perf_event__output_id_sample(event
, &handle
, &sample
);
8861 perf_output_end(&handle
);
8863 mmap_event
->event_id
.header
.size
= size
;
8864 mmap_event
->event_id
.header
.type
= type
;
8867 static void perf_event_mmap_event(struct perf_mmap_event
*mmap_event
)
8869 struct vm_area_struct
*vma
= mmap_event
->vma
;
8870 struct file
*file
= vma
->vm_file
;
8871 int maj
= 0, min
= 0;
8872 u64 ino
= 0, gen
= 0;
8873 u32 prot
= 0, flags
= 0;
8879 if (vma
->vm_flags
& VM_READ
)
8881 if (vma
->vm_flags
& VM_WRITE
)
8883 if (vma
->vm_flags
& VM_EXEC
)
8886 if (vma
->vm_flags
& VM_MAYSHARE
)
8889 flags
= MAP_PRIVATE
;
8891 if (vma
->vm_flags
& VM_LOCKED
)
8892 flags
|= MAP_LOCKED
;
8893 if (is_vm_hugetlb_page(vma
))
8894 flags
|= MAP_HUGETLB
;
8897 struct inode
*inode
;
8900 buf
= kmalloc(PATH_MAX
, GFP_KERNEL
);
8906 * d_path() works from the end of the rb backwards, so we
8907 * need to add enough zero bytes after the string to handle
8908 * the 64bit alignment we do later.
8910 name
= file_path(file
, buf
, PATH_MAX
- sizeof(u64
));
8915 inode
= file_inode(vma
->vm_file
);
8916 dev
= inode
->i_sb
->s_dev
;
8918 gen
= inode
->i_generation
;
8924 if (vma
->vm_ops
&& vma
->vm_ops
->name
)
8925 name
= (char *) vma
->vm_ops
->name(vma
);
8927 name
= (char *)arch_vma_name(vma
);
8929 if (vma_is_initial_heap(vma
))
8931 else if (vma_is_initial_stack(vma
))
8939 strscpy(tmp
, name
, sizeof(tmp
));
8943 * Since our buffer works in 8 byte units we need to align our string
8944 * size to a multiple of 8. However, we must guarantee the tail end is
8945 * zero'd out to avoid leaking random bits to userspace.
8947 size
= strlen(name
)+1;
8948 while (!IS_ALIGNED(size
, sizeof(u64
)))
8949 name
[size
++] = '\0';
8951 mmap_event
->file_name
= name
;
8952 mmap_event
->file_size
= size
;
8953 mmap_event
->maj
= maj
;
8954 mmap_event
->min
= min
;
8955 mmap_event
->ino
= ino
;
8956 mmap_event
->ino_generation
= gen
;
8957 mmap_event
->prot
= prot
;
8958 mmap_event
->flags
= flags
;
8960 if (!(vma
->vm_flags
& VM_EXEC
))
8961 mmap_event
->event_id
.header
.misc
|= PERF_RECORD_MISC_MMAP_DATA
;
8963 mmap_event
->event_id
.header
.size
= sizeof(mmap_event
->event_id
) + size
;
8965 if (atomic_read(&nr_build_id_events
))
8966 build_id_parse_nofault(vma
, mmap_event
->build_id
, &mmap_event
->build_id_size
);
8968 perf_iterate_sb(perf_event_mmap_output
,
8976 * Check whether inode and address range match filter criteria.
8978 static bool perf_addr_filter_match(struct perf_addr_filter
*filter
,
8979 struct file
*file
, unsigned long offset
,
8982 /* d_inode(NULL) won't be equal to any mapped user-space file */
8983 if (!filter
->path
.dentry
)
8986 if (d_inode(filter
->path
.dentry
) != file_inode(file
))
8989 if (filter
->offset
> offset
+ size
)
8992 if (filter
->offset
+ filter
->size
< offset
)
8998 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter
*filter
,
8999 struct vm_area_struct
*vma
,
9000 struct perf_addr_filter_range
*fr
)
9002 unsigned long vma_size
= vma
->vm_end
- vma
->vm_start
;
9003 unsigned long off
= vma
->vm_pgoff
<< PAGE_SHIFT
;
9004 struct file
*file
= vma
->vm_file
;
9006 if (!perf_addr_filter_match(filter
, file
, off
, vma_size
))
9009 if (filter
->offset
< off
) {
9010 fr
->start
= vma
->vm_start
;
9011 fr
->size
= min(vma_size
, filter
->size
- (off
- filter
->offset
));
9013 fr
->start
= vma
->vm_start
+ filter
->offset
- off
;
9014 fr
->size
= min(vma
->vm_end
- fr
->start
, filter
->size
);
9020 static void __perf_addr_filters_adjust(struct perf_event
*event
, void *data
)
9022 struct perf_addr_filters_head
*ifh
= perf_event_addr_filters(event
);
9023 struct vm_area_struct
*vma
= data
;
9024 struct perf_addr_filter
*filter
;
9025 unsigned int restart
= 0, count
= 0;
9026 unsigned long flags
;
9028 if (!has_addr_filter(event
))
9034 raw_spin_lock_irqsave(&ifh
->lock
, flags
);
9035 list_for_each_entry(filter
, &ifh
->list
, entry
) {
9036 if (perf_addr_filter_vma_adjust(filter
, vma
,
9037 &event
->addr_filter_ranges
[count
]))
9044 event
->addr_filters_gen
++;
9045 raw_spin_unlock_irqrestore(&ifh
->lock
, flags
);
9048 perf_event_stop(event
, 1);
9052 * Adjust all task's events' filters to the new vma
9054 static void perf_addr_filters_adjust(struct vm_area_struct
*vma
)
9056 struct perf_event_context
*ctx
;
9059 * Data tracing isn't supported yet and as such there is no need
9060 * to keep track of anything that isn't related to executable code:
9062 if (!(vma
->vm_flags
& VM_EXEC
))
9066 ctx
= rcu_dereference(current
->perf_event_ctxp
);
9068 perf_iterate_ctx(ctx
, __perf_addr_filters_adjust
, vma
, true);
9072 void perf_event_mmap(struct vm_area_struct
*vma
)
9074 struct perf_mmap_event mmap_event
;
9076 if (!atomic_read(&nr_mmap_events
))
9079 mmap_event
= (struct perf_mmap_event
){
9085 .type
= PERF_RECORD_MMAP
,
9086 .misc
= PERF_RECORD_MISC_USER
,
9091 .start
= vma
->vm_start
,
9092 .len
= vma
->vm_end
- vma
->vm_start
,
9093 .pgoff
= (u64
)vma
->vm_pgoff
<< PAGE_SHIFT
,
9095 /* .maj (attr_mmap2 only) */
9096 /* .min (attr_mmap2 only) */
9097 /* .ino (attr_mmap2 only) */
9098 /* .ino_generation (attr_mmap2 only) */
9099 /* .prot (attr_mmap2 only) */
9100 /* .flags (attr_mmap2 only) */
9103 perf_addr_filters_adjust(vma
);
9104 perf_event_mmap_event(&mmap_event
);
9107 void perf_event_aux_event(struct perf_event
*event
, unsigned long head
,
9108 unsigned long size
, u64 flags
)
9110 struct perf_output_handle handle
;
9111 struct perf_sample_data sample
;
9112 struct perf_aux_event
{
9113 struct perf_event_header header
;
9119 .type
= PERF_RECORD_AUX
,
9121 .size
= sizeof(rec
),
9129 perf_event_header__init_id(&rec
.header
, &sample
, event
);
9130 ret
= perf_output_begin(&handle
, &sample
, event
, rec
.header
.size
);
9135 perf_output_put(&handle
, rec
);
9136 perf_event__output_id_sample(event
, &handle
, &sample
);
9138 perf_output_end(&handle
);
9142 * Lost/dropped samples logging
9144 void perf_log_lost_samples(struct perf_event
*event
, u64 lost
)
9146 struct perf_output_handle handle
;
9147 struct perf_sample_data sample
;
9151 struct perf_event_header header
;
9153 } lost_samples_event
= {
9155 .type
= PERF_RECORD_LOST_SAMPLES
,
9157 .size
= sizeof(lost_samples_event
),
9162 perf_event_header__init_id(&lost_samples_event
.header
, &sample
, event
);
9164 ret
= perf_output_begin(&handle
, &sample
, event
,
9165 lost_samples_event
.header
.size
);
9169 perf_output_put(&handle
, lost_samples_event
);
9170 perf_event__output_id_sample(event
, &handle
, &sample
);
9171 perf_output_end(&handle
);
9175 * context_switch tracking
9178 struct perf_switch_event
{
9179 struct task_struct
*task
;
9180 struct task_struct
*next_prev
;
9183 struct perf_event_header header
;
9189 static int perf_event_switch_match(struct perf_event
*event
)
9191 return event
->attr
.context_switch
;
9194 static void perf_event_switch_output(struct perf_event
*event
, void *data
)
9196 struct perf_switch_event
*se
= data
;
9197 struct perf_output_handle handle
;
9198 struct perf_sample_data sample
;
9201 if (!perf_event_switch_match(event
))
9204 /* Only CPU-wide events are allowed to see next/prev pid/tid */
9205 if (event
->ctx
->task
) {
9206 se
->event_id
.header
.type
= PERF_RECORD_SWITCH
;
9207 se
->event_id
.header
.size
= sizeof(se
->event_id
.header
);
9209 se
->event_id
.header
.type
= PERF_RECORD_SWITCH_CPU_WIDE
;
9210 se
->event_id
.header
.size
= sizeof(se
->event_id
);
9211 se
->event_id
.next_prev_pid
=
9212 perf_event_pid(event
, se
->next_prev
);
9213 se
->event_id
.next_prev_tid
=
9214 perf_event_tid(event
, se
->next_prev
);
9217 perf_event_header__init_id(&se
->event_id
.header
, &sample
, event
);
9219 ret
= perf_output_begin(&handle
, &sample
, event
, se
->event_id
.header
.size
);
9223 if (event
->ctx
->task
)
9224 perf_output_put(&handle
, se
->event_id
.header
);
9226 perf_output_put(&handle
, se
->event_id
);
9228 perf_event__output_id_sample(event
, &handle
, &sample
);
9230 perf_output_end(&handle
);
9233 static void perf_event_switch(struct task_struct
*task
,
9234 struct task_struct
*next_prev
, bool sched_in
)
9236 struct perf_switch_event switch_event
;
9238 /* N.B. caller checks nr_switch_events != 0 */
9240 switch_event
= (struct perf_switch_event
){
9242 .next_prev
= next_prev
,
9246 .misc
= sched_in
? 0 : PERF_RECORD_MISC_SWITCH_OUT
,
9249 /* .next_prev_pid */
9250 /* .next_prev_tid */
9254 if (!sched_in
&& task
->on_rq
) {
9255 switch_event
.event_id
.header
.misc
|=
9256 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT
;
9259 perf_iterate_sb(perf_event_switch_output
, &switch_event
, NULL
);
9263 * IRQ throttle logging
9266 static void perf_log_throttle(struct perf_event
*event
, int enable
)
9268 struct perf_output_handle handle
;
9269 struct perf_sample_data sample
;
9273 struct perf_event_header header
;
9277 } throttle_event
= {
9279 .type
= PERF_RECORD_THROTTLE
,
9281 .size
= sizeof(throttle_event
),
9283 .time
= perf_event_clock(event
),
9284 .id
= primary_event_id(event
),
9285 .stream_id
= event
->id
,
9289 throttle_event
.header
.type
= PERF_RECORD_UNTHROTTLE
;
9291 perf_event_header__init_id(&throttle_event
.header
, &sample
, event
);
9293 ret
= perf_output_begin(&handle
, &sample
, event
,
9294 throttle_event
.header
.size
);
9298 perf_output_put(&handle
, throttle_event
);
9299 perf_event__output_id_sample(event
, &handle
, &sample
);
9300 perf_output_end(&handle
);
9304 * ksymbol register/unregister tracking
9307 struct perf_ksymbol_event
{
9311 struct perf_event_header header
;
9319 static int perf_event_ksymbol_match(struct perf_event
*event
)
9321 return event
->attr
.ksymbol
;
9324 static void perf_event_ksymbol_output(struct perf_event
*event
, void *data
)
9326 struct perf_ksymbol_event
*ksymbol_event
= data
;
9327 struct perf_output_handle handle
;
9328 struct perf_sample_data sample
;
9331 if (!perf_event_ksymbol_match(event
))
9334 perf_event_header__init_id(&ksymbol_event
->event_id
.header
,
9336 ret
= perf_output_begin(&handle
, &sample
, event
,
9337 ksymbol_event
->event_id
.header
.size
);
9341 perf_output_put(&handle
, ksymbol_event
->event_id
);
9342 __output_copy(&handle
, ksymbol_event
->name
, ksymbol_event
->name_len
);
9343 perf_event__output_id_sample(event
, &handle
, &sample
);
9345 perf_output_end(&handle
);
9348 void perf_event_ksymbol(u16 ksym_type
, u64 addr
, u32 len
, bool unregister
,
9351 struct perf_ksymbol_event ksymbol_event
;
9352 char name
[KSYM_NAME_LEN
];
9356 if (!atomic_read(&nr_ksymbol_events
))
9359 if (ksym_type
>= PERF_RECORD_KSYMBOL_TYPE_MAX
||
9360 ksym_type
== PERF_RECORD_KSYMBOL_TYPE_UNKNOWN
)
9363 strscpy(name
, sym
, KSYM_NAME_LEN
);
9364 name_len
= strlen(name
) + 1;
9365 while (!IS_ALIGNED(name_len
, sizeof(u64
)))
9366 name
[name_len
++] = '\0';
9367 BUILD_BUG_ON(KSYM_NAME_LEN
% sizeof(u64
));
9370 flags
|= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER
;
9372 ksymbol_event
= (struct perf_ksymbol_event
){
9374 .name_len
= name_len
,
9377 .type
= PERF_RECORD_KSYMBOL
,
9378 .size
= sizeof(ksymbol_event
.event_id
) +
9383 .ksym_type
= ksym_type
,
9388 perf_iterate_sb(perf_event_ksymbol_output
, &ksymbol_event
, NULL
);
9391 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__
, ksym_type
);
9395 * bpf program load/unload tracking
9398 struct perf_bpf_event
{
9399 struct bpf_prog
*prog
;
9401 struct perf_event_header header
;
9405 u8 tag
[BPF_TAG_SIZE
];
9409 static int perf_event_bpf_match(struct perf_event
*event
)
9411 return event
->attr
.bpf_event
;
9414 static void perf_event_bpf_output(struct perf_event
*event
, void *data
)
9416 struct perf_bpf_event
*bpf_event
= data
;
9417 struct perf_output_handle handle
;
9418 struct perf_sample_data sample
;
9421 if (!perf_event_bpf_match(event
))
9424 perf_event_header__init_id(&bpf_event
->event_id
.header
,
9426 ret
= perf_output_begin(&handle
, &sample
, event
,
9427 bpf_event
->event_id
.header
.size
);
9431 perf_output_put(&handle
, bpf_event
->event_id
);
9432 perf_event__output_id_sample(event
, &handle
, &sample
);
9434 perf_output_end(&handle
);
9437 static void perf_event_bpf_emit_ksymbols(struct bpf_prog
*prog
,
9438 enum perf_bpf_event_type type
)
9440 bool unregister
= type
== PERF_BPF_EVENT_PROG_UNLOAD
;
9443 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF
,
9444 (u64
)(unsigned long)prog
->bpf_func
,
9445 prog
->jited_len
, unregister
,
9446 prog
->aux
->ksym
.name
);
9448 for (i
= 1; i
< prog
->aux
->func_cnt
; i
++) {
9449 struct bpf_prog
*subprog
= prog
->aux
->func
[i
];
9452 PERF_RECORD_KSYMBOL_TYPE_BPF
,
9453 (u64
)(unsigned long)subprog
->bpf_func
,
9454 subprog
->jited_len
, unregister
,
9455 subprog
->aux
->ksym
.name
);
9459 void perf_event_bpf_event(struct bpf_prog
*prog
,
9460 enum perf_bpf_event_type type
,
9463 struct perf_bpf_event bpf_event
;
9466 case PERF_BPF_EVENT_PROG_LOAD
:
9467 case PERF_BPF_EVENT_PROG_UNLOAD
:
9468 if (atomic_read(&nr_ksymbol_events
))
9469 perf_event_bpf_emit_ksymbols(prog
, type
);
9475 if (!atomic_read(&nr_bpf_events
))
9478 bpf_event
= (struct perf_bpf_event
){
9482 .type
= PERF_RECORD_BPF_EVENT
,
9483 .size
= sizeof(bpf_event
.event_id
),
9487 .id
= prog
->aux
->id
,
9491 BUILD_BUG_ON(BPF_TAG_SIZE
% sizeof(u64
));
9493 memcpy(bpf_event
.event_id
.tag
, prog
->tag
, BPF_TAG_SIZE
);
9494 perf_iterate_sb(perf_event_bpf_output
, &bpf_event
, NULL
);
9497 struct perf_text_poke_event
{
9498 const void *old_bytes
;
9499 const void *new_bytes
;
9505 struct perf_event_header header
;
9511 static int perf_event_text_poke_match(struct perf_event
*event
)
9513 return event
->attr
.text_poke
;
9516 static void perf_event_text_poke_output(struct perf_event
*event
, void *data
)
9518 struct perf_text_poke_event
*text_poke_event
= data
;
9519 struct perf_output_handle handle
;
9520 struct perf_sample_data sample
;
9524 if (!perf_event_text_poke_match(event
))
9527 perf_event_header__init_id(&text_poke_event
->event_id
.header
, &sample
, event
);
9529 ret
= perf_output_begin(&handle
, &sample
, event
,
9530 text_poke_event
->event_id
.header
.size
);
9534 perf_output_put(&handle
, text_poke_event
->event_id
);
9535 perf_output_put(&handle
, text_poke_event
->old_len
);
9536 perf_output_put(&handle
, text_poke_event
->new_len
);
9538 __output_copy(&handle
, text_poke_event
->old_bytes
, text_poke_event
->old_len
);
9539 __output_copy(&handle
, text_poke_event
->new_bytes
, text_poke_event
->new_len
);
9541 if (text_poke_event
->pad
)
9542 __output_copy(&handle
, &padding
, text_poke_event
->pad
);
9544 perf_event__output_id_sample(event
, &handle
, &sample
);
9546 perf_output_end(&handle
);
9549 void perf_event_text_poke(const void *addr
, const void *old_bytes
,
9550 size_t old_len
, const void *new_bytes
, size_t new_len
)
9552 struct perf_text_poke_event text_poke_event
;
9555 if (!atomic_read(&nr_text_poke_events
))
9558 tot
= sizeof(text_poke_event
.old_len
) + old_len
;
9559 tot
+= sizeof(text_poke_event
.new_len
) + new_len
;
9560 pad
= ALIGN(tot
, sizeof(u64
)) - tot
;
9562 text_poke_event
= (struct perf_text_poke_event
){
9563 .old_bytes
= old_bytes
,
9564 .new_bytes
= new_bytes
,
9570 .type
= PERF_RECORD_TEXT_POKE
,
9571 .misc
= PERF_RECORD_MISC_KERNEL
,
9572 .size
= sizeof(text_poke_event
.event_id
) + tot
+ pad
,
9574 .addr
= (unsigned long)addr
,
9578 perf_iterate_sb(perf_event_text_poke_output
, &text_poke_event
, NULL
);
9581 void perf_event_itrace_started(struct perf_event
*event
)
9583 event
->attach_state
|= PERF_ATTACH_ITRACE
;
9586 static void perf_log_itrace_start(struct perf_event
*event
)
9588 struct perf_output_handle handle
;
9589 struct perf_sample_data sample
;
9590 struct perf_aux_event
{
9591 struct perf_event_header header
;
9598 event
= event
->parent
;
9600 if (!(event
->pmu
->capabilities
& PERF_PMU_CAP_ITRACE
) ||
9601 event
->attach_state
& PERF_ATTACH_ITRACE
)
9604 rec
.header
.type
= PERF_RECORD_ITRACE_START
;
9605 rec
.header
.misc
= 0;
9606 rec
.header
.size
= sizeof(rec
);
9607 rec
.pid
= perf_event_pid(event
, current
);
9608 rec
.tid
= perf_event_tid(event
, current
);
9610 perf_event_header__init_id(&rec
.header
, &sample
, event
);
9611 ret
= perf_output_begin(&handle
, &sample
, event
, rec
.header
.size
);
9616 perf_output_put(&handle
, rec
);
9617 perf_event__output_id_sample(event
, &handle
, &sample
);
9619 perf_output_end(&handle
);
9622 void perf_report_aux_output_id(struct perf_event
*event
, u64 hw_id
)
9624 struct perf_output_handle handle
;
9625 struct perf_sample_data sample
;
9626 struct perf_aux_event
{
9627 struct perf_event_header header
;
9633 event
= event
->parent
;
9635 rec
.header
.type
= PERF_RECORD_AUX_OUTPUT_HW_ID
;
9636 rec
.header
.misc
= 0;
9637 rec
.header
.size
= sizeof(rec
);
9640 perf_event_header__init_id(&rec
.header
, &sample
, event
);
9641 ret
= perf_output_begin(&handle
, &sample
, event
, rec
.header
.size
);
9646 perf_output_put(&handle
, rec
);
9647 perf_event__output_id_sample(event
, &handle
, &sample
);
9649 perf_output_end(&handle
);
9651 EXPORT_SYMBOL_GPL(perf_report_aux_output_id
);
9654 __perf_event_account_interrupt(struct perf_event
*event
, int throttle
)
9656 struct hw_perf_event
*hwc
= &event
->hw
;
9660 seq
= __this_cpu_read(perf_throttled_seq
);
9661 if (seq
!= hwc
->interrupts_seq
) {
9662 hwc
->interrupts_seq
= seq
;
9663 hwc
->interrupts
= 1;
9666 if (unlikely(throttle
&&
9667 hwc
->interrupts
> max_samples_per_tick
)) {
9668 __this_cpu_inc(perf_throttled_count
);
9669 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS
);
9670 hwc
->interrupts
= MAX_INTERRUPTS
;
9671 perf_log_throttle(event
, 0);
9676 if (event
->attr
.freq
) {
9677 u64 now
= perf_clock();
9678 s64 delta
= now
- hwc
->freq_time_stamp
;
9680 hwc
->freq_time_stamp
= now
;
9682 if (delta
> 0 && delta
< 2*TICK_NSEC
)
9683 perf_adjust_period(event
, delta
, hwc
->last_period
, true);
9689 int perf_event_account_interrupt(struct perf_event
*event
)
9691 return __perf_event_account_interrupt(event
, 1);
9694 static inline bool sample_is_allowed(struct perf_event
*event
, struct pt_regs
*regs
)
9697 * Due to interrupt latency (AKA "skid"), we may enter the
9698 * kernel before taking an overflow, even if the PMU is only
9699 * counting user events.
9701 if (event
->attr
.exclude_kernel
&& !user_mode(regs
))
9707 #ifdef CONFIG_BPF_SYSCALL
9708 static int bpf_overflow_handler(struct perf_event
*event
,
9709 struct perf_sample_data
*data
,
9710 struct pt_regs
*regs
)
9712 struct bpf_perf_event_data_kern ctx
= {
9716 struct bpf_prog
*prog
;
9719 ctx
.regs
= perf_arch_bpf_user_pt_regs(regs
);
9720 if (unlikely(__this_cpu_inc_return(bpf_prog_active
) != 1))
9723 prog
= READ_ONCE(event
->prog
);
9725 perf_prepare_sample(data
, event
, regs
);
9726 ret
= bpf_prog_run(prog
, &ctx
);
9730 __this_cpu_dec(bpf_prog_active
);
9735 static inline int perf_event_set_bpf_handler(struct perf_event
*event
,
9736 struct bpf_prog
*prog
,
9739 if (event
->overflow_handler_context
)
9740 /* hw breakpoint or kernel counter */
9746 if (prog
->type
!= BPF_PROG_TYPE_PERF_EVENT
)
9749 if (event
->attr
.precise_ip
&&
9750 prog
->call_get_stack
&&
9751 (!(event
->attr
.sample_type
& PERF_SAMPLE_CALLCHAIN
) ||
9752 event
->attr
.exclude_callchain_kernel
||
9753 event
->attr
.exclude_callchain_user
)) {
9755 * On perf_event with precise_ip, calling bpf_get_stack()
9756 * may trigger unwinder warnings and occasional crashes.
9757 * bpf_get_[stack|stackid] works around this issue by using
9758 * callchain attached to perf_sample_data. If the
9759 * perf_event does not full (kernel and user) callchain
9760 * attached to perf_sample_data, do not allow attaching BPF
9761 * program that calls bpf_get_[stack|stackid].
9767 event
->bpf_cookie
= bpf_cookie
;
9771 static inline void perf_event_free_bpf_handler(struct perf_event
*event
)
9773 struct bpf_prog
*prog
= event
->prog
;
9782 static inline int bpf_overflow_handler(struct perf_event
*event
,
9783 struct perf_sample_data
*data
,
9784 struct pt_regs
*regs
)
9789 static inline int perf_event_set_bpf_handler(struct perf_event
*event
,
9790 struct bpf_prog
*prog
,
9796 static inline void perf_event_free_bpf_handler(struct perf_event
*event
)
9802 * Generic event overflow handling, sampling.
9805 static int __perf_event_overflow(struct perf_event
*event
,
9806 int throttle
, struct perf_sample_data
*data
,
9807 struct pt_regs
*regs
)
9809 int events
= atomic_read(&event
->event_limit
);
9813 * Non-sampling counters might still use the PMI to fold short
9814 * hardware counters, ignore those.
9816 if (unlikely(!is_sampling_event(event
)))
9819 ret
= __perf_event_account_interrupt(event
, throttle
);
9821 if (event
->prog
&& event
->prog
->type
== BPF_PROG_TYPE_PERF_EVENT
&&
9822 !bpf_overflow_handler(event
, data
, regs
))
9826 * XXX event_limit might not quite work as expected on inherited
9830 event
->pending_kill
= POLL_IN
;
9831 if (events
&& atomic_dec_and_test(&event
->event_limit
)) {
9833 event
->pending_kill
= POLL_HUP
;
9834 perf_event_disable_inatomic(event
);
9837 if (event
->attr
.sigtrap
) {
9839 * The desired behaviour of sigtrap vs invalid samples is a bit
9840 * tricky; on the one hand, one should not loose the SIGTRAP if
9841 * it is the first event, on the other hand, we should also not
9842 * trigger the WARN or override the data address.
9844 bool valid_sample
= sample_is_allowed(event
, regs
);
9845 unsigned int pending_id
= 1;
9846 enum task_work_notify_mode notify_mode
;
9849 pending_id
= hash32_ptr((void *)instruction_pointer(regs
)) ?: 1;
9851 notify_mode
= in_nmi() ? TWA_NMI_CURRENT
: TWA_RESUME
;
9853 if (!event
->pending_work
&&
9854 !task_work_add(current
, &event
->pending_task
, notify_mode
)) {
9855 event
->pending_work
= pending_id
;
9856 local_inc(&event
->ctx
->nr_no_switch_fast
);
9858 event
->pending_addr
= 0;
9859 if (valid_sample
&& (data
->sample_flags
& PERF_SAMPLE_ADDR
))
9860 event
->pending_addr
= data
->addr
;
9862 } else if (event
->attr
.exclude_kernel
&& valid_sample
) {
9864 * Should not be able to return to user space without
9865 * consuming pending_work; with exceptions:
9867 * 1. Where !exclude_kernel, events can overflow again
9868 * in the kernel without returning to user space.
9870 * 2. Events that can overflow again before the IRQ-
9871 * work without user space progress (e.g. hrtimer).
9872 * To approximate progress (with false negatives),
9873 * check 32-bit hash of the current IP.
9875 WARN_ON_ONCE(event
->pending_work
!= pending_id
);
9879 READ_ONCE(event
->overflow_handler
)(event
, data
, regs
);
9881 if (*perf_event_fasync(event
) && event
->pending_kill
) {
9882 event
->pending_wakeup
= 1;
9883 irq_work_queue(&event
->pending_irq
);
9889 int perf_event_overflow(struct perf_event
*event
,
9890 struct perf_sample_data
*data
,
9891 struct pt_regs
*regs
)
9893 return __perf_event_overflow(event
, 1, data
, regs
);
9897 * Generic software event infrastructure
9900 struct swevent_htable
{
9901 struct swevent_hlist
*swevent_hlist
;
9902 struct mutex hlist_mutex
;
9905 static DEFINE_PER_CPU(struct swevent_htable
, swevent_htable
);
9908 * We directly increment event->count and keep a second value in
9909 * event->hw.period_left to count intervals. This period event
9910 * is kept in the range [-sample_period, 0] so that we can use the
9914 u64
perf_swevent_set_period(struct perf_event
*event
)
9916 struct hw_perf_event
*hwc
= &event
->hw
;
9917 u64 period
= hwc
->last_period
;
9921 hwc
->last_period
= hwc
->sample_period
;
9923 old
= local64_read(&hwc
->period_left
);
9929 nr
= div64_u64(period
+ val
, period
);
9930 offset
= nr
* period
;
9932 } while (!local64_try_cmpxchg(&hwc
->period_left
, &old
, val
));
9937 static void perf_swevent_overflow(struct perf_event
*event
, u64 overflow
,
9938 struct perf_sample_data
*data
,
9939 struct pt_regs
*regs
)
9941 struct hw_perf_event
*hwc
= &event
->hw
;
9945 overflow
= perf_swevent_set_period(event
);
9947 if (hwc
->interrupts
== MAX_INTERRUPTS
)
9950 for (; overflow
; overflow
--) {
9951 if (__perf_event_overflow(event
, throttle
,
9954 * We inhibit the overflow from happening when
9955 * hwc->interrupts == MAX_INTERRUPTS.
9963 static void perf_swevent_event(struct perf_event
*event
, u64 nr
,
9964 struct perf_sample_data
*data
,
9965 struct pt_regs
*regs
)
9967 struct hw_perf_event
*hwc
= &event
->hw
;
9969 local64_add(nr
, &event
->count
);
9974 if (!is_sampling_event(event
))
9977 if ((event
->attr
.sample_type
& PERF_SAMPLE_PERIOD
) && !event
->attr
.freq
) {
9979 return perf_swevent_overflow(event
, 1, data
, regs
);
9981 data
->period
= event
->hw
.last_period
;
9983 if (nr
== 1 && hwc
->sample_period
== 1 && !event
->attr
.freq
)
9984 return perf_swevent_overflow(event
, 1, data
, regs
);
9986 if (local64_add_negative(nr
, &hwc
->period_left
))
9989 perf_swevent_overflow(event
, 0, data
, regs
);
9992 static int perf_exclude_event(struct perf_event
*event
,
9993 struct pt_regs
*regs
)
9995 if (event
->hw
.state
& PERF_HES_STOPPED
)
9999 if (event
->attr
.exclude_user
&& user_mode(regs
))
10002 if (event
->attr
.exclude_kernel
&& !user_mode(regs
))
10009 static int perf_swevent_match(struct perf_event
*event
,
10010 enum perf_type_id type
,
10012 struct perf_sample_data
*data
,
10013 struct pt_regs
*regs
)
10015 if (event
->attr
.type
!= type
)
10018 if (event
->attr
.config
!= event_id
)
10021 if (perf_exclude_event(event
, regs
))
10027 static inline u64
swevent_hash(u64 type
, u32 event_id
)
10029 u64 val
= event_id
| (type
<< 32);
10031 return hash_64(val
, SWEVENT_HLIST_BITS
);
10034 static inline struct hlist_head
*
10035 __find_swevent_head(struct swevent_hlist
*hlist
, u64 type
, u32 event_id
)
10037 u64 hash
= swevent_hash(type
, event_id
);
10039 return &hlist
->heads
[hash
];
10042 /* For the read side: events when they trigger */
10043 static inline struct hlist_head
*
10044 find_swevent_head_rcu(struct swevent_htable
*swhash
, u64 type
, u32 event_id
)
10046 struct swevent_hlist
*hlist
;
10048 hlist
= rcu_dereference(swhash
->swevent_hlist
);
10052 return __find_swevent_head(hlist
, type
, event_id
);
10055 /* For the event head insertion and removal in the hlist */
10056 static inline struct hlist_head
*
10057 find_swevent_head(struct swevent_htable
*swhash
, struct perf_event
*event
)
10059 struct swevent_hlist
*hlist
;
10060 u32 event_id
= event
->attr
.config
;
10061 u64 type
= event
->attr
.type
;
10064 * Event scheduling is always serialized against hlist allocation
10065 * and release. Which makes the protected version suitable here.
10066 * The context lock guarantees that.
10068 hlist
= rcu_dereference_protected(swhash
->swevent_hlist
,
10069 lockdep_is_held(&event
->ctx
->lock
));
10073 return __find_swevent_head(hlist
, type
, event_id
);
10076 static void do_perf_sw_event(enum perf_type_id type
, u32 event_id
,
10078 struct perf_sample_data
*data
,
10079 struct pt_regs
*regs
)
10081 struct swevent_htable
*swhash
= this_cpu_ptr(&swevent_htable
);
10082 struct perf_event
*event
;
10083 struct hlist_head
*head
;
10086 head
= find_swevent_head_rcu(swhash
, type
, event_id
);
10090 hlist_for_each_entry_rcu(event
, head
, hlist_entry
) {
10091 if (perf_swevent_match(event
, type
, event_id
, data
, regs
))
10092 perf_swevent_event(event
, nr
, data
, regs
);
10098 DEFINE_PER_CPU(struct pt_regs
, __perf_regs
[4]);
10100 int perf_swevent_get_recursion_context(void)
10102 return get_recursion_context(current
->perf_recursion
);
10104 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context
);
10106 void perf_swevent_put_recursion_context(int rctx
)
10108 put_recursion_context(current
->perf_recursion
, rctx
);
10111 void ___perf_sw_event(u32 event_id
, u64 nr
, struct pt_regs
*regs
, u64 addr
)
10113 struct perf_sample_data data
;
10115 if (WARN_ON_ONCE(!regs
))
10118 perf_sample_data_init(&data
, addr
, 0);
10119 do_perf_sw_event(PERF_TYPE_SOFTWARE
, event_id
, nr
, &data
, regs
);
10122 void __perf_sw_event(u32 event_id
, u64 nr
, struct pt_regs
*regs
, u64 addr
)
10126 preempt_disable_notrace();
10127 rctx
= perf_swevent_get_recursion_context();
10128 if (unlikely(rctx
< 0))
10131 ___perf_sw_event(event_id
, nr
, regs
, addr
);
10133 perf_swevent_put_recursion_context(rctx
);
10135 preempt_enable_notrace();
10138 static void perf_swevent_read(struct perf_event
*event
)
10142 static int perf_swevent_add(struct perf_event
*event
, int flags
)
10144 struct swevent_htable
*swhash
= this_cpu_ptr(&swevent_htable
);
10145 struct hw_perf_event
*hwc
= &event
->hw
;
10146 struct hlist_head
*head
;
10148 if (is_sampling_event(event
)) {
10149 hwc
->last_period
= hwc
->sample_period
;
10150 perf_swevent_set_period(event
);
10153 hwc
->state
= !(flags
& PERF_EF_START
);
10155 head
= find_swevent_head(swhash
, event
);
10156 if (WARN_ON_ONCE(!head
))
10159 hlist_add_head_rcu(&event
->hlist_entry
, head
);
10160 perf_event_update_userpage(event
);
10165 static void perf_swevent_del(struct perf_event
*event
, int flags
)
10167 hlist_del_rcu(&event
->hlist_entry
);
10170 static void perf_swevent_start(struct perf_event
*event
, int flags
)
10172 event
->hw
.state
= 0;
10175 static void perf_swevent_stop(struct perf_event
*event
, int flags
)
10177 event
->hw
.state
= PERF_HES_STOPPED
;
10180 /* Deref the hlist from the update side */
10181 static inline struct swevent_hlist
*
10182 swevent_hlist_deref(struct swevent_htable
*swhash
)
10184 return rcu_dereference_protected(swhash
->swevent_hlist
,
10185 lockdep_is_held(&swhash
->hlist_mutex
));
10188 static void swevent_hlist_release(struct swevent_htable
*swhash
)
10190 struct swevent_hlist
*hlist
= swevent_hlist_deref(swhash
);
10195 RCU_INIT_POINTER(swhash
->swevent_hlist
, NULL
);
10196 kfree_rcu(hlist
, rcu_head
);
10199 static void swevent_hlist_put_cpu(int cpu
)
10201 struct swevent_htable
*swhash
= &per_cpu(swevent_htable
, cpu
);
10203 mutex_lock(&swhash
->hlist_mutex
);
10205 if (!--swhash
->hlist_refcount
)
10206 swevent_hlist_release(swhash
);
10208 mutex_unlock(&swhash
->hlist_mutex
);
10211 static void swevent_hlist_put(void)
10215 for_each_possible_cpu(cpu
)
10216 swevent_hlist_put_cpu(cpu
);
10219 static int swevent_hlist_get_cpu(int cpu
)
10221 struct swevent_htable
*swhash
= &per_cpu(swevent_htable
, cpu
);
10224 mutex_lock(&swhash
->hlist_mutex
);
10225 if (!swevent_hlist_deref(swhash
) &&
10226 cpumask_test_cpu(cpu
, perf_online_mask
)) {
10227 struct swevent_hlist
*hlist
;
10229 hlist
= kzalloc(sizeof(*hlist
), GFP_KERNEL
);
10234 rcu_assign_pointer(swhash
->swevent_hlist
, hlist
);
10236 swhash
->hlist_refcount
++;
10238 mutex_unlock(&swhash
->hlist_mutex
);
10243 static int swevent_hlist_get(void)
10245 int err
, cpu
, failed_cpu
;
10247 mutex_lock(&pmus_lock
);
10248 for_each_possible_cpu(cpu
) {
10249 err
= swevent_hlist_get_cpu(cpu
);
10255 mutex_unlock(&pmus_lock
);
10258 for_each_possible_cpu(cpu
) {
10259 if (cpu
== failed_cpu
)
10261 swevent_hlist_put_cpu(cpu
);
10263 mutex_unlock(&pmus_lock
);
10267 struct static_key perf_swevent_enabled
[PERF_COUNT_SW_MAX
];
10269 static void sw_perf_event_destroy(struct perf_event
*event
)
10271 u64 event_id
= event
->attr
.config
;
10273 WARN_ON(event
->parent
);
10275 static_key_slow_dec(&perf_swevent_enabled
[event_id
]);
10276 swevent_hlist_put();
10279 static struct pmu perf_cpu_clock
; /* fwd declaration */
10280 static struct pmu perf_task_clock
;
10282 static int perf_swevent_init(struct perf_event
*event
)
10284 u64 event_id
= event
->attr
.config
;
10286 if (event
->attr
.type
!= PERF_TYPE_SOFTWARE
)
10290 * no branch sampling for software events
10292 if (has_branch_stack(event
))
10293 return -EOPNOTSUPP
;
10295 switch (event_id
) {
10296 case PERF_COUNT_SW_CPU_CLOCK
:
10297 event
->attr
.type
= perf_cpu_clock
.type
;
10299 case PERF_COUNT_SW_TASK_CLOCK
:
10300 event
->attr
.type
= perf_task_clock
.type
;
10307 if (event_id
>= PERF_COUNT_SW_MAX
)
10310 if (!event
->parent
) {
10313 err
= swevent_hlist_get();
10317 static_key_slow_inc(&perf_swevent_enabled
[event_id
]);
10318 event
->destroy
= sw_perf_event_destroy
;
10324 static struct pmu perf_swevent
= {
10325 .task_ctx_nr
= perf_sw_context
,
10327 .capabilities
= PERF_PMU_CAP_NO_NMI
,
10329 .event_init
= perf_swevent_init
,
10330 .add
= perf_swevent_add
,
10331 .del
= perf_swevent_del
,
10332 .start
= perf_swevent_start
,
10333 .stop
= perf_swevent_stop
,
10334 .read
= perf_swevent_read
,
10337 #ifdef CONFIG_EVENT_TRACING
10339 static void tp_perf_event_destroy(struct perf_event
*event
)
10341 perf_trace_destroy(event
);
10344 static int perf_tp_event_init(struct perf_event
*event
)
10348 if (event
->attr
.type
!= PERF_TYPE_TRACEPOINT
)
10352 * no branch sampling for tracepoint events
10354 if (has_branch_stack(event
))
10355 return -EOPNOTSUPP
;
10357 err
= perf_trace_init(event
);
10361 event
->destroy
= tp_perf_event_destroy
;
10366 static struct pmu perf_tracepoint
= {
10367 .task_ctx_nr
= perf_sw_context
,
10369 .event_init
= perf_tp_event_init
,
10370 .add
= perf_trace_add
,
10371 .del
= perf_trace_del
,
10372 .start
= perf_swevent_start
,
10373 .stop
= perf_swevent_stop
,
10374 .read
= perf_swevent_read
,
10377 static int perf_tp_filter_match(struct perf_event
*event
,
10378 struct perf_sample_data
*data
)
10380 void *record
= data
->raw
->frag
.data
;
10382 /* only top level events have filters set */
10384 event
= event
->parent
;
10386 if (likely(!event
->filter
) || filter_match_preds(event
->filter
, record
))
10391 static int perf_tp_event_match(struct perf_event
*event
,
10392 struct perf_sample_data
*data
,
10393 struct pt_regs
*regs
)
10395 if (event
->hw
.state
& PERF_HES_STOPPED
)
10398 * If exclude_kernel, only trace user-space tracepoints (uprobes)
10400 if (event
->attr
.exclude_kernel
&& !user_mode(regs
))
10403 if (!perf_tp_filter_match(event
, data
))
10409 void perf_trace_run_bpf_submit(void *raw_data
, int size
, int rctx
,
10410 struct trace_event_call
*call
, u64 count
,
10411 struct pt_regs
*regs
, struct hlist_head
*head
,
10412 struct task_struct
*task
)
10414 if (bpf_prog_array_valid(call
)) {
10415 *(struct pt_regs
**)raw_data
= regs
;
10416 if (!trace_call_bpf(call
, raw_data
) || hlist_empty(head
)) {
10417 perf_swevent_put_recursion_context(rctx
);
10421 perf_tp_event(call
->event
.type
, count
, raw_data
, size
, regs
, head
,
10424 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit
);
10426 static void __perf_tp_event_target_task(u64 count
, void *record
,
10427 struct pt_regs
*regs
,
10428 struct perf_sample_data
*data
,
10429 struct perf_event
*event
)
10431 struct trace_entry
*entry
= record
;
10433 if (event
->attr
.config
!= entry
->type
)
10435 /* Cannot deliver synchronous signal to other task. */
10436 if (event
->attr
.sigtrap
)
10438 if (perf_tp_event_match(event
, data
, regs
))
10439 perf_swevent_event(event
, count
, data
, regs
);
10442 static void perf_tp_event_target_task(u64 count
, void *record
,
10443 struct pt_regs
*regs
,
10444 struct perf_sample_data
*data
,
10445 struct perf_event_context
*ctx
)
10447 unsigned int cpu
= smp_processor_id();
10448 struct pmu
*pmu
= &perf_tracepoint
;
10449 struct perf_event
*event
, *sibling
;
10451 perf_event_groups_for_cpu_pmu(event
, &ctx
->pinned_groups
, cpu
, pmu
) {
10452 __perf_tp_event_target_task(count
, record
, regs
, data
, event
);
10453 for_each_sibling_event(sibling
, event
)
10454 __perf_tp_event_target_task(count
, record
, regs
, data
, sibling
);
10457 perf_event_groups_for_cpu_pmu(event
, &ctx
->flexible_groups
, cpu
, pmu
) {
10458 __perf_tp_event_target_task(count
, record
, regs
, data
, event
);
10459 for_each_sibling_event(sibling
, event
)
10460 __perf_tp_event_target_task(count
, record
, regs
, data
, sibling
);
10464 void perf_tp_event(u16 event_type
, u64 count
, void *record
, int entry_size
,
10465 struct pt_regs
*regs
, struct hlist_head
*head
, int rctx
,
10466 struct task_struct
*task
)
10468 struct perf_sample_data data
;
10469 struct perf_event
*event
;
10471 struct perf_raw_record raw
= {
10473 .size
= entry_size
,
10478 perf_sample_data_init(&data
, 0, 0);
10479 perf_sample_save_raw_data(&data
, &raw
);
10481 perf_trace_buf_update(record
, event_type
);
10483 hlist_for_each_entry_rcu(event
, head
, hlist_entry
) {
10484 if (perf_tp_event_match(event
, &data
, regs
)) {
10485 perf_swevent_event(event
, count
, &data
, regs
);
10488 * Here use the same on-stack perf_sample_data,
10489 * some members in data are event-specific and
10490 * need to be re-computed for different sweveents.
10491 * Re-initialize data->sample_flags safely to avoid
10492 * the problem that next event skips preparing data
10493 * because data->sample_flags is set.
10495 perf_sample_data_init(&data
, 0, 0);
10496 perf_sample_save_raw_data(&data
, &raw
);
10501 * If we got specified a target task, also iterate its context and
10502 * deliver this event there too.
10504 if (task
&& task
!= current
) {
10505 struct perf_event_context
*ctx
;
10508 ctx
= rcu_dereference(task
->perf_event_ctxp
);
10512 raw_spin_lock(&ctx
->lock
);
10513 perf_tp_event_target_task(count
, record
, regs
, &data
, ctx
);
10514 raw_spin_unlock(&ctx
->lock
);
10519 perf_swevent_put_recursion_context(rctx
);
10521 EXPORT_SYMBOL_GPL(perf_tp_event
);
10523 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
10525 * Flags in config, used by dynamic PMU kprobe and uprobe
10526 * The flags should match following PMU_FORMAT_ATTR().
10528 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
10529 * if not set, create kprobe/uprobe
10531 * The following values specify a reference counter (or semaphore in the
10532 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
10533 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
10535 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
10536 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
10538 enum perf_probe_config
{
10539 PERF_PROBE_CONFIG_IS_RETPROBE
= 1U << 0, /* [k,u]retprobe */
10540 PERF_UPROBE_REF_CTR_OFFSET_BITS
= 32,
10541 PERF_UPROBE_REF_CTR_OFFSET_SHIFT
= 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS
,
10544 PMU_FORMAT_ATTR(retprobe
, "config:0");
10547 #ifdef CONFIG_KPROBE_EVENTS
10548 static struct attribute
*kprobe_attrs
[] = {
10549 &format_attr_retprobe
.attr
,
10553 static struct attribute_group kprobe_format_group
= {
10555 .attrs
= kprobe_attrs
,
10558 static const struct attribute_group
*kprobe_attr_groups
[] = {
10559 &kprobe_format_group
,
10563 static int perf_kprobe_event_init(struct perf_event
*event
);
10564 static struct pmu perf_kprobe
= {
10565 .task_ctx_nr
= perf_sw_context
,
10566 .event_init
= perf_kprobe_event_init
,
10567 .add
= perf_trace_add
,
10568 .del
= perf_trace_del
,
10569 .start
= perf_swevent_start
,
10570 .stop
= perf_swevent_stop
,
10571 .read
= perf_swevent_read
,
10572 .attr_groups
= kprobe_attr_groups
,
10575 static int perf_kprobe_event_init(struct perf_event
*event
)
10580 if (event
->attr
.type
!= perf_kprobe
.type
)
10583 if (!perfmon_capable())
10587 * no branch sampling for probe events
10589 if (has_branch_stack(event
))
10590 return -EOPNOTSUPP
;
10592 is_retprobe
= event
->attr
.config
& PERF_PROBE_CONFIG_IS_RETPROBE
;
10593 err
= perf_kprobe_init(event
, is_retprobe
);
10597 event
->destroy
= perf_kprobe_destroy
;
10601 #endif /* CONFIG_KPROBE_EVENTS */
10603 #ifdef CONFIG_UPROBE_EVENTS
10604 PMU_FORMAT_ATTR(ref_ctr_offset
, "config:32-63");
10606 static struct attribute
*uprobe_attrs
[] = {
10607 &format_attr_retprobe
.attr
,
10608 &format_attr_ref_ctr_offset
.attr
,
10612 static struct attribute_group uprobe_format_group
= {
10614 .attrs
= uprobe_attrs
,
10617 static const struct attribute_group
*uprobe_attr_groups
[] = {
10618 &uprobe_format_group
,
10622 static int perf_uprobe_event_init(struct perf_event
*event
);
10623 static struct pmu perf_uprobe
= {
10624 .task_ctx_nr
= perf_sw_context
,
10625 .event_init
= perf_uprobe_event_init
,
10626 .add
= perf_trace_add
,
10627 .del
= perf_trace_del
,
10628 .start
= perf_swevent_start
,
10629 .stop
= perf_swevent_stop
,
10630 .read
= perf_swevent_read
,
10631 .attr_groups
= uprobe_attr_groups
,
10634 static int perf_uprobe_event_init(struct perf_event
*event
)
10637 unsigned long ref_ctr_offset
;
10640 if (event
->attr
.type
!= perf_uprobe
.type
)
10643 if (!perfmon_capable())
10647 * no branch sampling for probe events
10649 if (has_branch_stack(event
))
10650 return -EOPNOTSUPP
;
10652 is_retprobe
= event
->attr
.config
& PERF_PROBE_CONFIG_IS_RETPROBE
;
10653 ref_ctr_offset
= event
->attr
.config
>> PERF_UPROBE_REF_CTR_OFFSET_SHIFT
;
10654 err
= perf_uprobe_init(event
, ref_ctr_offset
, is_retprobe
);
10658 event
->destroy
= perf_uprobe_destroy
;
10662 #endif /* CONFIG_UPROBE_EVENTS */
10664 static inline void perf_tp_register(void)
10666 perf_pmu_register(&perf_tracepoint
, "tracepoint", PERF_TYPE_TRACEPOINT
);
10667 #ifdef CONFIG_KPROBE_EVENTS
10668 perf_pmu_register(&perf_kprobe
, "kprobe", -1);
10670 #ifdef CONFIG_UPROBE_EVENTS
10671 perf_pmu_register(&perf_uprobe
, "uprobe", -1);
10675 static void perf_event_free_filter(struct perf_event
*event
)
10677 ftrace_profile_free_filter(event
);
10681 * returns true if the event is a tracepoint, or a kprobe/upprobe created
10682 * with perf_event_open()
10684 static inline bool perf_event_is_tracing(struct perf_event
*event
)
10686 if (event
->pmu
== &perf_tracepoint
)
10688 #ifdef CONFIG_KPROBE_EVENTS
10689 if (event
->pmu
== &perf_kprobe
)
10692 #ifdef CONFIG_UPROBE_EVENTS
10693 if (event
->pmu
== &perf_uprobe
)
10699 int perf_event_set_bpf_prog(struct perf_event
*event
, struct bpf_prog
*prog
,
10702 bool is_kprobe
, is_uprobe
, is_tracepoint
, is_syscall_tp
;
10704 if (!perf_event_is_tracing(event
))
10705 return perf_event_set_bpf_handler(event
, prog
, bpf_cookie
);
10707 is_kprobe
= event
->tp_event
->flags
& TRACE_EVENT_FL_KPROBE
;
10708 is_uprobe
= event
->tp_event
->flags
& TRACE_EVENT_FL_UPROBE
;
10709 is_tracepoint
= event
->tp_event
->flags
& TRACE_EVENT_FL_TRACEPOINT
;
10710 is_syscall_tp
= is_syscall_trace_event(event
->tp_event
);
10711 if (!is_kprobe
&& !is_uprobe
&& !is_tracepoint
&& !is_syscall_tp
)
10712 /* bpf programs can only be attached to u/kprobe or tracepoint */
10715 if (((is_kprobe
|| is_uprobe
) && prog
->type
!= BPF_PROG_TYPE_KPROBE
) ||
10716 (is_tracepoint
&& prog
->type
!= BPF_PROG_TYPE_TRACEPOINT
) ||
10717 (is_syscall_tp
&& prog
->type
!= BPF_PROG_TYPE_TRACEPOINT
))
10720 if (prog
->type
== BPF_PROG_TYPE_KPROBE
&& prog
->sleepable
&& !is_uprobe
)
10721 /* only uprobe programs are allowed to be sleepable */
10724 /* Kprobe override only works for kprobes, not uprobes. */
10725 if (prog
->kprobe_override
&& !is_kprobe
)
10728 if (is_tracepoint
|| is_syscall_tp
) {
10729 int off
= trace_event_get_offsets(event
->tp_event
);
10731 if (prog
->aux
->max_ctx_offset
> off
)
10735 return perf_event_attach_bpf_prog(event
, prog
, bpf_cookie
);
10738 void perf_event_free_bpf_prog(struct perf_event
*event
)
10740 if (!perf_event_is_tracing(event
)) {
10741 perf_event_free_bpf_handler(event
);
10744 perf_event_detach_bpf_prog(event
);
10749 static inline void perf_tp_register(void)
10753 static void perf_event_free_filter(struct perf_event
*event
)
10757 int perf_event_set_bpf_prog(struct perf_event
*event
, struct bpf_prog
*prog
,
10763 void perf_event_free_bpf_prog(struct perf_event
*event
)
10766 #endif /* CONFIG_EVENT_TRACING */
10768 #ifdef CONFIG_HAVE_HW_BREAKPOINT
10769 void perf_bp_event(struct perf_event
*bp
, void *data
)
10771 struct perf_sample_data sample
;
10772 struct pt_regs
*regs
= data
;
10774 perf_sample_data_init(&sample
, bp
->attr
.bp_addr
, 0);
10776 if (!bp
->hw
.state
&& !perf_exclude_event(bp
, regs
))
10777 perf_swevent_event(bp
, 1, &sample
, regs
);
10782 * Allocate a new address filter
10784 static struct perf_addr_filter
*
10785 perf_addr_filter_new(struct perf_event
*event
, struct list_head
*filters
)
10787 int node
= cpu_to_node(event
->cpu
== -1 ? 0 : event
->cpu
);
10788 struct perf_addr_filter
*filter
;
10790 filter
= kzalloc_node(sizeof(*filter
), GFP_KERNEL
, node
);
10794 INIT_LIST_HEAD(&filter
->entry
);
10795 list_add_tail(&filter
->entry
, filters
);
10800 static void free_filters_list(struct list_head
*filters
)
10802 struct perf_addr_filter
*filter
, *iter
;
10804 list_for_each_entry_safe(filter
, iter
, filters
, entry
) {
10805 path_put(&filter
->path
);
10806 list_del(&filter
->entry
);
10812 * Free existing address filters and optionally install new ones
10814 static void perf_addr_filters_splice(struct perf_event
*event
,
10815 struct list_head
*head
)
10817 unsigned long flags
;
10820 if (!has_addr_filter(event
))
10823 /* don't bother with children, they don't have their own filters */
10827 raw_spin_lock_irqsave(&event
->addr_filters
.lock
, flags
);
10829 list_splice_init(&event
->addr_filters
.list
, &list
);
10831 list_splice(head
, &event
->addr_filters
.list
);
10833 raw_spin_unlock_irqrestore(&event
->addr_filters
.lock
, flags
);
10835 free_filters_list(&list
);
10839 * Scan through mm's vmas and see if one of them matches the
10840 * @filter; if so, adjust filter's address range.
10841 * Called with mm::mmap_lock down for reading.
10843 static void perf_addr_filter_apply(struct perf_addr_filter
*filter
,
10844 struct mm_struct
*mm
,
10845 struct perf_addr_filter_range
*fr
)
10847 struct vm_area_struct
*vma
;
10848 VMA_ITERATOR(vmi
, mm
, 0);
10850 for_each_vma(vmi
, vma
) {
10854 if (perf_addr_filter_vma_adjust(filter
, vma
, fr
))
10860 * Update event's address range filters based on the
10861 * task's existing mappings, if any.
10863 static void perf_event_addr_filters_apply(struct perf_event
*event
)
10865 struct perf_addr_filters_head
*ifh
= perf_event_addr_filters(event
);
10866 struct task_struct
*task
= READ_ONCE(event
->ctx
->task
);
10867 struct perf_addr_filter
*filter
;
10868 struct mm_struct
*mm
= NULL
;
10869 unsigned int count
= 0;
10870 unsigned long flags
;
10873 * We may observe TASK_TOMBSTONE, which means that the event tear-down
10874 * will stop on the parent's child_mutex that our caller is also holding
10876 if (task
== TASK_TOMBSTONE
)
10879 if (ifh
->nr_file_filters
) {
10880 mm
= get_task_mm(task
);
10884 mmap_read_lock(mm
);
10887 raw_spin_lock_irqsave(&ifh
->lock
, flags
);
10888 list_for_each_entry(filter
, &ifh
->list
, entry
) {
10889 if (filter
->path
.dentry
) {
10891 * Adjust base offset if the filter is associated to a
10892 * binary that needs to be mapped:
10894 event
->addr_filter_ranges
[count
].start
= 0;
10895 event
->addr_filter_ranges
[count
].size
= 0;
10897 perf_addr_filter_apply(filter
, mm
, &event
->addr_filter_ranges
[count
]);
10899 event
->addr_filter_ranges
[count
].start
= filter
->offset
;
10900 event
->addr_filter_ranges
[count
].size
= filter
->size
;
10906 event
->addr_filters_gen
++;
10907 raw_spin_unlock_irqrestore(&ifh
->lock
, flags
);
10909 if (ifh
->nr_file_filters
) {
10910 mmap_read_unlock(mm
);
10916 perf_event_stop(event
, 1);
10920 * Address range filtering: limiting the data to certain
10921 * instruction address ranges. Filters are ioctl()ed to us from
10922 * userspace as ascii strings.
10924 * Filter string format:
10926 * ACTION RANGE_SPEC
10927 * where ACTION is one of the
10928 * * "filter": limit the trace to this region
10929 * * "start": start tracing from this address
10930 * * "stop": stop tracing at this address/region;
10932 * * for kernel addresses: <start address>[/<size>]
10933 * * for object files: <start address>[/<size>]@</path/to/object/file>
10935 * if <size> is not specified or is zero, the range is treated as a single
10936 * address; not valid for ACTION=="filter".
10950 IF_STATE_ACTION
= 0,
10955 static const match_table_t if_tokens
= {
10956 { IF_ACT_FILTER
, "filter" },
10957 { IF_ACT_START
, "start" },
10958 { IF_ACT_STOP
, "stop" },
10959 { IF_SRC_FILE
, "%u/%u@%s" },
10960 { IF_SRC_KERNEL
, "%u/%u" },
10961 { IF_SRC_FILEADDR
, "%u@%s" },
10962 { IF_SRC_KERNELADDR
, "%u" },
10963 { IF_ACT_NONE
, NULL
},
10967 * Address filter string parser
10970 perf_event_parse_addr_filter(struct perf_event
*event
, char *fstr
,
10971 struct list_head
*filters
)
10973 struct perf_addr_filter
*filter
= NULL
;
10974 char *start
, *orig
, *filename
= NULL
;
10975 substring_t args
[MAX_OPT_ARGS
];
10976 int state
= IF_STATE_ACTION
, token
;
10977 unsigned int kernel
= 0;
10980 orig
= fstr
= kstrdup(fstr
, GFP_KERNEL
);
10984 while ((start
= strsep(&fstr
, " ,\n")) != NULL
) {
10985 static const enum perf_addr_filter_action_t actions
[] = {
10986 [IF_ACT_FILTER
] = PERF_ADDR_FILTER_ACTION_FILTER
,
10987 [IF_ACT_START
] = PERF_ADDR_FILTER_ACTION_START
,
10988 [IF_ACT_STOP
] = PERF_ADDR_FILTER_ACTION_STOP
,
10995 /* filter definition begins */
10996 if (state
== IF_STATE_ACTION
) {
10997 filter
= perf_addr_filter_new(event
, filters
);
11002 token
= match_token(start
, if_tokens
, args
);
11004 case IF_ACT_FILTER
:
11007 if (state
!= IF_STATE_ACTION
)
11010 filter
->action
= actions
[token
];
11011 state
= IF_STATE_SOURCE
;
11014 case IF_SRC_KERNELADDR
:
11015 case IF_SRC_KERNEL
:
11019 case IF_SRC_FILEADDR
:
11021 if (state
!= IF_STATE_SOURCE
)
11025 ret
= kstrtoul(args
[0].from
, 0, &filter
->offset
);
11029 if (token
== IF_SRC_KERNEL
|| token
== IF_SRC_FILE
) {
11031 ret
= kstrtoul(args
[1].from
, 0, &filter
->size
);
11036 if (token
== IF_SRC_FILE
|| token
== IF_SRC_FILEADDR
) {
11037 int fpos
= token
== IF_SRC_FILE
? 2 : 1;
11040 filename
= match_strdup(&args
[fpos
]);
11047 state
= IF_STATE_END
;
11055 * Filter definition is fully parsed, validate and install it.
11056 * Make sure that it doesn't contradict itself or the event's
11059 if (state
== IF_STATE_END
) {
11063 * ACTION "filter" must have a non-zero length region
11066 if (filter
->action
== PERF_ADDR_FILTER_ACTION_FILTER
&&
11075 * For now, we only support file-based filters
11076 * in per-task events; doing so for CPU-wide
11077 * events requires additional context switching
11078 * trickery, since same object code will be
11079 * mapped at different virtual addresses in
11080 * different processes.
11083 if (!event
->ctx
->task
)
11086 /* look up the path and grab its inode */
11087 ret
= kern_path(filename
, LOOKUP_FOLLOW
,
11093 if (!filter
->path
.dentry
||
11094 !S_ISREG(d_inode(filter
->path
.dentry
)
11098 event
->addr_filters
.nr_file_filters
++;
11101 /* ready to consume more filters */
11104 state
= IF_STATE_ACTION
;
11110 if (state
!= IF_STATE_ACTION
)
11120 free_filters_list(filters
);
11127 perf_event_set_addr_filter(struct perf_event
*event
, char *filter_str
)
11129 LIST_HEAD(filters
);
11133 * Since this is called in perf_ioctl() path, we're already holding
11136 lockdep_assert_held(&event
->ctx
->mutex
);
11138 if (WARN_ON_ONCE(event
->parent
))
11141 ret
= perf_event_parse_addr_filter(event
, filter_str
, &filters
);
11143 goto fail_clear_files
;
11145 ret
= event
->pmu
->addr_filters_validate(&filters
);
11147 goto fail_free_filters
;
11149 /* remove existing filters, if any */
11150 perf_addr_filters_splice(event
, &filters
);
11152 /* install new filters */
11153 perf_event_for_each_child(event
, perf_event_addr_filters_apply
);
11158 free_filters_list(&filters
);
11161 event
->addr_filters
.nr_file_filters
= 0;
11166 static int perf_event_set_filter(struct perf_event
*event
, void __user
*arg
)
11171 filter_str
= strndup_user(arg
, PAGE_SIZE
);
11172 if (IS_ERR(filter_str
))
11173 return PTR_ERR(filter_str
);
11175 #ifdef CONFIG_EVENT_TRACING
11176 if (perf_event_is_tracing(event
)) {
11177 struct perf_event_context
*ctx
= event
->ctx
;
11180 * Beware, here be dragons!!
11182 * the tracepoint muck will deadlock against ctx->mutex, but
11183 * the tracepoint stuff does not actually need it. So
11184 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
11185 * already have a reference on ctx.
11187 * This can result in event getting moved to a different ctx,
11188 * but that does not affect the tracepoint state.
11190 mutex_unlock(&ctx
->mutex
);
11191 ret
= ftrace_profile_set_filter(event
, event
->attr
.config
, filter_str
);
11192 mutex_lock(&ctx
->mutex
);
11195 if (has_addr_filter(event
))
11196 ret
= perf_event_set_addr_filter(event
, filter_str
);
11203 * hrtimer based swevent callback
11206 static enum hrtimer_restart
perf_swevent_hrtimer(struct hrtimer
*hrtimer
)
11208 enum hrtimer_restart ret
= HRTIMER_RESTART
;
11209 struct perf_sample_data data
;
11210 struct pt_regs
*regs
;
11211 struct perf_event
*event
;
11214 event
= container_of(hrtimer
, struct perf_event
, hw
.hrtimer
);
11216 if (event
->state
!= PERF_EVENT_STATE_ACTIVE
)
11217 return HRTIMER_NORESTART
;
11219 event
->pmu
->read(event
);
11221 perf_sample_data_init(&data
, 0, event
->hw
.last_period
);
11222 regs
= get_irq_regs();
11224 if (regs
&& !perf_exclude_event(event
, regs
)) {
11225 if (!(event
->attr
.exclude_idle
&& is_idle_task(current
)))
11226 if (__perf_event_overflow(event
, 1, &data
, regs
))
11227 ret
= HRTIMER_NORESTART
;
11230 period
= max_t(u64
, 10000, event
->hw
.sample_period
);
11231 hrtimer_forward_now(hrtimer
, ns_to_ktime(period
));
11236 static void perf_swevent_start_hrtimer(struct perf_event
*event
)
11238 struct hw_perf_event
*hwc
= &event
->hw
;
11241 if (!is_sampling_event(event
))
11244 period
= local64_read(&hwc
->period_left
);
11249 local64_set(&hwc
->period_left
, 0);
11251 period
= max_t(u64
, 10000, hwc
->sample_period
);
11253 hrtimer_start(&hwc
->hrtimer
, ns_to_ktime(period
),
11254 HRTIMER_MODE_REL_PINNED_HARD
);
11257 static void perf_swevent_cancel_hrtimer(struct perf_event
*event
)
11259 struct hw_perf_event
*hwc
= &event
->hw
;
11261 if (is_sampling_event(event
)) {
11262 ktime_t remaining
= hrtimer_get_remaining(&hwc
->hrtimer
);
11263 local64_set(&hwc
->period_left
, ktime_to_ns(remaining
));
11265 hrtimer_cancel(&hwc
->hrtimer
);
11269 static void perf_swevent_init_hrtimer(struct perf_event
*event
)
11271 struct hw_perf_event
*hwc
= &event
->hw
;
11273 if (!is_sampling_event(event
))
11276 hrtimer_init(&hwc
->hrtimer
, CLOCK_MONOTONIC
, HRTIMER_MODE_REL_HARD
);
11277 hwc
->hrtimer
.function
= perf_swevent_hrtimer
;
11280 * Since hrtimers have a fixed rate, we can do a static freq->period
11281 * mapping and avoid the whole period adjust feedback stuff.
11283 if (event
->attr
.freq
) {
11284 long freq
= event
->attr
.sample_freq
;
11286 event
->attr
.sample_period
= NSEC_PER_SEC
/ freq
;
11287 hwc
->sample_period
= event
->attr
.sample_period
;
11288 local64_set(&hwc
->period_left
, hwc
->sample_period
);
11289 hwc
->last_period
= hwc
->sample_period
;
11290 event
->attr
.freq
= 0;
11295 * Software event: cpu wall time clock
11298 static void cpu_clock_event_update(struct perf_event
*event
)
11303 now
= local_clock();
11304 prev
= local64_xchg(&event
->hw
.prev_count
, now
);
11305 local64_add(now
- prev
, &event
->count
);
11308 static void cpu_clock_event_start(struct perf_event
*event
, int flags
)
11310 local64_set(&event
->hw
.prev_count
, local_clock());
11311 perf_swevent_start_hrtimer(event
);
11314 static void cpu_clock_event_stop(struct perf_event
*event
, int flags
)
11316 perf_swevent_cancel_hrtimer(event
);
11317 cpu_clock_event_update(event
);
11320 static int cpu_clock_event_add(struct perf_event
*event
, int flags
)
11322 if (flags
& PERF_EF_START
)
11323 cpu_clock_event_start(event
, flags
);
11324 perf_event_update_userpage(event
);
11329 static void cpu_clock_event_del(struct perf_event
*event
, int flags
)
11331 cpu_clock_event_stop(event
, flags
);
11334 static void cpu_clock_event_read(struct perf_event
*event
)
11336 cpu_clock_event_update(event
);
11339 static int cpu_clock_event_init(struct perf_event
*event
)
11341 if (event
->attr
.type
!= perf_cpu_clock
.type
)
11344 if (event
->attr
.config
!= PERF_COUNT_SW_CPU_CLOCK
)
11348 * no branch sampling for software events
11350 if (has_branch_stack(event
))
11351 return -EOPNOTSUPP
;
11353 perf_swevent_init_hrtimer(event
);
11358 static struct pmu perf_cpu_clock
= {
11359 .task_ctx_nr
= perf_sw_context
,
11361 .capabilities
= PERF_PMU_CAP_NO_NMI
,
11362 .dev
= PMU_NULL_DEV
,
11364 .event_init
= cpu_clock_event_init
,
11365 .add
= cpu_clock_event_add
,
11366 .del
= cpu_clock_event_del
,
11367 .start
= cpu_clock_event_start
,
11368 .stop
= cpu_clock_event_stop
,
11369 .read
= cpu_clock_event_read
,
11373 * Software event: task time clock
11376 static void task_clock_event_update(struct perf_event
*event
, u64 now
)
11381 prev
= local64_xchg(&event
->hw
.prev_count
, now
);
11382 delta
= now
- prev
;
11383 local64_add(delta
, &event
->count
);
11386 static void task_clock_event_start(struct perf_event
*event
, int flags
)
11388 local64_set(&event
->hw
.prev_count
, event
->ctx
->time
);
11389 perf_swevent_start_hrtimer(event
);
11392 static void task_clock_event_stop(struct perf_event
*event
, int flags
)
11394 perf_swevent_cancel_hrtimer(event
);
11395 task_clock_event_update(event
, event
->ctx
->time
);
11398 static int task_clock_event_add(struct perf_event
*event
, int flags
)
11400 if (flags
& PERF_EF_START
)
11401 task_clock_event_start(event
, flags
);
11402 perf_event_update_userpage(event
);
11407 static void task_clock_event_del(struct perf_event
*event
, int flags
)
11409 task_clock_event_stop(event
, PERF_EF_UPDATE
);
11412 static void task_clock_event_read(struct perf_event
*event
)
11414 u64 now
= perf_clock();
11415 u64 delta
= now
- event
->ctx
->timestamp
;
11416 u64 time
= event
->ctx
->time
+ delta
;
11418 task_clock_event_update(event
, time
);
11421 static int task_clock_event_init(struct perf_event
*event
)
11423 if (event
->attr
.type
!= perf_task_clock
.type
)
11426 if (event
->attr
.config
!= PERF_COUNT_SW_TASK_CLOCK
)
11430 * no branch sampling for software events
11432 if (has_branch_stack(event
))
11433 return -EOPNOTSUPP
;
11435 perf_swevent_init_hrtimer(event
);
11440 static struct pmu perf_task_clock
= {
11441 .task_ctx_nr
= perf_sw_context
,
11443 .capabilities
= PERF_PMU_CAP_NO_NMI
,
11444 .dev
= PMU_NULL_DEV
,
11446 .event_init
= task_clock_event_init
,
11447 .add
= task_clock_event_add
,
11448 .del
= task_clock_event_del
,
11449 .start
= task_clock_event_start
,
11450 .stop
= task_clock_event_stop
,
11451 .read
= task_clock_event_read
,
11454 static void perf_pmu_nop_void(struct pmu
*pmu
)
11458 static void perf_pmu_nop_txn(struct pmu
*pmu
, unsigned int flags
)
11462 static int perf_pmu_nop_int(struct pmu
*pmu
)
11467 static int perf_event_nop_int(struct perf_event
*event
, u64 value
)
11472 static DEFINE_PER_CPU(unsigned int, nop_txn_flags
);
11474 static void perf_pmu_start_txn(struct pmu
*pmu
, unsigned int flags
)
11476 __this_cpu_write(nop_txn_flags
, flags
);
11478 if (flags
& ~PERF_PMU_TXN_ADD
)
11481 perf_pmu_disable(pmu
);
11484 static int perf_pmu_commit_txn(struct pmu
*pmu
)
11486 unsigned int flags
= __this_cpu_read(nop_txn_flags
);
11488 __this_cpu_write(nop_txn_flags
, 0);
11490 if (flags
& ~PERF_PMU_TXN_ADD
)
11493 perf_pmu_enable(pmu
);
11497 static void perf_pmu_cancel_txn(struct pmu
*pmu
)
11499 unsigned int flags
= __this_cpu_read(nop_txn_flags
);
11501 __this_cpu_write(nop_txn_flags
, 0);
11503 if (flags
& ~PERF_PMU_TXN_ADD
)
11506 perf_pmu_enable(pmu
);
11509 static int perf_event_idx_default(struct perf_event
*event
)
11514 static void free_pmu_context(struct pmu
*pmu
)
11516 free_percpu(pmu
->cpu_pmu_context
);
11520 * Let userspace know that this PMU supports address range filtering:
11522 static ssize_t
nr_addr_filters_show(struct device
*dev
,
11523 struct device_attribute
*attr
,
11526 struct pmu
*pmu
= dev_get_drvdata(dev
);
11528 return scnprintf(page
, PAGE_SIZE
- 1, "%d\n", pmu
->nr_addr_filters
);
11530 DEVICE_ATTR_RO(nr_addr_filters
);
11532 static struct idr pmu_idr
;
11535 type_show(struct device
*dev
, struct device_attribute
*attr
, char *page
)
11537 struct pmu
*pmu
= dev_get_drvdata(dev
);
11539 return scnprintf(page
, PAGE_SIZE
- 1, "%d\n", pmu
->type
);
11541 static DEVICE_ATTR_RO(type
);
11544 perf_event_mux_interval_ms_show(struct device
*dev
,
11545 struct device_attribute
*attr
,
11548 struct pmu
*pmu
= dev_get_drvdata(dev
);
11550 return scnprintf(page
, PAGE_SIZE
- 1, "%d\n", pmu
->hrtimer_interval_ms
);
11553 static DEFINE_MUTEX(mux_interval_mutex
);
11556 perf_event_mux_interval_ms_store(struct device
*dev
,
11557 struct device_attribute
*attr
,
11558 const char *buf
, size_t count
)
11560 struct pmu
*pmu
= dev_get_drvdata(dev
);
11561 int timer
, cpu
, ret
;
11563 ret
= kstrtoint(buf
, 0, &timer
);
11570 /* same value, noting to do */
11571 if (timer
== pmu
->hrtimer_interval_ms
)
11574 mutex_lock(&mux_interval_mutex
);
11575 pmu
->hrtimer_interval_ms
= timer
;
11577 /* update all cpuctx for this PMU */
11579 for_each_online_cpu(cpu
) {
11580 struct perf_cpu_pmu_context
*cpc
;
11581 cpc
= per_cpu_ptr(pmu
->cpu_pmu_context
, cpu
);
11582 cpc
->hrtimer_interval
= ns_to_ktime(NSEC_PER_MSEC
* timer
);
11584 cpu_function_call(cpu
, perf_mux_hrtimer_restart_ipi
, cpc
);
11586 cpus_read_unlock();
11587 mutex_unlock(&mux_interval_mutex
);
11591 static DEVICE_ATTR_RW(perf_event_mux_interval_ms
);
11593 static inline const struct cpumask
*perf_scope_cpu_topology_cpumask(unsigned int scope
, int cpu
)
11596 case PERF_PMU_SCOPE_CORE
:
11597 return topology_sibling_cpumask(cpu
);
11598 case PERF_PMU_SCOPE_DIE
:
11599 return topology_die_cpumask(cpu
);
11600 case PERF_PMU_SCOPE_CLUSTER
:
11601 return topology_cluster_cpumask(cpu
);
11602 case PERF_PMU_SCOPE_PKG
:
11603 return topology_core_cpumask(cpu
);
11604 case PERF_PMU_SCOPE_SYS_WIDE
:
11605 return cpu_online_mask
;
11611 static inline struct cpumask
*perf_scope_cpumask(unsigned int scope
)
11614 case PERF_PMU_SCOPE_CORE
:
11615 return perf_online_core_mask
;
11616 case PERF_PMU_SCOPE_DIE
:
11617 return perf_online_die_mask
;
11618 case PERF_PMU_SCOPE_CLUSTER
:
11619 return perf_online_cluster_mask
;
11620 case PERF_PMU_SCOPE_PKG
:
11621 return perf_online_pkg_mask
;
11622 case PERF_PMU_SCOPE_SYS_WIDE
:
11623 return perf_online_sys_mask
;
11629 static ssize_t
cpumask_show(struct device
*dev
, struct device_attribute
*attr
,
11632 struct pmu
*pmu
= dev_get_drvdata(dev
);
11633 struct cpumask
*mask
= perf_scope_cpumask(pmu
->scope
);
11636 return cpumap_print_to_pagebuf(true, buf
, mask
);
11640 static DEVICE_ATTR_RO(cpumask
);
11642 static struct attribute
*pmu_dev_attrs
[] = {
11643 &dev_attr_type
.attr
,
11644 &dev_attr_perf_event_mux_interval_ms
.attr
,
11645 &dev_attr_nr_addr_filters
.attr
,
11646 &dev_attr_cpumask
.attr
,
11650 static umode_t
pmu_dev_is_visible(struct kobject
*kobj
, struct attribute
*a
, int n
)
11652 struct device
*dev
= kobj_to_dev(kobj
);
11653 struct pmu
*pmu
= dev_get_drvdata(dev
);
11655 if (n
== 2 && !pmu
->nr_addr_filters
)
11659 if (n
== 3 && pmu
->scope
== PERF_PMU_SCOPE_NONE
)
11665 static struct attribute_group pmu_dev_attr_group
= {
11666 .is_visible
= pmu_dev_is_visible
,
11667 .attrs
= pmu_dev_attrs
,
11670 static const struct attribute_group
*pmu_dev_groups
[] = {
11671 &pmu_dev_attr_group
,
11675 static int pmu_bus_running
;
11676 static struct bus_type pmu_bus
= {
11677 .name
= "event_source",
11678 .dev_groups
= pmu_dev_groups
,
11681 static void pmu_dev_release(struct device
*dev
)
11686 static int pmu_dev_alloc(struct pmu
*pmu
)
11690 pmu
->dev
= kzalloc(sizeof(struct device
), GFP_KERNEL
);
11694 pmu
->dev
->groups
= pmu
->attr_groups
;
11695 device_initialize(pmu
->dev
);
11697 dev_set_drvdata(pmu
->dev
, pmu
);
11698 pmu
->dev
->bus
= &pmu_bus
;
11699 pmu
->dev
->parent
= pmu
->parent
;
11700 pmu
->dev
->release
= pmu_dev_release
;
11702 ret
= dev_set_name(pmu
->dev
, "%s", pmu
->name
);
11706 ret
= device_add(pmu
->dev
);
11710 if (pmu
->attr_update
) {
11711 ret
= sysfs_update_groups(&pmu
->dev
->kobj
, pmu
->attr_update
);
11720 device_del(pmu
->dev
);
11723 put_device(pmu
->dev
);
11727 static struct lock_class_key cpuctx_mutex
;
11728 static struct lock_class_key cpuctx_lock
;
11730 int perf_pmu_register(struct pmu
*pmu
, const char *name
, int type
)
11732 int cpu
, ret
, max
= PERF_TYPE_MAX
;
11734 mutex_lock(&pmus_lock
);
11736 pmu
->pmu_disable_count
= alloc_percpu(int);
11737 if (!pmu
->pmu_disable_count
)
11741 if (WARN_ONCE(!name
, "Can not register anonymous pmu.\n")) {
11746 if (WARN_ONCE(pmu
->scope
>= PERF_PMU_MAX_SCOPE
, "Can not register a pmu with an invalid scope.\n")) {
11756 ret
= idr_alloc(&pmu_idr
, pmu
, max
, 0, GFP_KERNEL
);
11760 WARN_ON(type
>= 0 && ret
!= type
);
11765 if (pmu_bus_running
&& !pmu
->dev
) {
11766 ret
= pmu_dev_alloc(pmu
);
11772 pmu
->cpu_pmu_context
= alloc_percpu(struct perf_cpu_pmu_context
);
11773 if (!pmu
->cpu_pmu_context
)
11776 for_each_possible_cpu(cpu
) {
11777 struct perf_cpu_pmu_context
*cpc
;
11779 cpc
= per_cpu_ptr(pmu
->cpu_pmu_context
, cpu
);
11780 __perf_init_event_pmu_context(&cpc
->epc
, pmu
);
11781 __perf_mux_hrtimer_init(cpc
, cpu
);
11784 if (!pmu
->start_txn
) {
11785 if (pmu
->pmu_enable
) {
11787 * If we have pmu_enable/pmu_disable calls, install
11788 * transaction stubs that use that to try and batch
11789 * hardware accesses.
11791 pmu
->start_txn
= perf_pmu_start_txn
;
11792 pmu
->commit_txn
= perf_pmu_commit_txn
;
11793 pmu
->cancel_txn
= perf_pmu_cancel_txn
;
11795 pmu
->start_txn
= perf_pmu_nop_txn
;
11796 pmu
->commit_txn
= perf_pmu_nop_int
;
11797 pmu
->cancel_txn
= perf_pmu_nop_void
;
11801 if (!pmu
->pmu_enable
) {
11802 pmu
->pmu_enable
= perf_pmu_nop_void
;
11803 pmu
->pmu_disable
= perf_pmu_nop_void
;
11806 if (!pmu
->check_period
)
11807 pmu
->check_period
= perf_event_nop_int
;
11809 if (!pmu
->event_idx
)
11810 pmu
->event_idx
= perf_event_idx_default
;
11812 list_add_rcu(&pmu
->entry
, &pmus
);
11813 atomic_set(&pmu
->exclusive_cnt
, 0);
11816 mutex_unlock(&pmus_lock
);
11821 if (pmu
->dev
&& pmu
->dev
!= PMU_NULL_DEV
) {
11822 device_del(pmu
->dev
);
11823 put_device(pmu
->dev
);
11827 idr_remove(&pmu_idr
, pmu
->type
);
11830 free_percpu(pmu
->pmu_disable_count
);
11833 EXPORT_SYMBOL_GPL(perf_pmu_register
);
11835 void perf_pmu_unregister(struct pmu
*pmu
)
11837 mutex_lock(&pmus_lock
);
11838 list_del_rcu(&pmu
->entry
);
11841 * We dereference the pmu list under both SRCU and regular RCU, so
11842 * synchronize against both of those.
11844 synchronize_srcu(&pmus_srcu
);
11847 free_percpu(pmu
->pmu_disable_count
);
11848 idr_remove(&pmu_idr
, pmu
->type
);
11849 if (pmu_bus_running
&& pmu
->dev
&& pmu
->dev
!= PMU_NULL_DEV
) {
11850 if (pmu
->nr_addr_filters
)
11851 device_remove_file(pmu
->dev
, &dev_attr_nr_addr_filters
);
11852 device_del(pmu
->dev
);
11853 put_device(pmu
->dev
);
11855 free_pmu_context(pmu
);
11856 mutex_unlock(&pmus_lock
);
11858 EXPORT_SYMBOL_GPL(perf_pmu_unregister
);
11860 static inline bool has_extended_regs(struct perf_event
*event
)
11862 return (event
->attr
.sample_regs_user
& PERF_REG_EXTENDED_MASK
) ||
11863 (event
->attr
.sample_regs_intr
& PERF_REG_EXTENDED_MASK
);
11866 static int perf_try_init_event(struct pmu
*pmu
, struct perf_event
*event
)
11868 struct perf_event_context
*ctx
= NULL
;
11871 if (!try_module_get(pmu
->module
))
11875 * A number of pmu->event_init() methods iterate the sibling_list to,
11876 * for example, validate if the group fits on the PMU. Therefore,
11877 * if this is a sibling event, acquire the ctx->mutex to protect
11878 * the sibling_list.
11880 if (event
->group_leader
!= event
&& pmu
->task_ctx_nr
!= perf_sw_context
) {
11882 * This ctx->mutex can nest when we're called through
11883 * inheritance. See the perf_event_ctx_lock_nested() comment.
11885 ctx
= perf_event_ctx_lock_nested(event
->group_leader
,
11886 SINGLE_DEPTH_NESTING
);
11891 ret
= pmu
->event_init(event
);
11894 perf_event_ctx_unlock(event
->group_leader
, ctx
);
11897 if (!(pmu
->capabilities
& PERF_PMU_CAP_EXTENDED_REGS
) &&
11898 has_extended_regs(event
))
11901 if (pmu
->capabilities
& PERF_PMU_CAP_NO_EXCLUDE
&&
11902 event_has_any_exclude_flag(event
))
11905 if (pmu
->scope
!= PERF_PMU_SCOPE_NONE
&& event
->cpu
>= 0) {
11906 const struct cpumask
*cpumask
= perf_scope_cpu_topology_cpumask(pmu
->scope
, event
->cpu
);
11907 struct cpumask
*pmu_cpumask
= perf_scope_cpumask(pmu
->scope
);
11910 if (pmu_cpumask
&& cpumask
) {
11911 cpu
= cpumask_any_and(pmu_cpumask
, cpumask
);
11912 if (cpu
>= nr_cpu_ids
)
11915 event
->event_caps
|= PERF_EV_CAP_READ_SCOPE
;
11921 if (ret
&& event
->destroy
)
11922 event
->destroy(event
);
11926 module_put(pmu
->module
);
11931 static struct pmu
*perf_init_event(struct perf_event
*event
)
11933 bool extended_type
= false;
11934 int idx
, type
, ret
;
11937 idx
= srcu_read_lock(&pmus_srcu
);
11940 * Save original type before calling pmu->event_init() since certain
11941 * pmus overwrites event->attr.type to forward event to another pmu.
11943 event
->orig_type
= event
->attr
.type
;
11945 /* Try parent's PMU first: */
11946 if (event
->parent
&& event
->parent
->pmu
) {
11947 pmu
= event
->parent
->pmu
;
11948 ret
= perf_try_init_event(pmu
, event
);
11954 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
11955 * are often aliases for PERF_TYPE_RAW.
11957 type
= event
->attr
.type
;
11958 if (type
== PERF_TYPE_HARDWARE
|| type
== PERF_TYPE_HW_CACHE
) {
11959 type
= event
->attr
.config
>> PERF_PMU_TYPE_SHIFT
;
11961 type
= PERF_TYPE_RAW
;
11963 extended_type
= true;
11964 event
->attr
.config
&= PERF_HW_EVENT_MASK
;
11970 pmu
= idr_find(&pmu_idr
, type
);
11973 if (event
->attr
.type
!= type
&& type
!= PERF_TYPE_RAW
&&
11974 !(pmu
->capabilities
& PERF_PMU_CAP_EXTENDED_HW_TYPE
))
11977 ret
= perf_try_init_event(pmu
, event
);
11978 if (ret
== -ENOENT
&& event
->attr
.type
!= type
&& !extended_type
) {
11979 type
= event
->attr
.type
;
11984 pmu
= ERR_PTR(ret
);
11989 list_for_each_entry_rcu(pmu
, &pmus
, entry
, lockdep_is_held(&pmus_srcu
)) {
11990 ret
= perf_try_init_event(pmu
, event
);
11994 if (ret
!= -ENOENT
) {
11995 pmu
= ERR_PTR(ret
);
12000 pmu
= ERR_PTR(-ENOENT
);
12002 srcu_read_unlock(&pmus_srcu
, idx
);
12007 static void attach_sb_event(struct perf_event
*event
)
12009 struct pmu_event_list
*pel
= per_cpu_ptr(&pmu_sb_events
, event
->cpu
);
12011 raw_spin_lock(&pel
->lock
);
12012 list_add_rcu(&event
->sb_list
, &pel
->list
);
12013 raw_spin_unlock(&pel
->lock
);
12017 * We keep a list of all !task (and therefore per-cpu) events
12018 * that need to receive side-band records.
12020 * This avoids having to scan all the various PMU per-cpu contexts
12021 * looking for them.
12023 static void account_pmu_sb_event(struct perf_event
*event
)
12025 if (is_sb_event(event
))
12026 attach_sb_event(event
);
12029 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
12030 static void account_freq_event_nohz(void)
12032 #ifdef CONFIG_NO_HZ_FULL
12033 /* Lock so we don't race with concurrent unaccount */
12034 spin_lock(&nr_freq_lock
);
12035 if (atomic_inc_return(&nr_freq_events
) == 1)
12036 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS
);
12037 spin_unlock(&nr_freq_lock
);
12041 static void account_freq_event(void)
12043 if (tick_nohz_full_enabled())
12044 account_freq_event_nohz();
12046 atomic_inc(&nr_freq_events
);
12050 static void account_event(struct perf_event
*event
)
12057 if (event
->attach_state
& (PERF_ATTACH_TASK
| PERF_ATTACH_SCHED_CB
))
12059 if (event
->attr
.mmap
|| event
->attr
.mmap_data
)
12060 atomic_inc(&nr_mmap_events
);
12061 if (event
->attr
.build_id
)
12062 atomic_inc(&nr_build_id_events
);
12063 if (event
->attr
.comm
)
12064 atomic_inc(&nr_comm_events
);
12065 if (event
->attr
.namespaces
)
12066 atomic_inc(&nr_namespaces_events
);
12067 if (event
->attr
.cgroup
)
12068 atomic_inc(&nr_cgroup_events
);
12069 if (event
->attr
.task
)
12070 atomic_inc(&nr_task_events
);
12071 if (event
->attr
.freq
)
12072 account_freq_event();
12073 if (event
->attr
.context_switch
) {
12074 atomic_inc(&nr_switch_events
);
12077 if (has_branch_stack(event
))
12079 if (is_cgroup_event(event
))
12081 if (event
->attr
.ksymbol
)
12082 atomic_inc(&nr_ksymbol_events
);
12083 if (event
->attr
.bpf_event
)
12084 atomic_inc(&nr_bpf_events
);
12085 if (event
->attr
.text_poke
)
12086 atomic_inc(&nr_text_poke_events
);
12090 * We need the mutex here because static_branch_enable()
12091 * must complete *before* the perf_sched_count increment
12094 if (atomic_inc_not_zero(&perf_sched_count
))
12097 mutex_lock(&perf_sched_mutex
);
12098 if (!atomic_read(&perf_sched_count
)) {
12099 static_branch_enable(&perf_sched_events
);
12101 * Guarantee that all CPUs observe they key change and
12102 * call the perf scheduling hooks before proceeding to
12103 * install events that need them.
12108 * Now that we have waited for the sync_sched(), allow further
12109 * increments to by-pass the mutex.
12111 atomic_inc(&perf_sched_count
);
12112 mutex_unlock(&perf_sched_mutex
);
12116 account_pmu_sb_event(event
);
12120 * Allocate and initialize an event structure
12122 static struct perf_event
*
12123 perf_event_alloc(struct perf_event_attr
*attr
, int cpu
,
12124 struct task_struct
*task
,
12125 struct perf_event
*group_leader
,
12126 struct perf_event
*parent_event
,
12127 perf_overflow_handler_t overflow_handler
,
12128 void *context
, int cgroup_fd
)
12131 struct perf_event
*event
;
12132 struct hw_perf_event
*hwc
;
12133 long err
= -EINVAL
;
12136 if ((unsigned)cpu
>= nr_cpu_ids
) {
12137 if (!task
|| cpu
!= -1)
12138 return ERR_PTR(-EINVAL
);
12140 if (attr
->sigtrap
&& !task
) {
12141 /* Requires a task: avoid signalling random tasks. */
12142 return ERR_PTR(-EINVAL
);
12145 node
= (cpu
>= 0) ? cpu_to_node(cpu
) : -1;
12146 event
= kmem_cache_alloc_node(perf_event_cache
, GFP_KERNEL
| __GFP_ZERO
,
12149 return ERR_PTR(-ENOMEM
);
12152 * Single events are their own group leaders, with an
12153 * empty sibling list:
12156 group_leader
= event
;
12158 mutex_init(&event
->child_mutex
);
12159 INIT_LIST_HEAD(&event
->child_list
);
12161 INIT_LIST_HEAD(&event
->event_entry
);
12162 INIT_LIST_HEAD(&event
->sibling_list
);
12163 INIT_LIST_HEAD(&event
->active_list
);
12164 init_event_group(event
);
12165 INIT_LIST_HEAD(&event
->rb_entry
);
12166 INIT_LIST_HEAD(&event
->active_entry
);
12167 INIT_LIST_HEAD(&event
->addr_filters
.list
);
12168 INIT_HLIST_NODE(&event
->hlist_entry
);
12171 init_waitqueue_head(&event
->waitq
);
12172 init_irq_work(&event
->pending_irq
, perf_pending_irq
);
12173 event
->pending_disable_irq
= IRQ_WORK_INIT_HARD(perf_pending_disable
);
12174 init_task_work(&event
->pending_task
, perf_pending_task
);
12175 rcuwait_init(&event
->pending_work_wait
);
12177 mutex_init(&event
->mmap_mutex
);
12178 raw_spin_lock_init(&event
->addr_filters
.lock
);
12180 atomic_long_set(&event
->refcount
, 1);
12182 event
->attr
= *attr
;
12183 event
->group_leader
= group_leader
;
12187 event
->parent
= parent_event
;
12189 event
->ns
= get_pid_ns(task_active_pid_ns(current
));
12190 event
->id
= atomic64_inc_return(&perf_event_id
);
12192 event
->state
= PERF_EVENT_STATE_INACTIVE
;
12195 event
->event_caps
= parent_event
->event_caps
;
12198 event
->attach_state
= PERF_ATTACH_TASK
;
12200 * XXX pmu::event_init needs to know what task to account to
12201 * and we cannot use the ctx information because we need the
12202 * pmu before we get a ctx.
12204 event
->hw
.target
= get_task_struct(task
);
12207 event
->clock
= &local_clock
;
12209 event
->clock
= parent_event
->clock
;
12211 if (!overflow_handler
&& parent_event
) {
12212 overflow_handler
= parent_event
->overflow_handler
;
12213 context
= parent_event
->overflow_handler_context
;
12214 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
12215 if (parent_event
->prog
) {
12216 struct bpf_prog
*prog
= parent_event
->prog
;
12218 bpf_prog_inc(prog
);
12219 event
->prog
= prog
;
12224 if (overflow_handler
) {
12225 event
->overflow_handler
= overflow_handler
;
12226 event
->overflow_handler_context
= context
;
12227 } else if (is_write_backward(event
)){
12228 event
->overflow_handler
= perf_event_output_backward
;
12229 event
->overflow_handler_context
= NULL
;
12231 event
->overflow_handler
= perf_event_output_forward
;
12232 event
->overflow_handler_context
= NULL
;
12235 perf_event__state_init(event
);
12240 hwc
->sample_period
= attr
->sample_period
;
12241 if (attr
->freq
&& attr
->sample_freq
)
12242 hwc
->sample_period
= 1;
12243 hwc
->last_period
= hwc
->sample_period
;
12245 local64_set(&hwc
->period_left
, hwc
->sample_period
);
12248 * We do not support PERF_SAMPLE_READ on inherited events unless
12249 * PERF_SAMPLE_TID is also selected, which allows inherited events to
12250 * collect per-thread samples.
12251 * See perf_output_read().
12253 if (has_inherit_and_sample_read(attr
) && !(attr
->sample_type
& PERF_SAMPLE_TID
))
12256 if (!has_branch_stack(event
))
12257 event
->attr
.branch_sample_type
= 0;
12259 pmu
= perf_init_event(event
);
12261 err
= PTR_ERR(pmu
);
12266 * Disallow uncore-task events. Similarly, disallow uncore-cgroup
12267 * events (they don't make sense as the cgroup will be different
12268 * on other CPUs in the uncore mask).
12270 if (pmu
->task_ctx_nr
== perf_invalid_context
&& (task
|| cgroup_fd
!= -1)) {
12275 if (event
->attr
.aux_output
&&
12276 !(pmu
->capabilities
& PERF_PMU_CAP_AUX_OUTPUT
)) {
12281 if (cgroup_fd
!= -1) {
12282 err
= perf_cgroup_connect(cgroup_fd
, event
, attr
, group_leader
);
12287 err
= exclusive_event_init(event
);
12291 if (has_addr_filter(event
)) {
12292 event
->addr_filter_ranges
= kcalloc(pmu
->nr_addr_filters
,
12293 sizeof(struct perf_addr_filter_range
),
12295 if (!event
->addr_filter_ranges
) {
12301 * Clone the parent's vma offsets: they are valid until exec()
12302 * even if the mm is not shared with the parent.
12304 if (event
->parent
) {
12305 struct perf_addr_filters_head
*ifh
= perf_event_addr_filters(event
);
12307 raw_spin_lock_irq(&ifh
->lock
);
12308 memcpy(event
->addr_filter_ranges
,
12309 event
->parent
->addr_filter_ranges
,
12310 pmu
->nr_addr_filters
* sizeof(struct perf_addr_filter_range
));
12311 raw_spin_unlock_irq(&ifh
->lock
);
12314 /* force hw sync on the address filters */
12315 event
->addr_filters_gen
= 1;
12318 if (!event
->parent
) {
12319 if (event
->attr
.sample_type
& PERF_SAMPLE_CALLCHAIN
) {
12320 err
= get_callchain_buffers(attr
->sample_max_stack
);
12322 goto err_addr_filters
;
12326 err
= security_perf_event_alloc(event
);
12328 goto err_callchain_buffer
;
12330 /* symmetric to unaccount_event() in _free_event() */
12331 account_event(event
);
12335 err_callchain_buffer
:
12336 if (!event
->parent
) {
12337 if (event
->attr
.sample_type
& PERF_SAMPLE_CALLCHAIN
)
12338 put_callchain_buffers();
12341 kfree(event
->addr_filter_ranges
);
12344 exclusive_event_destroy(event
);
12347 if (is_cgroup_event(event
))
12348 perf_detach_cgroup(event
);
12349 if (event
->destroy
)
12350 event
->destroy(event
);
12351 module_put(pmu
->module
);
12353 if (event
->hw
.target
)
12354 put_task_struct(event
->hw
.target
);
12355 call_rcu(&event
->rcu_head
, free_event_rcu
);
12357 return ERR_PTR(err
);
12360 static int perf_copy_attr(struct perf_event_attr __user
*uattr
,
12361 struct perf_event_attr
*attr
)
12366 /* Zero the full structure, so that a short copy will be nice. */
12367 memset(attr
, 0, sizeof(*attr
));
12369 ret
= get_user(size
, &uattr
->size
);
12373 /* ABI compatibility quirk: */
12375 size
= PERF_ATTR_SIZE_VER0
;
12376 if (size
< PERF_ATTR_SIZE_VER0
|| size
> PAGE_SIZE
)
12379 ret
= copy_struct_from_user(attr
, sizeof(*attr
), uattr
, size
);
12388 if (attr
->__reserved_1
|| attr
->__reserved_2
|| attr
->__reserved_3
)
12391 if (attr
->sample_type
& ~(PERF_SAMPLE_MAX
-1))
12394 if (attr
->read_format
& ~(PERF_FORMAT_MAX
-1))
12397 if (attr
->sample_type
& PERF_SAMPLE_BRANCH_STACK
) {
12398 u64 mask
= attr
->branch_sample_type
;
12400 /* only using defined bits */
12401 if (mask
& ~(PERF_SAMPLE_BRANCH_MAX
-1))
12404 /* at least one branch bit must be set */
12405 if (!(mask
& ~PERF_SAMPLE_BRANCH_PLM_ALL
))
12408 /* propagate priv level, when not set for branch */
12409 if (!(mask
& PERF_SAMPLE_BRANCH_PLM_ALL
)) {
12411 /* exclude_kernel checked on syscall entry */
12412 if (!attr
->exclude_kernel
)
12413 mask
|= PERF_SAMPLE_BRANCH_KERNEL
;
12415 if (!attr
->exclude_user
)
12416 mask
|= PERF_SAMPLE_BRANCH_USER
;
12418 if (!attr
->exclude_hv
)
12419 mask
|= PERF_SAMPLE_BRANCH_HV
;
12421 * adjust user setting (for HW filter setup)
12423 attr
->branch_sample_type
= mask
;
12425 /* privileged levels capture (kernel, hv): check permissions */
12426 if (mask
& PERF_SAMPLE_BRANCH_PERM_PLM
) {
12427 ret
= perf_allow_kernel(attr
);
12433 if (attr
->sample_type
& PERF_SAMPLE_REGS_USER
) {
12434 ret
= perf_reg_validate(attr
->sample_regs_user
);
12439 if (attr
->sample_type
& PERF_SAMPLE_STACK_USER
) {
12440 if (!arch_perf_have_user_stack_dump())
12444 * We have __u32 type for the size, but so far
12445 * we can only use __u16 as maximum due to the
12446 * __u16 sample size limit.
12448 if (attr
->sample_stack_user
>= USHRT_MAX
)
12450 else if (!IS_ALIGNED(attr
->sample_stack_user
, sizeof(u64
)))
12454 if (!attr
->sample_max_stack
)
12455 attr
->sample_max_stack
= sysctl_perf_event_max_stack
;
12457 if (attr
->sample_type
& PERF_SAMPLE_REGS_INTR
)
12458 ret
= perf_reg_validate(attr
->sample_regs_intr
);
12460 #ifndef CONFIG_CGROUP_PERF
12461 if (attr
->sample_type
& PERF_SAMPLE_CGROUP
)
12464 if ((attr
->sample_type
& PERF_SAMPLE_WEIGHT
) &&
12465 (attr
->sample_type
& PERF_SAMPLE_WEIGHT_STRUCT
))
12468 if (!attr
->inherit
&& attr
->inherit_thread
)
12471 if (attr
->remove_on_exec
&& attr
->enable_on_exec
)
12474 if (attr
->sigtrap
&& !attr
->remove_on_exec
)
12481 put_user(sizeof(*attr
), &uattr
->size
);
12486 static void mutex_lock_double(struct mutex
*a
, struct mutex
*b
)
12492 mutex_lock_nested(b
, SINGLE_DEPTH_NESTING
);
12496 perf_event_set_output(struct perf_event
*event
, struct perf_event
*output_event
)
12498 struct perf_buffer
*rb
= NULL
;
12501 if (!output_event
) {
12502 mutex_lock(&event
->mmap_mutex
);
12506 /* don't allow circular references */
12507 if (event
== output_event
)
12511 * Don't allow cross-cpu buffers
12513 if (output_event
->cpu
!= event
->cpu
)
12517 * If its not a per-cpu rb, it must be the same task.
12519 if (output_event
->cpu
== -1 && output_event
->hw
.target
!= event
->hw
.target
)
12523 * Mixing clocks in the same buffer is trouble you don't need.
12525 if (output_event
->clock
!= event
->clock
)
12529 * Either writing ring buffer from beginning or from end.
12530 * Mixing is not allowed.
12532 if (is_write_backward(output_event
) != is_write_backward(event
))
12536 * If both events generate aux data, they must be on the same PMU
12538 if (has_aux(event
) && has_aux(output_event
) &&
12539 event
->pmu
!= output_event
->pmu
)
12543 * Hold both mmap_mutex to serialize against perf_mmap_close(). Since
12544 * output_event is already on rb->event_list, and the list iteration
12545 * restarts after every removal, it is guaranteed this new event is
12546 * observed *OR* if output_event is already removed, it's guaranteed we
12547 * observe !rb->mmap_count.
12549 mutex_lock_double(&event
->mmap_mutex
, &output_event
->mmap_mutex
);
12551 /* Can't redirect output if we've got an active mmap() */
12552 if (atomic_read(&event
->mmap_count
))
12555 if (output_event
) {
12556 /* get the rb we want to redirect to */
12557 rb
= ring_buffer_get(output_event
);
12561 /* did we race against perf_mmap_close() */
12562 if (!atomic_read(&rb
->mmap_count
)) {
12563 ring_buffer_put(rb
);
12568 ring_buffer_attach(event
, rb
);
12572 mutex_unlock(&event
->mmap_mutex
);
12574 mutex_unlock(&output_event
->mmap_mutex
);
12580 static int perf_event_set_clock(struct perf_event
*event
, clockid_t clk_id
)
12582 bool nmi_safe
= false;
12585 case CLOCK_MONOTONIC
:
12586 event
->clock
= &ktime_get_mono_fast_ns
;
12590 case CLOCK_MONOTONIC_RAW
:
12591 event
->clock
= &ktime_get_raw_fast_ns
;
12595 case CLOCK_REALTIME
:
12596 event
->clock
= &ktime_get_real_ns
;
12599 case CLOCK_BOOTTIME
:
12600 event
->clock
= &ktime_get_boottime_ns
;
12604 event
->clock
= &ktime_get_clocktai_ns
;
12611 if (!nmi_safe
&& !(event
->pmu
->capabilities
& PERF_PMU_CAP_NO_NMI
))
12618 perf_check_permission(struct perf_event_attr
*attr
, struct task_struct
*task
)
12620 unsigned int ptrace_mode
= PTRACE_MODE_READ_REALCREDS
;
12621 bool is_capable
= perfmon_capable();
12623 if (attr
->sigtrap
) {
12625 * perf_event_attr::sigtrap sends signals to the other task.
12626 * Require the current task to also have CAP_KILL.
12629 is_capable
&= ns_capable(__task_cred(task
)->user_ns
, CAP_KILL
);
12633 * If the required capabilities aren't available, checks for
12634 * ptrace permissions: upgrade to ATTACH, since sending signals
12635 * can effectively change the target task.
12637 ptrace_mode
= PTRACE_MODE_ATTACH_REALCREDS
;
12641 * Preserve ptrace permission check for backwards compatibility. The
12642 * ptrace check also includes checks that the current task and other
12643 * task have matching uids, and is therefore not done here explicitly.
12645 return is_capable
|| ptrace_may_access(task
, ptrace_mode
);
12649 * sys_perf_event_open - open a performance event, associate it to a task/cpu
12651 * @attr_uptr: event_id type attributes for monitoring/sampling
12654 * @group_fd: group leader event fd
12655 * @flags: perf event open flags
12657 SYSCALL_DEFINE5(perf_event_open
,
12658 struct perf_event_attr __user
*, attr_uptr
,
12659 pid_t
, pid
, int, cpu
, int, group_fd
, unsigned long, flags
)
12661 struct perf_event
*group_leader
= NULL
, *output_event
= NULL
;
12662 struct perf_event_pmu_context
*pmu_ctx
;
12663 struct perf_event
*event
, *sibling
;
12664 struct perf_event_attr attr
;
12665 struct perf_event_context
*ctx
;
12666 struct file
*event_file
= NULL
;
12667 struct fd group
= EMPTY_FD
;
12668 struct task_struct
*task
= NULL
;
12671 int move_group
= 0;
12673 int f_flags
= O_RDWR
;
12674 int cgroup_fd
= -1;
12676 /* for future expandability... */
12677 if (flags
& ~PERF_FLAG_ALL
)
12680 err
= perf_copy_attr(attr_uptr
, &attr
);
12684 /* Do we allow access to perf_event_open(2) ? */
12685 err
= security_perf_event_open(&attr
, PERF_SECURITY_OPEN
);
12689 if (!attr
.exclude_kernel
) {
12690 err
= perf_allow_kernel(&attr
);
12695 if (attr
.namespaces
) {
12696 if (!perfmon_capable())
12701 if (attr
.sample_freq
> sysctl_perf_event_sample_rate
)
12704 if (attr
.sample_period
& (1ULL << 63))
12708 /* Only privileged users can get physical addresses */
12709 if ((attr
.sample_type
& PERF_SAMPLE_PHYS_ADDR
)) {
12710 err
= perf_allow_kernel(&attr
);
12715 /* REGS_INTR can leak data, lockdown must prevent this */
12716 if (attr
.sample_type
& PERF_SAMPLE_REGS_INTR
) {
12717 err
= security_locked_down(LOCKDOWN_PERF
);
12723 * In cgroup mode, the pid argument is used to pass the fd
12724 * opened to the cgroup directory in cgroupfs. The cpu argument
12725 * designates the cpu on which to monitor threads from that
12728 if ((flags
& PERF_FLAG_PID_CGROUP
) && (pid
== -1 || cpu
== -1))
12731 if (flags
& PERF_FLAG_FD_CLOEXEC
)
12732 f_flags
|= O_CLOEXEC
;
12734 event_fd
= get_unused_fd_flags(f_flags
);
12738 if (group_fd
!= -1) {
12739 err
= perf_fget_light(group_fd
, &group
);
12742 group_leader
= fd_file(group
)->private_data
;
12743 if (flags
& PERF_FLAG_FD_OUTPUT
)
12744 output_event
= group_leader
;
12745 if (flags
& PERF_FLAG_FD_NO_GROUP
)
12746 group_leader
= NULL
;
12749 if (pid
!= -1 && !(flags
& PERF_FLAG_PID_CGROUP
)) {
12750 task
= find_lively_task_by_vpid(pid
);
12751 if (IS_ERR(task
)) {
12752 err
= PTR_ERR(task
);
12757 if (task
&& group_leader
&&
12758 group_leader
->attr
.inherit
!= attr
.inherit
) {
12763 if (flags
& PERF_FLAG_PID_CGROUP
)
12766 event
= perf_event_alloc(&attr
, cpu
, task
, group_leader
, NULL
,
12767 NULL
, NULL
, cgroup_fd
);
12768 if (IS_ERR(event
)) {
12769 err
= PTR_ERR(event
);
12773 if (is_sampling_event(event
)) {
12774 if (event
->pmu
->capabilities
& PERF_PMU_CAP_NO_INTERRUPT
) {
12781 * Special case software events and allow them to be part of
12782 * any hardware group.
12786 if (attr
.use_clockid
) {
12787 err
= perf_event_set_clock(event
, attr
.clockid
);
12792 if (pmu
->task_ctx_nr
== perf_sw_context
)
12793 event
->event_caps
|= PERF_EV_CAP_SOFTWARE
;
12796 err
= down_read_interruptible(&task
->signal
->exec_update_lock
);
12801 * We must hold exec_update_lock across this and any potential
12802 * perf_install_in_context() call for this new event to
12803 * serialize against exec() altering our credentials (and the
12804 * perf_event_exit_task() that could imply).
12807 if (!perf_check_permission(&attr
, task
))
12812 * Get the target context (task or percpu):
12814 ctx
= find_get_context(task
, event
);
12816 err
= PTR_ERR(ctx
);
12820 mutex_lock(&ctx
->mutex
);
12822 if (ctx
->task
== TASK_TOMBSTONE
) {
12829 * Check if the @cpu we're creating an event for is online.
12831 * We use the perf_cpu_context::ctx::mutex to serialize against
12832 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12834 struct perf_cpu_context
*cpuctx
= per_cpu_ptr(&perf_cpu_context
, event
->cpu
);
12836 if (!cpuctx
->online
) {
12842 if (group_leader
) {
12846 * Do not allow a recursive hierarchy (this new sibling
12847 * becoming part of another group-sibling):
12849 if (group_leader
->group_leader
!= group_leader
)
12852 /* All events in a group should have the same clock */
12853 if (group_leader
->clock
!= event
->clock
)
12857 * Make sure we're both events for the same CPU;
12858 * grouping events for different CPUs is broken; since
12859 * you can never concurrently schedule them anyhow.
12861 if (group_leader
->cpu
!= event
->cpu
)
12865 * Make sure we're both on the same context; either task or cpu.
12867 if (group_leader
->ctx
!= ctx
)
12871 * Only a group leader can be exclusive or pinned
12873 if (attr
.exclusive
|| attr
.pinned
)
12876 if (is_software_event(event
) &&
12877 !in_software_context(group_leader
)) {
12879 * If the event is a sw event, but the group_leader
12880 * is on hw context.
12882 * Allow the addition of software events to hw
12883 * groups, this is safe because software events
12884 * never fail to schedule.
12886 * Note the comment that goes with struct
12887 * perf_event_pmu_context.
12889 pmu
= group_leader
->pmu_ctx
->pmu
;
12890 } else if (!is_software_event(event
)) {
12891 if (is_software_event(group_leader
) &&
12892 (group_leader
->group_caps
& PERF_EV_CAP_SOFTWARE
)) {
12894 * In case the group is a pure software group, and we
12895 * try to add a hardware event, move the whole group to
12896 * the hardware context.
12901 /* Don't allow group of multiple hw events from different pmus */
12902 if (!in_software_context(group_leader
) &&
12903 group_leader
->pmu_ctx
->pmu
!= pmu
)
12909 * Now that we're certain of the pmu; find the pmu_ctx.
12911 pmu_ctx
= find_get_pmu_context(pmu
, ctx
, event
);
12912 if (IS_ERR(pmu_ctx
)) {
12913 err
= PTR_ERR(pmu_ctx
);
12916 event
->pmu_ctx
= pmu_ctx
;
12918 if (output_event
) {
12919 err
= perf_event_set_output(event
, output_event
);
12924 if (!perf_event_validate_size(event
)) {
12929 if (perf_need_aux_event(event
) && !perf_get_aux_event(event
, group_leader
)) {
12935 * Must be under the same ctx::mutex as perf_install_in_context(),
12936 * because we need to serialize with concurrent event creation.
12938 if (!exclusive_event_installable(event
, ctx
)) {
12943 WARN_ON_ONCE(ctx
->parent_ctx
);
12945 event_file
= anon_inode_getfile("[perf_event]", &perf_fops
, event
, f_flags
);
12946 if (IS_ERR(event_file
)) {
12947 err
= PTR_ERR(event_file
);
12953 * This is the point on no return; we cannot fail hereafter. This is
12954 * where we start modifying current state.
12958 perf_remove_from_context(group_leader
, 0);
12959 put_pmu_ctx(group_leader
->pmu_ctx
);
12961 for_each_sibling_event(sibling
, group_leader
) {
12962 perf_remove_from_context(sibling
, 0);
12963 put_pmu_ctx(sibling
->pmu_ctx
);
12967 * Install the group siblings before the group leader.
12969 * Because a group leader will try and install the entire group
12970 * (through the sibling list, which is still in-tact), we can
12971 * end up with siblings installed in the wrong context.
12973 * By installing siblings first we NO-OP because they're not
12974 * reachable through the group lists.
12976 for_each_sibling_event(sibling
, group_leader
) {
12977 sibling
->pmu_ctx
= pmu_ctx
;
12978 get_pmu_ctx(pmu_ctx
);
12979 perf_event__state_init(sibling
);
12980 perf_install_in_context(ctx
, sibling
, sibling
->cpu
);
12984 * Removing from the context ends up with disabled
12985 * event. What we want here is event in the initial
12986 * startup state, ready to be add into new context.
12988 group_leader
->pmu_ctx
= pmu_ctx
;
12989 get_pmu_ctx(pmu_ctx
);
12990 perf_event__state_init(group_leader
);
12991 perf_install_in_context(ctx
, group_leader
, group_leader
->cpu
);
12995 * Precalculate sample_data sizes; do while holding ctx::mutex such
12996 * that we're serialized against further additions and before
12997 * perf_install_in_context() which is the point the event is active and
12998 * can use these values.
13000 perf_event__header_size(event
);
13001 perf_event__id_header_size(event
);
13003 event
->owner
= current
;
13005 perf_install_in_context(ctx
, event
, event
->cpu
);
13006 perf_unpin_context(ctx
);
13008 mutex_unlock(&ctx
->mutex
);
13011 up_read(&task
->signal
->exec_update_lock
);
13012 put_task_struct(task
);
13015 mutex_lock(¤t
->perf_event_mutex
);
13016 list_add_tail(&event
->owner_entry
, ¤t
->perf_event_list
);
13017 mutex_unlock(¤t
->perf_event_mutex
);
13020 * Drop the reference on the group_event after placing the
13021 * new event on the sibling_list. This ensures destruction
13022 * of the group leader will find the pointer to itself in
13023 * perf_group_detach().
13026 fd_install(event_fd
, event_file
);
13030 put_pmu_ctx(event
->pmu_ctx
);
13031 event
->pmu_ctx
= NULL
; /* _free_event() */
13033 mutex_unlock(&ctx
->mutex
);
13034 perf_unpin_context(ctx
);
13038 up_read(&task
->signal
->exec_update_lock
);
13043 put_task_struct(task
);
13047 put_unused_fd(event_fd
);
13052 * perf_event_create_kernel_counter
13054 * @attr: attributes of the counter to create
13055 * @cpu: cpu in which the counter is bound
13056 * @task: task to profile (NULL for percpu)
13057 * @overflow_handler: callback to trigger when we hit the event
13058 * @context: context data could be used in overflow_handler callback
13060 struct perf_event
*
13061 perf_event_create_kernel_counter(struct perf_event_attr
*attr
, int cpu
,
13062 struct task_struct
*task
,
13063 perf_overflow_handler_t overflow_handler
,
13066 struct perf_event_pmu_context
*pmu_ctx
;
13067 struct perf_event_context
*ctx
;
13068 struct perf_event
*event
;
13073 * Grouping is not supported for kernel events, neither is 'AUX',
13074 * make sure the caller's intentions are adjusted.
13076 if (attr
->aux_output
)
13077 return ERR_PTR(-EINVAL
);
13079 event
= perf_event_alloc(attr
, cpu
, task
, NULL
, NULL
,
13080 overflow_handler
, context
, -1);
13081 if (IS_ERR(event
)) {
13082 err
= PTR_ERR(event
);
13086 /* Mark owner so we could distinguish it from user events. */
13087 event
->owner
= TASK_TOMBSTONE
;
13090 if (pmu
->task_ctx_nr
== perf_sw_context
)
13091 event
->event_caps
|= PERF_EV_CAP_SOFTWARE
;
13094 * Get the target context (task or percpu):
13096 ctx
= find_get_context(task
, event
);
13098 err
= PTR_ERR(ctx
);
13102 WARN_ON_ONCE(ctx
->parent_ctx
);
13103 mutex_lock(&ctx
->mutex
);
13104 if (ctx
->task
== TASK_TOMBSTONE
) {
13109 pmu_ctx
= find_get_pmu_context(pmu
, ctx
, event
);
13110 if (IS_ERR(pmu_ctx
)) {
13111 err
= PTR_ERR(pmu_ctx
);
13114 event
->pmu_ctx
= pmu_ctx
;
13118 * Check if the @cpu we're creating an event for is online.
13120 * We use the perf_cpu_context::ctx::mutex to serialize against
13121 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
13123 struct perf_cpu_context
*cpuctx
=
13124 container_of(ctx
, struct perf_cpu_context
, ctx
);
13125 if (!cpuctx
->online
) {
13131 if (!exclusive_event_installable(event
, ctx
)) {
13136 perf_install_in_context(ctx
, event
, event
->cpu
);
13137 perf_unpin_context(ctx
);
13138 mutex_unlock(&ctx
->mutex
);
13143 put_pmu_ctx(pmu_ctx
);
13144 event
->pmu_ctx
= NULL
; /* _free_event() */
13146 mutex_unlock(&ctx
->mutex
);
13147 perf_unpin_context(ctx
);
13152 return ERR_PTR(err
);
13154 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter
);
13156 static void __perf_pmu_remove(struct perf_event_context
*ctx
,
13157 int cpu
, struct pmu
*pmu
,
13158 struct perf_event_groups
*groups
,
13159 struct list_head
*events
)
13161 struct perf_event
*event
, *sibling
;
13163 perf_event_groups_for_cpu_pmu(event
, groups
, cpu
, pmu
) {
13164 perf_remove_from_context(event
, 0);
13165 put_pmu_ctx(event
->pmu_ctx
);
13166 list_add(&event
->migrate_entry
, events
);
13168 for_each_sibling_event(sibling
, event
) {
13169 perf_remove_from_context(sibling
, 0);
13170 put_pmu_ctx(sibling
->pmu_ctx
);
13171 list_add(&sibling
->migrate_entry
, events
);
13176 static void __perf_pmu_install_event(struct pmu
*pmu
,
13177 struct perf_event_context
*ctx
,
13178 int cpu
, struct perf_event
*event
)
13180 struct perf_event_pmu_context
*epc
;
13181 struct perf_event_context
*old_ctx
= event
->ctx
;
13183 get_ctx(ctx
); /* normally find_get_context() */
13186 epc
= find_get_pmu_context(pmu
, ctx
, event
);
13187 event
->pmu_ctx
= epc
;
13189 if (event
->state
>= PERF_EVENT_STATE_OFF
)
13190 event
->state
= PERF_EVENT_STATE_INACTIVE
;
13191 perf_install_in_context(ctx
, event
, cpu
);
13194 * Now that event->ctx is updated and visible, put the old ctx.
13199 static void __perf_pmu_install(struct perf_event_context
*ctx
,
13200 int cpu
, struct pmu
*pmu
, struct list_head
*events
)
13202 struct perf_event
*event
, *tmp
;
13205 * Re-instate events in 2 passes.
13207 * Skip over group leaders and only install siblings on this first
13208 * pass, siblings will not get enabled without a leader, however a
13209 * leader will enable its siblings, even if those are still on the old
13212 list_for_each_entry_safe(event
, tmp
, events
, migrate_entry
) {
13213 if (event
->group_leader
== event
)
13216 list_del(&event
->migrate_entry
);
13217 __perf_pmu_install_event(pmu
, ctx
, cpu
, event
);
13221 * Once all the siblings are setup properly, install the group leaders
13224 list_for_each_entry_safe(event
, tmp
, events
, migrate_entry
) {
13225 list_del(&event
->migrate_entry
);
13226 __perf_pmu_install_event(pmu
, ctx
, cpu
, event
);
13230 void perf_pmu_migrate_context(struct pmu
*pmu
, int src_cpu
, int dst_cpu
)
13232 struct perf_event_context
*src_ctx
, *dst_ctx
;
13236 * Since per-cpu context is persistent, no need to grab an extra
13239 src_ctx
= &per_cpu_ptr(&perf_cpu_context
, src_cpu
)->ctx
;
13240 dst_ctx
= &per_cpu_ptr(&perf_cpu_context
, dst_cpu
)->ctx
;
13243 * See perf_event_ctx_lock() for comments on the details
13244 * of swizzling perf_event::ctx.
13246 mutex_lock_double(&src_ctx
->mutex
, &dst_ctx
->mutex
);
13248 __perf_pmu_remove(src_ctx
, src_cpu
, pmu
, &src_ctx
->pinned_groups
, &events
);
13249 __perf_pmu_remove(src_ctx
, src_cpu
, pmu
, &src_ctx
->flexible_groups
, &events
);
13251 if (!list_empty(&events
)) {
13253 * Wait for the events to quiesce before re-instating them.
13257 __perf_pmu_install(dst_ctx
, dst_cpu
, pmu
, &events
);
13260 mutex_unlock(&dst_ctx
->mutex
);
13261 mutex_unlock(&src_ctx
->mutex
);
13263 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context
);
13265 static void sync_child_event(struct perf_event
*child_event
)
13267 struct perf_event
*parent_event
= child_event
->parent
;
13270 if (child_event
->attr
.inherit_stat
) {
13271 struct task_struct
*task
= child_event
->ctx
->task
;
13273 if (task
&& task
!= TASK_TOMBSTONE
)
13274 perf_event_read_event(child_event
, task
);
13277 child_val
= perf_event_count(child_event
, false);
13280 * Add back the child's count to the parent's count:
13282 atomic64_add(child_val
, &parent_event
->child_count
);
13283 atomic64_add(child_event
->total_time_enabled
,
13284 &parent_event
->child_total_time_enabled
);
13285 atomic64_add(child_event
->total_time_running
,
13286 &parent_event
->child_total_time_running
);
13290 perf_event_exit_event(struct perf_event
*event
, struct perf_event_context
*ctx
)
13292 struct perf_event
*parent_event
= event
->parent
;
13293 unsigned long detach_flags
= 0;
13295 if (parent_event
) {
13297 * Do not destroy the 'original' grouping; because of the
13298 * context switch optimization the original events could've
13299 * ended up in a random child task.
13301 * If we were to destroy the original group, all group related
13302 * operations would cease to function properly after this
13303 * random child dies.
13305 * Do destroy all inherited groups, we don't care about those
13306 * and being thorough is better.
13308 detach_flags
= DETACH_GROUP
| DETACH_CHILD
;
13309 mutex_lock(&parent_event
->child_mutex
);
13312 perf_remove_from_context(event
, detach_flags
);
13314 raw_spin_lock_irq(&ctx
->lock
);
13315 if (event
->state
> PERF_EVENT_STATE_EXIT
)
13316 perf_event_set_state(event
, PERF_EVENT_STATE_EXIT
);
13317 raw_spin_unlock_irq(&ctx
->lock
);
13320 * Child events can be freed.
13322 if (parent_event
) {
13323 mutex_unlock(&parent_event
->child_mutex
);
13325 * Kick perf_poll() for is_event_hup();
13327 perf_event_wakeup(parent_event
);
13329 put_event(parent_event
);
13334 * Parent events are governed by their filedesc, retain them.
13336 perf_event_wakeup(event
);
13339 static void perf_event_exit_task_context(struct task_struct
*child
)
13341 struct perf_event_context
*child_ctx
, *clone_ctx
= NULL
;
13342 struct perf_event
*child_event
, *next
;
13344 WARN_ON_ONCE(child
!= current
);
13346 child_ctx
= perf_pin_task_context(child
);
13351 * In order to reduce the amount of tricky in ctx tear-down, we hold
13352 * ctx::mutex over the entire thing. This serializes against almost
13353 * everything that wants to access the ctx.
13355 * The exception is sys_perf_event_open() /
13356 * perf_event_create_kernel_count() which does find_get_context()
13357 * without ctx::mutex (it cannot because of the move_group double mutex
13358 * lock thing). See the comments in perf_install_in_context().
13360 mutex_lock(&child_ctx
->mutex
);
13363 * In a single ctx::lock section, de-schedule the events and detach the
13364 * context from the task such that we cannot ever get it scheduled back
13367 raw_spin_lock_irq(&child_ctx
->lock
);
13368 task_ctx_sched_out(child_ctx
, NULL
, EVENT_ALL
);
13371 * Now that the context is inactive, destroy the task <-> ctx relation
13372 * and mark the context dead.
13374 RCU_INIT_POINTER(child
->perf_event_ctxp
, NULL
);
13375 put_ctx(child_ctx
); /* cannot be last */
13376 WRITE_ONCE(child_ctx
->task
, TASK_TOMBSTONE
);
13377 put_task_struct(current
); /* cannot be last */
13379 clone_ctx
= unclone_ctx(child_ctx
);
13380 raw_spin_unlock_irq(&child_ctx
->lock
);
13383 put_ctx(clone_ctx
);
13386 * Report the task dead after unscheduling the events so that we
13387 * won't get any samples after PERF_RECORD_EXIT. We can however still
13388 * get a few PERF_RECORD_READ events.
13390 perf_event_task(child
, child_ctx
, 0);
13392 list_for_each_entry_safe(child_event
, next
, &child_ctx
->event_list
, event_entry
)
13393 perf_event_exit_event(child_event
, child_ctx
);
13395 mutex_unlock(&child_ctx
->mutex
);
13397 put_ctx(child_ctx
);
13401 * When a child task exits, feed back event values to parent events.
13403 * Can be called with exec_update_lock held when called from
13404 * setup_new_exec().
13406 void perf_event_exit_task(struct task_struct
*child
)
13408 struct perf_event
*event
, *tmp
;
13410 mutex_lock(&child
->perf_event_mutex
);
13411 list_for_each_entry_safe(event
, tmp
, &child
->perf_event_list
,
13413 list_del_init(&event
->owner_entry
);
13416 * Ensure the list deletion is visible before we clear
13417 * the owner, closes a race against perf_release() where
13418 * we need to serialize on the owner->perf_event_mutex.
13420 smp_store_release(&event
->owner
, NULL
);
13422 mutex_unlock(&child
->perf_event_mutex
);
13424 perf_event_exit_task_context(child
);
13427 * The perf_event_exit_task_context calls perf_event_task
13428 * with child's task_ctx, which generates EXIT events for
13429 * child contexts and sets child->perf_event_ctxp[] to NULL.
13430 * At this point we need to send EXIT events to cpu contexts.
13432 perf_event_task(child
, NULL
, 0);
13435 static void perf_free_event(struct perf_event
*event
,
13436 struct perf_event_context
*ctx
)
13438 struct perf_event
*parent
= event
->parent
;
13440 if (WARN_ON_ONCE(!parent
))
13443 mutex_lock(&parent
->child_mutex
);
13444 list_del_init(&event
->child_list
);
13445 mutex_unlock(&parent
->child_mutex
);
13449 raw_spin_lock_irq(&ctx
->lock
);
13450 perf_group_detach(event
);
13451 list_del_event(event
, ctx
);
13452 raw_spin_unlock_irq(&ctx
->lock
);
13457 * Free a context as created by inheritance by perf_event_init_task() below,
13458 * used by fork() in case of fail.
13460 * Even though the task has never lived, the context and events have been
13461 * exposed through the child_list, so we must take care tearing it all down.
13463 void perf_event_free_task(struct task_struct
*task
)
13465 struct perf_event_context
*ctx
;
13466 struct perf_event
*event
, *tmp
;
13468 ctx
= rcu_access_pointer(task
->perf_event_ctxp
);
13472 mutex_lock(&ctx
->mutex
);
13473 raw_spin_lock_irq(&ctx
->lock
);
13475 * Destroy the task <-> ctx relation and mark the context dead.
13477 * This is important because even though the task hasn't been
13478 * exposed yet the context has been (through child_list).
13480 RCU_INIT_POINTER(task
->perf_event_ctxp
, NULL
);
13481 WRITE_ONCE(ctx
->task
, TASK_TOMBSTONE
);
13482 put_task_struct(task
); /* cannot be last */
13483 raw_spin_unlock_irq(&ctx
->lock
);
13486 list_for_each_entry_safe(event
, tmp
, &ctx
->event_list
, event_entry
)
13487 perf_free_event(event
, ctx
);
13489 mutex_unlock(&ctx
->mutex
);
13492 * perf_event_release_kernel() could've stolen some of our
13493 * child events and still have them on its free_list. In that
13494 * case we must wait for these events to have been freed (in
13495 * particular all their references to this task must've been
13498 * Without this copy_process() will unconditionally free this
13499 * task (irrespective of its reference count) and
13500 * _free_event()'s put_task_struct(event->hw.target) will be a
13503 * Wait for all events to drop their context reference.
13505 wait_var_event(&ctx
->refcount
, refcount_read(&ctx
->refcount
) == 1);
13506 put_ctx(ctx
); /* must be last */
13509 void perf_event_delayed_put(struct task_struct
*task
)
13511 WARN_ON_ONCE(task
->perf_event_ctxp
);
13514 struct file
*perf_event_get(unsigned int fd
)
13516 struct file
*file
= fget(fd
);
13518 return ERR_PTR(-EBADF
);
13520 if (file
->f_op
!= &perf_fops
) {
13522 return ERR_PTR(-EBADF
);
13528 const struct perf_event
*perf_get_event(struct file
*file
)
13530 if (file
->f_op
!= &perf_fops
)
13531 return ERR_PTR(-EINVAL
);
13533 return file
->private_data
;
13536 const struct perf_event_attr
*perf_event_attrs(struct perf_event
*event
)
13539 return ERR_PTR(-EINVAL
);
13541 return &event
->attr
;
13544 int perf_allow_kernel(struct perf_event_attr
*attr
)
13546 if (sysctl_perf_event_paranoid
> 1 && !perfmon_capable())
13549 return security_perf_event_open(attr
, PERF_SECURITY_KERNEL
);
13551 EXPORT_SYMBOL_GPL(perf_allow_kernel
);
13554 * Inherit an event from parent task to child task.
13557 * - valid pointer on success
13558 * - NULL for orphaned events
13559 * - IS_ERR() on error
13561 static struct perf_event
*
13562 inherit_event(struct perf_event
*parent_event
,
13563 struct task_struct
*parent
,
13564 struct perf_event_context
*parent_ctx
,
13565 struct task_struct
*child
,
13566 struct perf_event
*group_leader
,
13567 struct perf_event_context
*child_ctx
)
13569 enum perf_event_state parent_state
= parent_event
->state
;
13570 struct perf_event_pmu_context
*pmu_ctx
;
13571 struct perf_event
*child_event
;
13572 unsigned long flags
;
13575 * Instead of creating recursive hierarchies of events,
13576 * we link inherited events back to the original parent,
13577 * which has a filp for sure, which we use as the reference
13580 if (parent_event
->parent
)
13581 parent_event
= parent_event
->parent
;
13583 child_event
= perf_event_alloc(&parent_event
->attr
,
13586 group_leader
, parent_event
,
13588 if (IS_ERR(child_event
))
13589 return child_event
;
13591 pmu_ctx
= find_get_pmu_context(child_event
->pmu
, child_ctx
, child_event
);
13592 if (IS_ERR(pmu_ctx
)) {
13593 free_event(child_event
);
13594 return ERR_CAST(pmu_ctx
);
13596 child_event
->pmu_ctx
= pmu_ctx
;
13599 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
13600 * must be under the same lock in order to serialize against
13601 * perf_event_release_kernel(), such that either we must observe
13602 * is_orphaned_event() or they will observe us on the child_list.
13604 mutex_lock(&parent_event
->child_mutex
);
13605 if (is_orphaned_event(parent_event
) ||
13606 !atomic_long_inc_not_zero(&parent_event
->refcount
)) {
13607 mutex_unlock(&parent_event
->child_mutex
);
13608 /* task_ctx_data is freed with child_ctx */
13609 free_event(child_event
);
13613 get_ctx(child_ctx
);
13616 * Make the child state follow the state of the parent event,
13617 * not its attr.disabled bit. We hold the parent's mutex,
13618 * so we won't race with perf_event_{en, dis}able_family.
13620 if (parent_state
>= PERF_EVENT_STATE_INACTIVE
)
13621 child_event
->state
= PERF_EVENT_STATE_INACTIVE
;
13623 child_event
->state
= PERF_EVENT_STATE_OFF
;
13625 if (parent_event
->attr
.freq
) {
13626 u64 sample_period
= parent_event
->hw
.sample_period
;
13627 struct hw_perf_event
*hwc
= &child_event
->hw
;
13629 hwc
->sample_period
= sample_period
;
13630 hwc
->last_period
= sample_period
;
13632 local64_set(&hwc
->period_left
, sample_period
);
13635 child_event
->ctx
= child_ctx
;
13636 child_event
->overflow_handler
= parent_event
->overflow_handler
;
13637 child_event
->overflow_handler_context
13638 = parent_event
->overflow_handler_context
;
13641 * Precalculate sample_data sizes
13643 perf_event__header_size(child_event
);
13644 perf_event__id_header_size(child_event
);
13647 * Link it up in the child's context:
13649 raw_spin_lock_irqsave(&child_ctx
->lock
, flags
);
13650 add_event_to_ctx(child_event
, child_ctx
);
13651 child_event
->attach_state
|= PERF_ATTACH_CHILD
;
13652 raw_spin_unlock_irqrestore(&child_ctx
->lock
, flags
);
13655 * Link this into the parent event's child list
13657 list_add_tail(&child_event
->child_list
, &parent_event
->child_list
);
13658 mutex_unlock(&parent_event
->child_mutex
);
13660 return child_event
;
13664 * Inherits an event group.
13666 * This will quietly suppress orphaned events; !inherit_event() is not an error.
13667 * This matches with perf_event_release_kernel() removing all child events.
13673 static int inherit_group(struct perf_event
*parent_event
,
13674 struct task_struct
*parent
,
13675 struct perf_event_context
*parent_ctx
,
13676 struct task_struct
*child
,
13677 struct perf_event_context
*child_ctx
)
13679 struct perf_event
*leader
;
13680 struct perf_event
*sub
;
13681 struct perf_event
*child_ctr
;
13683 leader
= inherit_event(parent_event
, parent
, parent_ctx
,
13684 child
, NULL
, child_ctx
);
13685 if (IS_ERR(leader
))
13686 return PTR_ERR(leader
);
13688 * @leader can be NULL here because of is_orphaned_event(). In this
13689 * case inherit_event() will create individual events, similar to what
13690 * perf_group_detach() would do anyway.
13692 for_each_sibling_event(sub
, parent_event
) {
13693 child_ctr
= inherit_event(sub
, parent
, parent_ctx
,
13694 child
, leader
, child_ctx
);
13695 if (IS_ERR(child_ctr
))
13696 return PTR_ERR(child_ctr
);
13698 if (sub
->aux_event
== parent_event
&& child_ctr
&&
13699 !perf_get_aux_event(child_ctr
, leader
))
13703 leader
->group_generation
= parent_event
->group_generation
;
13708 * Creates the child task context and tries to inherit the event-group.
13710 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
13711 * inherited_all set when we 'fail' to inherit an orphaned event; this is
13712 * consistent with perf_event_release_kernel() removing all child events.
13719 inherit_task_group(struct perf_event
*event
, struct task_struct
*parent
,
13720 struct perf_event_context
*parent_ctx
,
13721 struct task_struct
*child
,
13722 u64 clone_flags
, int *inherited_all
)
13724 struct perf_event_context
*child_ctx
;
13727 if (!event
->attr
.inherit
||
13728 (event
->attr
.inherit_thread
&& !(clone_flags
& CLONE_THREAD
)) ||
13729 /* Do not inherit if sigtrap and signal handlers were cleared. */
13730 (event
->attr
.sigtrap
&& (clone_flags
& CLONE_CLEAR_SIGHAND
))) {
13731 *inherited_all
= 0;
13735 child_ctx
= child
->perf_event_ctxp
;
13738 * This is executed from the parent task context, so
13739 * inherit events that have been marked for cloning.
13740 * First allocate and initialize a context for the
13743 child_ctx
= alloc_perf_context(child
);
13747 child
->perf_event_ctxp
= child_ctx
;
13750 ret
= inherit_group(event
, parent
, parent_ctx
, child
, child_ctx
);
13752 *inherited_all
= 0;
13758 * Initialize the perf_event context in task_struct
13760 static int perf_event_init_context(struct task_struct
*child
, u64 clone_flags
)
13762 struct perf_event_context
*child_ctx
, *parent_ctx
;
13763 struct perf_event_context
*cloned_ctx
;
13764 struct perf_event
*event
;
13765 struct task_struct
*parent
= current
;
13766 int inherited_all
= 1;
13767 unsigned long flags
;
13770 if (likely(!parent
->perf_event_ctxp
))
13774 * If the parent's context is a clone, pin it so it won't get
13775 * swapped under us.
13777 parent_ctx
= perf_pin_task_context(parent
);
13782 * No need to check if parent_ctx != NULL here; since we saw
13783 * it non-NULL earlier, the only reason for it to become NULL
13784 * is if we exit, and since we're currently in the middle of
13785 * a fork we can't be exiting at the same time.
13789 * Lock the parent list. No need to lock the child - not PID
13790 * hashed yet and not running, so nobody can access it.
13792 mutex_lock(&parent_ctx
->mutex
);
13795 * We dont have to disable NMIs - we are only looking at
13796 * the list, not manipulating it:
13798 perf_event_groups_for_each(event
, &parent_ctx
->pinned_groups
) {
13799 ret
= inherit_task_group(event
, parent
, parent_ctx
,
13800 child
, clone_flags
, &inherited_all
);
13806 * We can't hold ctx->lock when iterating the ->flexible_group list due
13807 * to allocations, but we need to prevent rotation because
13808 * rotate_ctx() will change the list from interrupt context.
13810 raw_spin_lock_irqsave(&parent_ctx
->lock
, flags
);
13811 parent_ctx
->rotate_disable
= 1;
13812 raw_spin_unlock_irqrestore(&parent_ctx
->lock
, flags
);
13814 perf_event_groups_for_each(event
, &parent_ctx
->flexible_groups
) {
13815 ret
= inherit_task_group(event
, parent
, parent_ctx
,
13816 child
, clone_flags
, &inherited_all
);
13821 raw_spin_lock_irqsave(&parent_ctx
->lock
, flags
);
13822 parent_ctx
->rotate_disable
= 0;
13824 child_ctx
= child
->perf_event_ctxp
;
13826 if (child_ctx
&& inherited_all
) {
13828 * Mark the child context as a clone of the parent
13829 * context, or of whatever the parent is a clone of.
13831 * Note that if the parent is a clone, the holding of
13832 * parent_ctx->lock avoids it from being uncloned.
13834 cloned_ctx
= parent_ctx
->parent_ctx
;
13836 child_ctx
->parent_ctx
= cloned_ctx
;
13837 child_ctx
->parent_gen
= parent_ctx
->parent_gen
;
13839 child_ctx
->parent_ctx
= parent_ctx
;
13840 child_ctx
->parent_gen
= parent_ctx
->generation
;
13842 get_ctx(child_ctx
->parent_ctx
);
13845 raw_spin_unlock_irqrestore(&parent_ctx
->lock
, flags
);
13847 mutex_unlock(&parent_ctx
->mutex
);
13849 perf_unpin_context(parent_ctx
);
13850 put_ctx(parent_ctx
);
13856 * Initialize the perf_event context in task_struct
13858 int perf_event_init_task(struct task_struct
*child
, u64 clone_flags
)
13862 memset(child
->perf_recursion
, 0, sizeof(child
->perf_recursion
));
13863 child
->perf_event_ctxp
= NULL
;
13864 mutex_init(&child
->perf_event_mutex
);
13865 INIT_LIST_HEAD(&child
->perf_event_list
);
13867 ret
= perf_event_init_context(child
, clone_flags
);
13869 perf_event_free_task(child
);
13876 static void __init
perf_event_init_all_cpus(void)
13878 struct swevent_htable
*swhash
;
13879 struct perf_cpu_context
*cpuctx
;
13882 zalloc_cpumask_var(&perf_online_mask
, GFP_KERNEL
);
13883 zalloc_cpumask_var(&perf_online_core_mask
, GFP_KERNEL
);
13884 zalloc_cpumask_var(&perf_online_die_mask
, GFP_KERNEL
);
13885 zalloc_cpumask_var(&perf_online_cluster_mask
, GFP_KERNEL
);
13886 zalloc_cpumask_var(&perf_online_pkg_mask
, GFP_KERNEL
);
13887 zalloc_cpumask_var(&perf_online_sys_mask
, GFP_KERNEL
);
13890 for_each_possible_cpu(cpu
) {
13891 swhash
= &per_cpu(swevent_htable
, cpu
);
13892 mutex_init(&swhash
->hlist_mutex
);
13894 INIT_LIST_HEAD(&per_cpu(pmu_sb_events
.list
, cpu
));
13895 raw_spin_lock_init(&per_cpu(pmu_sb_events
.lock
, cpu
));
13897 INIT_LIST_HEAD(&per_cpu(sched_cb_list
, cpu
));
13899 cpuctx
= per_cpu_ptr(&perf_cpu_context
, cpu
);
13900 __perf_event_init_context(&cpuctx
->ctx
);
13901 lockdep_set_class(&cpuctx
->ctx
.mutex
, &cpuctx_mutex
);
13902 lockdep_set_class(&cpuctx
->ctx
.lock
, &cpuctx_lock
);
13903 cpuctx
->online
= cpumask_test_cpu(cpu
, perf_online_mask
);
13904 cpuctx
->heap_size
= ARRAY_SIZE(cpuctx
->heap_default
);
13905 cpuctx
->heap
= cpuctx
->heap_default
;
13909 static void perf_swevent_init_cpu(unsigned int cpu
)
13911 struct swevent_htable
*swhash
= &per_cpu(swevent_htable
, cpu
);
13913 mutex_lock(&swhash
->hlist_mutex
);
13914 if (swhash
->hlist_refcount
> 0 && !swevent_hlist_deref(swhash
)) {
13915 struct swevent_hlist
*hlist
;
13917 hlist
= kzalloc_node(sizeof(*hlist
), GFP_KERNEL
, cpu_to_node(cpu
));
13919 rcu_assign_pointer(swhash
->swevent_hlist
, hlist
);
13921 mutex_unlock(&swhash
->hlist_mutex
);
13924 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
13925 static void __perf_event_exit_context(void *__info
)
13927 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
13928 struct perf_event_context
*ctx
= __info
;
13929 struct perf_event
*event
;
13931 raw_spin_lock(&ctx
->lock
);
13932 ctx_sched_out(ctx
, NULL
, EVENT_TIME
);
13933 list_for_each_entry(event
, &ctx
->event_list
, event_entry
)
13934 __perf_remove_from_context(event
, cpuctx
, ctx
, (void *)DETACH_GROUP
);
13935 raw_spin_unlock(&ctx
->lock
);
13938 static void perf_event_clear_cpumask(unsigned int cpu
)
13940 int target
[PERF_PMU_MAX_SCOPE
];
13941 unsigned int scope
;
13944 cpumask_clear_cpu(cpu
, perf_online_mask
);
13946 for (scope
= PERF_PMU_SCOPE_NONE
+ 1; scope
< PERF_PMU_MAX_SCOPE
; scope
++) {
13947 const struct cpumask
*cpumask
= perf_scope_cpu_topology_cpumask(scope
, cpu
);
13948 struct cpumask
*pmu_cpumask
= perf_scope_cpumask(scope
);
13950 target
[scope
] = -1;
13951 if (WARN_ON_ONCE(!pmu_cpumask
|| !cpumask
))
13954 if (!cpumask_test_and_clear_cpu(cpu
, pmu_cpumask
))
13956 target
[scope
] = cpumask_any_but(cpumask
, cpu
);
13957 if (target
[scope
] < nr_cpu_ids
)
13958 cpumask_set_cpu(target
[scope
], pmu_cpumask
);
13962 list_for_each_entry_rcu(pmu
, &pmus
, entry
, lockdep_is_held(&pmus_srcu
)) {
13963 if (pmu
->scope
== PERF_PMU_SCOPE_NONE
||
13964 WARN_ON_ONCE(pmu
->scope
>= PERF_PMU_MAX_SCOPE
))
13967 if (target
[pmu
->scope
] >= 0 && target
[pmu
->scope
] < nr_cpu_ids
)
13968 perf_pmu_migrate_context(pmu
, cpu
, target
[pmu
->scope
]);
13972 static void perf_event_exit_cpu_context(int cpu
)
13974 struct perf_cpu_context
*cpuctx
;
13975 struct perf_event_context
*ctx
;
13977 // XXX simplify cpuctx->online
13978 mutex_lock(&pmus_lock
);
13980 * Clear the cpumasks, and migrate to other CPUs if possible.
13981 * Must be invoked before the __perf_event_exit_context.
13983 perf_event_clear_cpumask(cpu
);
13984 cpuctx
= per_cpu_ptr(&perf_cpu_context
, cpu
);
13985 ctx
= &cpuctx
->ctx
;
13987 mutex_lock(&ctx
->mutex
);
13988 smp_call_function_single(cpu
, __perf_event_exit_context
, ctx
, 1);
13989 cpuctx
->online
= 0;
13990 mutex_unlock(&ctx
->mutex
);
13991 mutex_unlock(&pmus_lock
);
13995 static void perf_event_exit_cpu_context(int cpu
) { }
13999 static void perf_event_setup_cpumask(unsigned int cpu
)
14001 struct cpumask
*pmu_cpumask
;
14002 unsigned int scope
;
14005 * Early boot stage, the cpumask hasn't been set yet.
14006 * The perf_online_<domain>_masks includes the first CPU of each domain.
14007 * Always unconditionally set the boot CPU for the perf_online_<domain>_masks.
14009 if (cpumask_empty(perf_online_mask
)) {
14010 for (scope
= PERF_PMU_SCOPE_NONE
+ 1; scope
< PERF_PMU_MAX_SCOPE
; scope
++) {
14011 pmu_cpumask
= perf_scope_cpumask(scope
);
14012 if (WARN_ON_ONCE(!pmu_cpumask
))
14014 cpumask_set_cpu(cpu
, pmu_cpumask
);
14019 for (scope
= PERF_PMU_SCOPE_NONE
+ 1; scope
< PERF_PMU_MAX_SCOPE
; scope
++) {
14020 const struct cpumask
*cpumask
= perf_scope_cpu_topology_cpumask(scope
, cpu
);
14022 pmu_cpumask
= perf_scope_cpumask(scope
);
14024 if (WARN_ON_ONCE(!pmu_cpumask
|| !cpumask
))
14027 if (!cpumask_empty(cpumask
) &&
14028 cpumask_any_and(pmu_cpumask
, cpumask
) >= nr_cpu_ids
)
14029 cpumask_set_cpu(cpu
, pmu_cpumask
);
14032 cpumask_set_cpu(cpu
, perf_online_mask
);
14035 int perf_event_init_cpu(unsigned int cpu
)
14037 struct perf_cpu_context
*cpuctx
;
14038 struct perf_event_context
*ctx
;
14040 perf_swevent_init_cpu(cpu
);
14042 mutex_lock(&pmus_lock
);
14043 perf_event_setup_cpumask(cpu
);
14044 cpuctx
= per_cpu_ptr(&perf_cpu_context
, cpu
);
14045 ctx
= &cpuctx
->ctx
;
14047 mutex_lock(&ctx
->mutex
);
14048 cpuctx
->online
= 1;
14049 mutex_unlock(&ctx
->mutex
);
14050 mutex_unlock(&pmus_lock
);
14055 int perf_event_exit_cpu(unsigned int cpu
)
14057 perf_event_exit_cpu_context(cpu
);
14062 perf_reboot(struct notifier_block
*notifier
, unsigned long val
, void *v
)
14066 for_each_online_cpu(cpu
)
14067 perf_event_exit_cpu(cpu
);
14073 * Run the perf reboot notifier at the very last possible moment so that
14074 * the generic watchdog code runs as long as possible.
14076 static struct notifier_block perf_reboot_notifier
= {
14077 .notifier_call
= perf_reboot
,
14078 .priority
= INT_MIN
,
14081 void __init
perf_event_init(void)
14085 idr_init(&pmu_idr
);
14087 perf_event_init_all_cpus();
14088 init_srcu_struct(&pmus_srcu
);
14089 perf_pmu_register(&perf_swevent
, "software", PERF_TYPE_SOFTWARE
);
14090 perf_pmu_register(&perf_cpu_clock
, "cpu_clock", -1);
14091 perf_pmu_register(&perf_task_clock
, "task_clock", -1);
14092 perf_tp_register();
14093 perf_event_init_cpu(smp_processor_id());
14094 register_reboot_notifier(&perf_reboot_notifier
);
14096 ret
= init_hw_breakpoint();
14097 WARN(ret
, "hw_breakpoint initialization failed with: %d", ret
);
14099 perf_event_cache
= KMEM_CACHE(perf_event
, SLAB_PANIC
);
14102 * Build time assertion that we keep the data_head at the intended
14103 * location. IOW, validation we got the __reserved[] size right.
14105 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page
, data_head
))
14109 ssize_t
perf_event_sysfs_show(struct device
*dev
, struct device_attribute
*attr
,
14112 struct perf_pmu_events_attr
*pmu_attr
=
14113 container_of(attr
, struct perf_pmu_events_attr
, attr
);
14115 if (pmu_attr
->event_str
)
14116 return sprintf(page
, "%s\n", pmu_attr
->event_str
);
14120 EXPORT_SYMBOL_GPL(perf_event_sysfs_show
);
14122 static int __init
perf_event_sysfs_init(void)
14127 mutex_lock(&pmus_lock
);
14129 ret
= bus_register(&pmu_bus
);
14133 list_for_each_entry(pmu
, &pmus
, entry
) {
14137 ret
= pmu_dev_alloc(pmu
);
14138 WARN(ret
, "Failed to register pmu: %s, reason %d\n", pmu
->name
, ret
);
14140 pmu_bus_running
= 1;
14144 mutex_unlock(&pmus_lock
);
14148 device_initcall(perf_event_sysfs_init
);
14150 #ifdef CONFIG_CGROUP_PERF
14151 static struct cgroup_subsys_state
*
14152 perf_cgroup_css_alloc(struct cgroup_subsys_state
*parent_css
)
14154 struct perf_cgroup
*jc
;
14156 jc
= kzalloc(sizeof(*jc
), GFP_KERNEL
);
14158 return ERR_PTR(-ENOMEM
);
14160 jc
->info
= alloc_percpu(struct perf_cgroup_info
);
14163 return ERR_PTR(-ENOMEM
);
14169 static void perf_cgroup_css_free(struct cgroup_subsys_state
*css
)
14171 struct perf_cgroup
*jc
= container_of(css
, struct perf_cgroup
, css
);
14173 free_percpu(jc
->info
);
14177 static int perf_cgroup_css_online(struct cgroup_subsys_state
*css
)
14179 perf_event_cgroup(css
->cgroup
);
14183 static int __perf_cgroup_move(void *info
)
14185 struct task_struct
*task
= info
;
14188 perf_cgroup_switch(task
);
14194 static void perf_cgroup_attach(struct cgroup_taskset
*tset
)
14196 struct task_struct
*task
;
14197 struct cgroup_subsys_state
*css
;
14199 cgroup_taskset_for_each(task
, css
, tset
)
14200 task_function_call(task
, __perf_cgroup_move
, task
);
14203 struct cgroup_subsys perf_event_cgrp_subsys
= {
14204 .css_alloc
= perf_cgroup_css_alloc
,
14205 .css_free
= perf_cgroup_css_free
,
14206 .css_online
= perf_cgroup_css_online
,
14207 .attach
= perf_cgroup_attach
,
14209 * Implicitly enable on dfl hierarchy so that perf events can
14210 * always be filtered by cgroup2 path as long as perf_event
14211 * controller is not mounted on a legacy hierarchy.
14213 .implicit_on_dfl
= true,
14216 #endif /* CONFIG_CGROUP_PERF */
14218 DEFINE_STATIC_CALL_RET0(perf_snapshot_branch_stack
, perf_snapshot_branch_stack_t
);