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>
58 #include <linux/percpu-rwsem.h>
62 #include <asm/irq_regs.h>
64 typedef int (*remote_function_f
)(void *);
66 struct remote_function_call
{
67 struct task_struct
*p
;
68 remote_function_f func
;
73 static void remote_function(void *data
)
75 struct remote_function_call
*tfc
= data
;
76 struct task_struct
*p
= tfc
->p
;
80 if (task_cpu(p
) != smp_processor_id())
84 * Now that we're on right CPU with IRQs disabled, we can test
85 * if we hit the right task without races.
88 tfc
->ret
= -ESRCH
; /* No such (running) process */
93 tfc
->ret
= tfc
->func(tfc
->info
);
97 * task_function_call - call a function on the cpu on which a task runs
98 * @p: the task to evaluate
99 * @func: the function to be called
100 * @info: the function call argument
102 * Calls the function @func when the task is currently running. This might
103 * be on the current CPU, which just calls the function directly. This will
104 * retry due to any failures in smp_call_function_single(), such as if the
105 * task_cpu() goes offline concurrently.
107 * returns @func return value or -ESRCH or -ENXIO when the process isn't running
110 task_function_call(struct task_struct
*p
, remote_function_f func
, void *info
)
112 struct remote_function_call data
= {
121 ret
= smp_call_function_single(task_cpu(p
), remote_function
,
136 * cpu_function_call - call a function on the cpu
137 * @cpu: target cpu to queue this function
138 * @func: the function to be called
139 * @info: the function call argument
141 * Calls the function @func on the remote cpu.
143 * returns: @func return value or -ENXIO when the cpu is offline
145 static int cpu_function_call(int cpu
, remote_function_f func
, void *info
)
147 struct remote_function_call data
= {
151 .ret
= -ENXIO
, /* No such CPU */
154 smp_call_function_single(cpu
, remote_function
, &data
, 1);
160 EVENT_FLEXIBLE
= 0x01,
164 /* see ctx_resched() for details */
168 /* compound helpers */
169 EVENT_ALL
= EVENT_FLEXIBLE
| EVENT_PINNED
,
170 EVENT_TIME_FROZEN
= EVENT_TIME
| EVENT_FROZEN
,
173 static inline void __perf_ctx_lock(struct perf_event_context
*ctx
)
175 raw_spin_lock(&ctx
->lock
);
176 WARN_ON_ONCE(ctx
->is_active
& EVENT_FROZEN
);
179 static void perf_ctx_lock(struct perf_cpu_context
*cpuctx
,
180 struct perf_event_context
*ctx
)
182 __perf_ctx_lock(&cpuctx
->ctx
);
184 __perf_ctx_lock(ctx
);
187 static inline void __perf_ctx_unlock(struct perf_event_context
*ctx
)
190 * If ctx_sched_in() didn't again set any ALL flags, clean up
191 * after ctx_sched_out() by clearing is_active.
193 if (ctx
->is_active
& EVENT_FROZEN
) {
194 if (!(ctx
->is_active
& EVENT_ALL
))
197 ctx
->is_active
&= ~EVENT_FROZEN
;
199 raw_spin_unlock(&ctx
->lock
);
202 static void perf_ctx_unlock(struct perf_cpu_context
*cpuctx
,
203 struct perf_event_context
*ctx
)
206 __perf_ctx_unlock(ctx
);
207 __perf_ctx_unlock(&cpuctx
->ctx
);
211 struct perf_cpu_context
*cpuctx
;
212 struct perf_event_context
*ctx
;
213 } class_perf_ctx_lock_t
;
215 static inline void class_perf_ctx_lock_destructor(class_perf_ctx_lock_t
*_T
)
216 { perf_ctx_unlock(_T
->cpuctx
, _T
->ctx
); }
218 static inline class_perf_ctx_lock_t
219 class_perf_ctx_lock_constructor(struct perf_cpu_context
*cpuctx
,
220 struct perf_event_context
*ctx
)
221 { perf_ctx_lock(cpuctx
, ctx
); return (class_perf_ctx_lock_t
){ cpuctx
, ctx
}; }
223 #define TASK_TOMBSTONE ((void *)-1L)
225 static bool is_kernel_event(struct perf_event
*event
)
227 return READ_ONCE(event
->owner
) == TASK_TOMBSTONE
;
230 static DEFINE_PER_CPU(struct perf_cpu_context
, perf_cpu_context
);
232 struct perf_event_context
*perf_cpu_task_ctx(void)
234 lockdep_assert_irqs_disabled();
235 return this_cpu_ptr(&perf_cpu_context
)->task_ctx
;
239 * On task ctx scheduling...
241 * When !ctx->nr_events a task context will not be scheduled. This means
242 * we can disable the scheduler hooks (for performance) without leaving
243 * pending task ctx state.
245 * This however results in two special cases:
247 * - removing the last event from a task ctx; this is relatively straight
248 * forward and is done in __perf_remove_from_context.
250 * - adding the first event to a task ctx; this is tricky because we cannot
251 * rely on ctx->is_active and therefore cannot use event_function_call().
252 * See perf_install_in_context().
254 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
257 typedef void (*event_f
)(struct perf_event
*, struct perf_cpu_context
*,
258 struct perf_event_context
*, void *);
260 struct event_function_struct
{
261 struct perf_event
*event
;
266 static int event_function(void *info
)
268 struct event_function_struct
*efs
= info
;
269 struct perf_event
*event
= efs
->event
;
270 struct perf_event_context
*ctx
= event
->ctx
;
271 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
272 struct perf_event_context
*task_ctx
= cpuctx
->task_ctx
;
275 lockdep_assert_irqs_disabled();
277 perf_ctx_lock(cpuctx
, task_ctx
);
279 * Since we do the IPI call without holding ctx->lock things can have
280 * changed, double check we hit the task we set out to hit.
283 if (ctx
->task
!= current
) {
289 * We only use event_function_call() on established contexts,
290 * and event_function() is only ever called when active (or
291 * rather, we'll have bailed in task_function_call() or the
292 * above ctx->task != current test), therefore we must have
293 * ctx->is_active here.
295 WARN_ON_ONCE(!ctx
->is_active
);
297 * And since we have ctx->is_active, cpuctx->task_ctx must
300 WARN_ON_ONCE(task_ctx
!= ctx
);
302 WARN_ON_ONCE(&cpuctx
->ctx
!= ctx
);
305 efs
->func(event
, cpuctx
, ctx
, efs
->data
);
307 perf_ctx_unlock(cpuctx
, task_ctx
);
312 static void event_function_call(struct perf_event
*event
, event_f func
, void *data
)
314 struct perf_event_context
*ctx
= event
->ctx
;
315 struct task_struct
*task
= READ_ONCE(ctx
->task
); /* verified in event_function */
316 struct perf_cpu_context
*cpuctx
;
317 struct event_function_struct efs
= {
323 if (!event
->parent
) {
325 * If this is a !child event, we must hold ctx::mutex to
326 * stabilize the event->ctx relation. See
327 * perf_event_ctx_lock().
329 lockdep_assert_held(&ctx
->mutex
);
333 cpu_function_call(event
->cpu
, event_function
, &efs
);
337 if (task
== TASK_TOMBSTONE
)
341 if (!task_function_call(task
, event_function
, &efs
))
345 cpuctx
= this_cpu_ptr(&perf_cpu_context
);
346 perf_ctx_lock(cpuctx
, ctx
);
348 * Reload the task pointer, it might have been changed by
349 * a concurrent perf_event_context_sched_out().
352 if (task
== TASK_TOMBSTONE
)
354 if (ctx
->is_active
) {
355 perf_ctx_unlock(cpuctx
, ctx
);
359 func(event
, NULL
, ctx
, data
);
361 perf_ctx_unlock(cpuctx
, ctx
);
366 * Similar to event_function_call() + event_function(), but hard assumes IRQs
367 * are already disabled and we're on the right CPU.
369 static void event_function_local(struct perf_event
*event
, event_f func
, void *data
)
371 struct perf_event_context
*ctx
= event
->ctx
;
372 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
373 struct task_struct
*task
= READ_ONCE(ctx
->task
);
374 struct perf_event_context
*task_ctx
= NULL
;
376 lockdep_assert_irqs_disabled();
379 if (task
== TASK_TOMBSTONE
)
385 perf_ctx_lock(cpuctx
, task_ctx
);
388 if (task
== TASK_TOMBSTONE
)
393 * We must be either inactive or active and the right task,
394 * otherwise we're screwed, since we cannot IPI to somewhere
397 if (ctx
->is_active
) {
398 if (WARN_ON_ONCE(task
!= current
))
401 if (WARN_ON_ONCE(cpuctx
->task_ctx
!= ctx
))
405 WARN_ON_ONCE(&cpuctx
->ctx
!= ctx
);
408 func(event
, cpuctx
, ctx
, data
);
410 perf_ctx_unlock(cpuctx
, task_ctx
);
413 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
414 PERF_FLAG_FD_OUTPUT |\
415 PERF_FLAG_PID_CGROUP |\
416 PERF_FLAG_FD_CLOEXEC)
419 * branch priv levels that need permission checks
421 #define PERF_SAMPLE_BRANCH_PERM_PLM \
422 (PERF_SAMPLE_BRANCH_KERNEL |\
423 PERF_SAMPLE_BRANCH_HV)
426 * perf_sched_events : >0 events exist
429 static void perf_sched_delayed(struct work_struct
*work
);
430 DEFINE_STATIC_KEY_FALSE(perf_sched_events
);
431 static DECLARE_DELAYED_WORK(perf_sched_work
, perf_sched_delayed
);
432 static DEFINE_MUTEX(perf_sched_mutex
);
433 static atomic_t perf_sched_count
;
435 static DEFINE_PER_CPU(struct pmu_event_list
, pmu_sb_events
);
437 static atomic_t nr_mmap_events __read_mostly
;
438 static atomic_t nr_comm_events __read_mostly
;
439 static atomic_t nr_namespaces_events __read_mostly
;
440 static atomic_t nr_task_events __read_mostly
;
441 static atomic_t nr_freq_events __read_mostly
;
442 static atomic_t nr_switch_events __read_mostly
;
443 static atomic_t nr_ksymbol_events __read_mostly
;
444 static atomic_t nr_bpf_events __read_mostly
;
445 static atomic_t nr_cgroup_events __read_mostly
;
446 static atomic_t nr_text_poke_events __read_mostly
;
447 static atomic_t nr_build_id_events __read_mostly
;
449 static LIST_HEAD(pmus
);
450 static DEFINE_MUTEX(pmus_lock
);
451 static struct srcu_struct pmus_srcu
;
452 static cpumask_var_t perf_online_mask
;
453 static cpumask_var_t perf_online_core_mask
;
454 static cpumask_var_t perf_online_die_mask
;
455 static cpumask_var_t perf_online_cluster_mask
;
456 static cpumask_var_t perf_online_pkg_mask
;
457 static cpumask_var_t perf_online_sys_mask
;
458 static struct kmem_cache
*perf_event_cache
;
461 * perf event paranoia level:
462 * -1 - not paranoid at all
463 * 0 - disallow raw tracepoint access for unpriv
464 * 1 - disallow cpu events for unpriv
465 * 2 - disallow kernel profiling for unpriv
467 int sysctl_perf_event_paranoid __read_mostly
= 2;
469 /* Minimum for 512 kiB + 1 user control page. 'free' kiB per user. */
470 static int sysctl_perf_event_mlock __read_mostly
= 512 + (PAGE_SIZE
/ 1024);
473 * max perf event sample rate
475 #define DEFAULT_MAX_SAMPLE_RATE 100000
476 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
477 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
479 int sysctl_perf_event_sample_rate __read_mostly
= DEFAULT_MAX_SAMPLE_RATE
;
480 static int sysctl_perf_cpu_time_max_percent __read_mostly
= DEFAULT_CPU_TIME_MAX_PERCENT
;
482 static int max_samples_per_tick __read_mostly
= DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE
, HZ
);
483 static int perf_sample_period_ns __read_mostly
= DEFAULT_SAMPLE_PERIOD_NS
;
485 static int perf_sample_allowed_ns __read_mostly
=
486 DEFAULT_SAMPLE_PERIOD_NS
* DEFAULT_CPU_TIME_MAX_PERCENT
/ 100;
488 static void update_perf_cpu_limits(void)
490 u64 tmp
= perf_sample_period_ns
;
492 tmp
*= sysctl_perf_cpu_time_max_percent
;
493 tmp
= div_u64(tmp
, 100);
497 WRITE_ONCE(perf_sample_allowed_ns
, tmp
);
500 static bool perf_rotate_context(struct perf_cpu_pmu_context
*cpc
);
502 static int perf_event_max_sample_rate_handler(const struct ctl_table
*table
, int write
,
503 void *buffer
, size_t *lenp
, loff_t
*ppos
)
506 int perf_cpu
= sysctl_perf_cpu_time_max_percent
;
508 * If throttling is disabled don't allow the write:
510 if (write
&& (perf_cpu
== 100 || perf_cpu
== 0))
513 ret
= proc_dointvec_minmax(table
, write
, buffer
, lenp
, ppos
);
517 max_samples_per_tick
= DIV_ROUND_UP(sysctl_perf_event_sample_rate
, HZ
);
518 perf_sample_period_ns
= NSEC_PER_SEC
/ sysctl_perf_event_sample_rate
;
519 update_perf_cpu_limits();
524 static int perf_cpu_time_max_percent_handler(const struct ctl_table
*table
, int write
,
525 void *buffer
, size_t *lenp
, loff_t
*ppos
)
527 int ret
= proc_dointvec_minmax(table
, write
, buffer
, lenp
, ppos
);
532 if (sysctl_perf_cpu_time_max_percent
== 100 ||
533 sysctl_perf_cpu_time_max_percent
== 0) {
535 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
536 WRITE_ONCE(perf_sample_allowed_ns
, 0);
538 update_perf_cpu_limits();
544 static const struct ctl_table events_core_sysctl_table
[] = {
546 * User-space relies on this file as a feature check for
547 * perf_events being enabled. It's an ABI, do not remove!
550 .procname
= "perf_event_paranoid",
551 .data
= &sysctl_perf_event_paranoid
,
552 .maxlen
= sizeof(sysctl_perf_event_paranoid
),
554 .proc_handler
= proc_dointvec
,
557 .procname
= "perf_event_mlock_kb",
558 .data
= &sysctl_perf_event_mlock
,
559 .maxlen
= sizeof(sysctl_perf_event_mlock
),
561 .proc_handler
= proc_dointvec
,
564 .procname
= "perf_event_max_sample_rate",
565 .data
= &sysctl_perf_event_sample_rate
,
566 .maxlen
= sizeof(sysctl_perf_event_sample_rate
),
568 .proc_handler
= perf_event_max_sample_rate_handler
,
569 .extra1
= SYSCTL_ONE
,
572 .procname
= "perf_cpu_time_max_percent",
573 .data
= &sysctl_perf_cpu_time_max_percent
,
574 .maxlen
= sizeof(sysctl_perf_cpu_time_max_percent
),
576 .proc_handler
= perf_cpu_time_max_percent_handler
,
577 .extra1
= SYSCTL_ZERO
,
578 .extra2
= SYSCTL_ONE_HUNDRED
,
582 static int __init
init_events_core_sysctls(void)
584 register_sysctl_init("kernel", events_core_sysctl_table
);
587 core_initcall(init_events_core_sysctls
);
591 * perf samples are done in some very critical code paths (NMIs).
592 * If they take too much CPU time, the system can lock up and not
593 * get any real work done. This will drop the sample rate when
594 * we detect that events are taking too long.
596 #define NR_ACCUMULATED_SAMPLES 128
597 static DEFINE_PER_CPU(u64
, running_sample_length
);
599 static u64 __report_avg
;
600 static u64 __report_allowed
;
602 static void perf_duration_warn(struct irq_work
*w
)
604 printk_ratelimited(KERN_INFO
605 "perf: interrupt took too long (%lld > %lld), lowering "
606 "kernel.perf_event_max_sample_rate to %d\n",
607 __report_avg
, __report_allowed
,
608 sysctl_perf_event_sample_rate
);
611 static DEFINE_IRQ_WORK(perf_duration_work
, perf_duration_warn
);
613 void perf_sample_event_took(u64 sample_len_ns
)
615 u64 max_len
= READ_ONCE(perf_sample_allowed_ns
);
623 /* Decay the counter by 1 average sample. */
624 running_len
= __this_cpu_read(running_sample_length
);
625 running_len
-= running_len
/NR_ACCUMULATED_SAMPLES
;
626 running_len
+= sample_len_ns
;
627 __this_cpu_write(running_sample_length
, running_len
);
630 * Note: this will be biased artificially low until we have
631 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
632 * from having to maintain a count.
634 avg_len
= running_len
/NR_ACCUMULATED_SAMPLES
;
635 if (avg_len
<= max_len
)
638 __report_avg
= avg_len
;
639 __report_allowed
= max_len
;
642 * Compute a throttle threshold 25% below the current duration.
644 avg_len
+= avg_len
/ 4;
645 max
= (TICK_NSEC
/ 100) * sysctl_perf_cpu_time_max_percent
;
651 WRITE_ONCE(perf_sample_allowed_ns
, avg_len
);
652 WRITE_ONCE(max_samples_per_tick
, max
);
654 sysctl_perf_event_sample_rate
= max
* HZ
;
655 perf_sample_period_ns
= NSEC_PER_SEC
/ sysctl_perf_event_sample_rate
;
657 if (!irq_work_queue(&perf_duration_work
)) {
658 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
659 "kernel.perf_event_max_sample_rate to %d\n",
660 __report_avg
, __report_allowed
,
661 sysctl_perf_event_sample_rate
);
665 static atomic64_t perf_event_id
;
667 static void update_context_time(struct perf_event_context
*ctx
);
668 static u64
perf_event_time(struct perf_event
*event
);
670 void __weak
perf_event_print_debug(void) { }
672 static inline u64
perf_clock(void)
674 return local_clock();
677 static inline u64
perf_event_clock(struct perf_event
*event
)
679 return event
->clock();
683 * State based event timekeeping...
685 * The basic idea is to use event->state to determine which (if any) time
686 * fields to increment with the current delta. This means we only need to
687 * update timestamps when we change state or when they are explicitly requested
690 * Event groups make things a little more complicated, but not terribly so. The
691 * rules for a group are that if the group leader is OFF the entire group is
692 * OFF, irrespective of what the group member states are. This results in
693 * __perf_effective_state().
695 * A further ramification is that when a group leader flips between OFF and
696 * !OFF, we need to update all group member times.
699 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
700 * need to make sure the relevant context time is updated before we try and
701 * update our timestamps.
704 static __always_inline
enum perf_event_state
705 __perf_effective_state(struct perf_event
*event
)
707 struct perf_event
*leader
= event
->group_leader
;
709 if (leader
->state
<= PERF_EVENT_STATE_OFF
)
710 return leader
->state
;
715 static __always_inline
void
716 __perf_update_times(struct perf_event
*event
, u64 now
, u64
*enabled
, u64
*running
)
718 enum perf_event_state state
= __perf_effective_state(event
);
719 u64 delta
= now
- event
->tstamp
;
721 *enabled
= event
->total_time_enabled
;
722 if (state
>= PERF_EVENT_STATE_INACTIVE
)
725 *running
= event
->total_time_running
;
726 if (state
>= PERF_EVENT_STATE_ACTIVE
)
730 static void perf_event_update_time(struct perf_event
*event
)
732 u64 now
= perf_event_time(event
);
734 __perf_update_times(event
, now
, &event
->total_time_enabled
,
735 &event
->total_time_running
);
739 static void perf_event_update_sibling_time(struct perf_event
*leader
)
741 struct perf_event
*sibling
;
743 for_each_sibling_event(sibling
, leader
)
744 perf_event_update_time(sibling
);
748 perf_event_set_state(struct perf_event
*event
, enum perf_event_state state
)
750 if (event
->state
== state
)
753 perf_event_update_time(event
);
755 * If a group leader gets enabled/disabled all its siblings
758 if ((event
->state
< 0) ^ (state
< 0))
759 perf_event_update_sibling_time(event
);
761 WRITE_ONCE(event
->state
, state
);
765 * UP store-release, load-acquire
768 #define __store_release(ptr, val) \
771 WRITE_ONCE(*(ptr), (val)); \
774 #define __load_acquire(ptr) \
776 __unqual_scalar_typeof(*(ptr)) ___p = READ_ONCE(*(ptr)); \
781 #define for_each_epc(_epc, _ctx, _pmu, _cgroup) \
782 list_for_each_entry(_epc, &((_ctx)->pmu_ctx_list), pmu_ctx_entry) \
783 if (_cgroup && !_epc->nr_cgroups) \
785 else if (_pmu && _epc->pmu != _pmu) \
789 static void perf_ctx_disable(struct perf_event_context
*ctx
, bool cgroup
)
791 struct perf_event_pmu_context
*pmu_ctx
;
793 for_each_epc(pmu_ctx
, ctx
, NULL
, cgroup
)
794 perf_pmu_disable(pmu_ctx
->pmu
);
797 static void perf_ctx_enable(struct perf_event_context
*ctx
, bool cgroup
)
799 struct perf_event_pmu_context
*pmu_ctx
;
801 for_each_epc(pmu_ctx
, ctx
, NULL
, cgroup
)
802 perf_pmu_enable(pmu_ctx
->pmu
);
805 static void ctx_sched_out(struct perf_event_context
*ctx
, struct pmu
*pmu
, enum event_type_t event_type
);
806 static void ctx_sched_in(struct perf_event_context
*ctx
, struct pmu
*pmu
, enum event_type_t event_type
);
808 #ifdef CONFIG_CGROUP_PERF
811 perf_cgroup_match(struct perf_event
*event
)
813 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
815 /* @event doesn't care about cgroup */
819 /* wants specific cgroup scope but @cpuctx isn't associated with any */
824 * Cgroup scoping is recursive. An event enabled for a cgroup is
825 * also enabled for all its descendant cgroups. If @cpuctx's
826 * cgroup is a descendant of @event's (the test covers identity
827 * case), it's a match.
829 return cgroup_is_descendant(cpuctx
->cgrp
->css
.cgroup
,
830 event
->cgrp
->css
.cgroup
);
833 static inline void perf_detach_cgroup(struct perf_event
*event
)
835 css_put(&event
->cgrp
->css
);
839 static inline int is_cgroup_event(struct perf_event
*event
)
841 return event
->cgrp
!= NULL
;
844 static inline u64
perf_cgroup_event_time(struct perf_event
*event
)
846 struct perf_cgroup_info
*t
;
848 t
= per_cpu_ptr(event
->cgrp
->info
, event
->cpu
);
852 static inline u64
perf_cgroup_event_time_now(struct perf_event
*event
, u64 now
)
854 struct perf_cgroup_info
*t
;
856 t
= per_cpu_ptr(event
->cgrp
->info
, event
->cpu
);
857 if (!__load_acquire(&t
->active
))
859 now
+= READ_ONCE(t
->timeoffset
);
863 static inline void __update_cgrp_time(struct perf_cgroup_info
*info
, u64 now
, bool adv
)
866 info
->time
+= now
- info
->timestamp
;
867 info
->timestamp
= now
;
869 * see update_context_time()
871 WRITE_ONCE(info
->timeoffset
, info
->time
- info
->timestamp
);
874 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context
*cpuctx
, bool final
)
876 struct perf_cgroup
*cgrp
= cpuctx
->cgrp
;
877 struct cgroup_subsys_state
*css
;
878 struct perf_cgroup_info
*info
;
881 u64 now
= perf_clock();
883 for (css
= &cgrp
->css
; css
; css
= css
->parent
) {
884 cgrp
= container_of(css
, struct perf_cgroup
, css
);
885 info
= this_cpu_ptr(cgrp
->info
);
887 __update_cgrp_time(info
, now
, true);
889 __store_release(&info
->active
, 0);
894 static inline void update_cgrp_time_from_event(struct perf_event
*event
)
896 struct perf_cgroup_info
*info
;
899 * ensure we access cgroup data only when needed and
900 * when we know the cgroup is pinned (css_get)
902 if (!is_cgroup_event(event
))
905 info
= this_cpu_ptr(event
->cgrp
->info
);
907 * Do not update time when cgroup is not active
910 __update_cgrp_time(info
, perf_clock(), true);
914 perf_cgroup_set_timestamp(struct perf_cpu_context
*cpuctx
)
916 struct perf_event_context
*ctx
= &cpuctx
->ctx
;
917 struct perf_cgroup
*cgrp
= cpuctx
->cgrp
;
918 struct perf_cgroup_info
*info
;
919 struct cgroup_subsys_state
*css
;
922 * ctx->lock held by caller
923 * ensure we do not access cgroup data
924 * unless we have the cgroup pinned (css_get)
929 WARN_ON_ONCE(!ctx
->nr_cgroups
);
931 for (css
= &cgrp
->css
; css
; css
= css
->parent
) {
932 cgrp
= container_of(css
, struct perf_cgroup
, css
);
933 info
= this_cpu_ptr(cgrp
->info
);
934 __update_cgrp_time(info
, ctx
->timestamp
, false);
935 __store_release(&info
->active
, 1);
940 * reschedule events based on the cgroup constraint of task.
942 static void perf_cgroup_switch(struct task_struct
*task
)
944 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
945 struct perf_cgroup
*cgrp
;
948 * cpuctx->cgrp is set when the first cgroup event enabled,
949 * and is cleared when the last cgroup event disabled.
951 if (READ_ONCE(cpuctx
->cgrp
) == NULL
)
954 WARN_ON_ONCE(cpuctx
->ctx
.nr_cgroups
== 0);
956 cgrp
= perf_cgroup_from_task(task
, NULL
);
957 if (READ_ONCE(cpuctx
->cgrp
) == cgrp
)
960 guard(perf_ctx_lock
)(cpuctx
, cpuctx
->task_ctx
);
962 * Re-check, could've raced vs perf_remove_from_context().
964 if (READ_ONCE(cpuctx
->cgrp
) == NULL
)
967 perf_ctx_disable(&cpuctx
->ctx
, true);
969 ctx_sched_out(&cpuctx
->ctx
, NULL
, EVENT_ALL
|EVENT_CGROUP
);
971 * must not be done before ctxswout due
972 * to update_cgrp_time_from_cpuctx() in
977 * set cgrp before ctxsw in to allow
978 * perf_cgroup_set_timestamp() in ctx_sched_in()
979 * to not have to pass task around
981 ctx_sched_in(&cpuctx
->ctx
, NULL
, EVENT_ALL
|EVENT_CGROUP
);
983 perf_ctx_enable(&cpuctx
->ctx
, true);
986 static int perf_cgroup_ensure_storage(struct perf_event
*event
,
987 struct cgroup_subsys_state
*css
)
989 struct perf_cpu_context
*cpuctx
;
990 struct perf_event
**storage
;
991 int cpu
, heap_size
, ret
= 0;
994 * Allow storage to have sufficient space for an iterator for each
995 * possibly nested cgroup plus an iterator for events with no cgroup.
997 for (heap_size
= 1; css
; css
= css
->parent
)
1000 for_each_possible_cpu(cpu
) {
1001 cpuctx
= per_cpu_ptr(&perf_cpu_context
, cpu
);
1002 if (heap_size
<= cpuctx
->heap_size
)
1005 storage
= kmalloc_node(heap_size
* sizeof(struct perf_event
*),
1006 GFP_KERNEL
, cpu_to_node(cpu
));
1012 raw_spin_lock_irq(&cpuctx
->ctx
.lock
);
1013 if (cpuctx
->heap_size
< heap_size
) {
1014 swap(cpuctx
->heap
, storage
);
1015 if (storage
== cpuctx
->heap_default
)
1017 cpuctx
->heap_size
= heap_size
;
1019 raw_spin_unlock_irq(&cpuctx
->ctx
.lock
);
1027 static inline int perf_cgroup_connect(int fd
, struct perf_event
*event
,
1028 struct perf_event_attr
*attr
,
1029 struct perf_event
*group_leader
)
1031 struct perf_cgroup
*cgrp
;
1032 struct cgroup_subsys_state
*css
;
1039 css
= css_tryget_online_from_dir(fd_file(f
)->f_path
.dentry
,
1040 &perf_event_cgrp_subsys
);
1042 return PTR_ERR(css
);
1044 ret
= perf_cgroup_ensure_storage(event
, css
);
1048 cgrp
= container_of(css
, struct perf_cgroup
, css
);
1052 * all events in a group must monitor
1053 * the same cgroup because a task belongs
1054 * to only one perf cgroup at a time
1056 if (group_leader
&& group_leader
->cgrp
!= cgrp
) {
1057 perf_detach_cgroup(event
);
1064 perf_cgroup_event_enable(struct perf_event
*event
, struct perf_event_context
*ctx
)
1066 struct perf_cpu_context
*cpuctx
;
1068 if (!is_cgroup_event(event
))
1071 event
->pmu_ctx
->nr_cgroups
++;
1074 * Because cgroup events are always per-cpu events,
1075 * @ctx == &cpuctx->ctx.
1077 cpuctx
= container_of(ctx
, struct perf_cpu_context
, ctx
);
1079 if (ctx
->nr_cgroups
++)
1082 cpuctx
->cgrp
= perf_cgroup_from_task(current
, ctx
);
1086 perf_cgroup_event_disable(struct perf_event
*event
, struct perf_event_context
*ctx
)
1088 struct perf_cpu_context
*cpuctx
;
1090 if (!is_cgroup_event(event
))
1093 event
->pmu_ctx
->nr_cgroups
--;
1096 * Because cgroup events are always per-cpu events,
1097 * @ctx == &cpuctx->ctx.
1099 cpuctx
= container_of(ctx
, struct perf_cpu_context
, ctx
);
1101 if (--ctx
->nr_cgroups
)
1104 cpuctx
->cgrp
= NULL
;
1107 #else /* !CONFIG_CGROUP_PERF */
1110 perf_cgroup_match(struct perf_event
*event
)
1115 static inline void perf_detach_cgroup(struct perf_event
*event
)
1118 static inline int is_cgroup_event(struct perf_event
*event
)
1123 static inline void update_cgrp_time_from_event(struct perf_event
*event
)
1127 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context
*cpuctx
,
1132 static inline int perf_cgroup_connect(pid_t pid
, struct perf_event
*event
,
1133 struct perf_event_attr
*attr
,
1134 struct perf_event
*group_leader
)
1140 perf_cgroup_set_timestamp(struct perf_cpu_context
*cpuctx
)
1144 static inline u64
perf_cgroup_event_time(struct perf_event
*event
)
1149 static inline u64
perf_cgroup_event_time_now(struct perf_event
*event
, u64 now
)
1155 perf_cgroup_event_enable(struct perf_event
*event
, struct perf_event_context
*ctx
)
1160 perf_cgroup_event_disable(struct perf_event
*event
, struct perf_event_context
*ctx
)
1164 static void perf_cgroup_switch(struct task_struct
*task
)
1170 * set default to be dependent on timer tick just
1171 * like original code
1173 #define PERF_CPU_HRTIMER (1000 / HZ)
1175 * function must be called with interrupts disabled
1177 static enum hrtimer_restart
perf_mux_hrtimer_handler(struct hrtimer
*hr
)
1179 struct perf_cpu_pmu_context
*cpc
;
1182 lockdep_assert_irqs_disabled();
1184 cpc
= container_of(hr
, struct perf_cpu_pmu_context
, hrtimer
);
1185 rotations
= perf_rotate_context(cpc
);
1187 raw_spin_lock(&cpc
->hrtimer_lock
);
1189 hrtimer_forward_now(hr
, cpc
->hrtimer_interval
);
1191 cpc
->hrtimer_active
= 0;
1192 raw_spin_unlock(&cpc
->hrtimer_lock
);
1194 return rotations
? HRTIMER_RESTART
: HRTIMER_NORESTART
;
1197 static void __perf_mux_hrtimer_init(struct perf_cpu_pmu_context
*cpc
, int cpu
)
1199 struct hrtimer
*timer
= &cpc
->hrtimer
;
1200 struct pmu
*pmu
= cpc
->epc
.pmu
;
1204 * check default is sane, if not set then force to
1205 * default interval (1/tick)
1207 interval
= pmu
->hrtimer_interval_ms
;
1209 interval
= pmu
->hrtimer_interval_ms
= PERF_CPU_HRTIMER
;
1211 cpc
->hrtimer_interval
= ns_to_ktime(NSEC_PER_MSEC
* interval
);
1213 raw_spin_lock_init(&cpc
->hrtimer_lock
);
1214 hrtimer_setup(timer
, perf_mux_hrtimer_handler
, CLOCK_MONOTONIC
,
1215 HRTIMER_MODE_ABS_PINNED_HARD
);
1218 static int perf_mux_hrtimer_restart(struct perf_cpu_pmu_context
*cpc
)
1220 struct hrtimer
*timer
= &cpc
->hrtimer
;
1221 unsigned long flags
;
1223 raw_spin_lock_irqsave(&cpc
->hrtimer_lock
, flags
);
1224 if (!cpc
->hrtimer_active
) {
1225 cpc
->hrtimer_active
= 1;
1226 hrtimer_forward_now(timer
, cpc
->hrtimer_interval
);
1227 hrtimer_start_expires(timer
, HRTIMER_MODE_ABS_PINNED_HARD
);
1229 raw_spin_unlock_irqrestore(&cpc
->hrtimer_lock
, flags
);
1234 static int perf_mux_hrtimer_restart_ipi(void *arg
)
1236 return perf_mux_hrtimer_restart(arg
);
1239 static __always_inline
struct perf_cpu_pmu_context
*this_cpc(struct pmu
*pmu
)
1241 return *this_cpu_ptr(pmu
->cpu_pmu_context
);
1244 void perf_pmu_disable(struct pmu
*pmu
)
1246 int *count
= &this_cpc(pmu
)->pmu_disable_count
;
1248 pmu
->pmu_disable(pmu
);
1251 void perf_pmu_enable(struct pmu
*pmu
)
1253 int *count
= &this_cpc(pmu
)->pmu_disable_count
;
1255 pmu
->pmu_enable(pmu
);
1258 static void perf_assert_pmu_disabled(struct pmu
*pmu
)
1260 int *count
= &this_cpc(pmu
)->pmu_disable_count
;
1261 WARN_ON_ONCE(*count
== 0);
1264 static inline void perf_pmu_read(struct perf_event
*event
)
1266 if (event
->state
== PERF_EVENT_STATE_ACTIVE
)
1267 event
->pmu
->read(event
);
1270 static void get_ctx(struct perf_event_context
*ctx
)
1272 refcount_inc(&ctx
->refcount
);
1275 static void free_ctx(struct rcu_head
*head
)
1277 struct perf_event_context
*ctx
;
1279 ctx
= container_of(head
, struct perf_event_context
, rcu_head
);
1283 static void put_ctx(struct perf_event_context
*ctx
)
1285 if (refcount_dec_and_test(&ctx
->refcount
)) {
1286 if (ctx
->parent_ctx
)
1287 put_ctx(ctx
->parent_ctx
);
1288 if (ctx
->task
&& ctx
->task
!= TASK_TOMBSTONE
)
1289 put_task_struct(ctx
->task
);
1290 call_rcu(&ctx
->rcu_head
, free_ctx
);
1292 smp_mb__after_atomic(); /* pairs with wait_var_event() */
1293 if (ctx
->task
== TASK_TOMBSTONE
)
1294 wake_up_var(&ctx
->refcount
);
1299 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1300 * perf_pmu_migrate_context() we need some magic.
1302 * Those places that change perf_event::ctx will hold both
1303 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1305 * Lock ordering is by mutex address. There are two other sites where
1306 * perf_event_context::mutex nests and those are:
1308 * - perf_event_exit_task_context() [ child , 0 ]
1309 * perf_event_exit_event()
1310 * put_event() [ parent, 1 ]
1312 * - perf_event_init_context() [ parent, 0 ]
1313 * inherit_task_group()
1316 * perf_event_alloc()
1318 * perf_try_init_event() [ child , 1 ]
1320 * While it appears there is an obvious deadlock here -- the parent and child
1321 * nesting levels are inverted between the two. This is in fact safe because
1322 * life-time rules separate them. That is an exiting task cannot fork, and a
1323 * spawning task cannot (yet) exit.
1325 * But remember that these are parent<->child context relations, and
1326 * migration does not affect children, therefore these two orderings should not
1329 * The change in perf_event::ctx does not affect children (as claimed above)
1330 * because the sys_perf_event_open() case will install a new event and break
1331 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1332 * concerned with cpuctx and that doesn't have children.
1334 * The places that change perf_event::ctx will issue:
1336 * perf_remove_from_context();
1337 * synchronize_rcu();
1338 * perf_install_in_context();
1340 * to affect the change. The remove_from_context() + synchronize_rcu() should
1341 * quiesce the event, after which we can install it in the new location. This
1342 * means that only external vectors (perf_fops, prctl) can perturb the event
1343 * while in transit. Therefore all such accessors should also acquire
1344 * perf_event_context::mutex to serialize against this.
1346 * However; because event->ctx can change while we're waiting to acquire
1347 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1352 * task_struct::perf_event_mutex
1353 * perf_event_context::mutex
1354 * perf_event::child_mutex;
1355 * perf_event_context::lock
1357 * perf_event::mmap_mutex
1358 * perf_buffer::aux_mutex
1359 * perf_addr_filters_head::lock
1363 * cpuctx->mutex / perf_event_context::mutex
1365 static struct perf_event_context
*
1366 perf_event_ctx_lock_nested(struct perf_event
*event
, int nesting
)
1368 struct perf_event_context
*ctx
;
1372 ctx
= READ_ONCE(event
->ctx
);
1373 if (!refcount_inc_not_zero(&ctx
->refcount
)) {
1379 mutex_lock_nested(&ctx
->mutex
, nesting
);
1380 if (event
->ctx
!= ctx
) {
1381 mutex_unlock(&ctx
->mutex
);
1389 static inline struct perf_event_context
*
1390 perf_event_ctx_lock(struct perf_event
*event
)
1392 return perf_event_ctx_lock_nested(event
, 0);
1395 static void perf_event_ctx_unlock(struct perf_event
*event
,
1396 struct perf_event_context
*ctx
)
1398 mutex_unlock(&ctx
->mutex
);
1403 * This must be done under the ctx->lock, such as to serialize against
1404 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1405 * calling scheduler related locks and ctx->lock nests inside those.
1407 static __must_check
struct perf_event_context
*
1408 unclone_ctx(struct perf_event_context
*ctx
)
1410 struct perf_event_context
*parent_ctx
= ctx
->parent_ctx
;
1412 lockdep_assert_held(&ctx
->lock
);
1415 ctx
->parent_ctx
= NULL
;
1421 static u32
perf_event_pid_type(struct perf_event
*event
, struct task_struct
*p
,
1426 * only top level events have the pid namespace they were created in
1429 event
= event
->parent
;
1431 nr
= __task_pid_nr_ns(p
, type
, event
->ns
);
1432 /* avoid -1 if it is idle thread or runs in another ns */
1433 if (!nr
&& !pid_alive(p
))
1438 static u32
perf_event_pid(struct perf_event
*event
, struct task_struct
*p
)
1440 return perf_event_pid_type(event
, p
, PIDTYPE_TGID
);
1443 static u32
perf_event_tid(struct perf_event
*event
, struct task_struct
*p
)
1445 return perf_event_pid_type(event
, p
, PIDTYPE_PID
);
1449 * If we inherit events we want to return the parent event id
1452 static u64
primary_event_id(struct perf_event
*event
)
1457 id
= event
->parent
->id
;
1463 * Get the perf_event_context for a task and lock it.
1465 * This has to cope with the fact that until it is locked,
1466 * the context could get moved to another task.
1468 static struct perf_event_context
*
1469 perf_lock_task_context(struct task_struct
*task
, unsigned long *flags
)
1471 struct perf_event_context
*ctx
;
1475 * One of the few rules of preemptible RCU is that one cannot do
1476 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1477 * part of the read side critical section was irqs-enabled -- see
1478 * rcu_read_unlock_special().
1480 * Since ctx->lock nests under rq->lock we must ensure the entire read
1481 * side critical section has interrupts disabled.
1483 local_irq_save(*flags
);
1485 ctx
= rcu_dereference(task
->perf_event_ctxp
);
1488 * If this context is a clone of another, it might
1489 * get swapped for another underneath us by
1490 * perf_event_task_sched_out, though the
1491 * rcu_read_lock() protects us from any context
1492 * getting freed. Lock the context and check if it
1493 * got swapped before we could get the lock, and retry
1494 * if so. If we locked the right context, then it
1495 * can't get swapped on us any more.
1497 raw_spin_lock(&ctx
->lock
);
1498 if (ctx
!= rcu_dereference(task
->perf_event_ctxp
)) {
1499 raw_spin_unlock(&ctx
->lock
);
1501 local_irq_restore(*flags
);
1505 if (ctx
->task
== TASK_TOMBSTONE
||
1506 !refcount_inc_not_zero(&ctx
->refcount
)) {
1507 raw_spin_unlock(&ctx
->lock
);
1510 WARN_ON_ONCE(ctx
->task
!= task
);
1515 local_irq_restore(*flags
);
1520 * Get the context for a task and increment its pin_count so it
1521 * can't get swapped to another task. This also increments its
1522 * reference count so that the context can't get freed.
1524 static struct perf_event_context
*
1525 perf_pin_task_context(struct task_struct
*task
)
1527 struct perf_event_context
*ctx
;
1528 unsigned long flags
;
1530 ctx
= perf_lock_task_context(task
, &flags
);
1533 raw_spin_unlock_irqrestore(&ctx
->lock
, flags
);
1538 static void perf_unpin_context(struct perf_event_context
*ctx
)
1540 unsigned long flags
;
1542 raw_spin_lock_irqsave(&ctx
->lock
, flags
);
1544 raw_spin_unlock_irqrestore(&ctx
->lock
, flags
);
1548 * Update the record of the current time in a context.
1550 static void __update_context_time(struct perf_event_context
*ctx
, bool adv
)
1552 u64 now
= perf_clock();
1554 lockdep_assert_held(&ctx
->lock
);
1557 ctx
->time
+= now
- ctx
->timestamp
;
1558 ctx
->timestamp
= now
;
1561 * The above: time' = time + (now - timestamp), can be re-arranged
1562 * into: time` = now + (time - timestamp), which gives a single value
1563 * offset to compute future time without locks on.
1565 * See perf_event_time_now(), which can be used from NMI context where
1566 * it's (obviously) not possible to acquire ctx->lock in order to read
1567 * both the above values in a consistent manner.
1569 WRITE_ONCE(ctx
->timeoffset
, ctx
->time
- ctx
->timestamp
);
1572 static void update_context_time(struct perf_event_context
*ctx
)
1574 __update_context_time(ctx
, true);
1577 static u64
perf_event_time(struct perf_event
*event
)
1579 struct perf_event_context
*ctx
= event
->ctx
;
1584 if (is_cgroup_event(event
))
1585 return perf_cgroup_event_time(event
);
1590 static u64
perf_event_time_now(struct perf_event
*event
, u64 now
)
1592 struct perf_event_context
*ctx
= event
->ctx
;
1597 if (is_cgroup_event(event
))
1598 return perf_cgroup_event_time_now(event
, now
);
1600 if (!(__load_acquire(&ctx
->is_active
) & EVENT_TIME
))
1603 now
+= READ_ONCE(ctx
->timeoffset
);
1607 static enum event_type_t
get_event_type(struct perf_event
*event
)
1609 struct perf_event_context
*ctx
= event
->ctx
;
1610 enum event_type_t event_type
;
1612 lockdep_assert_held(&ctx
->lock
);
1615 * It's 'group type', really, because if our group leader is
1616 * pinned, so are we.
1618 if (event
->group_leader
!= event
)
1619 event
= event
->group_leader
;
1621 event_type
= event
->attr
.pinned
? EVENT_PINNED
: EVENT_FLEXIBLE
;
1623 event_type
|= EVENT_CPU
;
1629 * Helper function to initialize event group nodes.
1631 static void init_event_group(struct perf_event
*event
)
1633 RB_CLEAR_NODE(&event
->group_node
);
1634 event
->group_index
= 0;
1638 * Extract pinned or flexible groups from the context
1639 * based on event attrs bits.
1641 static struct perf_event_groups
*
1642 get_event_groups(struct perf_event
*event
, struct perf_event_context
*ctx
)
1644 if (event
->attr
.pinned
)
1645 return &ctx
->pinned_groups
;
1647 return &ctx
->flexible_groups
;
1651 * Helper function to initializes perf_event_group trees.
1653 static void perf_event_groups_init(struct perf_event_groups
*groups
)
1655 groups
->tree
= RB_ROOT
;
1659 static inline struct cgroup
*event_cgroup(const struct perf_event
*event
)
1661 struct cgroup
*cgroup
= NULL
;
1663 #ifdef CONFIG_CGROUP_PERF
1665 cgroup
= event
->cgrp
->css
.cgroup
;
1672 * Compare function for event groups;
1674 * Implements complex key that first sorts by CPU and then by virtual index
1675 * which provides ordering when rotating groups for the same CPU.
1677 static __always_inline
int
1678 perf_event_groups_cmp(const int left_cpu
, const struct pmu
*left_pmu
,
1679 const struct cgroup
*left_cgroup
, const u64 left_group_index
,
1680 const struct perf_event
*right
)
1682 if (left_cpu
< right
->cpu
)
1684 if (left_cpu
> right
->cpu
)
1688 if (left_pmu
< right
->pmu_ctx
->pmu
)
1690 if (left_pmu
> right
->pmu_ctx
->pmu
)
1694 #ifdef CONFIG_CGROUP_PERF
1696 const struct cgroup
*right_cgroup
= event_cgroup(right
);
1698 if (left_cgroup
!= right_cgroup
) {
1701 * Left has no cgroup but right does, no
1702 * cgroups come first.
1706 if (!right_cgroup
) {
1708 * Right has no cgroup but left does, no
1709 * cgroups come first.
1713 /* Two dissimilar cgroups, order by id. */
1714 if (cgroup_id(left_cgroup
) < cgroup_id(right_cgroup
))
1722 if (left_group_index
< right
->group_index
)
1724 if (left_group_index
> right
->group_index
)
1730 #define __node_2_pe(node) \
1731 rb_entry((node), struct perf_event, group_node)
1733 static inline bool __group_less(struct rb_node
*a
, const struct rb_node
*b
)
1735 struct perf_event
*e
= __node_2_pe(a
);
1736 return perf_event_groups_cmp(e
->cpu
, e
->pmu_ctx
->pmu
, event_cgroup(e
),
1737 e
->group_index
, __node_2_pe(b
)) < 0;
1740 struct __group_key
{
1743 struct cgroup
*cgroup
;
1746 static inline int __group_cmp(const void *key
, const struct rb_node
*node
)
1748 const struct __group_key
*a
= key
;
1749 const struct perf_event
*b
= __node_2_pe(node
);
1751 /* partial/subtree match: @cpu, @pmu, @cgroup; ignore: @group_index */
1752 return perf_event_groups_cmp(a
->cpu
, a
->pmu
, a
->cgroup
, b
->group_index
, b
);
1756 __group_cmp_ignore_cgroup(const void *key
, const struct rb_node
*node
)
1758 const struct __group_key
*a
= key
;
1759 const struct perf_event
*b
= __node_2_pe(node
);
1761 /* partial/subtree match: @cpu, @pmu, ignore: @cgroup, @group_index */
1762 return perf_event_groups_cmp(a
->cpu
, a
->pmu
, event_cgroup(b
),
1767 * Insert @event into @groups' tree; using
1768 * {@event->cpu, @event->pmu_ctx->pmu, event_cgroup(@event), ++@groups->index}
1769 * as key. This places it last inside the {cpu,pmu,cgroup} subtree.
1772 perf_event_groups_insert(struct perf_event_groups
*groups
,
1773 struct perf_event
*event
)
1775 event
->group_index
= ++groups
->index
;
1777 rb_add(&event
->group_node
, &groups
->tree
, __group_less
);
1781 * Helper function to insert event into the pinned or flexible groups.
1784 add_event_to_groups(struct perf_event
*event
, struct perf_event_context
*ctx
)
1786 struct perf_event_groups
*groups
;
1788 groups
= get_event_groups(event
, ctx
);
1789 perf_event_groups_insert(groups
, event
);
1793 * Delete a group from a tree.
1796 perf_event_groups_delete(struct perf_event_groups
*groups
,
1797 struct perf_event
*event
)
1799 WARN_ON_ONCE(RB_EMPTY_NODE(&event
->group_node
) ||
1800 RB_EMPTY_ROOT(&groups
->tree
));
1802 rb_erase(&event
->group_node
, &groups
->tree
);
1803 init_event_group(event
);
1807 * Helper function to delete event from its groups.
1810 del_event_from_groups(struct perf_event
*event
, struct perf_event_context
*ctx
)
1812 struct perf_event_groups
*groups
;
1814 groups
= get_event_groups(event
, ctx
);
1815 perf_event_groups_delete(groups
, event
);
1819 * Get the leftmost event in the {cpu,pmu,cgroup} subtree.
1821 static struct perf_event
*
1822 perf_event_groups_first(struct perf_event_groups
*groups
, int cpu
,
1823 struct pmu
*pmu
, struct cgroup
*cgrp
)
1825 struct __group_key key
= {
1830 struct rb_node
*node
;
1832 node
= rb_find_first(&key
, &groups
->tree
, __group_cmp
);
1834 return __node_2_pe(node
);
1839 static struct perf_event
*
1840 perf_event_groups_next(struct perf_event
*event
, struct pmu
*pmu
)
1842 struct __group_key key
= {
1845 .cgroup
= event_cgroup(event
),
1847 struct rb_node
*next
;
1849 next
= rb_next_match(&key
, &event
->group_node
, __group_cmp
);
1851 return __node_2_pe(next
);
1856 #define perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) \
1857 for (event = perf_event_groups_first(groups, cpu, pmu, NULL); \
1858 event; event = perf_event_groups_next(event, pmu))
1861 * Iterate through the whole groups tree.
1863 #define perf_event_groups_for_each(event, groups) \
1864 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1865 typeof(*event), group_node); event; \
1866 event = rb_entry_safe(rb_next(&event->group_node), \
1867 typeof(*event), group_node))
1870 * Does the event attribute request inherit with PERF_SAMPLE_READ
1872 static inline bool has_inherit_and_sample_read(struct perf_event_attr
*attr
)
1874 return attr
->inherit
&& (attr
->sample_type
& PERF_SAMPLE_READ
);
1878 * Add an event from the lists for its context.
1879 * Must be called with ctx->mutex and ctx->lock held.
1882 list_add_event(struct perf_event
*event
, struct perf_event_context
*ctx
)
1884 lockdep_assert_held(&ctx
->lock
);
1886 WARN_ON_ONCE(event
->attach_state
& PERF_ATTACH_CONTEXT
);
1887 event
->attach_state
|= PERF_ATTACH_CONTEXT
;
1889 event
->tstamp
= perf_event_time(event
);
1892 * If we're a stand alone event or group leader, we go to the context
1893 * list, group events are kept attached to the group so that
1894 * perf_group_detach can, at all times, locate all siblings.
1896 if (event
->group_leader
== event
) {
1897 event
->group_caps
= event
->event_caps
;
1898 add_event_to_groups(event
, ctx
);
1901 list_add_rcu(&event
->event_entry
, &ctx
->event_list
);
1903 if (event
->hw
.flags
& PERF_EVENT_FLAG_USER_READ_CNT
)
1905 if (event
->attr
.inherit_stat
)
1907 if (has_inherit_and_sample_read(&event
->attr
))
1908 local_inc(&ctx
->nr_no_switch_fast
);
1910 if (event
->state
> PERF_EVENT_STATE_OFF
)
1911 perf_cgroup_event_enable(event
, ctx
);
1914 event
->pmu_ctx
->nr_events
++;
1918 * Initialize event state based on the perf_event_attr::disabled.
1920 static inline void perf_event__state_init(struct perf_event
*event
)
1922 event
->state
= event
->attr
.disabled
? PERF_EVENT_STATE_OFF
:
1923 PERF_EVENT_STATE_INACTIVE
;
1926 static int __perf_event_read_size(u64 read_format
, int nr_siblings
)
1928 int entry
= sizeof(u64
); /* value */
1932 if (read_format
& PERF_FORMAT_TOTAL_TIME_ENABLED
)
1933 size
+= sizeof(u64
);
1935 if (read_format
& PERF_FORMAT_TOTAL_TIME_RUNNING
)
1936 size
+= sizeof(u64
);
1938 if (read_format
& PERF_FORMAT_ID
)
1939 entry
+= sizeof(u64
);
1941 if (read_format
& PERF_FORMAT_LOST
)
1942 entry
+= sizeof(u64
);
1944 if (read_format
& PERF_FORMAT_GROUP
) {
1946 size
+= sizeof(u64
);
1950 * Since perf_event_validate_size() limits this to 16k and inhibits
1951 * adding more siblings, this will never overflow.
1953 return size
+ nr
* entry
;
1956 static void __perf_event_header_size(struct perf_event
*event
, u64 sample_type
)
1958 struct perf_sample_data
*data
;
1961 if (sample_type
& PERF_SAMPLE_IP
)
1962 size
+= sizeof(data
->ip
);
1964 if (sample_type
& PERF_SAMPLE_ADDR
)
1965 size
+= sizeof(data
->addr
);
1967 if (sample_type
& PERF_SAMPLE_PERIOD
)
1968 size
+= sizeof(data
->period
);
1970 if (sample_type
& PERF_SAMPLE_WEIGHT_TYPE
)
1971 size
+= sizeof(data
->weight
.full
);
1973 if (sample_type
& PERF_SAMPLE_READ
)
1974 size
+= event
->read_size
;
1976 if (sample_type
& PERF_SAMPLE_DATA_SRC
)
1977 size
+= sizeof(data
->data_src
.val
);
1979 if (sample_type
& PERF_SAMPLE_TRANSACTION
)
1980 size
+= sizeof(data
->txn
);
1982 if (sample_type
& PERF_SAMPLE_PHYS_ADDR
)
1983 size
+= sizeof(data
->phys_addr
);
1985 if (sample_type
& PERF_SAMPLE_CGROUP
)
1986 size
+= sizeof(data
->cgroup
);
1988 if (sample_type
& PERF_SAMPLE_DATA_PAGE_SIZE
)
1989 size
+= sizeof(data
->data_page_size
);
1991 if (sample_type
& PERF_SAMPLE_CODE_PAGE_SIZE
)
1992 size
+= sizeof(data
->code_page_size
);
1994 event
->header_size
= size
;
1998 * Called at perf_event creation and when events are attached/detached from a
2001 static void perf_event__header_size(struct perf_event
*event
)
2004 __perf_event_read_size(event
->attr
.read_format
,
2005 event
->group_leader
->nr_siblings
);
2006 __perf_event_header_size(event
, event
->attr
.sample_type
);
2009 static void perf_event__id_header_size(struct perf_event
*event
)
2011 struct perf_sample_data
*data
;
2012 u64 sample_type
= event
->attr
.sample_type
;
2015 if (sample_type
& PERF_SAMPLE_TID
)
2016 size
+= sizeof(data
->tid_entry
);
2018 if (sample_type
& PERF_SAMPLE_TIME
)
2019 size
+= sizeof(data
->time
);
2021 if (sample_type
& PERF_SAMPLE_IDENTIFIER
)
2022 size
+= sizeof(data
->id
);
2024 if (sample_type
& PERF_SAMPLE_ID
)
2025 size
+= sizeof(data
->id
);
2027 if (sample_type
& PERF_SAMPLE_STREAM_ID
)
2028 size
+= sizeof(data
->stream_id
);
2030 if (sample_type
& PERF_SAMPLE_CPU
)
2031 size
+= sizeof(data
->cpu_entry
);
2033 event
->id_header_size
= size
;
2037 * Check that adding an event to the group does not result in anybody
2038 * overflowing the 64k event limit imposed by the output buffer.
2040 * Specifically, check that the read_size for the event does not exceed 16k,
2041 * read_size being the one term that grows with groups size. Since read_size
2042 * depends on per-event read_format, also (re)check the existing events.
2044 * This leaves 48k for the constant size fields and things like callchains,
2045 * branch stacks and register sets.
2047 static bool perf_event_validate_size(struct perf_event
*event
)
2049 struct perf_event
*sibling
, *group_leader
= event
->group_leader
;
2051 if (__perf_event_read_size(event
->attr
.read_format
,
2052 group_leader
->nr_siblings
+ 1) > 16*1024)
2055 if (__perf_event_read_size(group_leader
->attr
.read_format
,
2056 group_leader
->nr_siblings
+ 1) > 16*1024)
2060 * When creating a new group leader, group_leader->ctx is initialized
2061 * after the size has been validated, but we cannot safely use
2062 * for_each_sibling_event() until group_leader->ctx is set. A new group
2063 * leader cannot have any siblings yet, so we can safely skip checking
2064 * the non-existent siblings.
2066 if (event
== group_leader
)
2069 for_each_sibling_event(sibling
, group_leader
) {
2070 if (__perf_event_read_size(sibling
->attr
.read_format
,
2071 group_leader
->nr_siblings
+ 1) > 16*1024)
2078 static void perf_group_attach(struct perf_event
*event
)
2080 struct perf_event
*group_leader
= event
->group_leader
, *pos
;
2082 lockdep_assert_held(&event
->ctx
->lock
);
2085 * We can have double attach due to group movement (move_group) in
2086 * perf_event_open().
2088 if (event
->attach_state
& PERF_ATTACH_GROUP
)
2091 event
->attach_state
|= PERF_ATTACH_GROUP
;
2093 if (group_leader
== event
)
2096 WARN_ON_ONCE(group_leader
->ctx
!= event
->ctx
);
2098 group_leader
->group_caps
&= event
->event_caps
;
2100 list_add_tail(&event
->sibling_list
, &group_leader
->sibling_list
);
2101 group_leader
->nr_siblings
++;
2102 group_leader
->group_generation
++;
2104 perf_event__header_size(group_leader
);
2106 for_each_sibling_event(pos
, group_leader
)
2107 perf_event__header_size(pos
);
2111 * Remove an event from the lists for its context.
2112 * Must be called with ctx->mutex and ctx->lock held.
2115 list_del_event(struct perf_event
*event
, struct perf_event_context
*ctx
)
2117 WARN_ON_ONCE(event
->ctx
!= ctx
);
2118 lockdep_assert_held(&ctx
->lock
);
2121 * We can have double detach due to exit/hot-unplug + close.
2123 if (!(event
->attach_state
& PERF_ATTACH_CONTEXT
))
2126 event
->attach_state
&= ~PERF_ATTACH_CONTEXT
;
2129 if (event
->hw
.flags
& PERF_EVENT_FLAG_USER_READ_CNT
)
2131 if (event
->attr
.inherit_stat
)
2133 if (has_inherit_and_sample_read(&event
->attr
))
2134 local_dec(&ctx
->nr_no_switch_fast
);
2136 list_del_rcu(&event
->event_entry
);
2138 if (event
->group_leader
== event
)
2139 del_event_from_groups(event
, ctx
);
2142 event
->pmu_ctx
->nr_events
--;
2146 perf_aux_output_match(struct perf_event
*event
, struct perf_event
*aux_event
)
2148 if (!has_aux(aux_event
))
2151 if (!event
->pmu
->aux_output_match
)
2154 return event
->pmu
->aux_output_match(aux_event
);
2157 static void put_event(struct perf_event
*event
);
2158 static void __event_disable(struct perf_event
*event
,
2159 struct perf_event_context
*ctx
,
2160 enum perf_event_state state
);
2162 static void perf_put_aux_event(struct perf_event
*event
)
2164 struct perf_event_context
*ctx
= event
->ctx
;
2165 struct perf_event
*iter
;
2168 * If event uses aux_event tear down the link
2170 if (event
->aux_event
) {
2171 iter
= event
->aux_event
;
2172 event
->aux_event
= NULL
;
2178 * If the event is an aux_event, tear down all links to
2179 * it from other events.
2181 for_each_sibling_event(iter
, event
) {
2182 if (iter
->aux_event
!= event
)
2185 iter
->aux_event
= NULL
;
2189 * If it's ACTIVE, schedule it out and put it into ERROR
2190 * state so that we don't try to schedule it again. Note
2191 * that perf_event_enable() will clear the ERROR status.
2193 __event_disable(iter
, ctx
, PERF_EVENT_STATE_ERROR
);
2197 static bool perf_need_aux_event(struct perf_event
*event
)
2199 return event
->attr
.aux_output
|| has_aux_action(event
);
2202 static int perf_get_aux_event(struct perf_event
*event
,
2203 struct perf_event
*group_leader
)
2206 * Our group leader must be an aux event if we want to be
2207 * an aux_output. This way, the aux event will precede its
2208 * aux_output events in the group, and therefore will always
2215 * aux_output and aux_sample_size are mutually exclusive.
2217 if (event
->attr
.aux_output
&& event
->attr
.aux_sample_size
)
2220 if (event
->attr
.aux_output
&&
2221 !perf_aux_output_match(event
, group_leader
))
2224 if ((event
->attr
.aux_pause
|| event
->attr
.aux_resume
) &&
2225 !(group_leader
->pmu
->capabilities
& PERF_PMU_CAP_AUX_PAUSE
))
2228 if (event
->attr
.aux_sample_size
&& !group_leader
->pmu
->snapshot_aux
)
2231 if (!atomic_long_inc_not_zero(&group_leader
->refcount
))
2235 * Link aux_outputs to their aux event; this is undone in
2236 * perf_group_detach() by perf_put_aux_event(). When the
2237 * group in torn down, the aux_output events loose their
2238 * link to the aux_event and can't schedule any more.
2240 event
->aux_event
= group_leader
;
2245 static inline struct list_head
*get_event_list(struct perf_event
*event
)
2247 return event
->attr
.pinned
? &event
->pmu_ctx
->pinned_active
:
2248 &event
->pmu_ctx
->flexible_active
;
2251 static void perf_group_detach(struct perf_event
*event
)
2253 struct perf_event
*leader
= event
->group_leader
;
2254 struct perf_event
*sibling
, *tmp
;
2255 struct perf_event_context
*ctx
= event
->ctx
;
2257 lockdep_assert_held(&ctx
->lock
);
2260 * We can have double detach due to exit/hot-unplug + close.
2262 if (!(event
->attach_state
& PERF_ATTACH_GROUP
))
2265 event
->attach_state
&= ~PERF_ATTACH_GROUP
;
2267 perf_put_aux_event(event
);
2270 * If this is a sibling, remove it from its group.
2272 if (leader
!= event
) {
2273 list_del_init(&event
->sibling_list
);
2274 event
->group_leader
->nr_siblings
--;
2275 event
->group_leader
->group_generation
++;
2280 * If this was a group event with sibling events then
2281 * upgrade the siblings to singleton events by adding them
2282 * to whatever list we are on.
2284 list_for_each_entry_safe(sibling
, tmp
, &event
->sibling_list
, sibling_list
) {
2287 * Events that have PERF_EV_CAP_SIBLING require being part of
2288 * a group and cannot exist on their own, schedule them out
2289 * and move them into the ERROR state. Also see
2290 * _perf_event_enable(), it will not be able to recover this
2293 if (sibling
->event_caps
& PERF_EV_CAP_SIBLING
)
2294 __event_disable(sibling
, ctx
, PERF_EVENT_STATE_ERROR
);
2296 sibling
->group_leader
= sibling
;
2297 list_del_init(&sibling
->sibling_list
);
2299 /* Inherit group flags from the previous leader */
2300 sibling
->group_caps
= event
->group_caps
;
2302 if (sibling
->attach_state
& PERF_ATTACH_CONTEXT
) {
2303 add_event_to_groups(sibling
, event
->ctx
);
2305 if (sibling
->state
== PERF_EVENT_STATE_ACTIVE
)
2306 list_add_tail(&sibling
->active_list
, get_event_list(sibling
));
2309 WARN_ON_ONCE(sibling
->ctx
!= event
->ctx
);
2313 for_each_sibling_event(tmp
, leader
)
2314 perf_event__header_size(tmp
);
2316 perf_event__header_size(leader
);
2319 static void sync_child_event(struct perf_event
*child_event
);
2321 static void perf_child_detach(struct perf_event
*event
)
2323 struct perf_event
*parent_event
= event
->parent
;
2325 if (!(event
->attach_state
& PERF_ATTACH_CHILD
))
2328 event
->attach_state
&= ~PERF_ATTACH_CHILD
;
2330 if (WARN_ON_ONCE(!parent_event
))
2334 * Can't check this from an IPI, the holder is likey another CPU.
2336 lockdep_assert_held(&parent_event->child_mutex);
2339 sync_child_event(event
);
2340 list_del_init(&event
->child_list
);
2343 static bool is_orphaned_event(struct perf_event
*event
)
2345 return event
->state
== PERF_EVENT_STATE_DEAD
;
2349 event_filter_match(struct perf_event
*event
)
2351 return (event
->cpu
== -1 || event
->cpu
== smp_processor_id()) &&
2352 perf_cgroup_match(event
);
2355 static inline bool is_event_in_freq_mode(struct perf_event
*event
)
2357 return event
->attr
.freq
&& event
->attr
.sample_freq
;
2361 event_sched_out(struct perf_event
*event
, struct perf_event_context
*ctx
)
2363 struct perf_event_pmu_context
*epc
= event
->pmu_ctx
;
2364 struct perf_cpu_pmu_context
*cpc
= this_cpc(epc
->pmu
);
2365 enum perf_event_state state
= PERF_EVENT_STATE_INACTIVE
;
2367 // XXX cpc serialization, probably per-cpu IRQ disabled
2369 WARN_ON_ONCE(event
->ctx
!= ctx
);
2370 lockdep_assert_held(&ctx
->lock
);
2372 if (event
->state
!= PERF_EVENT_STATE_ACTIVE
)
2376 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2377 * we can schedule events _OUT_ individually through things like
2378 * __perf_remove_from_context().
2380 list_del_init(&event
->active_list
);
2382 perf_pmu_disable(event
->pmu
);
2384 event
->pmu
->del(event
, 0);
2387 if (event
->pending_disable
) {
2388 event
->pending_disable
= 0;
2389 perf_cgroup_event_disable(event
, ctx
);
2390 state
= PERF_EVENT_STATE_OFF
;
2393 perf_event_set_state(event
, state
);
2395 if (!is_software_event(event
))
2396 cpc
->active_oncpu
--;
2397 if (is_event_in_freq_mode(event
)) {
2401 if (event
->attr
.exclusive
|| !cpc
->active_oncpu
)
2404 perf_pmu_enable(event
->pmu
);
2408 group_sched_out(struct perf_event
*group_event
, struct perf_event_context
*ctx
)
2410 struct perf_event
*event
;
2412 if (group_event
->state
!= PERF_EVENT_STATE_ACTIVE
)
2415 perf_assert_pmu_disabled(group_event
->pmu_ctx
->pmu
);
2417 event_sched_out(group_event
, ctx
);
2420 * Schedule out siblings (if any):
2422 for_each_sibling_event(event
, group_event
)
2423 event_sched_out(event
, ctx
);
2427 __ctx_time_update(struct perf_cpu_context
*cpuctx
, struct perf_event_context
*ctx
, bool final
)
2429 if (ctx
->is_active
& EVENT_TIME
) {
2430 if (ctx
->is_active
& EVENT_FROZEN
)
2432 update_context_time(ctx
);
2433 update_cgrp_time_from_cpuctx(cpuctx
, final
);
2438 ctx_time_update(struct perf_cpu_context
*cpuctx
, struct perf_event_context
*ctx
)
2440 __ctx_time_update(cpuctx
, ctx
, false);
2444 * To be used inside perf_ctx_lock() / perf_ctx_unlock(). Lasts until perf_ctx_unlock().
2447 ctx_time_freeze(struct perf_cpu_context
*cpuctx
, struct perf_event_context
*ctx
)
2449 ctx_time_update(cpuctx
, ctx
);
2450 if (ctx
->is_active
& EVENT_TIME
)
2451 ctx
->is_active
|= EVENT_FROZEN
;
2455 ctx_time_update_event(struct perf_event_context
*ctx
, struct perf_event
*event
)
2457 if (ctx
->is_active
& EVENT_TIME
) {
2458 if (ctx
->is_active
& EVENT_FROZEN
)
2460 update_context_time(ctx
);
2461 update_cgrp_time_from_event(event
);
2465 #define DETACH_GROUP 0x01UL
2466 #define DETACH_CHILD 0x02UL
2467 #define DETACH_EXIT 0x04UL
2468 #define DETACH_REVOKE 0x08UL
2469 #define DETACH_DEAD 0x10UL
2472 * Cross CPU call to remove a performance event
2474 * We disable the event on the hardware level first. After that we
2475 * remove it from the context list.
2478 __perf_remove_from_context(struct perf_event
*event
,
2479 struct perf_cpu_context
*cpuctx
,
2480 struct perf_event_context
*ctx
,
2483 struct perf_event_pmu_context
*pmu_ctx
= event
->pmu_ctx
;
2484 enum perf_event_state state
= PERF_EVENT_STATE_OFF
;
2485 unsigned long flags
= (unsigned long)info
;
2487 ctx_time_update(cpuctx
, ctx
);
2490 * Ensure event_sched_out() switches to OFF, at the very least
2491 * this avoids raising perf_pending_task() at this time.
2493 if (flags
& DETACH_EXIT
)
2494 state
= PERF_EVENT_STATE_EXIT
;
2495 if (flags
& DETACH_REVOKE
)
2496 state
= PERF_EVENT_STATE_REVOKED
;
2497 if (flags
& DETACH_DEAD
)
2498 state
= PERF_EVENT_STATE_DEAD
;
2500 event_sched_out(event
, ctx
);
2502 if (event
->state
> PERF_EVENT_STATE_OFF
)
2503 perf_cgroup_event_disable(event
, ctx
);
2505 perf_event_set_state(event
, min(event
->state
, state
));
2507 if (flags
& DETACH_GROUP
)
2508 perf_group_detach(event
);
2509 if (flags
& DETACH_CHILD
)
2510 perf_child_detach(event
);
2511 list_del_event(event
, ctx
);
2513 if (!pmu_ctx
->nr_events
) {
2514 pmu_ctx
->rotate_necessary
= 0;
2516 if (ctx
->task
&& ctx
->is_active
) {
2517 struct perf_cpu_pmu_context
*cpc
= this_cpc(pmu_ctx
->pmu
);
2519 WARN_ON_ONCE(cpc
->task_epc
&& cpc
->task_epc
!= pmu_ctx
);
2520 cpc
->task_epc
= NULL
;
2524 if (!ctx
->nr_events
&& ctx
->is_active
) {
2525 if (ctx
== &cpuctx
->ctx
)
2526 update_cgrp_time_from_cpuctx(cpuctx
, true);
2530 WARN_ON_ONCE(cpuctx
->task_ctx
!= ctx
);
2531 cpuctx
->task_ctx
= NULL
;
2537 * Remove the event from a task's (or a CPU's) list of events.
2539 * If event->ctx is a cloned context, callers must make sure that
2540 * every task struct that event->ctx->task could possibly point to
2541 * remains valid. This is OK when called from perf_release since
2542 * that only calls us on the top-level context, which can't be a clone.
2543 * When called from perf_event_exit_task, it's OK because the
2544 * context has been detached from its task.
2546 static void perf_remove_from_context(struct perf_event
*event
, unsigned long flags
)
2548 struct perf_event_context
*ctx
= event
->ctx
;
2550 lockdep_assert_held(&ctx
->mutex
);
2553 * Because of perf_event_exit_task(), perf_remove_from_context() ought
2554 * to work in the face of TASK_TOMBSTONE, unlike every other
2555 * event_function_call() user.
2557 raw_spin_lock_irq(&ctx
->lock
);
2558 if (!ctx
->is_active
) {
2559 __perf_remove_from_context(event
, this_cpu_ptr(&perf_cpu_context
),
2560 ctx
, (void *)flags
);
2561 raw_spin_unlock_irq(&ctx
->lock
);
2564 raw_spin_unlock_irq(&ctx
->lock
);
2566 event_function_call(event
, __perf_remove_from_context
, (void *)flags
);
2569 static void __event_disable(struct perf_event
*event
,
2570 struct perf_event_context
*ctx
,
2571 enum perf_event_state state
)
2573 event_sched_out(event
, ctx
);
2574 perf_cgroup_event_disable(event
, ctx
);
2575 perf_event_set_state(event
, state
);
2579 * Cross CPU call to disable a performance event
2581 static void __perf_event_disable(struct perf_event
*event
,
2582 struct perf_cpu_context
*cpuctx
,
2583 struct perf_event_context
*ctx
,
2586 if (event
->state
< PERF_EVENT_STATE_INACTIVE
)
2589 perf_pmu_disable(event
->pmu_ctx
->pmu
);
2590 ctx_time_update_event(ctx
, event
);
2593 * When disabling a group leader, the whole group becomes ineligible
2594 * to run, so schedule out the full group.
2596 if (event
== event
->group_leader
)
2597 group_sched_out(event
, ctx
);
2600 * But only mark the leader OFF; the siblings will remain
2603 __event_disable(event
, ctx
, PERF_EVENT_STATE_OFF
);
2605 perf_pmu_enable(event
->pmu_ctx
->pmu
);
2611 * If event->ctx is a cloned context, callers must make sure that
2612 * every task struct that event->ctx->task could possibly point to
2613 * remains valid. This condition is satisfied when called through
2614 * perf_event_for_each_child or perf_event_for_each because they
2615 * hold the top-level event's child_mutex, so any descendant that
2616 * goes to exit will block in perf_event_exit_event().
2618 * When called from perf_pending_disable it's OK because event->ctx
2619 * is the current context on this CPU and preemption is disabled,
2620 * hence we can't get into perf_event_task_sched_out for this context.
2622 static void _perf_event_disable(struct perf_event
*event
)
2624 struct perf_event_context
*ctx
= event
->ctx
;
2626 raw_spin_lock_irq(&ctx
->lock
);
2627 if (event
->state
<= PERF_EVENT_STATE_OFF
) {
2628 raw_spin_unlock_irq(&ctx
->lock
);
2631 raw_spin_unlock_irq(&ctx
->lock
);
2633 event_function_call(event
, __perf_event_disable
, NULL
);
2636 void perf_event_disable_local(struct perf_event
*event
)
2638 event_function_local(event
, __perf_event_disable
, NULL
);
2642 * Strictly speaking kernel users cannot create groups and therefore this
2643 * interface does not need the perf_event_ctx_lock() magic.
2645 void perf_event_disable(struct perf_event
*event
)
2647 struct perf_event_context
*ctx
;
2649 ctx
= perf_event_ctx_lock(event
);
2650 _perf_event_disable(event
);
2651 perf_event_ctx_unlock(event
, ctx
);
2653 EXPORT_SYMBOL_GPL(perf_event_disable
);
2655 void perf_event_disable_inatomic(struct perf_event
*event
)
2657 event
->pending_disable
= 1;
2658 irq_work_queue(&event
->pending_disable_irq
);
2661 #define MAX_INTERRUPTS (~0ULL)
2663 static void perf_log_throttle(struct perf_event
*event
, int enable
);
2664 static void perf_log_itrace_start(struct perf_event
*event
);
2666 static void perf_event_unthrottle(struct perf_event
*event
, bool start
)
2668 event
->hw
.interrupts
= 0;
2670 event
->pmu
->start(event
, 0);
2671 if (event
== event
->group_leader
)
2672 perf_log_throttle(event
, 1);
2675 static void perf_event_throttle(struct perf_event
*event
)
2677 event
->hw
.interrupts
= MAX_INTERRUPTS
;
2678 event
->pmu
->stop(event
, 0);
2679 if (event
== event
->group_leader
)
2680 perf_log_throttle(event
, 0);
2683 static void perf_event_unthrottle_group(struct perf_event
*event
, bool skip_start_event
)
2685 struct perf_event
*sibling
, *leader
= event
->group_leader
;
2687 perf_event_unthrottle(leader
, skip_start_event
? leader
!= event
: true);
2688 for_each_sibling_event(sibling
, leader
)
2689 perf_event_unthrottle(sibling
, skip_start_event
? sibling
!= event
: true);
2692 static void perf_event_throttle_group(struct perf_event
*event
)
2694 struct perf_event
*sibling
, *leader
= event
->group_leader
;
2696 perf_event_throttle(leader
);
2697 for_each_sibling_event(sibling
, leader
)
2698 perf_event_throttle(sibling
);
2702 event_sched_in(struct perf_event
*event
, struct perf_event_context
*ctx
)
2704 struct perf_event_pmu_context
*epc
= event
->pmu_ctx
;
2705 struct perf_cpu_pmu_context
*cpc
= this_cpc(epc
->pmu
);
2708 WARN_ON_ONCE(event
->ctx
!= ctx
);
2710 lockdep_assert_held(&ctx
->lock
);
2712 if (event
->state
<= PERF_EVENT_STATE_OFF
)
2715 WRITE_ONCE(event
->oncpu
, smp_processor_id());
2717 * Order event::oncpu write to happen before the ACTIVE state is
2718 * visible. This allows perf_event_{stop,read}() to observe the correct
2719 * ->oncpu if it sees ACTIVE.
2722 perf_event_set_state(event
, PERF_EVENT_STATE_ACTIVE
);
2725 * Unthrottle events, since we scheduled we might have missed several
2726 * ticks already, also for a heavily scheduling task there is little
2727 * guarantee it'll get a tick in a timely manner.
2729 if (unlikely(event
->hw
.interrupts
== MAX_INTERRUPTS
))
2730 perf_event_unthrottle(event
, false);
2732 perf_pmu_disable(event
->pmu
);
2734 perf_log_itrace_start(event
);
2736 if (event
->pmu
->add(event
, PERF_EF_START
)) {
2737 perf_event_set_state(event
, PERF_EVENT_STATE_INACTIVE
);
2743 if (!is_software_event(event
))
2744 cpc
->active_oncpu
++;
2745 if (is_event_in_freq_mode(event
)) {
2749 if (event
->attr
.exclusive
)
2753 perf_pmu_enable(event
->pmu
);
2759 group_sched_in(struct perf_event
*group_event
, struct perf_event_context
*ctx
)
2761 struct perf_event
*event
, *partial_group
= NULL
;
2762 struct pmu
*pmu
= group_event
->pmu_ctx
->pmu
;
2764 if (group_event
->state
== PERF_EVENT_STATE_OFF
)
2767 pmu
->start_txn(pmu
, PERF_PMU_TXN_ADD
);
2769 if (event_sched_in(group_event
, ctx
))
2773 * Schedule in siblings as one group (if any):
2775 for_each_sibling_event(event
, group_event
) {
2776 if (event_sched_in(event
, ctx
)) {
2777 partial_group
= event
;
2782 if (!pmu
->commit_txn(pmu
))
2787 * Groups can be scheduled in as one unit only, so undo any
2788 * partial group before returning:
2789 * The events up to the failed event are scheduled out normally.
2791 for_each_sibling_event(event
, group_event
) {
2792 if (event
== partial_group
)
2795 event_sched_out(event
, ctx
);
2797 event_sched_out(group_event
, ctx
);
2800 pmu
->cancel_txn(pmu
);
2805 * Work out whether we can put this event group on the CPU now.
2807 static int group_can_go_on(struct perf_event
*event
, int can_add_hw
)
2809 struct perf_event_pmu_context
*epc
= event
->pmu_ctx
;
2810 struct perf_cpu_pmu_context
*cpc
= this_cpc(epc
->pmu
);
2813 * Groups consisting entirely of software events can always go on.
2815 if (event
->group_caps
& PERF_EV_CAP_SOFTWARE
)
2818 * If an exclusive group is already on, no other hardware
2824 * If this group is exclusive and there are already
2825 * events on the CPU, it can't go on.
2827 if (event
->attr
.exclusive
&& !list_empty(get_event_list(event
)))
2830 * Otherwise, try to add it if all previous groups were able
2836 static void add_event_to_ctx(struct perf_event
*event
,
2837 struct perf_event_context
*ctx
)
2839 list_add_event(event
, ctx
);
2840 perf_group_attach(event
);
2843 static void task_ctx_sched_out(struct perf_event_context
*ctx
,
2845 enum event_type_t event_type
)
2847 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
2849 if (!cpuctx
->task_ctx
)
2852 if (WARN_ON_ONCE(ctx
!= cpuctx
->task_ctx
))
2855 ctx_sched_out(ctx
, pmu
, event_type
);
2858 static void perf_event_sched_in(struct perf_cpu_context
*cpuctx
,
2859 struct perf_event_context
*ctx
,
2862 ctx_sched_in(&cpuctx
->ctx
, pmu
, EVENT_PINNED
);
2864 ctx_sched_in(ctx
, pmu
, EVENT_PINNED
);
2865 ctx_sched_in(&cpuctx
->ctx
, pmu
, EVENT_FLEXIBLE
);
2867 ctx_sched_in(ctx
, pmu
, EVENT_FLEXIBLE
);
2871 * We want to maintain the following priority of scheduling:
2872 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2873 * - task pinned (EVENT_PINNED)
2874 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2875 * - task flexible (EVENT_FLEXIBLE).
2877 * In order to avoid unscheduling and scheduling back in everything every
2878 * time an event is added, only do it for the groups of equal priority and
2881 * This can be called after a batch operation on task events, in which case
2882 * event_type is a bit mask of the types of events involved. For CPU events,
2883 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2885 static void ctx_resched(struct perf_cpu_context
*cpuctx
,
2886 struct perf_event_context
*task_ctx
,
2887 struct pmu
*pmu
, enum event_type_t event_type
)
2889 bool cpu_event
= !!(event_type
& EVENT_CPU
);
2890 struct perf_event_pmu_context
*epc
;
2893 * If pinned groups are involved, flexible groups also need to be
2896 if (event_type
& EVENT_PINNED
)
2897 event_type
|= EVENT_FLEXIBLE
;
2899 event_type
&= EVENT_ALL
;
2901 for_each_epc(epc
, &cpuctx
->ctx
, pmu
, false)
2902 perf_pmu_disable(epc
->pmu
);
2905 for_each_epc(epc
, task_ctx
, pmu
, false)
2906 perf_pmu_disable(epc
->pmu
);
2908 task_ctx_sched_out(task_ctx
, pmu
, event_type
);
2912 * Decide which cpu ctx groups to schedule out based on the types
2913 * of events that caused rescheduling:
2914 * - EVENT_CPU: schedule out corresponding groups;
2915 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2916 * - otherwise, do nothing more.
2919 ctx_sched_out(&cpuctx
->ctx
, pmu
, event_type
);
2920 else if (event_type
& EVENT_PINNED
)
2921 ctx_sched_out(&cpuctx
->ctx
, pmu
, EVENT_FLEXIBLE
);
2923 perf_event_sched_in(cpuctx
, task_ctx
, pmu
);
2925 for_each_epc(epc
, &cpuctx
->ctx
, pmu
, false)
2926 perf_pmu_enable(epc
->pmu
);
2929 for_each_epc(epc
, task_ctx
, pmu
, false)
2930 perf_pmu_enable(epc
->pmu
);
2934 void perf_pmu_resched(struct pmu
*pmu
)
2936 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
2937 struct perf_event_context
*task_ctx
= cpuctx
->task_ctx
;
2939 perf_ctx_lock(cpuctx
, task_ctx
);
2940 ctx_resched(cpuctx
, task_ctx
, pmu
, EVENT_ALL
|EVENT_CPU
);
2941 perf_ctx_unlock(cpuctx
, task_ctx
);
2945 * Cross CPU call to install and enable a performance event
2947 * Very similar to remote_function() + event_function() but cannot assume that
2948 * things like ctx->is_active and cpuctx->task_ctx are set.
2950 static int __perf_install_in_context(void *info
)
2952 struct perf_event
*event
= info
;
2953 struct perf_event_context
*ctx
= event
->ctx
;
2954 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
2955 struct perf_event_context
*task_ctx
= cpuctx
->task_ctx
;
2956 bool reprogram
= true;
2959 raw_spin_lock(&cpuctx
->ctx
.lock
);
2961 raw_spin_lock(&ctx
->lock
);
2964 reprogram
= (ctx
->task
== current
);
2967 * If the task is running, it must be running on this CPU,
2968 * otherwise we cannot reprogram things.
2970 * If its not running, we don't care, ctx->lock will
2971 * serialize against it becoming runnable.
2973 if (task_curr(ctx
->task
) && !reprogram
) {
2978 WARN_ON_ONCE(reprogram
&& cpuctx
->task_ctx
&& cpuctx
->task_ctx
!= ctx
);
2979 } else if (task_ctx
) {
2980 raw_spin_lock(&task_ctx
->lock
);
2983 #ifdef CONFIG_CGROUP_PERF
2984 if (event
->state
> PERF_EVENT_STATE_OFF
&& is_cgroup_event(event
)) {
2986 * If the current cgroup doesn't match the event's
2987 * cgroup, we should not try to schedule it.
2989 struct perf_cgroup
*cgrp
= perf_cgroup_from_task(current
, ctx
);
2990 reprogram
= cgroup_is_descendant(cgrp
->css
.cgroup
,
2991 event
->cgrp
->css
.cgroup
);
2996 ctx_time_freeze(cpuctx
, ctx
);
2997 add_event_to_ctx(event
, ctx
);
2998 ctx_resched(cpuctx
, task_ctx
, event
->pmu_ctx
->pmu
,
2999 get_event_type(event
));
3001 add_event_to_ctx(event
, ctx
);
3005 perf_ctx_unlock(cpuctx
, task_ctx
);
3010 static bool exclusive_event_installable(struct perf_event
*event
,
3011 struct perf_event_context
*ctx
);
3014 * Attach a performance event to a context.
3016 * Very similar to event_function_call, see comment there.
3019 perf_install_in_context(struct perf_event_context
*ctx
,
3020 struct perf_event
*event
,
3023 struct task_struct
*task
= READ_ONCE(ctx
->task
);
3025 lockdep_assert_held(&ctx
->mutex
);
3027 WARN_ON_ONCE(!exclusive_event_installable(event
, ctx
));
3029 if (event
->cpu
!= -1)
3030 WARN_ON_ONCE(event
->cpu
!= cpu
);
3033 * Ensures that if we can observe event->ctx, both the event and ctx
3034 * will be 'complete'. See perf_iterate_sb_cpu().
3036 smp_store_release(&event
->ctx
, ctx
);
3039 * perf_event_attr::disabled events will not run and can be initialized
3040 * without IPI. Except when this is the first event for the context, in
3041 * that case we need the magic of the IPI to set ctx->is_active.
3043 * The IOC_ENABLE that is sure to follow the creation of a disabled
3044 * event will issue the IPI and reprogram the hardware.
3046 if (__perf_effective_state(event
) == PERF_EVENT_STATE_OFF
&&
3047 ctx
->nr_events
&& !is_cgroup_event(event
)) {
3048 raw_spin_lock_irq(&ctx
->lock
);
3049 if (ctx
->task
== TASK_TOMBSTONE
) {
3050 raw_spin_unlock_irq(&ctx
->lock
);
3053 add_event_to_ctx(event
, ctx
);
3054 raw_spin_unlock_irq(&ctx
->lock
);
3059 cpu_function_call(cpu
, __perf_install_in_context
, event
);
3064 * Should not happen, we validate the ctx is still alive before calling.
3066 if (WARN_ON_ONCE(task
== TASK_TOMBSTONE
))
3070 * Installing events is tricky because we cannot rely on ctx->is_active
3071 * to be set in case this is the nr_events 0 -> 1 transition.
3073 * Instead we use task_curr(), which tells us if the task is running.
3074 * However, since we use task_curr() outside of rq::lock, we can race
3075 * against the actual state. This means the result can be wrong.
3077 * If we get a false positive, we retry, this is harmless.
3079 * If we get a false negative, things are complicated. If we are after
3080 * perf_event_context_sched_in() ctx::lock will serialize us, and the
3081 * value must be correct. If we're before, it doesn't matter since
3082 * perf_event_context_sched_in() will program the counter.
3084 * However, this hinges on the remote context switch having observed
3085 * our task->perf_event_ctxp[] store, such that it will in fact take
3086 * ctx::lock in perf_event_context_sched_in().
3088 * We do this by task_function_call(), if the IPI fails to hit the task
3089 * we know any future context switch of task must see the
3090 * perf_event_ctpx[] store.
3094 * This smp_mb() orders the task->perf_event_ctxp[] store with the
3095 * task_cpu() load, such that if the IPI then does not find the task
3096 * running, a future context switch of that task must observe the
3101 if (!task_function_call(task
, __perf_install_in_context
, event
))
3104 raw_spin_lock_irq(&ctx
->lock
);
3106 if (WARN_ON_ONCE(task
== TASK_TOMBSTONE
)) {
3108 * Cannot happen because we already checked above (which also
3109 * cannot happen), and we hold ctx->mutex, which serializes us
3110 * against perf_event_exit_task_context().
3112 raw_spin_unlock_irq(&ctx
->lock
);
3116 * If the task is not running, ctx->lock will avoid it becoming so,
3117 * thus we can safely install the event.
3119 if (task_curr(task
)) {
3120 raw_spin_unlock_irq(&ctx
->lock
);
3123 add_event_to_ctx(event
, ctx
);
3124 raw_spin_unlock_irq(&ctx
->lock
);
3128 * Cross CPU call to enable a performance event
3130 static void __perf_event_enable(struct perf_event
*event
,
3131 struct perf_cpu_context
*cpuctx
,
3132 struct perf_event_context
*ctx
,
3135 struct perf_event
*leader
= event
->group_leader
;
3136 struct perf_event_context
*task_ctx
;
3138 if (event
->state
>= PERF_EVENT_STATE_INACTIVE
||
3139 event
->state
<= PERF_EVENT_STATE_ERROR
)
3142 ctx_time_freeze(cpuctx
, ctx
);
3144 perf_event_set_state(event
, PERF_EVENT_STATE_INACTIVE
);
3145 perf_cgroup_event_enable(event
, ctx
);
3147 if (!ctx
->is_active
)
3150 if (!event_filter_match(event
))
3154 * If the event is in a group and isn't the group leader,
3155 * then don't put it on unless the group is on.
3157 if (leader
!= event
&& leader
->state
!= PERF_EVENT_STATE_ACTIVE
)
3160 task_ctx
= cpuctx
->task_ctx
;
3162 WARN_ON_ONCE(task_ctx
!= ctx
);
3164 ctx_resched(cpuctx
, task_ctx
, event
->pmu_ctx
->pmu
, get_event_type(event
));
3170 * If event->ctx is a cloned context, callers must make sure that
3171 * every task struct that event->ctx->task could possibly point to
3172 * remains valid. This condition is satisfied when called through
3173 * perf_event_for_each_child or perf_event_for_each as described
3174 * for perf_event_disable.
3176 static void _perf_event_enable(struct perf_event
*event
)
3178 struct perf_event_context
*ctx
= event
->ctx
;
3180 raw_spin_lock_irq(&ctx
->lock
);
3181 if (event
->state
>= PERF_EVENT_STATE_INACTIVE
||
3182 event
->state
< PERF_EVENT_STATE_ERROR
) {
3184 raw_spin_unlock_irq(&ctx
->lock
);
3189 * If the event is in error state, clear that first.
3191 * That way, if we see the event in error state below, we know that it
3192 * has gone back into error state, as distinct from the task having
3193 * been scheduled away before the cross-call arrived.
3195 if (event
->state
== PERF_EVENT_STATE_ERROR
) {
3197 * Detached SIBLING events cannot leave ERROR state.
3199 if (event
->event_caps
& PERF_EV_CAP_SIBLING
&&
3200 event
->group_leader
== event
)
3203 event
->state
= PERF_EVENT_STATE_OFF
;
3205 raw_spin_unlock_irq(&ctx
->lock
);
3207 event_function_call(event
, __perf_event_enable
, NULL
);
3211 * See perf_event_disable();
3213 void perf_event_enable(struct perf_event
*event
)
3215 struct perf_event_context
*ctx
;
3217 ctx
= perf_event_ctx_lock(event
);
3218 _perf_event_enable(event
);
3219 perf_event_ctx_unlock(event
, ctx
);
3221 EXPORT_SYMBOL_GPL(perf_event_enable
);
3223 struct stop_event_data
{
3224 struct perf_event
*event
;
3225 unsigned int restart
;
3228 static int __perf_event_stop(void *info
)
3230 struct stop_event_data
*sd
= info
;
3231 struct perf_event
*event
= sd
->event
;
3233 /* if it's already INACTIVE, do nothing */
3234 if (READ_ONCE(event
->state
) != PERF_EVENT_STATE_ACTIVE
)
3237 /* matches smp_wmb() in event_sched_in() */
3241 * There is a window with interrupts enabled before we get here,
3242 * so we need to check again lest we try to stop another CPU's event.
3244 if (READ_ONCE(event
->oncpu
) != smp_processor_id())
3247 event
->pmu
->stop(event
, PERF_EF_UPDATE
);
3250 * May race with the actual stop (through perf_pmu_output_stop()),
3251 * but it is only used for events with AUX ring buffer, and such
3252 * events will refuse to restart because of rb::aux_mmap_count==0,
3253 * see comments in perf_aux_output_begin().
3255 * Since this is happening on an event-local CPU, no trace is lost
3259 event
->pmu
->start(event
, 0);
3264 static int perf_event_stop(struct perf_event
*event
, int restart
)
3266 struct stop_event_data sd
= {
3273 if (READ_ONCE(event
->state
) != PERF_EVENT_STATE_ACTIVE
)
3276 /* matches smp_wmb() in event_sched_in() */
3280 * We only want to restart ACTIVE events, so if the event goes
3281 * inactive here (event->oncpu==-1), there's nothing more to do;
3282 * fall through with ret==-ENXIO.
3284 ret
= cpu_function_call(READ_ONCE(event
->oncpu
),
3285 __perf_event_stop
, &sd
);
3286 } while (ret
== -EAGAIN
);
3292 * In order to contain the amount of racy and tricky in the address filter
3293 * configuration management, it is a two part process:
3295 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3296 * we update the addresses of corresponding vmas in
3297 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3298 * (p2) when an event is scheduled in (pmu::add), it calls
3299 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3300 * if the generation has changed since the previous call.
3302 * If (p1) happens while the event is active, we restart it to force (p2).
3304 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3305 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3307 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3308 * registered mapping, called for every new mmap(), with mm::mmap_lock down
3310 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3313 void perf_event_addr_filters_sync(struct perf_event
*event
)
3315 struct perf_addr_filters_head
*ifh
= perf_event_addr_filters(event
);
3317 if (!has_addr_filter(event
))
3320 raw_spin_lock(&ifh
->lock
);
3321 if (event
->addr_filters_gen
!= event
->hw
.addr_filters_gen
) {
3322 event
->pmu
->addr_filters_sync(event
);
3323 event
->hw
.addr_filters_gen
= event
->addr_filters_gen
;
3325 raw_spin_unlock(&ifh
->lock
);
3327 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync
);
3329 static int _perf_event_refresh(struct perf_event
*event
, int refresh
)
3332 * not supported on inherited events
3334 if (event
->attr
.inherit
|| !is_sampling_event(event
))
3337 atomic_add(refresh
, &event
->event_limit
);
3338 _perf_event_enable(event
);
3344 * See perf_event_disable()
3346 int perf_event_refresh(struct perf_event
*event
, int refresh
)
3348 struct perf_event_context
*ctx
;
3351 ctx
= perf_event_ctx_lock(event
);
3352 ret
= _perf_event_refresh(event
, refresh
);
3353 perf_event_ctx_unlock(event
, ctx
);
3357 EXPORT_SYMBOL_GPL(perf_event_refresh
);
3359 static int perf_event_modify_breakpoint(struct perf_event
*bp
,
3360 struct perf_event_attr
*attr
)
3364 _perf_event_disable(bp
);
3366 err
= modify_user_hw_breakpoint_check(bp
, attr
, true);
3368 if (!bp
->attr
.disabled
)
3369 _perf_event_enable(bp
);
3375 * Copy event-type-independent attributes that may be modified.
3377 static void perf_event_modify_copy_attr(struct perf_event_attr
*to
,
3378 const struct perf_event_attr
*from
)
3380 to
->sig_data
= from
->sig_data
;
3383 static int perf_event_modify_attr(struct perf_event
*event
,
3384 struct perf_event_attr
*attr
)
3386 int (*func
)(struct perf_event
*, struct perf_event_attr
*);
3387 struct perf_event
*child
;
3390 if (event
->attr
.type
!= attr
->type
)
3393 switch (event
->attr
.type
) {
3394 case PERF_TYPE_BREAKPOINT
:
3395 func
= perf_event_modify_breakpoint
;
3398 /* Place holder for future additions. */
3402 WARN_ON_ONCE(event
->ctx
->parent_ctx
);
3404 mutex_lock(&event
->child_mutex
);
3406 * Event-type-independent attributes must be copied before event-type
3407 * modification, which will validate that final attributes match the
3408 * source attributes after all relevant attributes have been copied.
3410 perf_event_modify_copy_attr(&event
->attr
, attr
);
3411 err
= func(event
, attr
);
3414 list_for_each_entry(child
, &event
->child_list
, child_list
) {
3415 perf_event_modify_copy_attr(&child
->attr
, attr
);
3416 err
= func(child
, attr
);
3421 mutex_unlock(&event
->child_mutex
);
3425 static void __pmu_ctx_sched_out(struct perf_event_pmu_context
*pmu_ctx
,
3426 enum event_type_t event_type
)
3428 struct perf_event_context
*ctx
= pmu_ctx
->ctx
;
3429 struct perf_event
*event
, *tmp
;
3430 struct pmu
*pmu
= pmu_ctx
->pmu
;
3432 if (ctx
->task
&& !(ctx
->is_active
& EVENT_ALL
)) {
3433 struct perf_cpu_pmu_context
*cpc
= this_cpc(pmu
);
3435 WARN_ON_ONCE(cpc
->task_epc
&& cpc
->task_epc
!= pmu_ctx
);
3436 cpc
->task_epc
= NULL
;
3439 if (!(event_type
& EVENT_ALL
))
3442 perf_pmu_disable(pmu
);
3443 if (event_type
& EVENT_PINNED
) {
3444 list_for_each_entry_safe(event
, tmp
,
3445 &pmu_ctx
->pinned_active
,
3447 group_sched_out(event
, ctx
);
3450 if (event_type
& EVENT_FLEXIBLE
) {
3451 list_for_each_entry_safe(event
, tmp
,
3452 &pmu_ctx
->flexible_active
,
3454 group_sched_out(event
, ctx
);
3456 * Since we cleared EVENT_FLEXIBLE, also clear
3457 * rotate_necessary, is will be reset by
3458 * ctx_flexible_sched_in() when needed.
3460 pmu_ctx
->rotate_necessary
= 0;
3462 perf_pmu_enable(pmu
);
3466 * Be very careful with the @pmu argument since this will change ctx state.
3467 * The @pmu argument works for ctx_resched(), because that is symmetric in
3468 * ctx_sched_out() / ctx_sched_in() usage and the ctx state ends up invariant.
3470 * However, if you were to be asymmetrical, you could end up with messed up
3471 * state, eg. ctx->is_active cleared even though most EPCs would still actually
3475 ctx_sched_out(struct perf_event_context
*ctx
, struct pmu
*pmu
, enum event_type_t event_type
)
3477 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
3478 struct perf_event_pmu_context
*pmu_ctx
;
3479 int is_active
= ctx
->is_active
;
3480 bool cgroup
= event_type
& EVENT_CGROUP
;
3482 event_type
&= ~EVENT_CGROUP
;
3484 lockdep_assert_held(&ctx
->lock
);
3486 if (likely(!ctx
->nr_events
)) {
3488 * See __perf_remove_from_context().
3490 WARN_ON_ONCE(ctx
->is_active
);
3492 WARN_ON_ONCE(cpuctx
->task_ctx
);
3497 * Always update time if it was set; not only when it changes.
3498 * Otherwise we can 'forget' to update time for any but the last
3499 * context we sched out. For example:
3501 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3502 * ctx_sched_out(.event_type = EVENT_PINNED)
3504 * would only update time for the pinned events.
3506 __ctx_time_update(cpuctx
, ctx
, ctx
== &cpuctx
->ctx
);
3509 * CPU-release for the below ->is_active store,
3510 * see __load_acquire() in perf_event_time_now()
3513 ctx
->is_active
&= ~event_type
;
3515 if (!(ctx
->is_active
& EVENT_ALL
)) {
3517 * For FROZEN, preserve TIME|FROZEN such that perf_event_time_now()
3518 * does not observe a hole. perf_ctx_unlock() will clean up.
3520 if (ctx
->is_active
& EVENT_FROZEN
)
3521 ctx
->is_active
&= EVENT_TIME_FROZEN
;
3527 WARN_ON_ONCE(cpuctx
->task_ctx
!= ctx
);
3528 if (!(ctx
->is_active
& EVENT_ALL
))
3529 cpuctx
->task_ctx
= NULL
;
3532 is_active
^= ctx
->is_active
; /* changed bits */
3534 for_each_epc(pmu_ctx
, ctx
, pmu
, cgroup
)
3535 __pmu_ctx_sched_out(pmu_ctx
, is_active
);
3539 * Test whether two contexts are equivalent, i.e. whether they have both been
3540 * cloned from the same version of the same context.
3542 * Equivalence is measured using a generation number in the context that is
3543 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3544 * and list_del_event().
3546 static int context_equiv(struct perf_event_context
*ctx1
,
3547 struct perf_event_context
*ctx2
)
3549 lockdep_assert_held(&ctx1
->lock
);
3550 lockdep_assert_held(&ctx2
->lock
);
3552 /* Pinning disables the swap optimization */
3553 if (ctx1
->pin_count
|| ctx2
->pin_count
)
3556 /* If ctx1 is the parent of ctx2 */
3557 if (ctx1
== ctx2
->parent_ctx
&& ctx1
->generation
== ctx2
->parent_gen
)
3560 /* If ctx2 is the parent of ctx1 */
3561 if (ctx1
->parent_ctx
== ctx2
&& ctx1
->parent_gen
== ctx2
->generation
)
3565 * If ctx1 and ctx2 have the same parent; we flatten the parent
3566 * hierarchy, see perf_event_init_context().
3568 if (ctx1
->parent_ctx
&& ctx1
->parent_ctx
== ctx2
->parent_ctx
&&
3569 ctx1
->parent_gen
== ctx2
->parent_gen
)
3576 static void __perf_event_sync_stat(struct perf_event
*event
,
3577 struct perf_event
*next_event
)
3581 if (!event
->attr
.inherit_stat
)
3585 * Update the event value, we cannot use perf_event_read()
3586 * because we're in the middle of a context switch and have IRQs
3587 * disabled, which upsets smp_call_function_single(), however
3588 * we know the event must be on the current CPU, therefore we
3589 * don't need to use it.
3591 perf_pmu_read(event
);
3593 perf_event_update_time(event
);
3596 * In order to keep per-task stats reliable we need to flip the event
3597 * values when we flip the contexts.
3599 value
= local64_read(&next_event
->count
);
3600 value
= local64_xchg(&event
->count
, value
);
3601 local64_set(&next_event
->count
, value
);
3603 swap(event
->total_time_enabled
, next_event
->total_time_enabled
);
3604 swap(event
->total_time_running
, next_event
->total_time_running
);
3607 * Since we swizzled the values, update the user visible data too.
3609 perf_event_update_userpage(event
);
3610 perf_event_update_userpage(next_event
);
3613 static void perf_event_sync_stat(struct perf_event_context
*ctx
,
3614 struct perf_event_context
*next_ctx
)
3616 struct perf_event
*event
, *next_event
;
3621 update_context_time(ctx
);
3623 event
= list_first_entry(&ctx
->event_list
,
3624 struct perf_event
, event_entry
);
3626 next_event
= list_first_entry(&next_ctx
->event_list
,
3627 struct perf_event
, event_entry
);
3629 while (&event
->event_entry
!= &ctx
->event_list
&&
3630 &next_event
->event_entry
!= &next_ctx
->event_list
) {
3632 __perf_event_sync_stat(event
, next_event
);
3634 event
= list_next_entry(event
, event_entry
);
3635 next_event
= list_next_entry(next_event
, event_entry
);
3639 static void perf_ctx_sched_task_cb(struct perf_event_context
*ctx
,
3640 struct task_struct
*task
, bool sched_in
)
3642 struct perf_event_pmu_context
*pmu_ctx
;
3643 struct perf_cpu_pmu_context
*cpc
;
3645 list_for_each_entry(pmu_ctx
, &ctx
->pmu_ctx_list
, pmu_ctx_entry
) {
3646 cpc
= this_cpc(pmu_ctx
->pmu
);
3648 if (cpc
->sched_cb_usage
&& pmu_ctx
->pmu
->sched_task
)
3649 pmu_ctx
->pmu
->sched_task(pmu_ctx
, task
, sched_in
);
3654 perf_event_context_sched_out(struct task_struct
*task
, struct task_struct
*next
)
3656 struct perf_event_context
*ctx
= task
->perf_event_ctxp
;
3657 struct perf_event_context
*next_ctx
;
3658 struct perf_event_context
*parent
, *next_parent
;
3665 next_ctx
= rcu_dereference(next
->perf_event_ctxp
);
3669 parent
= rcu_dereference(ctx
->parent_ctx
);
3670 next_parent
= rcu_dereference(next_ctx
->parent_ctx
);
3672 /* If neither context have a parent context; they cannot be clones. */
3673 if (!parent
&& !next_parent
)
3676 if (next_parent
== ctx
|| next_ctx
== parent
|| next_parent
== parent
) {
3678 * Looks like the two contexts are clones, so we might be
3679 * able to optimize the context switch. We lock both
3680 * contexts and check that they are clones under the
3681 * lock (including re-checking that neither has been
3682 * uncloned in the meantime). It doesn't matter which
3683 * order we take the locks because no other cpu could
3684 * be trying to lock both of these tasks.
3686 raw_spin_lock(&ctx
->lock
);
3687 raw_spin_lock_nested(&next_ctx
->lock
, SINGLE_DEPTH_NESTING
);
3688 if (context_equiv(ctx
, next_ctx
)) {
3690 perf_ctx_disable(ctx
, false);
3692 /* PMIs are disabled; ctx->nr_no_switch_fast is stable. */
3693 if (local_read(&ctx
->nr_no_switch_fast
) ||
3694 local_read(&next_ctx
->nr_no_switch_fast
)) {
3696 * Must not swap out ctx when there's pending
3697 * events that rely on the ctx->task relation.
3699 * Likewise, when a context contains inherit +
3700 * SAMPLE_READ events they should be switched
3701 * out using the slow path so that they are
3702 * treated as if they were distinct contexts.
3704 raw_spin_unlock(&next_ctx
->lock
);
3709 WRITE_ONCE(ctx
->task
, next
);
3710 WRITE_ONCE(next_ctx
->task
, task
);
3712 perf_ctx_sched_task_cb(ctx
, task
, false);
3714 perf_ctx_enable(ctx
, false);
3717 * RCU_INIT_POINTER here is safe because we've not
3718 * modified the ctx and the above modification of
3719 * ctx->task is immaterial since this value is
3720 * always verified under ctx->lock which we're now
3723 RCU_INIT_POINTER(task
->perf_event_ctxp
, next_ctx
);
3724 RCU_INIT_POINTER(next
->perf_event_ctxp
, ctx
);
3728 perf_event_sync_stat(ctx
, next_ctx
);
3730 raw_spin_unlock(&next_ctx
->lock
);
3731 raw_spin_unlock(&ctx
->lock
);
3737 raw_spin_lock(&ctx
->lock
);
3738 perf_ctx_disable(ctx
, false);
3741 perf_ctx_sched_task_cb(ctx
, task
, false);
3742 task_ctx_sched_out(ctx
, NULL
, EVENT_ALL
);
3744 perf_ctx_enable(ctx
, false);
3745 raw_spin_unlock(&ctx
->lock
);
3749 static DEFINE_PER_CPU(struct list_head
, sched_cb_list
);
3750 static DEFINE_PER_CPU(int, perf_sched_cb_usages
);
3752 void perf_sched_cb_dec(struct pmu
*pmu
)
3754 struct perf_cpu_pmu_context
*cpc
= this_cpc(pmu
);
3756 this_cpu_dec(perf_sched_cb_usages
);
3759 if (!--cpc
->sched_cb_usage
)
3760 list_del(&cpc
->sched_cb_entry
);
3764 void perf_sched_cb_inc(struct pmu
*pmu
)
3766 struct perf_cpu_pmu_context
*cpc
= this_cpc(pmu
);
3768 if (!cpc
->sched_cb_usage
++)
3769 list_add(&cpc
->sched_cb_entry
, this_cpu_ptr(&sched_cb_list
));
3772 this_cpu_inc(perf_sched_cb_usages
);
3776 * This function provides the context switch callback to the lower code
3777 * layer. It is invoked ONLY when the context switch callback is enabled.
3779 * This callback is relevant even to per-cpu events; for example multi event
3780 * PEBS requires this to provide PID/TID information. This requires we flush
3781 * all queued PEBS records before we context switch to a new task.
3783 static void __perf_pmu_sched_task(struct perf_cpu_pmu_context
*cpc
,
3784 struct task_struct
*task
, bool sched_in
)
3786 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
3791 /* software PMUs will not have sched_task */
3792 if (WARN_ON_ONCE(!pmu
->sched_task
))
3795 perf_ctx_lock(cpuctx
, cpuctx
->task_ctx
);
3796 perf_pmu_disable(pmu
);
3798 pmu
->sched_task(cpc
->task_epc
, task
, sched_in
);
3800 perf_pmu_enable(pmu
);
3801 perf_ctx_unlock(cpuctx
, cpuctx
->task_ctx
);
3804 static void perf_pmu_sched_task(struct task_struct
*prev
,
3805 struct task_struct
*next
,
3808 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
3809 struct perf_cpu_pmu_context
*cpc
;
3811 /* cpuctx->task_ctx will be handled in perf_event_context_sched_in/out */
3812 if (prev
== next
|| cpuctx
->task_ctx
)
3815 list_for_each_entry(cpc
, this_cpu_ptr(&sched_cb_list
), sched_cb_entry
)
3816 __perf_pmu_sched_task(cpc
, sched_in
? next
: prev
, sched_in
);
3819 static void perf_event_switch(struct task_struct
*task
,
3820 struct task_struct
*next_prev
, bool sched_in
);
3823 * Called from scheduler to remove the events of the current task,
3824 * with interrupts disabled.
3826 * We stop each event and update the event value in event->count.
3828 * This does not protect us against NMI, but disable()
3829 * sets the disabled bit in the control field of event _before_
3830 * accessing the event control register. If a NMI hits, then it will
3831 * not restart the event.
3833 void __perf_event_task_sched_out(struct task_struct
*task
,
3834 struct task_struct
*next
)
3836 if (__this_cpu_read(perf_sched_cb_usages
))
3837 perf_pmu_sched_task(task
, next
, false);
3839 if (atomic_read(&nr_switch_events
))
3840 perf_event_switch(task
, next
, false);
3842 perf_event_context_sched_out(task
, next
);
3845 * if cgroup events exist on this CPU, then we need
3846 * to check if we have to switch out PMU state.
3847 * cgroup event are system-wide mode only
3849 perf_cgroup_switch(next
);
3852 static bool perf_less_group_idx(const void *l
, const void *r
, void __always_unused
*args
)
3854 const struct perf_event
*le
= *(const struct perf_event
**)l
;
3855 const struct perf_event
*re
= *(const struct perf_event
**)r
;
3857 return le
->group_index
< re
->group_index
;
3860 DEFINE_MIN_HEAP(struct perf_event
*, perf_event_min_heap
);
3862 static const struct min_heap_callbacks perf_min_heap
= {
3863 .less
= perf_less_group_idx
,
3867 static void __heap_add(struct perf_event_min_heap
*heap
, struct perf_event
*event
)
3869 struct perf_event
**itrs
= heap
->data
;
3872 itrs
[heap
->nr
] = event
;
3877 static void __link_epc(struct perf_event_pmu_context
*pmu_ctx
)
3879 struct perf_cpu_pmu_context
*cpc
;
3881 if (!pmu_ctx
->ctx
->task
)
3884 cpc
= this_cpc(pmu_ctx
->pmu
);
3885 WARN_ON_ONCE(cpc
->task_epc
&& cpc
->task_epc
!= pmu_ctx
);
3886 cpc
->task_epc
= pmu_ctx
;
3889 static noinline
int visit_groups_merge(struct perf_event_context
*ctx
,
3890 struct perf_event_groups
*groups
, int cpu
,
3892 int (*func
)(struct perf_event
*, void *),
3895 #ifdef CONFIG_CGROUP_PERF
3896 struct cgroup_subsys_state
*css
= NULL
;
3898 struct perf_cpu_context
*cpuctx
= NULL
;
3899 /* Space for per CPU and/or any CPU event iterators. */
3900 struct perf_event
*itrs
[2];
3901 struct perf_event_min_heap event_heap
;
3902 struct perf_event
**evt
;
3905 if (pmu
->filter
&& pmu
->filter(pmu
, cpu
))
3909 cpuctx
= this_cpu_ptr(&perf_cpu_context
);
3910 event_heap
= (struct perf_event_min_heap
){
3911 .data
= cpuctx
->heap
,
3913 .size
= cpuctx
->heap_size
,
3916 lockdep_assert_held(&cpuctx
->ctx
.lock
);
3918 #ifdef CONFIG_CGROUP_PERF
3920 css
= &cpuctx
->cgrp
->css
;
3923 event_heap
= (struct perf_event_min_heap
){
3926 .size
= ARRAY_SIZE(itrs
),
3928 /* Events not within a CPU context may be on any CPU. */
3929 __heap_add(&event_heap
, perf_event_groups_first(groups
, -1, pmu
, NULL
));
3931 evt
= event_heap
.data
;
3933 __heap_add(&event_heap
, perf_event_groups_first(groups
, cpu
, pmu
, NULL
));
3935 #ifdef CONFIG_CGROUP_PERF
3936 for (; css
; css
= css
->parent
)
3937 __heap_add(&event_heap
, perf_event_groups_first(groups
, cpu
, pmu
, css
->cgroup
));
3940 if (event_heap
.nr
) {
3941 __link_epc((*evt
)->pmu_ctx
);
3942 perf_assert_pmu_disabled((*evt
)->pmu_ctx
->pmu
);
3945 min_heapify_all_inline(&event_heap
, &perf_min_heap
, NULL
);
3947 while (event_heap
.nr
) {
3948 ret
= func(*evt
, data
);
3952 *evt
= perf_event_groups_next(*evt
, pmu
);
3954 min_heap_sift_down_inline(&event_heap
, 0, &perf_min_heap
, NULL
);
3956 min_heap_pop_inline(&event_heap
, &perf_min_heap
, NULL
);
3963 * Because the userpage is strictly per-event (there is no concept of context,
3964 * so there cannot be a context indirection), every userpage must be updated
3965 * when context time starts :-(
3967 * IOW, we must not miss EVENT_TIME edges.
3969 static inline bool event_update_userpage(struct perf_event
*event
)
3971 if (likely(!atomic_read(&event
->mmap_count
)))
3974 perf_event_update_time(event
);
3975 perf_event_update_userpage(event
);
3980 static inline void group_update_userpage(struct perf_event
*group_event
)
3982 struct perf_event
*event
;
3984 if (!event_update_userpage(group_event
))
3987 for_each_sibling_event(event
, group_event
)
3988 event_update_userpage(event
);
3991 static int merge_sched_in(struct perf_event
*event
, void *data
)
3993 struct perf_event_context
*ctx
= event
->ctx
;
3994 int *can_add_hw
= data
;
3996 if (event
->state
<= PERF_EVENT_STATE_OFF
)
3999 if (!event_filter_match(event
))
4002 if (group_can_go_on(event
, *can_add_hw
)) {
4003 if (!group_sched_in(event
, ctx
))
4004 list_add_tail(&event
->active_list
, get_event_list(event
));
4007 if (event
->state
== PERF_EVENT_STATE_INACTIVE
) {
4009 if (event
->attr
.pinned
) {
4010 perf_cgroup_event_disable(event
, ctx
);
4011 perf_event_set_state(event
, PERF_EVENT_STATE_ERROR
);
4013 if (*perf_event_fasync(event
))
4014 event
->pending_kill
= POLL_ERR
;
4016 perf_event_wakeup(event
);
4018 struct perf_cpu_pmu_context
*cpc
= this_cpc(event
->pmu_ctx
->pmu
);
4020 event
->pmu_ctx
->rotate_necessary
= 1;
4021 perf_mux_hrtimer_restart(cpc
);
4022 group_update_userpage(event
);
4029 static void pmu_groups_sched_in(struct perf_event_context
*ctx
,
4030 struct perf_event_groups
*groups
,
4034 visit_groups_merge(ctx
, groups
, smp_processor_id(), pmu
,
4035 merge_sched_in
, &can_add_hw
);
4038 static void __pmu_ctx_sched_in(struct perf_event_pmu_context
*pmu_ctx
,
4039 enum event_type_t event_type
)
4041 struct perf_event_context
*ctx
= pmu_ctx
->ctx
;
4043 if (event_type
& EVENT_PINNED
)
4044 pmu_groups_sched_in(ctx
, &ctx
->pinned_groups
, pmu_ctx
->pmu
);
4045 if (event_type
& EVENT_FLEXIBLE
)
4046 pmu_groups_sched_in(ctx
, &ctx
->flexible_groups
, pmu_ctx
->pmu
);
4050 ctx_sched_in(struct perf_event_context
*ctx
, struct pmu
*pmu
, enum event_type_t event_type
)
4052 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
4053 struct perf_event_pmu_context
*pmu_ctx
;
4054 int is_active
= ctx
->is_active
;
4055 bool cgroup
= event_type
& EVENT_CGROUP
;
4057 event_type
&= ~EVENT_CGROUP
;
4059 lockdep_assert_held(&ctx
->lock
);
4061 if (likely(!ctx
->nr_events
))
4064 if (!(is_active
& EVENT_TIME
)) {
4065 /* start ctx time */
4066 __update_context_time(ctx
, false);
4067 perf_cgroup_set_timestamp(cpuctx
);
4069 * CPU-release for the below ->is_active store,
4070 * see __load_acquire() in perf_event_time_now()
4075 ctx
->is_active
|= (event_type
| EVENT_TIME
);
4077 if (!(is_active
& EVENT_ALL
))
4078 cpuctx
->task_ctx
= ctx
;
4080 WARN_ON_ONCE(cpuctx
->task_ctx
!= ctx
);
4083 is_active
^= ctx
->is_active
; /* changed bits */
4086 * First go through the list and put on any pinned groups
4087 * in order to give them the best chance of going on.
4089 if (is_active
& EVENT_PINNED
) {
4090 for_each_epc(pmu_ctx
, ctx
, pmu
, cgroup
)
4091 __pmu_ctx_sched_in(pmu_ctx
, EVENT_PINNED
);
4094 /* Then walk through the lower prio flexible groups */
4095 if (is_active
& EVENT_FLEXIBLE
) {
4096 for_each_epc(pmu_ctx
, ctx
, pmu
, cgroup
)
4097 __pmu_ctx_sched_in(pmu_ctx
, EVENT_FLEXIBLE
);
4101 static void perf_event_context_sched_in(struct task_struct
*task
)
4103 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
4104 struct perf_event_context
*ctx
;
4107 ctx
= rcu_dereference(task
->perf_event_ctxp
);
4111 if (cpuctx
->task_ctx
== ctx
) {
4112 perf_ctx_lock(cpuctx
, ctx
);
4113 perf_ctx_disable(ctx
, false);
4115 perf_ctx_sched_task_cb(ctx
, task
, true);
4117 perf_ctx_enable(ctx
, false);
4118 perf_ctx_unlock(cpuctx
, ctx
);
4122 perf_ctx_lock(cpuctx
, ctx
);
4124 * We must check ctx->nr_events while holding ctx->lock, such
4125 * that we serialize against perf_install_in_context().
4127 if (!ctx
->nr_events
)
4130 perf_ctx_disable(ctx
, false);
4132 * We want to keep the following priority order:
4133 * cpu pinned (that don't need to move), task pinned,
4134 * cpu flexible, task flexible.
4136 * However, if task's ctx is not carrying any pinned
4137 * events, no need to flip the cpuctx's events around.
4139 if (!RB_EMPTY_ROOT(&ctx
->pinned_groups
.tree
)) {
4140 perf_ctx_disable(&cpuctx
->ctx
, false);
4141 ctx_sched_out(&cpuctx
->ctx
, NULL
, EVENT_FLEXIBLE
);
4144 perf_event_sched_in(cpuctx
, ctx
, NULL
);
4146 perf_ctx_sched_task_cb(cpuctx
->task_ctx
, task
, true);
4148 if (!RB_EMPTY_ROOT(&ctx
->pinned_groups
.tree
))
4149 perf_ctx_enable(&cpuctx
->ctx
, false);
4151 perf_ctx_enable(ctx
, false);
4154 perf_ctx_unlock(cpuctx
, ctx
);
4160 * Called from scheduler to add the events of the current task
4161 * with interrupts disabled.
4163 * We restore the event value and then enable it.
4165 * This does not protect us against NMI, but enable()
4166 * sets the enabled bit in the control field of event _before_
4167 * accessing the event control register. If a NMI hits, then it will
4168 * keep the event running.
4170 void __perf_event_task_sched_in(struct task_struct
*prev
,
4171 struct task_struct
*task
)
4173 perf_event_context_sched_in(task
);
4175 if (atomic_read(&nr_switch_events
))
4176 perf_event_switch(task
, prev
, true);
4178 if (__this_cpu_read(perf_sched_cb_usages
))
4179 perf_pmu_sched_task(prev
, task
, true);
4182 static u64
perf_calculate_period(struct perf_event
*event
, u64 nsec
, u64 count
)
4184 u64 frequency
= event
->attr
.sample_freq
;
4185 u64 sec
= NSEC_PER_SEC
;
4186 u64 divisor
, dividend
;
4188 int count_fls
, nsec_fls
, frequency_fls
, sec_fls
;
4190 count_fls
= fls64(count
);
4191 nsec_fls
= fls64(nsec
);
4192 frequency_fls
= fls64(frequency
);
4196 * We got @count in @nsec, with a target of sample_freq HZ
4197 * the target period becomes:
4200 * period = -------------------
4201 * @nsec * sample_freq
4206 * Reduce accuracy by one bit such that @a and @b converge
4207 * to a similar magnitude.
4209 #define REDUCE_FLS(a, b) \
4211 if (a##_fls > b##_fls) { \
4221 * Reduce accuracy until either term fits in a u64, then proceed with
4222 * the other, so that finally we can do a u64/u64 division.
4224 while (count_fls
+ sec_fls
> 64 && nsec_fls
+ frequency_fls
> 64) {
4225 REDUCE_FLS(nsec
, frequency
);
4226 REDUCE_FLS(sec
, count
);
4229 if (count_fls
+ sec_fls
> 64) {
4230 divisor
= nsec
* frequency
;
4232 while (count_fls
+ sec_fls
> 64) {
4233 REDUCE_FLS(count
, sec
);
4237 dividend
= count
* sec
;
4239 dividend
= count
* sec
;
4241 while (nsec_fls
+ frequency_fls
> 64) {
4242 REDUCE_FLS(nsec
, frequency
);
4246 divisor
= nsec
* frequency
;
4252 return div64_u64(dividend
, divisor
);
4255 static DEFINE_PER_CPU(int, perf_throttled_count
);
4256 static DEFINE_PER_CPU(u64
, perf_throttled_seq
);
4258 static void perf_adjust_period(struct perf_event
*event
, u64 nsec
, u64 count
, bool disable
)
4260 struct hw_perf_event
*hwc
= &event
->hw
;
4261 s64 period
, sample_period
;
4264 period
= perf_calculate_period(event
, nsec
, count
);
4266 delta
= (s64
)(period
- hwc
->sample_period
);
4271 delta
/= 8; /* low pass filter */
4273 sample_period
= hwc
->sample_period
+ delta
;
4278 hwc
->sample_period
= sample_period
;
4280 if (local64_read(&hwc
->period_left
) > 8*sample_period
) {
4282 event
->pmu
->stop(event
, PERF_EF_UPDATE
);
4284 local64_set(&hwc
->period_left
, 0);
4287 event
->pmu
->start(event
, PERF_EF_RELOAD
);
4291 static void perf_adjust_freq_unthr_events(struct list_head
*event_list
)
4293 struct perf_event
*event
;
4294 struct hw_perf_event
*hwc
;
4295 u64 now
, period
= TICK_NSEC
;
4298 list_for_each_entry(event
, event_list
, active_list
) {
4299 if (event
->state
!= PERF_EVENT_STATE_ACTIVE
)
4302 // XXX use visit thingy to avoid the -1,cpu match
4303 if (!event_filter_match(event
))
4308 if (hwc
->interrupts
== MAX_INTERRUPTS
)
4309 perf_event_unthrottle_group(event
, is_event_in_freq_mode(event
));
4311 if (!is_event_in_freq_mode(event
))
4315 * stop the event and update event->count
4317 event
->pmu
->stop(event
, PERF_EF_UPDATE
);
4319 now
= local64_read(&event
->count
);
4320 delta
= now
- hwc
->freq_count_stamp
;
4321 hwc
->freq_count_stamp
= now
;
4325 * reload only if value has changed
4326 * we have stopped the event so tell that
4327 * to perf_adjust_period() to avoid stopping it
4331 perf_adjust_period(event
, period
, delta
, false);
4333 event
->pmu
->start(event
, delta
> 0 ? PERF_EF_RELOAD
: 0);
4338 * combine freq adjustment with unthrottling to avoid two passes over the
4339 * events. At the same time, make sure, having freq events does not change
4340 * the rate of unthrottling as that would introduce bias.
4343 perf_adjust_freq_unthr_context(struct perf_event_context
*ctx
, bool unthrottle
)
4345 struct perf_event_pmu_context
*pmu_ctx
;
4348 * only need to iterate over all events iff:
4349 * - context have events in frequency mode (needs freq adjust)
4350 * - there are events to unthrottle on this cpu
4352 if (!(ctx
->nr_freq
|| unthrottle
))
4355 raw_spin_lock(&ctx
->lock
);
4357 list_for_each_entry(pmu_ctx
, &ctx
->pmu_ctx_list
, pmu_ctx_entry
) {
4358 if (!(pmu_ctx
->nr_freq
|| unthrottle
))
4360 if (!perf_pmu_ctx_is_active(pmu_ctx
))
4362 if (pmu_ctx
->pmu
->capabilities
& PERF_PMU_CAP_NO_INTERRUPT
)
4365 perf_pmu_disable(pmu_ctx
->pmu
);
4366 perf_adjust_freq_unthr_events(&pmu_ctx
->pinned_active
);
4367 perf_adjust_freq_unthr_events(&pmu_ctx
->flexible_active
);
4368 perf_pmu_enable(pmu_ctx
->pmu
);
4371 raw_spin_unlock(&ctx
->lock
);
4375 * Move @event to the tail of the @ctx's elegible events.
4377 static void rotate_ctx(struct perf_event_context
*ctx
, struct perf_event
*event
)
4380 * Rotate the first entry last of non-pinned groups. Rotation might be
4381 * disabled by the inheritance code.
4383 if (ctx
->rotate_disable
)
4386 perf_event_groups_delete(&ctx
->flexible_groups
, event
);
4387 perf_event_groups_insert(&ctx
->flexible_groups
, event
);
4390 /* pick an event from the flexible_groups to rotate */
4391 static inline struct perf_event
*
4392 ctx_event_to_rotate(struct perf_event_pmu_context
*pmu_ctx
)
4394 struct perf_event
*event
;
4395 struct rb_node
*node
;
4396 struct rb_root
*tree
;
4397 struct __group_key key
= {
4398 .pmu
= pmu_ctx
->pmu
,
4401 /* pick the first active flexible event */
4402 event
= list_first_entry_or_null(&pmu_ctx
->flexible_active
,
4403 struct perf_event
, active_list
);
4407 /* if no active flexible event, pick the first event */
4408 tree
= &pmu_ctx
->ctx
->flexible_groups
.tree
;
4410 if (!pmu_ctx
->ctx
->task
) {
4411 key
.cpu
= smp_processor_id();
4413 node
= rb_find_first(&key
, tree
, __group_cmp_ignore_cgroup
);
4415 event
= __node_2_pe(node
);
4420 node
= rb_find_first(&key
, tree
, __group_cmp_ignore_cgroup
);
4422 event
= __node_2_pe(node
);
4426 key
.cpu
= smp_processor_id();
4427 node
= rb_find_first(&key
, tree
, __group_cmp_ignore_cgroup
);
4429 event
= __node_2_pe(node
);
4433 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4434 * finds there are unschedulable events, it will set it again.
4436 pmu_ctx
->rotate_necessary
= 0;
4441 static bool perf_rotate_context(struct perf_cpu_pmu_context
*cpc
)
4443 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
4444 struct perf_event_pmu_context
*cpu_epc
, *task_epc
= NULL
;
4445 struct perf_event
*cpu_event
= NULL
, *task_event
= NULL
;
4446 int cpu_rotate
, task_rotate
;
4450 * Since we run this from IRQ context, nobody can install new
4451 * events, thus the event count values are stable.
4454 cpu_epc
= &cpc
->epc
;
4456 task_epc
= cpc
->task_epc
;
4458 cpu_rotate
= cpu_epc
->rotate_necessary
;
4459 task_rotate
= task_epc
? task_epc
->rotate_necessary
: 0;
4461 if (!(cpu_rotate
|| task_rotate
))
4464 perf_ctx_lock(cpuctx
, cpuctx
->task_ctx
);
4465 perf_pmu_disable(pmu
);
4468 task_event
= ctx_event_to_rotate(task_epc
);
4470 cpu_event
= ctx_event_to_rotate(cpu_epc
);
4473 * As per the order given at ctx_resched() first 'pop' task flexible
4474 * and then, if needed CPU flexible.
4476 if (task_event
|| (task_epc
&& cpu_event
)) {
4477 update_context_time(task_epc
->ctx
);
4478 __pmu_ctx_sched_out(task_epc
, EVENT_FLEXIBLE
);
4482 update_context_time(&cpuctx
->ctx
);
4483 __pmu_ctx_sched_out(cpu_epc
, EVENT_FLEXIBLE
);
4484 rotate_ctx(&cpuctx
->ctx
, cpu_event
);
4485 __pmu_ctx_sched_in(cpu_epc
, EVENT_FLEXIBLE
);
4489 rotate_ctx(task_epc
->ctx
, task_event
);
4491 if (task_event
|| (task_epc
&& cpu_event
))
4492 __pmu_ctx_sched_in(task_epc
, EVENT_FLEXIBLE
);
4494 perf_pmu_enable(pmu
);
4495 perf_ctx_unlock(cpuctx
, cpuctx
->task_ctx
);
4500 void perf_event_task_tick(void)
4502 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
4503 struct perf_event_context
*ctx
;
4506 lockdep_assert_irqs_disabled();
4508 __this_cpu_inc(perf_throttled_seq
);
4509 throttled
= __this_cpu_xchg(perf_throttled_count
, 0);
4510 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS
);
4512 perf_adjust_freq_unthr_context(&cpuctx
->ctx
, !!throttled
);
4515 ctx
= rcu_dereference(current
->perf_event_ctxp
);
4517 perf_adjust_freq_unthr_context(ctx
, !!throttled
);
4521 static int event_enable_on_exec(struct perf_event
*event
,
4522 struct perf_event_context
*ctx
)
4524 if (!event
->attr
.enable_on_exec
)
4527 event
->attr
.enable_on_exec
= 0;
4528 if (event
->state
>= PERF_EVENT_STATE_INACTIVE
)
4531 perf_event_set_state(event
, PERF_EVENT_STATE_INACTIVE
);
4537 * Enable all of a task's events that have been marked enable-on-exec.
4538 * This expects task == current.
4540 static void perf_event_enable_on_exec(struct perf_event_context
*ctx
)
4542 struct perf_event_context
*clone_ctx
= NULL
;
4543 enum event_type_t event_type
= 0;
4544 struct perf_cpu_context
*cpuctx
;
4545 struct perf_event
*event
;
4546 unsigned long flags
;
4549 local_irq_save(flags
);
4550 if (WARN_ON_ONCE(current
->perf_event_ctxp
!= ctx
))
4553 if (!ctx
->nr_events
)
4556 cpuctx
= this_cpu_ptr(&perf_cpu_context
);
4557 perf_ctx_lock(cpuctx
, ctx
);
4558 ctx_time_freeze(cpuctx
, ctx
);
4560 list_for_each_entry(event
, &ctx
->event_list
, event_entry
) {
4561 enabled
|= event_enable_on_exec(event
, ctx
);
4562 event_type
|= get_event_type(event
);
4566 * Unclone and reschedule this context if we enabled any event.
4569 clone_ctx
= unclone_ctx(ctx
);
4570 ctx_resched(cpuctx
, ctx
, NULL
, event_type
);
4572 perf_ctx_unlock(cpuctx
, ctx
);
4575 local_irq_restore(flags
);
4581 static void perf_remove_from_owner(struct perf_event
*event
);
4582 static void perf_event_exit_event(struct perf_event
*event
,
4583 struct perf_event_context
*ctx
,
4587 * Removes all events from the current task that have been marked
4588 * remove-on-exec, and feeds their values back to parent events.
4590 static void perf_event_remove_on_exec(struct perf_event_context
*ctx
)
4592 struct perf_event_context
*clone_ctx
= NULL
;
4593 struct perf_event
*event
, *next
;
4594 unsigned long flags
;
4595 bool modified
= false;
4597 mutex_lock(&ctx
->mutex
);
4599 if (WARN_ON_ONCE(ctx
->task
!= current
))
4602 list_for_each_entry_safe(event
, next
, &ctx
->event_list
, event_entry
) {
4603 if (!event
->attr
.remove_on_exec
)
4606 if (!is_kernel_event(event
))
4607 perf_remove_from_owner(event
);
4611 perf_event_exit_event(event
, ctx
, false);
4614 raw_spin_lock_irqsave(&ctx
->lock
, flags
);
4616 clone_ctx
= unclone_ctx(ctx
);
4617 raw_spin_unlock_irqrestore(&ctx
->lock
, flags
);
4620 mutex_unlock(&ctx
->mutex
);
4626 struct perf_read_data
{
4627 struct perf_event
*event
;
4632 static inline const struct cpumask
*perf_scope_cpu_topology_cpumask(unsigned int scope
, int cpu
);
4634 static int __perf_event_read_cpu(struct perf_event
*event
, int event_cpu
)
4636 int local_cpu
= smp_processor_id();
4637 u16 local_pkg
, event_pkg
;
4639 if ((unsigned)event_cpu
>= nr_cpu_ids
)
4642 if (event
->group_caps
& PERF_EV_CAP_READ_SCOPE
) {
4643 const struct cpumask
*cpumask
= perf_scope_cpu_topology_cpumask(event
->pmu
->scope
, event_cpu
);
4645 if (cpumask
&& cpumask_test_cpu(local_cpu
, cpumask
))
4649 if (event
->group_caps
& PERF_EV_CAP_READ_ACTIVE_PKG
) {
4650 event_pkg
= topology_physical_package_id(event_cpu
);
4651 local_pkg
= topology_physical_package_id(local_cpu
);
4653 if (event_pkg
== local_pkg
)
4661 * Cross CPU call to read the hardware event
4663 static void __perf_event_read(void *info
)
4665 struct perf_read_data
*data
= info
;
4666 struct perf_event
*sub
, *event
= data
->event
;
4667 struct perf_event_context
*ctx
= event
->ctx
;
4668 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
4669 struct pmu
*pmu
= event
->pmu
;
4672 * If this is a task context, we need to check whether it is
4673 * the current task context of this cpu. If not it has been
4674 * scheduled out before the smp call arrived. In that case
4675 * event->count would have been updated to a recent sample
4676 * when the event was scheduled out.
4678 if (ctx
->task
&& cpuctx
->task_ctx
!= ctx
)
4681 raw_spin_lock(&ctx
->lock
);
4682 ctx_time_update_event(ctx
, event
);
4684 perf_event_update_time(event
);
4686 perf_event_update_sibling_time(event
);
4688 if (event
->state
!= PERF_EVENT_STATE_ACTIVE
)
4697 pmu
->start_txn(pmu
, PERF_PMU_TXN_READ
);
4701 for_each_sibling_event(sub
, event
)
4704 data
->ret
= pmu
->commit_txn(pmu
);
4707 raw_spin_unlock(&ctx
->lock
);
4710 static inline u64
perf_event_count(struct perf_event
*event
, bool self
)
4713 return local64_read(&event
->count
);
4715 return local64_read(&event
->count
) + atomic64_read(&event
->child_count
);
4718 static void calc_timer_values(struct perf_event
*event
,
4725 *now
= perf_clock();
4726 ctx_time
= perf_event_time_now(event
, *now
);
4727 __perf_update_times(event
, ctx_time
, enabled
, running
);
4731 * NMI-safe method to read a local event, that is an event that
4733 * - either for the current task, or for this CPU
4734 * - does not have inherit set, for inherited task events
4735 * will not be local and we cannot read them atomically
4736 * - must not have a pmu::count method
4738 int perf_event_read_local(struct perf_event
*event
, u64
*value
,
4739 u64
*enabled
, u64
*running
)
4741 unsigned long flags
;
4747 * Disabling interrupts avoids all counter scheduling (context
4748 * switches, timer based rotation and IPIs).
4750 local_irq_save(flags
);
4753 * It must not be an event with inherit set, we cannot read
4754 * all child counters from atomic context.
4756 if (event
->attr
.inherit
) {
4761 /* If this is a per-task event, it must be for current */
4762 if ((event
->attach_state
& PERF_ATTACH_TASK
) &&
4763 event
->hw
.target
!= current
) {
4769 * Get the event CPU numbers, and adjust them to local if the event is
4770 * a per-package event that can be read locally
4772 event_oncpu
= __perf_event_read_cpu(event
, event
->oncpu
);
4773 event_cpu
= __perf_event_read_cpu(event
, event
->cpu
);
4775 /* If this is a per-CPU event, it must be for this CPU */
4776 if (!(event
->attach_state
& PERF_ATTACH_TASK
) &&
4777 event_cpu
!= smp_processor_id()) {
4782 /* If this is a pinned event it must be running on this CPU */
4783 if (event
->attr
.pinned
&& event_oncpu
!= smp_processor_id()) {
4789 * If the event is currently on this CPU, its either a per-task event,
4790 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4793 if (event_oncpu
== smp_processor_id())
4794 event
->pmu
->read(event
);
4796 *value
= local64_read(&event
->count
);
4797 if (enabled
|| running
) {
4798 u64 __enabled
, __running
, __now
;
4800 calc_timer_values(event
, &__now
, &__enabled
, &__running
);
4802 *enabled
= __enabled
;
4804 *running
= __running
;
4807 local_irq_restore(flags
);
4812 static int perf_event_read(struct perf_event
*event
, bool group
)
4814 enum perf_event_state state
= READ_ONCE(event
->state
);
4815 int event_cpu
, ret
= 0;
4818 * If event is enabled and currently active on a CPU, update the
4819 * value in the event structure:
4822 if (state
== PERF_EVENT_STATE_ACTIVE
) {
4823 struct perf_read_data data
;
4826 * Orders the ->state and ->oncpu loads such that if we see
4827 * ACTIVE we must also see the right ->oncpu.
4829 * Matches the smp_wmb() from event_sched_in().
4833 event_cpu
= READ_ONCE(event
->oncpu
);
4834 if ((unsigned)event_cpu
>= nr_cpu_ids
)
4837 data
= (struct perf_read_data
){
4844 event_cpu
= __perf_event_read_cpu(event
, event_cpu
);
4847 * Purposely ignore the smp_call_function_single() return
4850 * If event_cpu isn't a valid CPU it means the event got
4851 * scheduled out and that will have updated the event count.
4853 * Therefore, either way, we'll have an up-to-date event count
4856 (void)smp_call_function_single(event_cpu
, __perf_event_read
, &data
, 1);
4860 } else if (state
== PERF_EVENT_STATE_INACTIVE
) {
4861 struct perf_event_context
*ctx
= event
->ctx
;
4862 unsigned long flags
;
4864 raw_spin_lock_irqsave(&ctx
->lock
, flags
);
4865 state
= event
->state
;
4866 if (state
!= PERF_EVENT_STATE_INACTIVE
) {
4867 raw_spin_unlock_irqrestore(&ctx
->lock
, flags
);
4872 * May read while context is not active (e.g., thread is
4873 * blocked), in that case we cannot update context time
4875 ctx_time_update_event(ctx
, event
);
4877 perf_event_update_time(event
);
4879 perf_event_update_sibling_time(event
);
4880 raw_spin_unlock_irqrestore(&ctx
->lock
, flags
);
4887 * Initialize the perf_event context in a task_struct:
4889 static void __perf_event_init_context(struct perf_event_context
*ctx
)
4891 raw_spin_lock_init(&ctx
->lock
);
4892 mutex_init(&ctx
->mutex
);
4893 INIT_LIST_HEAD(&ctx
->pmu_ctx_list
);
4894 perf_event_groups_init(&ctx
->pinned_groups
);
4895 perf_event_groups_init(&ctx
->flexible_groups
);
4896 INIT_LIST_HEAD(&ctx
->event_list
);
4897 refcount_set(&ctx
->refcount
, 1);
4901 __perf_init_event_pmu_context(struct perf_event_pmu_context
*epc
, struct pmu
*pmu
)
4904 INIT_LIST_HEAD(&epc
->pmu_ctx_entry
);
4905 INIT_LIST_HEAD(&epc
->pinned_active
);
4906 INIT_LIST_HEAD(&epc
->flexible_active
);
4907 atomic_set(&epc
->refcount
, 1);
4910 static struct perf_event_context
*
4911 alloc_perf_context(struct task_struct
*task
)
4913 struct perf_event_context
*ctx
;
4915 ctx
= kzalloc(sizeof(struct perf_event_context
), GFP_KERNEL
);
4919 __perf_event_init_context(ctx
);
4921 ctx
->task
= get_task_struct(task
);
4926 static struct task_struct
*
4927 find_lively_task_by_vpid(pid_t vpid
)
4929 struct task_struct
*task
;
4935 task
= find_task_by_vpid(vpid
);
4937 get_task_struct(task
);
4941 return ERR_PTR(-ESRCH
);
4947 * Returns a matching context with refcount and pincount.
4949 static struct perf_event_context
*
4950 find_get_context(struct task_struct
*task
, struct perf_event
*event
)
4952 struct perf_event_context
*ctx
, *clone_ctx
= NULL
;
4953 struct perf_cpu_context
*cpuctx
;
4954 unsigned long flags
;
4958 /* Must be root to operate on a CPU event: */
4959 err
= perf_allow_cpu();
4961 return ERR_PTR(err
);
4963 cpuctx
= per_cpu_ptr(&perf_cpu_context
, event
->cpu
);
4966 raw_spin_lock_irqsave(&ctx
->lock
, flags
);
4968 raw_spin_unlock_irqrestore(&ctx
->lock
, flags
);
4975 ctx
= perf_lock_task_context(task
, &flags
);
4977 clone_ctx
= unclone_ctx(ctx
);
4980 raw_spin_unlock_irqrestore(&ctx
->lock
, flags
);
4985 ctx
= alloc_perf_context(task
);
4991 mutex_lock(&task
->perf_event_mutex
);
4993 * If it has already passed perf_event_exit_task().
4994 * we must see PF_EXITING, it takes this mutex too.
4996 if (task
->flags
& PF_EXITING
)
4998 else if (task
->perf_event_ctxp
)
5003 rcu_assign_pointer(task
->perf_event_ctxp
, ctx
);
5005 mutex_unlock(&task
->perf_event_mutex
);
5007 if (unlikely(err
)) {
5019 return ERR_PTR(err
);
5022 static struct perf_event_pmu_context
*
5023 find_get_pmu_context(struct pmu
*pmu
, struct perf_event_context
*ctx
,
5024 struct perf_event
*event
)
5026 struct perf_event_pmu_context
*new = NULL
, *pos
= NULL
, *epc
;
5030 * perf_pmu_migrate_context() / __perf_pmu_install_event()
5031 * relies on the fact that find_get_pmu_context() cannot fail
5034 struct perf_cpu_pmu_context
*cpc
;
5036 cpc
= *per_cpu_ptr(pmu
->cpu_pmu_context
, event
->cpu
);
5038 raw_spin_lock_irq(&ctx
->lock
);
5041 * One extra reference for the pmu; see perf_pmu_free().
5043 atomic_set(&epc
->refcount
, 2);
5045 list_add(&epc
->pmu_ctx_entry
, &ctx
->pmu_ctx_list
);
5048 WARN_ON_ONCE(epc
->ctx
!= ctx
);
5049 atomic_inc(&epc
->refcount
);
5051 raw_spin_unlock_irq(&ctx
->lock
);
5055 new = kzalloc(sizeof(*epc
), GFP_KERNEL
);
5057 return ERR_PTR(-ENOMEM
);
5059 __perf_init_event_pmu_context(new, pmu
);
5064 * lockdep_assert_held(&ctx->mutex);
5066 * can't because perf_event_init_task() doesn't actually hold the
5070 raw_spin_lock_irq(&ctx
->lock
);
5071 list_for_each_entry(epc
, &ctx
->pmu_ctx_list
, pmu_ctx_entry
) {
5072 if (epc
->pmu
== pmu
) {
5073 WARN_ON_ONCE(epc
->ctx
!= ctx
);
5074 atomic_inc(&epc
->refcount
);
5077 /* Make sure the pmu_ctx_list is sorted by PMU type: */
5078 if (!pos
&& epc
->pmu
->type
> pmu
->type
)
5086 list_add_tail(&epc
->pmu_ctx_entry
, &ctx
->pmu_ctx_list
);
5088 list_add(&epc
->pmu_ctx_entry
, pos
->pmu_ctx_entry
.prev
);
5093 raw_spin_unlock_irq(&ctx
->lock
);
5099 static void get_pmu_ctx(struct perf_event_pmu_context
*epc
)
5101 WARN_ON_ONCE(!atomic_inc_not_zero(&epc
->refcount
));
5104 static void free_cpc_rcu(struct rcu_head
*head
)
5106 struct perf_cpu_pmu_context
*cpc
=
5107 container_of(head
, typeof(*cpc
), epc
.rcu_head
);
5112 static void free_epc_rcu(struct rcu_head
*head
)
5114 struct perf_event_pmu_context
*epc
= container_of(head
, typeof(*epc
), rcu_head
);
5119 static void put_pmu_ctx(struct perf_event_pmu_context
*epc
)
5121 struct perf_event_context
*ctx
= epc
->ctx
;
5122 unsigned long flags
;
5127 * lockdep_assert_held(&ctx->mutex);
5129 * can't because of the call-site in _free_event()/put_event()
5130 * which isn't always called under ctx->mutex.
5132 if (!atomic_dec_and_raw_lock_irqsave(&epc
->refcount
, &ctx
->lock
, flags
))
5135 WARN_ON_ONCE(list_empty(&epc
->pmu_ctx_entry
));
5137 list_del_init(&epc
->pmu_ctx_entry
);
5140 WARN_ON_ONCE(!list_empty(&epc
->pinned_active
));
5141 WARN_ON_ONCE(!list_empty(&epc
->flexible_active
));
5143 raw_spin_unlock_irqrestore(&ctx
->lock
, flags
);
5145 if (epc
->embedded
) {
5146 call_rcu(&epc
->rcu_head
, free_cpc_rcu
);
5150 call_rcu(&epc
->rcu_head
, free_epc_rcu
);
5153 static void perf_event_free_filter(struct perf_event
*event
);
5155 static void free_event_rcu(struct rcu_head
*head
)
5157 struct perf_event
*event
= container_of(head
, typeof(*event
), rcu_head
);
5160 put_pid_ns(event
->ns
);
5161 perf_event_free_filter(event
);
5162 kmem_cache_free(perf_event_cache
, event
);
5165 static void ring_buffer_attach(struct perf_event
*event
,
5166 struct perf_buffer
*rb
);
5168 static void detach_sb_event(struct perf_event
*event
)
5170 struct pmu_event_list
*pel
= per_cpu_ptr(&pmu_sb_events
, event
->cpu
);
5172 raw_spin_lock(&pel
->lock
);
5173 list_del_rcu(&event
->sb_list
);
5174 raw_spin_unlock(&pel
->lock
);
5177 static bool is_sb_event(struct perf_event
*event
)
5179 struct perf_event_attr
*attr
= &event
->attr
;
5184 if (event
->attach_state
& PERF_ATTACH_TASK
)
5187 if (attr
->mmap
|| attr
->mmap_data
|| attr
->mmap2
||
5188 attr
->comm
|| attr
->comm_exec
||
5189 attr
->task
|| attr
->ksymbol
||
5190 attr
->context_switch
|| attr
->text_poke
||
5197 static void unaccount_pmu_sb_event(struct perf_event
*event
)
5199 if (is_sb_event(event
))
5200 detach_sb_event(event
);
5203 #ifdef CONFIG_NO_HZ_FULL
5204 static DEFINE_SPINLOCK(nr_freq_lock
);
5207 static void unaccount_freq_event_nohz(void)
5209 #ifdef CONFIG_NO_HZ_FULL
5210 spin_lock(&nr_freq_lock
);
5211 if (atomic_dec_and_test(&nr_freq_events
))
5212 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS
);
5213 spin_unlock(&nr_freq_lock
);
5217 static void unaccount_freq_event(void)
5219 if (tick_nohz_full_enabled())
5220 unaccount_freq_event_nohz();
5222 atomic_dec(&nr_freq_events
);
5226 static struct perf_ctx_data
*
5227 alloc_perf_ctx_data(struct kmem_cache
*ctx_cache
, bool global
)
5229 struct perf_ctx_data
*cd
;
5231 cd
= kzalloc(sizeof(*cd
), GFP_KERNEL
);
5235 cd
->data
= kmem_cache_zalloc(ctx_cache
, GFP_KERNEL
);
5241 cd
->global
= global
;
5242 cd
->ctx_cache
= ctx_cache
;
5243 refcount_set(&cd
->refcount
, 1);
5248 static void free_perf_ctx_data(struct perf_ctx_data
*cd
)
5250 kmem_cache_free(cd
->ctx_cache
, cd
->data
);
5254 static void __free_perf_ctx_data_rcu(struct rcu_head
*rcu_head
)
5256 struct perf_ctx_data
*cd
;
5258 cd
= container_of(rcu_head
, struct perf_ctx_data
, rcu_head
);
5259 free_perf_ctx_data(cd
);
5262 static inline void perf_free_ctx_data_rcu(struct perf_ctx_data
*cd
)
5264 call_rcu(&cd
->rcu_head
, __free_perf_ctx_data_rcu
);
5268 attach_task_ctx_data(struct task_struct
*task
, struct kmem_cache
*ctx_cache
,
5271 struct perf_ctx_data
*cd
, *old
= NULL
;
5273 cd
= alloc_perf_ctx_data(ctx_cache
, global
);
5278 if (try_cmpxchg((struct perf_ctx_data
**)&task
->perf_ctx_data
, &old
, cd
)) {
5280 perf_free_ctx_data_rcu(old
);
5286 * After seeing a dead @old, we raced with
5287 * removal and lost, try again to install @cd.
5292 if (refcount_inc_not_zero(&old
->refcount
)) {
5293 free_perf_ctx_data(cd
); /* unused */
5298 * @old is a dead object, refcount==0 is stable, try and
5299 * replace it with @cd.
5305 static void __detach_global_ctx_data(void);
5306 DEFINE_STATIC_PERCPU_RWSEM(global_ctx_data_rwsem
);
5307 static refcount_t global_ctx_data_ref
;
5310 attach_global_ctx_data(struct kmem_cache
*ctx_cache
)
5312 struct task_struct
*g
, *p
;
5313 struct perf_ctx_data
*cd
;
5316 if (refcount_inc_not_zero(&global_ctx_data_ref
))
5319 guard(percpu_write
)(&global_ctx_data_rwsem
);
5320 if (refcount_inc_not_zero(&global_ctx_data_ref
))
5323 /* Allocate everything */
5324 scoped_guard (rcu
) {
5325 for_each_process_thread(g
, p
) {
5326 cd
= rcu_dereference(p
->perf_ctx_data
);
5327 if (cd
&& !cd
->global
) {
5329 if (!refcount_inc_not_zero(&cd
->refcount
))
5339 refcount_set(&global_ctx_data_ref
, 1);
5343 ret
= attach_task_ctx_data(p
, ctx_cache
, true);
5346 __detach_global_ctx_data();
5353 attach_perf_ctx_data(struct perf_event
*event
)
5355 struct task_struct
*task
= event
->hw
.target
;
5356 struct kmem_cache
*ctx_cache
= event
->pmu
->task_ctx_cache
;
5363 return attach_task_ctx_data(task
, ctx_cache
, false);
5365 ret
= attach_global_ctx_data(ctx_cache
);
5369 event
->attach_state
|= PERF_ATTACH_GLOBAL_DATA
;
5374 detach_task_ctx_data(struct task_struct
*p
)
5376 struct perf_ctx_data
*cd
;
5378 scoped_guard (rcu
) {
5379 cd
= rcu_dereference(p
->perf_ctx_data
);
5380 if (!cd
|| !refcount_dec_and_test(&cd
->refcount
))
5385 * The old ctx_data may be lost because of the race.
5386 * Nothing is required to do for the case.
5387 * See attach_task_ctx_data().
5389 if (try_cmpxchg((struct perf_ctx_data
**)&p
->perf_ctx_data
, &cd
, NULL
))
5390 perf_free_ctx_data_rcu(cd
);
5393 static void __detach_global_ctx_data(void)
5395 struct task_struct
*g
, *p
;
5396 struct perf_ctx_data
*cd
;
5399 scoped_guard (rcu
) {
5400 for_each_process_thread(g
, p
) {
5401 cd
= rcu_dereference(p
->perf_ctx_data
);
5402 if (!cd
|| !cd
->global
)
5411 detach_task_ctx_data(p
);
5416 static void detach_global_ctx_data(void)
5418 if (refcount_dec_not_one(&global_ctx_data_ref
))
5421 guard(percpu_write
)(&global_ctx_data_rwsem
);
5422 if (!refcount_dec_and_test(&global_ctx_data_ref
))
5425 /* remove everything */
5426 __detach_global_ctx_data();
5429 static void detach_perf_ctx_data(struct perf_event
*event
)
5431 struct task_struct
*task
= event
->hw
.target
;
5433 event
->attach_state
&= ~PERF_ATTACH_TASK_DATA
;
5436 return detach_task_ctx_data(task
);
5438 if (event
->attach_state
& PERF_ATTACH_GLOBAL_DATA
) {
5439 detach_global_ctx_data();
5440 event
->attach_state
&= ~PERF_ATTACH_GLOBAL_DATA
;
5444 static void unaccount_event(struct perf_event
*event
)
5451 if (event
->attach_state
& (PERF_ATTACH_TASK
| PERF_ATTACH_SCHED_CB
))
5453 if (event
->attr
.mmap
|| event
->attr
.mmap_data
)
5454 atomic_dec(&nr_mmap_events
);
5455 if (event
->attr
.build_id
)
5456 atomic_dec(&nr_build_id_events
);
5457 if (event
->attr
.comm
)
5458 atomic_dec(&nr_comm_events
);
5459 if (event
->attr
.namespaces
)
5460 atomic_dec(&nr_namespaces_events
);
5461 if (event
->attr
.cgroup
)
5462 atomic_dec(&nr_cgroup_events
);
5463 if (event
->attr
.task
)
5464 atomic_dec(&nr_task_events
);
5465 if (event
->attr
.freq
)
5466 unaccount_freq_event();
5467 if (event
->attr
.context_switch
) {
5469 atomic_dec(&nr_switch_events
);
5471 if (is_cgroup_event(event
))
5473 if (has_branch_stack(event
))
5475 if (event
->attr
.ksymbol
)
5476 atomic_dec(&nr_ksymbol_events
);
5477 if (event
->attr
.bpf_event
)
5478 atomic_dec(&nr_bpf_events
);
5479 if (event
->attr
.text_poke
)
5480 atomic_dec(&nr_text_poke_events
);
5483 if (!atomic_add_unless(&perf_sched_count
, -1, 1))
5484 schedule_delayed_work(&perf_sched_work
, HZ
);
5487 unaccount_pmu_sb_event(event
);
5490 static void perf_sched_delayed(struct work_struct
*work
)
5492 mutex_lock(&perf_sched_mutex
);
5493 if (atomic_dec_and_test(&perf_sched_count
))
5494 static_branch_disable(&perf_sched_events
);
5495 mutex_unlock(&perf_sched_mutex
);
5499 * The following implement mutual exclusion of events on "exclusive" pmus
5500 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
5501 * at a time, so we disallow creating events that might conflict, namely:
5503 * 1) cpu-wide events in the presence of per-task events,
5504 * 2) per-task events in the presence of cpu-wide events,
5505 * 3) two matching events on the same perf_event_context.
5507 * The former two cases are handled in the allocation path (perf_event_alloc(),
5508 * _free_event()), the latter -- before the first perf_install_in_context().
5510 static int exclusive_event_init(struct perf_event
*event
)
5512 struct pmu
*pmu
= event
->pmu
;
5514 if (!is_exclusive_pmu(pmu
))
5518 * Prevent co-existence of per-task and cpu-wide events on the
5519 * same exclusive pmu.
5521 * Negative pmu::exclusive_cnt means there are cpu-wide
5522 * events on this "exclusive" pmu, positive means there are
5525 * Since this is called in perf_event_alloc() path, event::ctx
5526 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
5527 * to mean "per-task event", because unlike other attach states it
5528 * never gets cleared.
5530 if (event
->attach_state
& PERF_ATTACH_TASK
) {
5531 if (!atomic_inc_unless_negative(&pmu
->exclusive_cnt
))
5534 if (!atomic_dec_unless_positive(&pmu
->exclusive_cnt
))
5538 event
->attach_state
|= PERF_ATTACH_EXCLUSIVE
;
5543 static void exclusive_event_destroy(struct perf_event
*event
)
5545 struct pmu
*pmu
= event
->pmu
;
5547 /* see comment in exclusive_event_init() */
5548 if (event
->attach_state
& PERF_ATTACH_TASK
)
5549 atomic_dec(&pmu
->exclusive_cnt
);
5551 atomic_inc(&pmu
->exclusive_cnt
);
5553 event
->attach_state
&= ~PERF_ATTACH_EXCLUSIVE
;
5556 static bool exclusive_event_match(struct perf_event
*e1
, struct perf_event
*e2
)
5558 if ((e1
->pmu
== e2
->pmu
) &&
5559 (e1
->cpu
== e2
->cpu
||
5566 static bool exclusive_event_installable(struct perf_event
*event
,
5567 struct perf_event_context
*ctx
)
5569 struct perf_event
*iter_event
;
5570 struct pmu
*pmu
= event
->pmu
;
5572 lockdep_assert_held(&ctx
->mutex
);
5574 if (!is_exclusive_pmu(pmu
))
5577 list_for_each_entry(iter_event
, &ctx
->event_list
, event_entry
) {
5578 if (exclusive_event_match(iter_event
, event
))
5585 static void perf_free_addr_filters(struct perf_event
*event
);
5587 /* vs perf_event_alloc() error */
5588 static void __free_event(struct perf_event
*event
)
5590 struct pmu
*pmu
= event
->pmu
;
5592 if (event
->attach_state
& PERF_ATTACH_CALLCHAIN
)
5593 put_callchain_buffers();
5595 kfree(event
->addr_filter_ranges
);
5597 if (event
->attach_state
& PERF_ATTACH_EXCLUSIVE
)
5598 exclusive_event_destroy(event
);
5600 if (is_cgroup_event(event
))
5601 perf_detach_cgroup(event
);
5603 if (event
->attach_state
& PERF_ATTACH_TASK_DATA
)
5604 detach_perf_ctx_data(event
);
5607 event
->destroy(event
);
5610 * Must be after ->destroy(), due to uprobe_perf_close() using
5613 if (event
->hw
.target
)
5614 put_task_struct(event
->hw
.target
);
5616 if (event
->pmu_ctx
) {
5618 * put_pmu_ctx() needs an event->ctx reference, because of
5622 WARN_ON_ONCE(!event
->ctx
);
5623 WARN_ON_ONCE(event
->pmu_ctx
->ctx
!= event
->ctx
);
5624 put_pmu_ctx(event
->pmu_ctx
);
5628 * perf_event_free_task() relies on put_ctx() being 'last', in
5629 * particular all task references must be cleaned up.
5632 put_ctx(event
->ctx
);
5635 module_put(pmu
->module
);
5636 scoped_guard (spinlock
, &pmu
->events_lock
) {
5637 list_del(&event
->pmu_list
);
5642 call_rcu(&event
->rcu_head
, free_event_rcu
);
5645 DEFINE_FREE(__free_event
, struct perf_event
*, if (_T
) __free_event(_T
))
5647 /* vs perf_event_alloc() success */
5648 static void _free_event(struct perf_event
*event
)
5650 irq_work_sync(&event
->pending_irq
);
5651 irq_work_sync(&event
->pending_disable_irq
);
5653 unaccount_event(event
);
5655 security_perf_event_free(event
);
5659 * Can happen when we close an event with re-directed output.
5661 * Since we have a 0 refcount, perf_mmap_close() will skip
5662 * over us; possibly making our ring_buffer_put() the last.
5664 mutex_lock(&event
->mmap_mutex
);
5665 ring_buffer_attach(event
, NULL
);
5666 mutex_unlock(&event
->mmap_mutex
);
5669 perf_event_free_bpf_prog(event
);
5670 perf_free_addr_filters(event
);
5672 __free_event(event
);
5676 * Used to free events which have a known refcount of 1, such as in error paths
5677 * of inherited events.
5679 static void free_event(struct perf_event
*event
)
5681 if (WARN(atomic_long_cmpxchg(&event
->refcount
, 1, 0) != 1,
5682 "unexpected event refcount: %ld; ptr=%p\n",
5683 atomic_long_read(&event
->refcount
), event
)) {
5684 /* leak to avoid use-after-free */
5692 * Remove user event from the owner task.
5694 static void perf_remove_from_owner(struct perf_event
*event
)
5696 struct task_struct
*owner
;
5700 * Matches the smp_store_release() in perf_event_exit_task(). If we
5701 * observe !owner it means the list deletion is complete and we can
5702 * indeed free this event, otherwise we need to serialize on
5703 * owner->perf_event_mutex.
5705 owner
= READ_ONCE(event
->owner
);
5708 * Since delayed_put_task_struct() also drops the last
5709 * task reference we can safely take a new reference
5710 * while holding the rcu_read_lock().
5712 get_task_struct(owner
);
5718 * If we're here through perf_event_exit_task() we're already
5719 * holding ctx->mutex which would be an inversion wrt. the
5720 * normal lock order.
5722 * However we can safely take this lock because its the child
5725 mutex_lock_nested(&owner
->perf_event_mutex
, SINGLE_DEPTH_NESTING
);
5728 * We have to re-check the event->owner field, if it is cleared
5729 * we raced with perf_event_exit_task(), acquiring the mutex
5730 * ensured they're done, and we can proceed with freeing the
5734 list_del_init(&event
->owner_entry
);
5735 smp_store_release(&event
->owner
, NULL
);
5737 mutex_unlock(&owner
->perf_event_mutex
);
5738 put_task_struct(owner
);
5742 static void put_event(struct perf_event
*event
)
5744 struct perf_event
*parent
;
5746 if (!atomic_long_dec_and_test(&event
->refcount
))
5749 parent
= event
->parent
;
5752 /* Matches the refcount bump in inherit_event() */
5758 * Kill an event dead; while event:refcount will preserve the event
5759 * object, it will not preserve its functionality. Once the last 'user'
5760 * gives up the object, we'll destroy the thing.
5762 int perf_event_release_kernel(struct perf_event
*event
)
5764 struct perf_event_context
*ctx
= event
->ctx
;
5765 struct perf_event
*child
, *tmp
;
5768 * If we got here through err_alloc: free_event(event); we will not
5769 * have attached to a context yet.
5772 WARN_ON_ONCE(event
->attach_state
&
5773 (PERF_ATTACH_CONTEXT
|PERF_ATTACH_GROUP
));
5777 if (!is_kernel_event(event
))
5778 perf_remove_from_owner(event
);
5780 ctx
= perf_event_ctx_lock(event
);
5781 WARN_ON_ONCE(ctx
->parent_ctx
);
5784 * Mark this event as STATE_DEAD, there is no external reference to it
5787 * Anybody acquiring event->child_mutex after the below loop _must_
5788 * also see this, most importantly inherit_event() which will avoid
5789 * placing more children on the list.
5791 * Thus this guarantees that we will in fact observe and kill _ALL_
5794 if (event
->state
> PERF_EVENT_STATE_REVOKED
) {
5795 perf_remove_from_context(event
, DETACH_GROUP
|DETACH_DEAD
);
5797 event
->state
= PERF_EVENT_STATE_DEAD
;
5800 perf_event_ctx_unlock(event
, ctx
);
5803 mutex_lock(&event
->child_mutex
);
5804 list_for_each_entry(child
, &event
->child_list
, child_list
) {
5806 * Cannot change, child events are not migrated, see the
5807 * comment with perf_event_ctx_lock_nested().
5809 ctx
= READ_ONCE(child
->ctx
);
5811 * Since child_mutex nests inside ctx::mutex, we must jump
5812 * through hoops. We start by grabbing a reference on the ctx.
5814 * Since the event cannot get freed while we hold the
5815 * child_mutex, the context must also exist and have a !0
5821 * Now that we have a ctx ref, we can drop child_mutex, and
5822 * acquire ctx::mutex without fear of it going away. Then we
5823 * can re-acquire child_mutex.
5825 mutex_unlock(&event
->child_mutex
);
5826 mutex_lock(&ctx
->mutex
);
5827 mutex_lock(&event
->child_mutex
);
5830 * Now that we hold ctx::mutex and child_mutex, revalidate our
5831 * state, if child is still the first entry, it didn't get freed
5832 * and we can continue doing so.
5834 tmp
= list_first_entry_or_null(&event
->child_list
,
5835 struct perf_event
, child_list
);
5837 perf_remove_from_context(child
, DETACH_GROUP
| DETACH_CHILD
);
5842 mutex_unlock(&event
->child_mutex
);
5843 mutex_unlock(&ctx
->mutex
);
5846 /* Last reference unless ->pending_task work is pending */
5853 mutex_unlock(&event
->child_mutex
);
5857 * Last reference unless ->pending_task work is pending on this event
5858 * or any of its children.
5863 EXPORT_SYMBOL_GPL(perf_event_release_kernel
);
5866 * Called when the last reference to the file is gone.
5868 static int perf_release(struct inode
*inode
, struct file
*file
)
5870 perf_event_release_kernel(file
->private_data
);
5874 static u64
__perf_event_read_value(struct perf_event
*event
, u64
*enabled
, u64
*running
)
5876 struct perf_event
*child
;
5882 mutex_lock(&event
->child_mutex
);
5884 (void)perf_event_read(event
, false);
5885 total
+= perf_event_count(event
, false);
5887 *enabled
+= event
->total_time_enabled
+
5888 atomic64_read(&event
->child_total_time_enabled
);
5889 *running
+= event
->total_time_running
+
5890 atomic64_read(&event
->child_total_time_running
);
5892 list_for_each_entry(child
, &event
->child_list
, child_list
) {
5893 (void)perf_event_read(child
, false);
5894 total
+= perf_event_count(child
, false);
5895 *enabled
+= child
->total_time_enabled
;
5896 *running
+= child
->total_time_running
;
5898 mutex_unlock(&event
->child_mutex
);
5903 u64
perf_event_read_value(struct perf_event
*event
, u64
*enabled
, u64
*running
)
5905 struct perf_event_context
*ctx
;
5908 ctx
= perf_event_ctx_lock(event
);
5909 count
= __perf_event_read_value(event
, enabled
, running
);
5910 perf_event_ctx_unlock(event
, ctx
);
5914 EXPORT_SYMBOL_GPL(perf_event_read_value
);
5916 static int __perf_read_group_add(struct perf_event
*leader
,
5917 u64 read_format
, u64
*values
)
5919 struct perf_event_context
*ctx
= leader
->ctx
;
5920 struct perf_event
*sub
, *parent
;
5921 unsigned long flags
;
5922 int n
= 1; /* skip @nr */
5925 ret
= perf_event_read(leader
, true);
5929 raw_spin_lock_irqsave(&ctx
->lock
, flags
);
5931 * Verify the grouping between the parent and child (inherited)
5932 * events is still in tact.
5935 * - leader->ctx->lock pins leader->sibling_list
5936 * - parent->child_mutex pins parent->child_list
5937 * - parent->ctx->mutex pins parent->sibling_list
5939 * Because parent->ctx != leader->ctx (and child_list nests inside
5940 * ctx->mutex), group destruction is not atomic between children, also
5941 * see perf_event_release_kernel(). Additionally, parent can grow the
5944 * Therefore it is possible to have parent and child groups in a
5945 * different configuration and summing over such a beast makes no sense
5950 parent
= leader
->parent
;
5952 (parent
->group_generation
!= leader
->group_generation
||
5953 parent
->nr_siblings
!= leader
->nr_siblings
)) {
5959 * Since we co-schedule groups, {enabled,running} times of siblings
5960 * will be identical to those of the leader, so we only publish one
5963 if (read_format
& PERF_FORMAT_TOTAL_TIME_ENABLED
) {
5964 values
[n
++] += leader
->total_time_enabled
+
5965 atomic64_read(&leader
->child_total_time_enabled
);
5968 if (read_format
& PERF_FORMAT_TOTAL_TIME_RUNNING
) {
5969 values
[n
++] += leader
->total_time_running
+
5970 atomic64_read(&leader
->child_total_time_running
);
5974 * Write {count,id} tuples for every sibling.
5976 values
[n
++] += perf_event_count(leader
, false);
5977 if (read_format
& PERF_FORMAT_ID
)
5978 values
[n
++] = primary_event_id(leader
);
5979 if (read_format
& PERF_FORMAT_LOST
)
5980 values
[n
++] = atomic64_read(&leader
->lost_samples
);
5982 for_each_sibling_event(sub
, leader
) {
5983 values
[n
++] += perf_event_count(sub
, false);
5984 if (read_format
& PERF_FORMAT_ID
)
5985 values
[n
++] = primary_event_id(sub
);
5986 if (read_format
& PERF_FORMAT_LOST
)
5987 values
[n
++] = atomic64_read(&sub
->lost_samples
);
5991 raw_spin_unlock_irqrestore(&ctx
->lock
, flags
);
5995 static int perf_read_group(struct perf_event
*event
,
5996 u64 read_format
, char __user
*buf
)
5998 struct perf_event
*leader
= event
->group_leader
, *child
;
5999 struct perf_event_context
*ctx
= leader
->ctx
;
6003 lockdep_assert_held(&ctx
->mutex
);
6005 values
= kzalloc(event
->read_size
, GFP_KERNEL
);
6009 values
[0] = 1 + leader
->nr_siblings
;
6011 mutex_lock(&leader
->child_mutex
);
6013 ret
= __perf_read_group_add(leader
, read_format
, values
);
6017 list_for_each_entry(child
, &leader
->child_list
, child_list
) {
6018 ret
= __perf_read_group_add(child
, read_format
, values
);
6023 mutex_unlock(&leader
->child_mutex
);
6025 ret
= event
->read_size
;
6026 if (copy_to_user(buf
, values
, event
->read_size
))
6031 mutex_unlock(&leader
->child_mutex
);
6037 static int perf_read_one(struct perf_event
*event
,
6038 u64 read_format
, char __user
*buf
)
6040 u64 enabled
, running
;
6044 values
[n
++] = __perf_event_read_value(event
, &enabled
, &running
);
6045 if (read_format
& PERF_FORMAT_TOTAL_TIME_ENABLED
)
6046 values
[n
++] = enabled
;
6047 if (read_format
& PERF_FORMAT_TOTAL_TIME_RUNNING
)
6048 values
[n
++] = running
;
6049 if (read_format
& PERF_FORMAT_ID
)
6050 values
[n
++] = primary_event_id(event
);
6051 if (read_format
& PERF_FORMAT_LOST
)
6052 values
[n
++] = atomic64_read(&event
->lost_samples
);
6054 if (copy_to_user(buf
, values
, n
* sizeof(u64
)))
6057 return n
* sizeof(u64
);
6060 static bool is_event_hup(struct perf_event
*event
)
6064 if (event
->state
> PERF_EVENT_STATE_EXIT
)
6067 mutex_lock(&event
->child_mutex
);
6068 no_children
= list_empty(&event
->child_list
);
6069 mutex_unlock(&event
->child_mutex
);
6074 * Read the performance event - simple non blocking version for now
6077 __perf_read(struct perf_event
*event
, char __user
*buf
, size_t count
)
6079 u64 read_format
= event
->attr
.read_format
;
6083 * Return end-of-file for a read on an event that is in
6084 * error state (i.e. because it was pinned but it couldn't be
6085 * scheduled on to the CPU at some point).
6087 if (event
->state
== PERF_EVENT_STATE_ERROR
)
6090 if (count
< event
->read_size
)
6093 WARN_ON_ONCE(event
->ctx
->parent_ctx
);
6094 if (read_format
& PERF_FORMAT_GROUP
)
6095 ret
= perf_read_group(event
, read_format
, buf
);
6097 ret
= perf_read_one(event
, read_format
, buf
);
6103 perf_read(struct file
*file
, char __user
*buf
, size_t count
, loff_t
*ppos
)
6105 struct perf_event
*event
= file
->private_data
;
6106 struct perf_event_context
*ctx
;
6109 ret
= security_perf_event_read(event
);
6113 ctx
= perf_event_ctx_lock(event
);
6114 ret
= __perf_read(event
, buf
, count
);
6115 perf_event_ctx_unlock(event
, ctx
);
6120 static __poll_t
perf_poll(struct file
*file
, poll_table
*wait
)
6122 struct perf_event
*event
= file
->private_data
;
6123 struct perf_buffer
*rb
;
6124 __poll_t events
= EPOLLHUP
;
6126 if (event
->state
<= PERF_EVENT_STATE_REVOKED
)
6129 poll_wait(file
, &event
->waitq
, wait
);
6131 if (event
->state
<= PERF_EVENT_STATE_REVOKED
)
6134 if (is_event_hup(event
))
6137 if (unlikely(READ_ONCE(event
->state
) == PERF_EVENT_STATE_ERROR
&&
6138 event
->attr
.pinned
))
6142 * Pin the event->rb by taking event->mmap_mutex; otherwise
6143 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
6145 mutex_lock(&event
->mmap_mutex
);
6148 events
= atomic_xchg(&rb
->poll
, 0);
6149 mutex_unlock(&event
->mmap_mutex
);
6153 static void _perf_event_reset(struct perf_event
*event
)
6155 (void)perf_event_read(event
, false);
6156 local64_set(&event
->count
, 0);
6157 perf_event_update_userpage(event
);
6160 /* Assume it's not an event with inherit set. */
6161 u64
perf_event_pause(struct perf_event
*event
, bool reset
)
6163 struct perf_event_context
*ctx
;
6166 ctx
= perf_event_ctx_lock(event
);
6167 WARN_ON_ONCE(event
->attr
.inherit
);
6168 _perf_event_disable(event
);
6169 count
= local64_read(&event
->count
);
6171 local64_set(&event
->count
, 0);
6172 perf_event_ctx_unlock(event
, ctx
);
6176 EXPORT_SYMBOL_GPL(perf_event_pause
);
6179 * Holding the top-level event's child_mutex means that any
6180 * descendant process that has inherited this event will block
6181 * in perf_event_exit_event() if it goes to exit, thus satisfying the
6182 * task existence requirements of perf_event_enable/disable.
6184 static void perf_event_for_each_child(struct perf_event
*event
,
6185 void (*func
)(struct perf_event
*))
6187 struct perf_event
*child
;
6189 WARN_ON_ONCE(event
->ctx
->parent_ctx
);
6191 mutex_lock(&event
->child_mutex
);
6193 list_for_each_entry(child
, &event
->child_list
, child_list
)
6195 mutex_unlock(&event
->child_mutex
);
6198 static void perf_event_for_each(struct perf_event
*event
,
6199 void (*func
)(struct perf_event
*))
6201 struct perf_event_context
*ctx
= event
->ctx
;
6202 struct perf_event
*sibling
;
6204 lockdep_assert_held(&ctx
->mutex
);
6206 event
= event
->group_leader
;
6208 perf_event_for_each_child(event
, func
);
6209 for_each_sibling_event(sibling
, event
)
6210 perf_event_for_each_child(sibling
, func
);
6213 static void __perf_event_period(struct perf_event
*event
,
6214 struct perf_cpu_context
*cpuctx
,
6215 struct perf_event_context
*ctx
,
6218 u64 value
= *((u64
*)info
);
6221 if (event
->attr
.freq
) {
6222 event
->attr
.sample_freq
= value
;
6224 event
->attr
.sample_period
= value
;
6225 event
->hw
.sample_period
= value
;
6228 active
= (event
->state
== PERF_EVENT_STATE_ACTIVE
);
6230 perf_pmu_disable(event
->pmu
);
6231 event
->pmu
->stop(event
, PERF_EF_UPDATE
);
6234 local64_set(&event
->hw
.period_left
, 0);
6237 event
->pmu
->start(event
, PERF_EF_RELOAD
);
6239 * Once the period is force-reset, the event starts immediately.
6240 * But the event/group could be throttled. Unthrottle the
6241 * event/group now to avoid the next tick trying to unthrottle
6242 * while we already re-started the event/group.
6244 if (event
->hw
.interrupts
== MAX_INTERRUPTS
)
6245 perf_event_unthrottle_group(event
, true);
6246 perf_pmu_enable(event
->pmu
);
6250 static int perf_event_check_period(struct perf_event
*event
, u64 value
)
6252 return event
->pmu
->check_period(event
, value
);
6255 static int _perf_event_period(struct perf_event
*event
, u64 value
)
6257 if (!is_sampling_event(event
))
6263 if (event
->attr
.freq
) {
6264 if (value
> sysctl_perf_event_sample_rate
)
6267 if (perf_event_check_period(event
, value
))
6269 if (value
& (1ULL << 63))
6273 event_function_call(event
, __perf_event_period
, &value
);
6278 int perf_event_period(struct perf_event
*event
, u64 value
)
6280 struct perf_event_context
*ctx
;
6283 ctx
= perf_event_ctx_lock(event
);
6284 ret
= _perf_event_period(event
, value
);
6285 perf_event_ctx_unlock(event
, ctx
);
6289 EXPORT_SYMBOL_GPL(perf_event_period
);
6291 static const struct file_operations perf_fops
;
6293 static inline bool is_perf_file(struct fd f
)
6295 return !fd_empty(f
) && fd_file(f
)->f_op
== &perf_fops
;
6298 static int perf_event_set_output(struct perf_event
*event
,
6299 struct perf_event
*output_event
);
6300 static int perf_event_set_filter(struct perf_event
*event
, void __user
*arg
);
6301 static int perf_copy_attr(struct perf_event_attr __user
*uattr
,
6302 struct perf_event_attr
*attr
);
6303 static int __perf_event_set_bpf_prog(struct perf_event
*event
,
6304 struct bpf_prog
*prog
,
6307 static long _perf_ioctl(struct perf_event
*event
, unsigned int cmd
, unsigned long arg
)
6309 void (*func
)(struct perf_event
*);
6312 if (event
->state
<= PERF_EVENT_STATE_REVOKED
)
6316 case PERF_EVENT_IOC_ENABLE
:
6317 func
= _perf_event_enable
;
6319 case PERF_EVENT_IOC_DISABLE
:
6320 func
= _perf_event_disable
;
6322 case PERF_EVENT_IOC_RESET
:
6323 func
= _perf_event_reset
;
6326 case PERF_EVENT_IOC_REFRESH
:
6327 return _perf_event_refresh(event
, arg
);
6329 case PERF_EVENT_IOC_PERIOD
:
6333 if (copy_from_user(&value
, (u64 __user
*)arg
, sizeof(value
)))
6336 return _perf_event_period(event
, value
);
6338 case PERF_EVENT_IOC_ID
:
6340 u64 id
= primary_event_id(event
);
6342 if (copy_to_user((void __user
*)arg
, &id
, sizeof(id
)))
6347 case PERF_EVENT_IOC_SET_OUTPUT
:
6349 CLASS(fd
, output
)(arg
); // arg == -1 => empty
6350 struct perf_event
*output_event
= NULL
;
6352 if (!is_perf_file(output
))
6354 output_event
= fd_file(output
)->private_data
;
6356 return perf_event_set_output(event
, output_event
);
6359 case PERF_EVENT_IOC_SET_FILTER
:
6360 return perf_event_set_filter(event
, (void __user
*)arg
);
6362 case PERF_EVENT_IOC_SET_BPF
:
6364 struct bpf_prog
*prog
;
6367 prog
= bpf_prog_get(arg
);
6369 return PTR_ERR(prog
);
6371 err
= __perf_event_set_bpf_prog(event
, prog
, 0);
6380 case PERF_EVENT_IOC_PAUSE_OUTPUT
: {
6381 struct perf_buffer
*rb
;
6384 rb
= rcu_dereference(event
->rb
);
6385 if (!rb
|| !rb
->nr_pages
) {
6389 rb_toggle_paused(rb
, !!arg
);
6394 case PERF_EVENT_IOC_QUERY_BPF
:
6395 return perf_event_query_prog_array(event
, (void __user
*)arg
);
6397 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES
: {
6398 struct perf_event_attr new_attr
;
6399 int err
= perf_copy_attr((struct perf_event_attr __user
*)arg
,
6405 return perf_event_modify_attr(event
, &new_attr
);
6411 if (flags
& PERF_IOC_FLAG_GROUP
)
6412 perf_event_for_each(event
, func
);
6414 perf_event_for_each_child(event
, func
);
6419 static long perf_ioctl(struct file
*file
, unsigned int cmd
, unsigned long arg
)
6421 struct perf_event
*event
= file
->private_data
;
6422 struct perf_event_context
*ctx
;
6425 /* Treat ioctl like writes as it is likely a mutating operation. */
6426 ret
= security_perf_event_write(event
);
6430 ctx
= perf_event_ctx_lock(event
);
6431 ret
= _perf_ioctl(event
, cmd
, arg
);
6432 perf_event_ctx_unlock(event
, ctx
);
6437 #ifdef CONFIG_COMPAT
6438 static long perf_compat_ioctl(struct file
*file
, unsigned int cmd
,
6441 switch (_IOC_NR(cmd
)) {
6442 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER
):
6443 case _IOC_NR(PERF_EVENT_IOC_ID
):
6444 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF
):
6445 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES
):
6446 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
6447 if (_IOC_SIZE(cmd
) == sizeof(compat_uptr_t
)) {
6448 cmd
&= ~IOCSIZE_MASK
;
6449 cmd
|= sizeof(void *) << IOCSIZE_SHIFT
;
6453 return perf_ioctl(file
, cmd
, arg
);
6456 # define perf_compat_ioctl NULL
6459 int perf_event_task_enable(void)
6461 struct perf_event_context
*ctx
;
6462 struct perf_event
*event
;
6464 mutex_lock(¤t
->perf_event_mutex
);
6465 list_for_each_entry(event
, ¤t
->perf_event_list
, owner_entry
) {
6466 ctx
= perf_event_ctx_lock(event
);
6467 perf_event_for_each_child(event
, _perf_event_enable
);
6468 perf_event_ctx_unlock(event
, ctx
);
6470 mutex_unlock(¤t
->perf_event_mutex
);
6475 int perf_event_task_disable(void)
6477 struct perf_event_context
*ctx
;
6478 struct perf_event
*event
;
6480 mutex_lock(¤t
->perf_event_mutex
);
6481 list_for_each_entry(event
, ¤t
->perf_event_list
, owner_entry
) {
6482 ctx
= perf_event_ctx_lock(event
);
6483 perf_event_for_each_child(event
, _perf_event_disable
);
6484 perf_event_ctx_unlock(event
, ctx
);
6486 mutex_unlock(¤t
->perf_event_mutex
);
6491 static int perf_event_index(struct perf_event
*event
)
6493 if (event
->hw
.state
& PERF_HES_STOPPED
)
6496 if (event
->state
!= PERF_EVENT_STATE_ACTIVE
)
6499 return event
->pmu
->event_idx(event
);
6502 static void perf_event_init_userpage(struct perf_event
*event
)
6504 struct perf_event_mmap_page
*userpg
;
6505 struct perf_buffer
*rb
;
6508 rb
= rcu_dereference(event
->rb
);
6512 userpg
= rb
->user_page
;
6514 /* Allow new userspace to detect that bit 0 is deprecated */
6515 userpg
->cap_bit0_is_deprecated
= 1;
6516 userpg
->size
= offsetof(struct perf_event_mmap_page
, __reserved
);
6517 userpg
->data_offset
= PAGE_SIZE
;
6518 userpg
->data_size
= perf_data_size(rb
);
6524 void __weak
arch_perf_update_userpage(
6525 struct perf_event
*event
, struct perf_event_mmap_page
*userpg
, u64 now
)
6530 * Callers need to ensure there can be no nesting of this function, otherwise
6531 * the seqlock logic goes bad. We can not serialize this because the arch
6532 * code calls this from NMI context.
6534 void perf_event_update_userpage(struct perf_event
*event
)
6536 struct perf_event_mmap_page
*userpg
;
6537 struct perf_buffer
*rb
;
6538 u64 enabled
, running
, now
;
6541 rb
= rcu_dereference(event
->rb
);
6546 * compute total_time_enabled, total_time_running
6547 * based on snapshot values taken when the event
6548 * was last scheduled in.
6550 * we cannot simply called update_context_time()
6551 * because of locking issue as we can be called in
6554 calc_timer_values(event
, &now
, &enabled
, &running
);
6556 userpg
= rb
->user_page
;
6558 * Disable preemption to guarantee consistent time stamps are stored to
6564 userpg
->index
= perf_event_index(event
);
6565 userpg
->offset
= perf_event_count(event
, false);
6567 userpg
->offset
-= local64_read(&event
->hw
.prev_count
);
6569 userpg
->time_enabled
= enabled
+
6570 atomic64_read(&event
->child_total_time_enabled
);
6572 userpg
->time_running
= running
+
6573 atomic64_read(&event
->child_total_time_running
);
6575 arch_perf_update_userpage(event
, userpg
, now
);
6583 EXPORT_SYMBOL_GPL(perf_event_update_userpage
);
6585 static void ring_buffer_attach(struct perf_event
*event
,
6586 struct perf_buffer
*rb
)
6588 struct perf_buffer
*old_rb
= NULL
;
6589 unsigned long flags
;
6591 WARN_ON_ONCE(event
->parent
);
6595 * Should be impossible, we set this when removing
6596 * event->rb_entry and wait/clear when adding event->rb_entry.
6598 WARN_ON_ONCE(event
->rcu_pending
);
6601 spin_lock_irqsave(&old_rb
->event_lock
, flags
);
6602 list_del_rcu(&event
->rb_entry
);
6603 spin_unlock_irqrestore(&old_rb
->event_lock
, flags
);
6605 event
->rcu_batches
= get_state_synchronize_rcu();
6606 event
->rcu_pending
= 1;
6610 if (event
->rcu_pending
) {
6611 cond_synchronize_rcu(event
->rcu_batches
);
6612 event
->rcu_pending
= 0;
6615 spin_lock_irqsave(&rb
->event_lock
, flags
);
6616 list_add_rcu(&event
->rb_entry
, &rb
->event_list
);
6617 spin_unlock_irqrestore(&rb
->event_lock
, flags
);
6621 * Avoid racing with perf_mmap_close(AUX): stop the event
6622 * before swizzling the event::rb pointer; if it's getting
6623 * unmapped, its aux_mmap_count will be 0 and it won't
6624 * restart. See the comment in __perf_pmu_output_stop().
6626 * Data will inevitably be lost when set_output is done in
6627 * mid-air, but then again, whoever does it like this is
6628 * not in for the data anyway.
6631 perf_event_stop(event
, 0);
6633 rcu_assign_pointer(event
->rb
, rb
);
6636 ring_buffer_put(old_rb
);
6638 * Since we detached before setting the new rb, so that we
6639 * could attach the new rb, we could have missed a wakeup.
6642 wake_up_all(&event
->waitq
);
6646 static void ring_buffer_wakeup(struct perf_event
*event
)
6648 struct perf_buffer
*rb
;
6651 event
= event
->parent
;
6654 rb
= rcu_dereference(event
->rb
);
6656 list_for_each_entry_rcu(event
, &rb
->event_list
, rb_entry
)
6657 wake_up_all(&event
->waitq
);
6662 struct perf_buffer
*ring_buffer_get(struct perf_event
*event
)
6664 struct perf_buffer
*rb
;
6667 event
= event
->parent
;
6670 rb
= rcu_dereference(event
->rb
);
6672 if (!refcount_inc_not_zero(&rb
->refcount
))
6680 void ring_buffer_put(struct perf_buffer
*rb
)
6682 if (!refcount_dec_and_test(&rb
->refcount
))
6685 WARN_ON_ONCE(!list_empty(&rb
->event_list
));
6687 call_rcu(&rb
->rcu_head
, rb_free_rcu
);
6690 typedef void (*mapped_f
)(struct perf_event
*event
, struct mm_struct
*mm
);
6692 #define get_mapped(event, func) \
6693 ({ struct pmu *pmu; \
6694 mapped_f f = NULL; \
6696 pmu = READ_ONCE(event->pmu); \
6702 static void perf_mmap_open(struct vm_area_struct
*vma
)
6704 struct perf_event
*event
= vma
->vm_file
->private_data
;
6705 mapped_f mapped
= get_mapped(event
, event_mapped
);
6707 atomic_inc(&event
->mmap_count
);
6708 atomic_inc(&event
->rb
->mmap_count
);
6711 atomic_inc(&event
->rb
->aux_mmap_count
);
6714 mapped(event
, vma
->vm_mm
);
6717 static void perf_pmu_output_stop(struct perf_event
*event
);
6720 * A buffer can be mmap()ed multiple times; either directly through the same
6721 * event, or through other events by use of perf_event_set_output().
6723 * In order to undo the VM accounting done by perf_mmap() we need to destroy
6724 * the buffer here, where we still have a VM context. This means we need
6725 * to detach all events redirecting to us.
6727 static void perf_mmap_close(struct vm_area_struct
*vma
)
6729 struct perf_event
*event
= vma
->vm_file
->private_data
;
6730 mapped_f unmapped
= get_mapped(event
, event_unmapped
);
6731 struct perf_buffer
*rb
= ring_buffer_get(event
);
6732 struct user_struct
*mmap_user
= rb
->mmap_user
;
6733 int mmap_locked
= rb
->mmap_locked
;
6734 unsigned long size
= perf_data_size(rb
);
6735 bool detach_rest
= false;
6737 /* FIXIES vs perf_pmu_unregister() */
6739 unmapped(event
, vma
->vm_mm
);
6742 * The AUX buffer is strictly a sub-buffer, serialize using aux_mutex
6743 * to avoid complications.
6745 if (rb_has_aux(rb
) && vma
->vm_pgoff
== rb
->aux_pgoff
&&
6746 atomic_dec_and_mutex_lock(&rb
->aux_mmap_count
, &rb
->aux_mutex
)) {
6748 * Stop all AUX events that are writing to this buffer,
6749 * so that we can free its AUX pages and corresponding PMU
6750 * data. Note that after rb::aux_mmap_count dropped to zero,
6751 * they won't start any more (see perf_aux_output_begin()).
6753 perf_pmu_output_stop(event
);
6755 /* now it's safe to free the pages */
6756 atomic_long_sub(rb
->aux_nr_pages
- rb
->aux_mmap_locked
, &mmap_user
->locked_vm
);
6757 atomic64_sub(rb
->aux_mmap_locked
, &vma
->vm_mm
->pinned_vm
);
6759 /* this has to be the last one */
6761 WARN_ON_ONCE(refcount_read(&rb
->aux_refcount
));
6763 mutex_unlock(&rb
->aux_mutex
);
6766 if (atomic_dec_and_test(&rb
->mmap_count
))
6769 if (!atomic_dec_and_mutex_lock(&event
->mmap_count
, &event
->mmap_mutex
))
6772 ring_buffer_attach(event
, NULL
);
6773 mutex_unlock(&event
->mmap_mutex
);
6775 /* If there's still other mmap()s of this buffer, we're done. */
6780 * No other mmap()s, detach from all other events that might redirect
6781 * into the now unreachable buffer. Somewhat complicated by the
6782 * fact that rb::event_lock otherwise nests inside mmap_mutex.
6786 list_for_each_entry_rcu(event
, &rb
->event_list
, rb_entry
) {
6787 if (!atomic_long_inc_not_zero(&event
->refcount
)) {
6789 * This event is en-route to free_event() which will
6790 * detach it and remove it from the list.
6796 mutex_lock(&event
->mmap_mutex
);
6798 * Check we didn't race with perf_event_set_output() which can
6799 * swizzle the rb from under us while we were waiting to
6800 * acquire mmap_mutex.
6802 * If we find a different rb; ignore this event, a next
6803 * iteration will no longer find it on the list. We have to
6804 * still restart the iteration to make sure we're not now
6805 * iterating the wrong list.
6807 if (event
->rb
== rb
)
6808 ring_buffer_attach(event
, NULL
);
6810 mutex_unlock(&event
->mmap_mutex
);
6814 * Restart the iteration; either we're on the wrong list or
6815 * destroyed its integrity by doing a deletion.
6822 * It could be there's still a few 0-ref events on the list; they'll
6823 * get cleaned up by free_event() -- they'll also still have their
6824 * ref on the rb and will free it whenever they are done with it.
6826 * Aside from that, this buffer is 'fully' detached and unmapped,
6827 * undo the VM accounting.
6830 atomic_long_sub((size
>> PAGE_SHIFT
) + 1 - mmap_locked
,
6831 &mmap_user
->locked_vm
);
6832 atomic64_sub(mmap_locked
, &vma
->vm_mm
->pinned_vm
);
6833 free_uid(mmap_user
);
6836 ring_buffer_put(rb
); /* could be last */
6839 static vm_fault_t
perf_mmap_pfn_mkwrite(struct vm_fault
*vmf
)
6841 /* The first page is the user control page, others are read-only. */
6842 return vmf
->pgoff
== 0 ? 0 : VM_FAULT_SIGBUS
;
6845 static const struct vm_operations_struct perf_mmap_vmops
= {
6846 .open
= perf_mmap_open
,
6847 .close
= perf_mmap_close
, /* non mergeable */
6848 .pfn_mkwrite
= perf_mmap_pfn_mkwrite
,
6851 static int map_range(struct perf_buffer
*rb
, struct vm_area_struct
*vma
)
6853 unsigned long nr_pages
= vma_pages(vma
);
6855 unsigned long pagenum
;
6858 * We map this as a VM_PFNMAP VMA.
6860 * This is not ideal as this is designed broadly for mappings of PFNs
6861 * referencing memory-mapped I/O ranges or non-system RAM i.e. for which
6864 * We are mapping kernel-allocated memory (memory we manage ourselves)
6865 * which would more ideally be mapped using vm_insert_page() or a
6866 * similar mechanism, that is as a VM_MIXEDMAP mapping.
6868 * However this won't work here, because:
6870 * 1. It uses vma->vm_page_prot, but this field has not been completely
6871 * setup at the point of the f_op->mmp() hook, so we are unable to
6872 * indicate that this should be mapped CoW in order that the
6873 * mkwrite() hook can be invoked to make the first page R/W and the
6874 * rest R/O as desired.
6876 * 2. Anything other than a VM_PFNMAP of valid PFNs will result in
6877 * vm_normal_page() returning a struct page * pointer, which means
6878 * vm_ops->page_mkwrite() will be invoked rather than
6879 * vm_ops->pfn_mkwrite(), and this means we have to set page->mapping
6880 * to work around retry logic in the fault handler, however this
6881 * field is no longer allowed to be used within struct page.
6883 * 3. Having a struct page * made available in the fault logic also
6884 * means that the page gets put on the rmap and becomes
6885 * inappropriately accessible and subject to map and ref counting.
6887 * Ideally we would have a mechanism that could explicitly express our
6888 * desires, but this is not currently the case, so we instead use
6891 * We manage the lifetime of these mappings with internal refcounts (see
6892 * perf_mmap_open() and perf_mmap_close()) so we ensure the lifetime of
6893 * this mapping is maintained correctly.
6895 for (pagenum
= 0; pagenum
< nr_pages
; pagenum
++) {
6896 unsigned long va
= vma
->vm_start
+ PAGE_SIZE
* pagenum
;
6897 struct page
*page
= perf_mmap_to_page(rb
, vma
->vm_pgoff
+ pagenum
);
6904 /* Map readonly, perf_mmap_pfn_mkwrite() called on write fault. */
6905 err
= remap_pfn_range(vma
, va
, page_to_pfn(page
), PAGE_SIZE
,
6906 vm_get_page_prot(vma
->vm_flags
& ~VM_SHARED
));
6912 /* Clear any partial mappings on error. */
6914 zap_page_range_single(vma
, vma
->vm_start
, nr_pages
* PAGE_SIZE
, NULL
);
6920 static int perf_mmap(struct file
*file
, struct vm_area_struct
*vma
)
6922 struct perf_event
*event
= file
->private_data
;
6923 unsigned long user_locked
, user_lock_limit
;
6924 struct user_struct
*user
= current_user();
6925 struct mutex
*aux_mutex
= NULL
;
6926 struct perf_buffer
*rb
= NULL
;
6927 unsigned long locked
, lock_limit
;
6928 unsigned long vma_size
;
6929 unsigned long nr_pages
;
6930 long user_extra
= 0, extra
= 0;
6935 * Don't allow mmap() of inherited per-task counters. This would
6936 * create a performance issue due to all children writing to the
6939 if (event
->cpu
== -1 && event
->attr
.inherit
)
6942 if (!(vma
->vm_flags
& VM_SHARED
))
6945 ret
= security_perf_event_read(event
);
6949 vma_size
= vma
->vm_end
- vma
->vm_start
;
6950 nr_pages
= vma_size
/ PAGE_SIZE
;
6952 if (nr_pages
> INT_MAX
)
6955 if (vma_size
!= PAGE_SIZE
* nr_pages
)
6958 user_extra
= nr_pages
;
6960 mutex_lock(&event
->mmap_mutex
);
6964 * This relies on __pmu_detach_event() taking mmap_mutex after marking
6965 * the event REVOKED. Either we observe the state, or __pmu_detach_event()
6966 * will detach the rb created here.
6968 if (event
->state
<= PERF_EVENT_STATE_REVOKED
) {
6973 if (vma
->vm_pgoff
== 0) {
6977 * If we have rb pages ensure they're a power-of-two number, so we
6978 * can do bitmasks instead of modulo.
6980 if (nr_pages
!= 0 && !is_power_of_2(nr_pages
))
6983 WARN_ON_ONCE(event
->ctx
->parent_ctx
);
6986 if (data_page_nr(event
->rb
) != nr_pages
)
6989 if (atomic_inc_not_zero(&event
->rb
->mmap_count
)) {
6991 * Success -- managed to mmap() the same buffer
6995 /* We need the rb to map pages. */
7001 * Raced against perf_mmap_close()'s
7002 * atomic_dec_and_mutex_lock() remove the
7003 * event and continue as if !event->rb
7005 ring_buffer_attach(event
, NULL
);
7010 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
7011 * mapped, all subsequent mappings should have the same size
7012 * and offset. Must be above the normal perf buffer.
7014 u64 aux_offset
, aux_size
;
7020 aux_mutex
= &rb
->aux_mutex
;
7021 mutex_lock(aux_mutex
);
7023 aux_offset
= READ_ONCE(rb
->user_page
->aux_offset
);
7024 aux_size
= READ_ONCE(rb
->user_page
->aux_size
);
7026 if (aux_offset
< perf_data_size(rb
) + PAGE_SIZE
)
7029 if (aux_offset
!= vma
->vm_pgoff
<< PAGE_SHIFT
)
7032 /* already mapped with a different offset */
7033 if (rb_has_aux(rb
) && rb
->aux_pgoff
!= vma
->vm_pgoff
)
7036 if (aux_size
!= vma_size
|| aux_size
!= nr_pages
* PAGE_SIZE
)
7039 /* already mapped with a different size */
7040 if (rb_has_aux(rb
) && rb
->aux_nr_pages
!= nr_pages
)
7043 if (!is_power_of_2(nr_pages
))
7046 if (!atomic_inc_not_zero(&rb
->mmap_count
))
7049 if (rb_has_aux(rb
)) {
7050 atomic_inc(&rb
->aux_mmap_count
);
7055 atomic_set(&rb
->aux_mmap_count
, 1);
7058 user_lock_limit
= sysctl_perf_event_mlock
>> (PAGE_SHIFT
- 10);
7061 * Increase the limit linearly with more CPUs:
7063 user_lock_limit
*= num_online_cpus();
7065 user_locked
= atomic_long_read(&user
->locked_vm
);
7068 * sysctl_perf_event_mlock may have changed, so that
7069 * user->locked_vm > user_lock_limit
7071 if (user_locked
> user_lock_limit
)
7072 user_locked
= user_lock_limit
;
7073 user_locked
+= user_extra
;
7075 if (user_locked
> user_lock_limit
) {
7077 * charge locked_vm until it hits user_lock_limit;
7078 * charge the rest from pinned_vm
7080 extra
= user_locked
- user_lock_limit
;
7081 user_extra
-= extra
;
7084 lock_limit
= rlimit(RLIMIT_MEMLOCK
);
7085 lock_limit
>>= PAGE_SHIFT
;
7086 locked
= atomic64_read(&vma
->vm_mm
->pinned_vm
) + extra
;
7088 if ((locked
> lock_limit
) && perf_is_paranoid() &&
7089 !capable(CAP_IPC_LOCK
)) {
7094 WARN_ON(!rb
&& event
->rb
);
7096 if (vma
->vm_flags
& VM_WRITE
)
7097 flags
|= RING_BUFFER_WRITABLE
;
7100 rb
= rb_alloc(nr_pages
,
7101 event
->attr
.watermark
? event
->attr
.wakeup_watermark
: 0,
7109 atomic_set(&rb
->mmap_count
, 1);
7110 rb
->mmap_user
= get_current_user();
7111 rb
->mmap_locked
= extra
;
7113 ring_buffer_attach(event
, rb
);
7115 perf_event_update_time(event
);
7116 perf_event_init_userpage(event
);
7117 perf_event_update_userpage(event
);
7119 ret
= rb_alloc_aux(rb
, event
, vma
->vm_pgoff
, nr_pages
,
7120 event
->attr
.aux_watermark
, flags
);
7122 rb
->aux_mmap_locked
= extra
;
7129 atomic_long_add(user_extra
, &user
->locked_vm
);
7130 atomic64_add(extra
, &vma
->vm_mm
->pinned_vm
);
7132 atomic_inc(&event
->mmap_count
);
7134 atomic_dec(&rb
->mmap_count
);
7138 mutex_unlock(aux_mutex
);
7139 mutex_unlock(&event
->mmap_mutex
);
7142 * Since pinned accounting is per vm we cannot allow fork() to copy our
7145 vm_flags_set(vma
, VM_DONTCOPY
| VM_DONTEXPAND
| VM_DONTDUMP
);
7146 vma
->vm_ops
= &perf_mmap_vmops
;
7149 ret
= map_range(rb
, vma
);
7151 mapped
= get_mapped(event
, event_mapped
);
7153 mapped(event
, vma
->vm_mm
);
7158 static int perf_fasync(int fd
, struct file
*filp
, int on
)
7160 struct inode
*inode
= file_inode(filp
);
7161 struct perf_event
*event
= filp
->private_data
;
7164 if (event
->state
<= PERF_EVENT_STATE_REVOKED
)
7168 retval
= fasync_helper(fd
, filp
, on
, &event
->fasync
);
7169 inode_unlock(inode
);
7177 static const struct file_operations perf_fops
= {
7178 .release
= perf_release
,
7181 .unlocked_ioctl
= perf_ioctl
,
7182 .compat_ioctl
= perf_compat_ioctl
,
7184 .fasync
= perf_fasync
,
7190 * If there's data, ensure we set the poll() state and publish everything
7191 * to user-space before waking everybody up.
7194 void perf_event_wakeup(struct perf_event
*event
)
7196 ring_buffer_wakeup(event
);
7198 if (event
->pending_kill
) {
7199 kill_fasync(perf_event_fasync(event
), SIGIO
, event
->pending_kill
);
7200 event
->pending_kill
= 0;
7204 static void perf_sigtrap(struct perf_event
*event
)
7207 * We'd expect this to only occur if the irq_work is delayed and either
7208 * ctx->task or current has changed in the meantime. This can be the
7209 * case on architectures that do not implement arch_irq_work_raise().
7211 if (WARN_ON_ONCE(event
->ctx
->task
!= current
))
7215 * Both perf_pending_task() and perf_pending_irq() can race with the
7218 if (current
->flags
& PF_EXITING
)
7221 send_sig_perf((void __user
*)event
->pending_addr
,
7222 event
->orig_type
, event
->attr
.sig_data
);
7226 * Deliver the pending work in-event-context or follow the context.
7228 static void __perf_pending_disable(struct perf_event
*event
)
7230 int cpu
= READ_ONCE(event
->oncpu
);
7233 * If the event isn't running; we done. event_sched_out() will have
7234 * taken care of things.
7240 * Yay, we hit home and are in the context of the event.
7242 if (cpu
== smp_processor_id()) {
7243 if (event
->pending_disable
) {
7244 event
->pending_disable
= 0;
7245 perf_event_disable_local(event
);
7253 * perf_event_disable_inatomic()
7254 * @pending_disable = 1;
7258 * @pending_disable = 0;
7261 * perf_event_disable_inatomic()
7262 * @pending_disable = 1;
7263 * irq_work_queue(); // FAILS
7266 * perf_pending_disable()
7268 * But the event runs on CPU-B and wants disabling there.
7270 irq_work_queue_on(&event
->pending_disable_irq
, cpu
);
7273 static void perf_pending_disable(struct irq_work
*entry
)
7275 struct perf_event
*event
= container_of(entry
, struct perf_event
, pending_disable_irq
);
7279 * If we 'fail' here, that's OK, it means recursion is already disabled
7280 * and we won't recurse 'further'.
7282 rctx
= perf_swevent_get_recursion_context();
7283 __perf_pending_disable(event
);
7285 perf_swevent_put_recursion_context(rctx
);
7288 static void perf_pending_irq(struct irq_work
*entry
)
7290 struct perf_event
*event
= container_of(entry
, struct perf_event
, pending_irq
);
7294 * If we 'fail' here, that's OK, it means recursion is already disabled
7295 * and we won't recurse 'further'.
7297 rctx
= perf_swevent_get_recursion_context();
7300 * The wakeup isn't bound to the context of the event -- it can happen
7301 * irrespective of where the event is.
7303 if (event
->pending_wakeup
) {
7304 event
->pending_wakeup
= 0;
7305 perf_event_wakeup(event
);
7309 perf_swevent_put_recursion_context(rctx
);
7312 static void perf_pending_task(struct callback_head
*head
)
7314 struct perf_event
*event
= container_of(head
, struct perf_event
, pending_task
);
7318 * If we 'fail' here, that's OK, it means recursion is already disabled
7319 * and we won't recurse 'further'.
7321 rctx
= perf_swevent_get_recursion_context();
7323 if (event
->pending_work
) {
7324 event
->pending_work
= 0;
7325 perf_sigtrap(event
);
7326 local_dec(&event
->ctx
->nr_no_switch_fast
);
7331 perf_swevent_put_recursion_context(rctx
);
7334 #ifdef CONFIG_GUEST_PERF_EVENTS
7335 struct perf_guest_info_callbacks __rcu
*perf_guest_cbs
;
7337 DEFINE_STATIC_CALL_RET0(__perf_guest_state
, *perf_guest_cbs
->state
);
7338 DEFINE_STATIC_CALL_RET0(__perf_guest_get_ip
, *perf_guest_cbs
->get_ip
);
7339 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_intel_pt_intr
, *perf_guest_cbs
->handle_intel_pt_intr
);
7341 void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks
*cbs
)
7343 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs
)))
7346 rcu_assign_pointer(perf_guest_cbs
, cbs
);
7347 static_call_update(__perf_guest_state
, cbs
->state
);
7348 static_call_update(__perf_guest_get_ip
, cbs
->get_ip
);
7350 /* Implementing ->handle_intel_pt_intr is optional. */
7351 if (cbs
->handle_intel_pt_intr
)
7352 static_call_update(__perf_guest_handle_intel_pt_intr
,
7353 cbs
->handle_intel_pt_intr
);
7355 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks
);
7357 void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks
*cbs
)
7359 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs
) != cbs
))
7362 rcu_assign_pointer(perf_guest_cbs
, NULL
);
7363 static_call_update(__perf_guest_state
, (void *)&__static_call_return0
);
7364 static_call_update(__perf_guest_get_ip
, (void *)&__static_call_return0
);
7365 static_call_update(__perf_guest_handle_intel_pt_intr
,
7366 (void *)&__static_call_return0
);
7369 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks
);
7372 static bool should_sample_guest(struct perf_event
*event
)
7374 return !event
->attr
.exclude_guest
&& perf_guest_state();
7377 unsigned long perf_misc_flags(struct perf_event
*event
,
7378 struct pt_regs
*regs
)
7380 if (should_sample_guest(event
))
7381 return perf_arch_guest_misc_flags(regs
);
7383 return perf_arch_misc_flags(regs
);
7386 unsigned long perf_instruction_pointer(struct perf_event
*event
,
7387 struct pt_regs
*regs
)
7389 if (should_sample_guest(event
))
7390 return perf_guest_get_ip();
7392 return perf_arch_instruction_pointer(regs
);
7396 perf_output_sample_regs(struct perf_output_handle
*handle
,
7397 struct pt_regs
*regs
, u64 mask
)
7400 DECLARE_BITMAP(_mask
, 64);
7402 bitmap_from_u64(_mask
, mask
);
7403 for_each_set_bit(bit
, _mask
, sizeof(mask
) * BITS_PER_BYTE
) {
7406 val
= perf_reg_value(regs
, bit
);
7407 perf_output_put(handle
, val
);
7411 static void perf_sample_regs_user(struct perf_regs
*regs_user
,
7412 struct pt_regs
*regs
)
7414 if (user_mode(regs
)) {
7415 regs_user
->abi
= perf_reg_abi(current
);
7416 regs_user
->regs
= regs
;
7417 } else if (!(current
->flags
& PF_KTHREAD
)) {
7418 perf_get_regs_user(regs_user
, regs
);
7420 regs_user
->abi
= PERF_SAMPLE_REGS_ABI_NONE
;
7421 regs_user
->regs
= NULL
;
7425 static void perf_sample_regs_intr(struct perf_regs
*regs_intr
,
7426 struct pt_regs
*regs
)
7428 regs_intr
->regs
= regs
;
7429 regs_intr
->abi
= perf_reg_abi(current
);
7434 * Get remaining task size from user stack pointer.
7436 * It'd be better to take stack vma map and limit this more
7437 * precisely, but there's no way to get it safely under interrupt,
7438 * so using TASK_SIZE as limit.
7440 static u64
perf_ustack_task_size(struct pt_regs
*regs
)
7442 unsigned long addr
= perf_user_stack_pointer(regs
);
7444 if (!addr
|| addr
>= TASK_SIZE
)
7447 return TASK_SIZE
- addr
;
7451 perf_sample_ustack_size(u16 stack_size
, u16 header_size
,
7452 struct pt_regs
*regs
)
7456 /* No regs, no stack pointer, no dump. */
7460 /* No mm, no stack, no dump. */
7465 * Check if we fit in with the requested stack size into the:
7467 * If we don't, we limit the size to the TASK_SIZE.
7469 * - remaining sample size
7470 * If we don't, we customize the stack size to
7471 * fit in to the remaining sample size.
7474 task_size
= min((u64
) USHRT_MAX
, perf_ustack_task_size(regs
));
7475 stack_size
= min(stack_size
, (u16
) task_size
);
7477 /* Current header size plus static size and dynamic size. */
7478 header_size
+= 2 * sizeof(u64
);
7480 /* Do we fit in with the current stack dump size? */
7481 if ((u16
) (header_size
+ stack_size
) < header_size
) {
7483 * If we overflow the maximum size for the sample,
7484 * we customize the stack dump size to fit in.
7486 stack_size
= USHRT_MAX
- header_size
- sizeof(u64
);
7487 stack_size
= round_up(stack_size
, sizeof(u64
));
7494 perf_output_sample_ustack(struct perf_output_handle
*handle
, u64 dump_size
,
7495 struct pt_regs
*regs
)
7497 /* Case of a kernel thread, nothing to dump */
7500 perf_output_put(handle
, size
);
7509 * - the size requested by user or the best one we can fit
7510 * in to the sample max size
7512 * - user stack dump data
7514 * - the actual dumped size
7518 perf_output_put(handle
, dump_size
);
7521 sp
= perf_user_stack_pointer(regs
);
7522 rem
= __output_copy_user(handle
, (void *) sp
, dump_size
);
7523 dyn_size
= dump_size
- rem
;
7525 perf_output_skip(handle
, rem
);
7528 perf_output_put(handle
, dyn_size
);
7532 static unsigned long perf_prepare_sample_aux(struct perf_event
*event
,
7533 struct perf_sample_data
*data
,
7536 struct perf_event
*sampler
= event
->aux_event
;
7537 struct perf_buffer
*rb
;
7544 if (WARN_ON_ONCE(READ_ONCE(sampler
->state
) != PERF_EVENT_STATE_ACTIVE
))
7547 if (WARN_ON_ONCE(READ_ONCE(sampler
->oncpu
) != smp_processor_id()))
7550 rb
= ring_buffer_get(sampler
);
7555 * If this is an NMI hit inside sampling code, don't take
7556 * the sample. See also perf_aux_sample_output().
7558 if (READ_ONCE(rb
->aux_in_sampling
)) {
7561 size
= min_t(size_t, size
, perf_aux_size(rb
));
7562 data
->aux_size
= ALIGN(size
, sizeof(u64
));
7564 ring_buffer_put(rb
);
7567 return data
->aux_size
;
7570 static long perf_pmu_snapshot_aux(struct perf_buffer
*rb
,
7571 struct perf_event
*event
,
7572 struct perf_output_handle
*handle
,
7575 unsigned long flags
;
7579 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
7580 * paths. If we start calling them in NMI context, they may race with
7581 * the IRQ ones, that is, for example, re-starting an event that's just
7582 * been stopped, which is why we're using a separate callback that
7583 * doesn't change the event state.
7585 * IRQs need to be disabled to prevent IPIs from racing with us.
7587 local_irq_save(flags
);
7589 * Guard against NMI hits inside the critical section;
7590 * see also perf_prepare_sample_aux().
7592 WRITE_ONCE(rb
->aux_in_sampling
, 1);
7595 ret
= event
->pmu
->snapshot_aux(event
, handle
, size
);
7598 WRITE_ONCE(rb
->aux_in_sampling
, 0);
7599 local_irq_restore(flags
);
7604 static void perf_aux_sample_output(struct perf_event
*event
,
7605 struct perf_output_handle
*handle
,
7606 struct perf_sample_data
*data
)
7608 struct perf_event
*sampler
= event
->aux_event
;
7609 struct perf_buffer
*rb
;
7613 if (WARN_ON_ONCE(!sampler
|| !data
->aux_size
))
7616 rb
= ring_buffer_get(sampler
);
7620 size
= perf_pmu_snapshot_aux(rb
, sampler
, handle
, data
->aux_size
);
7623 * An error here means that perf_output_copy() failed (returned a
7624 * non-zero surplus that it didn't copy), which in its current
7625 * enlightened implementation is not possible. If that changes, we'd
7628 if (WARN_ON_ONCE(size
< 0))
7632 * The pad comes from ALIGN()ing data->aux_size up to u64 in
7633 * perf_prepare_sample_aux(), so should not be more than that.
7635 pad
= data
->aux_size
- size
;
7636 if (WARN_ON_ONCE(pad
>= sizeof(u64
)))
7641 perf_output_copy(handle
, &zero
, pad
);
7645 ring_buffer_put(rb
);
7649 * A set of common sample data types saved even for non-sample records
7650 * when event->attr.sample_id_all is set.
7652 #define PERF_SAMPLE_ID_ALL (PERF_SAMPLE_TID | PERF_SAMPLE_TIME | \
7653 PERF_SAMPLE_ID | PERF_SAMPLE_STREAM_ID | \
7654 PERF_SAMPLE_CPU | PERF_SAMPLE_IDENTIFIER)
7656 static void __perf_event_header__init_id(struct perf_sample_data
*data
,
7657 struct perf_event
*event
,
7660 data
->type
= event
->attr
.sample_type
;
7661 data
->sample_flags
|= data
->type
& PERF_SAMPLE_ID_ALL
;
7663 if (sample_type
& PERF_SAMPLE_TID
) {
7664 /* namespace issues */
7665 data
->tid_entry
.pid
= perf_event_pid(event
, current
);
7666 data
->tid_entry
.tid
= perf_event_tid(event
, current
);
7669 if (sample_type
& PERF_SAMPLE_TIME
)
7670 data
->time
= perf_event_clock(event
);
7672 if (sample_type
& (PERF_SAMPLE_ID
| PERF_SAMPLE_IDENTIFIER
))
7673 data
->id
= primary_event_id(event
);
7675 if (sample_type
& PERF_SAMPLE_STREAM_ID
)
7676 data
->stream_id
= event
->id
;
7678 if (sample_type
& PERF_SAMPLE_CPU
) {
7679 data
->cpu_entry
.cpu
= raw_smp_processor_id();
7680 data
->cpu_entry
.reserved
= 0;
7684 void perf_event_header__init_id(struct perf_event_header
*header
,
7685 struct perf_sample_data
*data
,
7686 struct perf_event
*event
)
7688 if (event
->attr
.sample_id_all
) {
7689 header
->size
+= event
->id_header_size
;
7690 __perf_event_header__init_id(data
, event
, event
->attr
.sample_type
);
7694 static void __perf_event__output_id_sample(struct perf_output_handle
*handle
,
7695 struct perf_sample_data
*data
)
7697 u64 sample_type
= data
->type
;
7699 if (sample_type
& PERF_SAMPLE_TID
)
7700 perf_output_put(handle
, data
->tid_entry
);
7702 if (sample_type
& PERF_SAMPLE_TIME
)
7703 perf_output_put(handle
, data
->time
);
7705 if (sample_type
& PERF_SAMPLE_ID
)
7706 perf_output_put(handle
, data
->id
);
7708 if (sample_type
& PERF_SAMPLE_STREAM_ID
)
7709 perf_output_put(handle
, data
->stream_id
);
7711 if (sample_type
& PERF_SAMPLE_CPU
)
7712 perf_output_put(handle
, data
->cpu_entry
);
7714 if (sample_type
& PERF_SAMPLE_IDENTIFIER
)
7715 perf_output_put(handle
, data
->id
);
7718 void perf_event__output_id_sample(struct perf_event
*event
,
7719 struct perf_output_handle
*handle
,
7720 struct perf_sample_data
*sample
)
7722 if (event
->attr
.sample_id_all
)
7723 __perf_event__output_id_sample(handle
, sample
);
7726 static void perf_output_read_one(struct perf_output_handle
*handle
,
7727 struct perf_event
*event
,
7728 u64 enabled
, u64 running
)
7730 u64 read_format
= event
->attr
.read_format
;
7734 values
[n
++] = perf_event_count(event
, has_inherit_and_sample_read(&event
->attr
));
7735 if (read_format
& PERF_FORMAT_TOTAL_TIME_ENABLED
) {
7736 values
[n
++] = enabled
+
7737 atomic64_read(&event
->child_total_time_enabled
);
7739 if (read_format
& PERF_FORMAT_TOTAL_TIME_RUNNING
) {
7740 values
[n
++] = running
+
7741 atomic64_read(&event
->child_total_time_running
);
7743 if (read_format
& PERF_FORMAT_ID
)
7744 values
[n
++] = primary_event_id(event
);
7745 if (read_format
& PERF_FORMAT_LOST
)
7746 values
[n
++] = atomic64_read(&event
->lost_samples
);
7748 __output_copy(handle
, values
, n
* sizeof(u64
));
7751 static void perf_output_read_group(struct perf_output_handle
*handle
,
7752 struct perf_event
*event
,
7753 u64 enabled
, u64 running
)
7755 struct perf_event
*leader
= event
->group_leader
, *sub
;
7756 u64 read_format
= event
->attr
.read_format
;
7757 unsigned long flags
;
7760 bool self
= has_inherit_and_sample_read(&event
->attr
);
7763 * Disabling interrupts avoids all counter scheduling
7764 * (context switches, timer based rotation and IPIs).
7766 local_irq_save(flags
);
7768 values
[n
++] = 1 + leader
->nr_siblings
;
7770 if (read_format
& PERF_FORMAT_TOTAL_TIME_ENABLED
)
7771 values
[n
++] = enabled
;
7773 if (read_format
& PERF_FORMAT_TOTAL_TIME_RUNNING
)
7774 values
[n
++] = running
;
7776 if ((leader
!= event
) && !handle
->skip_read
)
7777 perf_pmu_read(leader
);
7779 values
[n
++] = perf_event_count(leader
, self
);
7780 if (read_format
& PERF_FORMAT_ID
)
7781 values
[n
++] = primary_event_id(leader
);
7782 if (read_format
& PERF_FORMAT_LOST
)
7783 values
[n
++] = atomic64_read(&leader
->lost_samples
);
7785 __output_copy(handle
, values
, n
* sizeof(u64
));
7787 for_each_sibling_event(sub
, leader
) {
7790 if ((sub
!= event
) && !handle
->skip_read
)
7793 values
[n
++] = perf_event_count(sub
, self
);
7794 if (read_format
& PERF_FORMAT_ID
)
7795 values
[n
++] = primary_event_id(sub
);
7796 if (read_format
& PERF_FORMAT_LOST
)
7797 values
[n
++] = atomic64_read(&sub
->lost_samples
);
7799 __output_copy(handle
, values
, n
* sizeof(u64
));
7802 local_irq_restore(flags
);
7805 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
7806 PERF_FORMAT_TOTAL_TIME_RUNNING)
7809 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
7811 * The problem is that its both hard and excessively expensive to iterate the
7812 * child list, not to mention that its impossible to IPI the children running
7813 * on another CPU, from interrupt/NMI context.
7815 * Instead the combination of PERF_SAMPLE_READ and inherit will track per-thread
7816 * counts rather than attempting to accumulate some value across all children on
7819 static void perf_output_read(struct perf_output_handle
*handle
,
7820 struct perf_event
*event
)
7822 u64 enabled
= 0, running
= 0, now
;
7823 u64 read_format
= event
->attr
.read_format
;
7826 * compute total_time_enabled, total_time_running
7827 * based on snapshot values taken when the event
7828 * was last scheduled in.
7830 * we cannot simply called update_context_time()
7831 * because of locking issue as we are called in
7834 if (read_format
& PERF_FORMAT_TOTAL_TIMES
)
7835 calc_timer_values(event
, &now
, &enabled
, &running
);
7837 if (event
->attr
.read_format
& PERF_FORMAT_GROUP
)
7838 perf_output_read_group(handle
, event
, enabled
, running
);
7840 perf_output_read_one(handle
, event
, enabled
, running
);
7843 void perf_output_sample(struct perf_output_handle
*handle
,
7844 struct perf_event_header
*header
,
7845 struct perf_sample_data
*data
,
7846 struct perf_event
*event
)
7848 u64 sample_type
= data
->type
;
7850 if (data
->sample_flags
& PERF_SAMPLE_READ
)
7851 handle
->skip_read
= 1;
7853 perf_output_put(handle
, *header
);
7855 if (sample_type
& PERF_SAMPLE_IDENTIFIER
)
7856 perf_output_put(handle
, data
->id
);
7858 if (sample_type
& PERF_SAMPLE_IP
)
7859 perf_output_put(handle
, data
->ip
);
7861 if (sample_type
& PERF_SAMPLE_TID
)
7862 perf_output_put(handle
, data
->tid_entry
);
7864 if (sample_type
& PERF_SAMPLE_TIME
)
7865 perf_output_put(handle
, data
->time
);
7867 if (sample_type
& PERF_SAMPLE_ADDR
)
7868 perf_output_put(handle
, data
->addr
);
7870 if (sample_type
& PERF_SAMPLE_ID
)
7871 perf_output_put(handle
, data
->id
);
7873 if (sample_type
& PERF_SAMPLE_STREAM_ID
)
7874 perf_output_put(handle
, data
->stream_id
);
7876 if (sample_type
& PERF_SAMPLE_CPU
)
7877 perf_output_put(handle
, data
->cpu_entry
);
7879 if (sample_type
& PERF_SAMPLE_PERIOD
)
7880 perf_output_put(handle
, data
->period
);
7882 if (sample_type
& PERF_SAMPLE_READ
)
7883 perf_output_read(handle
, event
);
7885 if (sample_type
& PERF_SAMPLE_CALLCHAIN
) {
7888 size
+= data
->callchain
->nr
;
7889 size
*= sizeof(u64
);
7890 __output_copy(handle
, data
->callchain
, size
);
7893 if (sample_type
& PERF_SAMPLE_RAW
) {
7894 struct perf_raw_record
*raw
= data
->raw
;
7897 struct perf_raw_frag
*frag
= &raw
->frag
;
7899 perf_output_put(handle
, raw
->size
);
7902 __output_custom(handle
, frag
->copy
,
7903 frag
->data
, frag
->size
);
7905 __output_copy(handle
, frag
->data
,
7908 if (perf_raw_frag_last(frag
))
7913 __output_skip(handle
, NULL
, frag
->pad
);
7919 .size
= sizeof(u32
),
7922 perf_output_put(handle
, raw
);
7926 if (sample_type
& PERF_SAMPLE_BRANCH_STACK
) {
7927 if (data
->br_stack
) {
7930 size
= data
->br_stack
->nr
7931 * sizeof(struct perf_branch_entry
);
7933 perf_output_put(handle
, data
->br_stack
->nr
);
7934 if (branch_sample_hw_index(event
))
7935 perf_output_put(handle
, data
->br_stack
->hw_idx
);
7936 perf_output_copy(handle
, data
->br_stack
->entries
, size
);
7938 * Add the extension space which is appended
7939 * right after the struct perf_branch_stack.
7941 if (data
->br_stack_cntr
) {
7942 size
= data
->br_stack
->nr
* sizeof(u64
);
7943 perf_output_copy(handle
, data
->br_stack_cntr
, size
);
7947 * we always store at least the value of nr
7950 perf_output_put(handle
, nr
);
7954 if (sample_type
& PERF_SAMPLE_REGS_USER
) {
7955 u64 abi
= data
->regs_user
.abi
;
7958 * If there are no regs to dump, notice it through
7959 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7961 perf_output_put(handle
, abi
);
7964 u64 mask
= event
->attr
.sample_regs_user
;
7965 perf_output_sample_regs(handle
,
7966 data
->regs_user
.regs
,
7971 if (sample_type
& PERF_SAMPLE_STACK_USER
) {
7972 perf_output_sample_ustack(handle
,
7973 data
->stack_user_size
,
7974 data
->regs_user
.regs
);
7977 if (sample_type
& PERF_SAMPLE_WEIGHT_TYPE
)
7978 perf_output_put(handle
, data
->weight
.full
);
7980 if (sample_type
& PERF_SAMPLE_DATA_SRC
)
7981 perf_output_put(handle
, data
->data_src
.val
);
7983 if (sample_type
& PERF_SAMPLE_TRANSACTION
)
7984 perf_output_put(handle
, data
->txn
);
7986 if (sample_type
& PERF_SAMPLE_REGS_INTR
) {
7987 u64 abi
= data
->regs_intr
.abi
;
7989 * If there are no regs to dump, notice it through
7990 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7992 perf_output_put(handle
, abi
);
7995 u64 mask
= event
->attr
.sample_regs_intr
;
7997 perf_output_sample_regs(handle
,
7998 data
->regs_intr
.regs
,
8003 if (sample_type
& PERF_SAMPLE_PHYS_ADDR
)
8004 perf_output_put(handle
, data
->phys_addr
);
8006 if (sample_type
& PERF_SAMPLE_CGROUP
)
8007 perf_output_put(handle
, data
->cgroup
);
8009 if (sample_type
& PERF_SAMPLE_DATA_PAGE_SIZE
)
8010 perf_output_put(handle
, data
->data_page_size
);
8012 if (sample_type
& PERF_SAMPLE_CODE_PAGE_SIZE
)
8013 perf_output_put(handle
, data
->code_page_size
);
8015 if (sample_type
& PERF_SAMPLE_AUX
) {
8016 perf_output_put(handle
, data
->aux_size
);
8019 perf_aux_sample_output(event
, handle
, data
);
8022 if (!event
->attr
.watermark
) {
8023 int wakeup_events
= event
->attr
.wakeup_events
;
8025 if (wakeup_events
) {
8026 struct perf_buffer
*rb
= handle
->rb
;
8027 int events
= local_inc_return(&rb
->events
);
8029 if (events
>= wakeup_events
) {
8030 local_sub(wakeup_events
, &rb
->events
);
8031 local_inc(&rb
->wakeup
);
8037 static u64
perf_virt_to_phys(u64 virt
)
8044 if (virt
>= TASK_SIZE
) {
8045 /* If it's vmalloc()d memory, leave phys_addr as 0 */
8046 if (virt_addr_valid((void *)(uintptr_t)virt
) &&
8047 !(virt
>= VMALLOC_START
&& virt
< VMALLOC_END
))
8048 phys_addr
= (u64
)virt_to_phys((void *)(uintptr_t)virt
);
8051 * Walking the pages tables for user address.
8052 * Interrupts are disabled, so it prevents any tear down
8053 * of the page tables.
8054 * Try IRQ-safe get_user_page_fast_only first.
8055 * If failed, leave phys_addr as 0.
8057 if (current
->mm
!= NULL
) {
8060 pagefault_disable();
8061 if (get_user_page_fast_only(virt
, 0, &p
)) {
8062 phys_addr
= page_to_phys(p
) + virt
% PAGE_SIZE
;
8073 * Return the pagetable size of a given virtual address.
8075 static u64
perf_get_pgtable_size(struct mm_struct
*mm
, unsigned long addr
)
8079 #ifdef CONFIG_HAVE_GUP_FAST
8086 pgdp
= pgd_offset(mm
, addr
);
8087 pgd
= READ_ONCE(*pgdp
);
8092 return pgd_leaf_size(pgd
);
8094 p4dp
= p4d_offset_lockless(pgdp
, pgd
, addr
);
8095 p4d
= READ_ONCE(*p4dp
);
8096 if (!p4d_present(p4d
))
8100 return p4d_leaf_size(p4d
);
8102 pudp
= pud_offset_lockless(p4dp
, p4d
, addr
);
8103 pud
= READ_ONCE(*pudp
);
8104 if (!pud_present(pud
))
8108 return pud_leaf_size(pud
);
8110 pmdp
= pmd_offset_lockless(pudp
, pud
, addr
);
8112 pmd
= pmdp_get_lockless(pmdp
);
8113 if (!pmd_present(pmd
))
8117 return pmd_leaf_size(pmd
);
8119 ptep
= pte_offset_map(&pmd
, addr
);
8123 pte
= ptep_get_lockless(ptep
);
8124 if (pte_present(pte
))
8125 size
= __pte_leaf_size(pmd
, pte
);
8127 #endif /* CONFIG_HAVE_GUP_FAST */
8132 static u64
perf_get_page_size(unsigned long addr
)
8134 struct mm_struct
*mm
;
8135 unsigned long flags
;
8142 * Software page-table walkers must disable IRQs,
8143 * which prevents any tear down of the page tables.
8145 local_irq_save(flags
);
8150 * For kernel threads and the like, use init_mm so that
8151 * we can find kernel memory.
8156 size
= perf_get_pgtable_size(mm
, addr
);
8158 local_irq_restore(flags
);
8163 static struct perf_callchain_entry __empty_callchain
= { .nr
= 0, };
8165 struct perf_callchain_entry
*
8166 perf_callchain(struct perf_event
*event
, struct pt_regs
*regs
)
8168 bool kernel
= !event
->attr
.exclude_callchain_kernel
;
8169 bool user
= !event
->attr
.exclude_callchain_user
;
8170 /* Disallow cross-task user callchains. */
8171 bool crosstask
= event
->ctx
->task
&& event
->ctx
->task
!= current
;
8172 const u32 max_stack
= event
->attr
.sample_max_stack
;
8173 struct perf_callchain_entry
*callchain
;
8178 if (!kernel
&& !user
)
8179 return &__empty_callchain
;
8181 callchain
= get_perf_callchain(regs
, 0, kernel
, user
,
8182 max_stack
, crosstask
, true);
8183 return callchain
?: &__empty_callchain
;
8186 static __always_inline u64
__cond_set(u64 flags
, u64 s
, u64 d
)
8188 return d
* !!(flags
& s
);
8191 void perf_prepare_sample(struct perf_sample_data
*data
,
8192 struct perf_event
*event
,
8193 struct pt_regs
*regs
)
8195 u64 sample_type
= event
->attr
.sample_type
;
8196 u64 filtered_sample_type
;
8199 * Add the sample flags that are dependent to others. And clear the
8200 * sample flags that have already been done by the PMU driver.
8202 filtered_sample_type
= sample_type
;
8203 filtered_sample_type
|= __cond_set(sample_type
, PERF_SAMPLE_CODE_PAGE_SIZE
,
8205 filtered_sample_type
|= __cond_set(sample_type
, PERF_SAMPLE_DATA_PAGE_SIZE
|
8206 PERF_SAMPLE_PHYS_ADDR
, PERF_SAMPLE_ADDR
);
8207 filtered_sample_type
|= __cond_set(sample_type
, PERF_SAMPLE_STACK_USER
,
8208 PERF_SAMPLE_REGS_USER
);
8209 filtered_sample_type
&= ~data
->sample_flags
;
8211 if (filtered_sample_type
== 0) {
8212 /* Make sure it has the correct data->type for output */
8213 data
->type
= event
->attr
.sample_type
;
8217 __perf_event_header__init_id(data
, event
, filtered_sample_type
);
8219 if (filtered_sample_type
& PERF_SAMPLE_IP
) {
8220 data
->ip
= perf_instruction_pointer(event
, regs
);
8221 data
->sample_flags
|= PERF_SAMPLE_IP
;
8224 if (filtered_sample_type
& PERF_SAMPLE_CALLCHAIN
)
8225 perf_sample_save_callchain(data
, event
, regs
);
8227 if (filtered_sample_type
& PERF_SAMPLE_RAW
) {
8229 data
->dyn_size
+= sizeof(u64
);
8230 data
->sample_flags
|= PERF_SAMPLE_RAW
;
8233 if (filtered_sample_type
& PERF_SAMPLE_BRANCH_STACK
) {
8234 data
->br_stack
= NULL
;
8235 data
->dyn_size
+= sizeof(u64
);
8236 data
->sample_flags
|= PERF_SAMPLE_BRANCH_STACK
;
8239 if (filtered_sample_type
& PERF_SAMPLE_REGS_USER
)
8240 perf_sample_regs_user(&data
->regs_user
, regs
);
8243 * It cannot use the filtered_sample_type here as REGS_USER can be set
8244 * by STACK_USER (using __cond_set() above) and we don't want to update
8245 * the dyn_size if it's not requested by users.
8247 if ((sample_type
& ~data
->sample_flags
) & PERF_SAMPLE_REGS_USER
) {
8248 /* regs dump ABI info */
8249 int size
= sizeof(u64
);
8251 if (data
->regs_user
.regs
) {
8252 u64 mask
= event
->attr
.sample_regs_user
;
8253 size
+= hweight64(mask
) * sizeof(u64
);
8256 data
->dyn_size
+= size
;
8257 data
->sample_flags
|= PERF_SAMPLE_REGS_USER
;
8260 if (filtered_sample_type
& PERF_SAMPLE_STACK_USER
) {
8262 * Either we need PERF_SAMPLE_STACK_USER bit to be always
8263 * processed as the last one or have additional check added
8264 * in case new sample type is added, because we could eat
8265 * up the rest of the sample size.
8267 u16 stack_size
= event
->attr
.sample_stack_user
;
8268 u16 header_size
= perf_sample_data_size(data
, event
);
8269 u16 size
= sizeof(u64
);
8271 stack_size
= perf_sample_ustack_size(stack_size
, header_size
,
8272 data
->regs_user
.regs
);
8275 * If there is something to dump, add space for the dump
8276 * itself and for the field that tells the dynamic size,
8277 * which is how many have been actually dumped.
8280 size
+= sizeof(u64
) + stack_size
;
8282 data
->stack_user_size
= stack_size
;
8283 data
->dyn_size
+= size
;
8284 data
->sample_flags
|= PERF_SAMPLE_STACK_USER
;
8287 if (filtered_sample_type
& PERF_SAMPLE_WEIGHT_TYPE
) {
8288 data
->weight
.full
= 0;
8289 data
->sample_flags
|= PERF_SAMPLE_WEIGHT_TYPE
;
8292 if (filtered_sample_type
& PERF_SAMPLE_DATA_SRC
) {
8293 data
->data_src
.val
= PERF_MEM_NA
;
8294 data
->sample_flags
|= PERF_SAMPLE_DATA_SRC
;
8297 if (filtered_sample_type
& PERF_SAMPLE_TRANSACTION
) {
8299 data
->sample_flags
|= PERF_SAMPLE_TRANSACTION
;
8302 if (filtered_sample_type
& PERF_SAMPLE_ADDR
) {
8304 data
->sample_flags
|= PERF_SAMPLE_ADDR
;
8307 if (filtered_sample_type
& PERF_SAMPLE_REGS_INTR
) {
8308 /* regs dump ABI info */
8309 int size
= sizeof(u64
);
8311 perf_sample_regs_intr(&data
->regs_intr
, regs
);
8313 if (data
->regs_intr
.regs
) {
8314 u64 mask
= event
->attr
.sample_regs_intr
;
8316 size
+= hweight64(mask
) * sizeof(u64
);
8319 data
->dyn_size
+= size
;
8320 data
->sample_flags
|= PERF_SAMPLE_REGS_INTR
;
8323 if (filtered_sample_type
& PERF_SAMPLE_PHYS_ADDR
) {
8324 data
->phys_addr
= perf_virt_to_phys(data
->addr
);
8325 data
->sample_flags
|= PERF_SAMPLE_PHYS_ADDR
;
8328 #ifdef CONFIG_CGROUP_PERF
8329 if (filtered_sample_type
& PERF_SAMPLE_CGROUP
) {
8330 struct cgroup
*cgrp
;
8332 /* protected by RCU */
8333 cgrp
= task_css_check(current
, perf_event_cgrp_id
, 1)->cgroup
;
8334 data
->cgroup
= cgroup_id(cgrp
);
8335 data
->sample_flags
|= PERF_SAMPLE_CGROUP
;
8340 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't
8341 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr,
8342 * but the value will not dump to the userspace.
8344 if (filtered_sample_type
& PERF_SAMPLE_DATA_PAGE_SIZE
) {
8345 data
->data_page_size
= perf_get_page_size(data
->addr
);
8346 data
->sample_flags
|= PERF_SAMPLE_DATA_PAGE_SIZE
;
8349 if (filtered_sample_type
& PERF_SAMPLE_CODE_PAGE_SIZE
) {
8350 data
->code_page_size
= perf_get_page_size(data
->ip
);
8351 data
->sample_flags
|= PERF_SAMPLE_CODE_PAGE_SIZE
;
8354 if (filtered_sample_type
& PERF_SAMPLE_AUX
) {
8356 u16 header_size
= perf_sample_data_size(data
, event
);
8358 header_size
+= sizeof(u64
); /* size */
8361 * Given the 16bit nature of header::size, an AUX sample can
8362 * easily overflow it, what with all the preceding sample bits.
8363 * Make sure this doesn't happen by using up to U16_MAX bytes
8364 * per sample in total (rounded down to 8 byte boundary).
8366 size
= min_t(size_t, U16_MAX
- header_size
,
8367 event
->attr
.aux_sample_size
);
8368 size
= rounddown(size
, 8);
8369 size
= perf_prepare_sample_aux(event
, data
, size
);
8371 WARN_ON_ONCE(size
+ header_size
> U16_MAX
);
8372 data
->dyn_size
+= size
+ sizeof(u64
); /* size above */
8373 data
->sample_flags
|= PERF_SAMPLE_AUX
;
8377 void perf_prepare_header(struct perf_event_header
*header
,
8378 struct perf_sample_data
*data
,
8379 struct perf_event
*event
,
8380 struct pt_regs
*regs
)
8382 header
->type
= PERF_RECORD_SAMPLE
;
8383 header
->size
= perf_sample_data_size(data
, event
);
8384 header
->misc
= perf_misc_flags(event
, regs
);
8387 * If you're adding more sample types here, you likely need to do
8388 * something about the overflowing header::size, like repurpose the
8389 * lowest 3 bits of size, which should be always zero at the moment.
8390 * This raises a more important question, do we really need 512k sized
8391 * samples and why, so good argumentation is in order for whatever you
8394 WARN_ON_ONCE(header
->size
& 7);
8397 static void __perf_event_aux_pause(struct perf_event
*event
, bool pause
)
8400 if (!event
->hw
.aux_paused
) {
8401 event
->hw
.aux_paused
= 1;
8402 event
->pmu
->stop(event
, PERF_EF_PAUSE
);
8405 if (event
->hw
.aux_paused
) {
8406 event
->hw
.aux_paused
= 0;
8407 event
->pmu
->start(event
, PERF_EF_RESUME
);
8412 static void perf_event_aux_pause(struct perf_event
*event
, bool pause
)
8414 struct perf_buffer
*rb
;
8416 if (WARN_ON_ONCE(!event
))
8419 rb
= ring_buffer_get(event
);
8423 scoped_guard (irqsave
) {
8425 * Guard against self-recursion here. Another event could trip
8426 * this same from NMI context.
8428 if (READ_ONCE(rb
->aux_in_pause_resume
))
8431 WRITE_ONCE(rb
->aux_in_pause_resume
, 1);
8433 __perf_event_aux_pause(event
, pause
);
8435 WRITE_ONCE(rb
->aux_in_pause_resume
, 0);
8437 ring_buffer_put(rb
);
8440 static __always_inline
int
8441 __perf_event_output(struct perf_event
*event
,
8442 struct perf_sample_data
*data
,
8443 struct pt_regs
*regs
,
8444 int (*output_begin
)(struct perf_output_handle
*,
8445 struct perf_sample_data
*,
8446 struct perf_event
*,
8449 struct perf_output_handle handle
;
8450 struct perf_event_header header
;
8453 /* protect the callchain buffers */
8456 perf_prepare_sample(data
, event
, regs
);
8457 perf_prepare_header(&header
, data
, event
, regs
);
8459 err
= output_begin(&handle
, data
, event
, header
.size
);
8463 perf_output_sample(&handle
, &header
, data
, event
);
8465 perf_output_end(&handle
);
8473 perf_event_output_forward(struct perf_event
*event
,
8474 struct perf_sample_data
*data
,
8475 struct pt_regs
*regs
)
8477 __perf_event_output(event
, data
, regs
, perf_output_begin_forward
);
8481 perf_event_output_backward(struct perf_event
*event
,
8482 struct perf_sample_data
*data
,
8483 struct pt_regs
*regs
)
8485 __perf_event_output(event
, data
, regs
, perf_output_begin_backward
);
8489 perf_event_output(struct perf_event
*event
,
8490 struct perf_sample_data
*data
,
8491 struct pt_regs
*regs
)
8493 return __perf_event_output(event
, data
, regs
, perf_output_begin
);
8500 struct perf_read_event
{
8501 struct perf_event_header header
;
8508 perf_event_read_event(struct perf_event
*event
,
8509 struct task_struct
*task
)
8511 struct perf_output_handle handle
;
8512 struct perf_sample_data sample
;
8513 struct perf_read_event read_event
= {
8515 .type
= PERF_RECORD_READ
,
8517 .size
= sizeof(read_event
) + event
->read_size
,
8519 .pid
= perf_event_pid(event
, task
),
8520 .tid
= perf_event_tid(event
, task
),
8524 perf_event_header__init_id(&read_event
.header
, &sample
, event
);
8525 ret
= perf_output_begin(&handle
, &sample
, event
, read_event
.header
.size
);
8529 perf_output_put(&handle
, read_event
);
8530 perf_output_read(&handle
, event
);
8531 perf_event__output_id_sample(event
, &handle
, &sample
);
8533 perf_output_end(&handle
);
8536 typedef void (perf_iterate_f
)(struct perf_event
*event
, void *data
);
8539 perf_iterate_ctx(struct perf_event_context
*ctx
,
8540 perf_iterate_f output
,
8541 void *data
, bool all
)
8543 struct perf_event
*event
;
8545 list_for_each_entry_rcu(event
, &ctx
->event_list
, event_entry
) {
8547 if (event
->state
< PERF_EVENT_STATE_INACTIVE
)
8549 if (!event_filter_match(event
))
8553 output(event
, data
);
8557 static void perf_iterate_sb_cpu(perf_iterate_f output
, void *data
)
8559 struct pmu_event_list
*pel
= this_cpu_ptr(&pmu_sb_events
);
8560 struct perf_event
*event
;
8562 list_for_each_entry_rcu(event
, &pel
->list
, sb_list
) {
8564 * Skip events that are not fully formed yet; ensure that
8565 * if we observe event->ctx, both event and ctx will be
8566 * complete enough. See perf_install_in_context().
8568 if (!smp_load_acquire(&event
->ctx
))
8571 if (event
->state
< PERF_EVENT_STATE_INACTIVE
)
8573 if (!event_filter_match(event
))
8575 output(event
, data
);
8580 * Iterate all events that need to receive side-band events.
8582 * For new callers; ensure that account_pmu_sb_event() includes
8583 * your event, otherwise it might not get delivered.
8586 perf_iterate_sb(perf_iterate_f output
, void *data
,
8587 struct perf_event_context
*task_ctx
)
8589 struct perf_event_context
*ctx
;
8595 * If we have task_ctx != NULL we only notify the task context itself.
8596 * The task_ctx is set only for EXIT events before releasing task
8600 perf_iterate_ctx(task_ctx
, output
, data
, false);
8604 perf_iterate_sb_cpu(output
, data
);
8606 ctx
= rcu_dereference(current
->perf_event_ctxp
);
8608 perf_iterate_ctx(ctx
, output
, data
, false);
8615 * Clear all file-based filters at exec, they'll have to be
8616 * re-instated when/if these objects are mmapped again.
8618 static void perf_event_addr_filters_exec(struct perf_event
*event
, void *data
)
8620 struct perf_addr_filters_head
*ifh
= perf_event_addr_filters(event
);
8621 struct perf_addr_filter
*filter
;
8622 unsigned int restart
= 0, count
= 0;
8623 unsigned long flags
;
8625 if (!has_addr_filter(event
))
8628 raw_spin_lock_irqsave(&ifh
->lock
, flags
);
8629 list_for_each_entry(filter
, &ifh
->list
, entry
) {
8630 if (filter
->path
.dentry
) {
8631 event
->addr_filter_ranges
[count
].start
= 0;
8632 event
->addr_filter_ranges
[count
].size
= 0;
8640 event
->addr_filters_gen
++;
8641 raw_spin_unlock_irqrestore(&ifh
->lock
, flags
);
8644 perf_event_stop(event
, 1);
8647 void perf_event_exec(void)
8649 struct perf_event_context
*ctx
;
8651 ctx
= perf_pin_task_context(current
);
8655 perf_event_enable_on_exec(ctx
);
8656 perf_event_remove_on_exec(ctx
);
8658 perf_iterate_ctx(ctx
, perf_event_addr_filters_exec
, NULL
, true);
8660 perf_unpin_context(ctx
);
8664 struct remote_output
{
8665 struct perf_buffer
*rb
;
8669 static void __perf_event_output_stop(struct perf_event
*event
, void *data
)
8671 struct perf_event
*parent
= event
->parent
;
8672 struct remote_output
*ro
= data
;
8673 struct perf_buffer
*rb
= ro
->rb
;
8674 struct stop_event_data sd
= {
8678 if (!has_aux(event
))
8685 * In case of inheritance, it will be the parent that links to the
8686 * ring-buffer, but it will be the child that's actually using it.
8688 * We are using event::rb to determine if the event should be stopped,
8689 * however this may race with ring_buffer_attach() (through set_output),
8690 * which will make us skip the event that actually needs to be stopped.
8691 * So ring_buffer_attach() has to stop an aux event before re-assigning
8694 if (rcu_dereference(parent
->rb
) == rb
)
8695 ro
->err
= __perf_event_stop(&sd
);
8698 static int __perf_pmu_output_stop(void *info
)
8700 struct perf_event
*event
= info
;
8701 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
8702 struct remote_output ro
= {
8707 perf_iterate_ctx(&cpuctx
->ctx
, __perf_event_output_stop
, &ro
, false);
8708 if (cpuctx
->task_ctx
)
8709 perf_iterate_ctx(cpuctx
->task_ctx
, __perf_event_output_stop
,
8716 static void perf_pmu_output_stop(struct perf_event
*event
)
8718 struct perf_event
*iter
;
8723 list_for_each_entry_rcu(iter
, &event
->rb
->event_list
, rb_entry
) {
8725 * For per-CPU events, we need to make sure that neither they
8726 * nor their children are running; for cpu==-1 events it's
8727 * sufficient to stop the event itself if it's active, since
8728 * it can't have children.
8732 cpu
= READ_ONCE(iter
->oncpu
);
8737 err
= cpu_function_call(cpu
, __perf_pmu_output_stop
, event
);
8738 if (err
== -EAGAIN
) {
8747 * task tracking -- fork/exit
8749 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
8752 struct perf_task_event
{
8753 struct task_struct
*task
;
8754 struct perf_event_context
*task_ctx
;
8757 struct perf_event_header header
;
8767 static int perf_event_task_match(struct perf_event
*event
)
8769 return event
->attr
.comm
|| event
->attr
.mmap
||
8770 event
->attr
.mmap2
|| event
->attr
.mmap_data
||
8774 static void perf_event_task_output(struct perf_event
*event
,
8777 struct perf_task_event
*task_event
= data
;
8778 struct perf_output_handle handle
;
8779 struct perf_sample_data sample
;
8780 struct task_struct
*task
= task_event
->task
;
8781 int ret
, size
= task_event
->event_id
.header
.size
;
8783 if (!perf_event_task_match(event
))
8786 perf_event_header__init_id(&task_event
->event_id
.header
, &sample
, event
);
8788 ret
= perf_output_begin(&handle
, &sample
, event
,
8789 task_event
->event_id
.header
.size
);
8793 task_event
->event_id
.pid
= perf_event_pid(event
, task
);
8794 task_event
->event_id
.tid
= perf_event_tid(event
, task
);
8796 if (task_event
->event_id
.header
.type
== PERF_RECORD_EXIT
) {
8797 task_event
->event_id
.ppid
= perf_event_pid(event
,
8799 task_event
->event_id
.ptid
= perf_event_pid(event
,
8801 } else { /* PERF_RECORD_FORK */
8802 task_event
->event_id
.ppid
= perf_event_pid(event
, current
);
8803 task_event
->event_id
.ptid
= perf_event_tid(event
, current
);
8806 task_event
->event_id
.time
= perf_event_clock(event
);
8808 perf_output_put(&handle
, task_event
->event_id
);
8810 perf_event__output_id_sample(event
, &handle
, &sample
);
8812 perf_output_end(&handle
);
8814 task_event
->event_id
.header
.size
= size
;
8817 static void perf_event_task(struct task_struct
*task
,
8818 struct perf_event_context
*task_ctx
,
8821 struct perf_task_event task_event
;
8823 if (!atomic_read(&nr_comm_events
) &&
8824 !atomic_read(&nr_mmap_events
) &&
8825 !atomic_read(&nr_task_events
))
8828 task_event
= (struct perf_task_event
){
8830 .task_ctx
= task_ctx
,
8833 .type
= new ? PERF_RECORD_FORK
: PERF_RECORD_EXIT
,
8835 .size
= sizeof(task_event
.event_id
),
8845 perf_iterate_sb(perf_event_task_output
,
8851 * Allocate data for a new task when profiling system-wide
8852 * events which require PMU specific data
8855 perf_event_alloc_task_data(struct task_struct
*child
,
8856 struct task_struct
*parent
)
8858 struct kmem_cache
*ctx_cache
= NULL
;
8859 struct perf_ctx_data
*cd
;
8861 if (!refcount_read(&global_ctx_data_ref
))
8864 scoped_guard (rcu
) {
8865 cd
= rcu_dereference(parent
->perf_ctx_data
);
8867 ctx_cache
= cd
->ctx_cache
;
8873 guard(percpu_read
)(&global_ctx_data_rwsem
);
8874 scoped_guard (rcu
) {
8875 cd
= rcu_dereference(child
->perf_ctx_data
);
8878 * A system-wide event may be unaccount,
8879 * when attaching the perf_ctx_data.
8881 if (!refcount_read(&global_ctx_data_ref
))
8888 refcount_inc(&cd
->refcount
);
8894 attach_task_ctx_data(child
, ctx_cache
, true);
8897 void perf_event_fork(struct task_struct
*task
)
8899 perf_event_task(task
, NULL
, 1);
8900 perf_event_namespaces(task
);
8901 perf_event_alloc_task_data(task
, current
);
8908 struct perf_comm_event
{
8909 struct task_struct
*task
;
8914 struct perf_event_header header
;
8921 static int perf_event_comm_match(struct perf_event
*event
)
8923 return event
->attr
.comm
;
8926 static void perf_event_comm_output(struct perf_event
*event
,
8929 struct perf_comm_event
*comm_event
= data
;
8930 struct perf_output_handle handle
;
8931 struct perf_sample_data sample
;
8932 int size
= comm_event
->event_id
.header
.size
;
8935 if (!perf_event_comm_match(event
))
8938 perf_event_header__init_id(&comm_event
->event_id
.header
, &sample
, event
);
8939 ret
= perf_output_begin(&handle
, &sample
, event
,
8940 comm_event
->event_id
.header
.size
);
8945 comm_event
->event_id
.pid
= perf_event_pid(event
, comm_event
->task
);
8946 comm_event
->event_id
.tid
= perf_event_tid(event
, comm_event
->task
);
8948 perf_output_put(&handle
, comm_event
->event_id
);
8949 __output_copy(&handle
, comm_event
->comm
,
8950 comm_event
->comm_size
);
8952 perf_event__output_id_sample(event
, &handle
, &sample
);
8954 perf_output_end(&handle
);
8956 comm_event
->event_id
.header
.size
= size
;
8959 static void perf_event_comm_event(struct perf_comm_event
*comm_event
)
8961 char comm
[TASK_COMM_LEN
];
8964 memset(comm
, 0, sizeof(comm
));
8965 strscpy(comm
, comm_event
->task
->comm
);
8966 size
= ALIGN(strlen(comm
)+1, sizeof(u64
));
8968 comm_event
->comm
= comm
;
8969 comm_event
->comm_size
= size
;
8971 comm_event
->event_id
.header
.size
= sizeof(comm_event
->event_id
) + size
;
8973 perf_iterate_sb(perf_event_comm_output
,
8978 void perf_event_comm(struct task_struct
*task
, bool exec
)
8980 struct perf_comm_event comm_event
;
8982 if (!atomic_read(&nr_comm_events
))
8985 comm_event
= (struct perf_comm_event
){
8991 .type
= PERF_RECORD_COMM
,
8992 .misc
= exec
? PERF_RECORD_MISC_COMM_EXEC
: 0,
9000 perf_event_comm_event(&comm_event
);
9004 * namespaces tracking
9007 struct perf_namespaces_event
{
9008 struct task_struct
*task
;
9011 struct perf_event_header header
;
9016 struct perf_ns_link_info link_info
[NR_NAMESPACES
];
9020 static int perf_event_namespaces_match(struct perf_event
*event
)
9022 return event
->attr
.namespaces
;
9025 static void perf_event_namespaces_output(struct perf_event
*event
,
9028 struct perf_namespaces_event
*namespaces_event
= data
;
9029 struct perf_output_handle handle
;
9030 struct perf_sample_data sample
;
9031 u16 header_size
= namespaces_event
->event_id
.header
.size
;
9034 if (!perf_event_namespaces_match(event
))
9037 perf_event_header__init_id(&namespaces_event
->event_id
.header
,
9039 ret
= perf_output_begin(&handle
, &sample
, event
,
9040 namespaces_event
->event_id
.header
.size
);
9044 namespaces_event
->event_id
.pid
= perf_event_pid(event
,
9045 namespaces_event
->task
);
9046 namespaces_event
->event_id
.tid
= perf_event_tid(event
,
9047 namespaces_event
->task
);
9049 perf_output_put(&handle
, namespaces_event
->event_id
);
9051 perf_event__output_id_sample(event
, &handle
, &sample
);
9053 perf_output_end(&handle
);
9055 namespaces_event
->event_id
.header
.size
= header_size
;
9058 static void perf_fill_ns_link_info(struct perf_ns_link_info
*ns_link_info
,
9059 struct task_struct
*task
,
9060 const struct proc_ns_operations
*ns_ops
)
9062 struct path ns_path
;
9063 struct inode
*ns_inode
;
9066 error
= ns_get_path(&ns_path
, task
, ns_ops
);
9068 ns_inode
= ns_path
.dentry
->d_inode
;
9069 ns_link_info
->dev
= new_encode_dev(ns_inode
->i_sb
->s_dev
);
9070 ns_link_info
->ino
= ns_inode
->i_ino
;
9075 void perf_event_namespaces(struct task_struct
*task
)
9077 struct perf_namespaces_event namespaces_event
;
9078 struct perf_ns_link_info
*ns_link_info
;
9080 if (!atomic_read(&nr_namespaces_events
))
9083 namespaces_event
= (struct perf_namespaces_event
){
9087 .type
= PERF_RECORD_NAMESPACES
,
9089 .size
= sizeof(namespaces_event
.event_id
),
9093 .nr_namespaces
= NR_NAMESPACES
,
9094 /* .link_info[NR_NAMESPACES] */
9098 ns_link_info
= namespaces_event
.event_id
.link_info
;
9100 perf_fill_ns_link_info(&ns_link_info
[MNT_NS_INDEX
],
9101 task
, &mntns_operations
);
9103 #ifdef CONFIG_USER_NS
9104 perf_fill_ns_link_info(&ns_link_info
[USER_NS_INDEX
],
9105 task
, &userns_operations
);
9107 #ifdef CONFIG_NET_NS
9108 perf_fill_ns_link_info(&ns_link_info
[NET_NS_INDEX
],
9109 task
, &netns_operations
);
9111 #ifdef CONFIG_UTS_NS
9112 perf_fill_ns_link_info(&ns_link_info
[UTS_NS_INDEX
],
9113 task
, &utsns_operations
);
9115 #ifdef CONFIG_IPC_NS
9116 perf_fill_ns_link_info(&ns_link_info
[IPC_NS_INDEX
],
9117 task
, &ipcns_operations
);
9119 #ifdef CONFIG_PID_NS
9120 perf_fill_ns_link_info(&ns_link_info
[PID_NS_INDEX
],
9121 task
, &pidns_operations
);
9123 #ifdef CONFIG_CGROUPS
9124 perf_fill_ns_link_info(&ns_link_info
[CGROUP_NS_INDEX
],
9125 task
, &cgroupns_operations
);
9128 perf_iterate_sb(perf_event_namespaces_output
,
9136 #ifdef CONFIG_CGROUP_PERF
9138 struct perf_cgroup_event
{
9142 struct perf_event_header header
;
9148 static int perf_event_cgroup_match(struct perf_event
*event
)
9150 return event
->attr
.cgroup
;
9153 static void perf_event_cgroup_output(struct perf_event
*event
, void *data
)
9155 struct perf_cgroup_event
*cgroup_event
= data
;
9156 struct perf_output_handle handle
;
9157 struct perf_sample_data sample
;
9158 u16 header_size
= cgroup_event
->event_id
.header
.size
;
9161 if (!perf_event_cgroup_match(event
))
9164 perf_event_header__init_id(&cgroup_event
->event_id
.header
,
9166 ret
= perf_output_begin(&handle
, &sample
, event
,
9167 cgroup_event
->event_id
.header
.size
);
9171 perf_output_put(&handle
, cgroup_event
->event_id
);
9172 __output_copy(&handle
, cgroup_event
->path
, cgroup_event
->path_size
);
9174 perf_event__output_id_sample(event
, &handle
, &sample
);
9176 perf_output_end(&handle
);
9178 cgroup_event
->event_id
.header
.size
= header_size
;
9181 static void perf_event_cgroup(struct cgroup
*cgrp
)
9183 struct perf_cgroup_event cgroup_event
;
9184 char path_enomem
[16] = "//enomem";
9188 if (!atomic_read(&nr_cgroup_events
))
9191 cgroup_event
= (struct perf_cgroup_event
){
9194 .type
= PERF_RECORD_CGROUP
,
9196 .size
= sizeof(cgroup_event
.event_id
),
9198 .id
= cgroup_id(cgrp
),
9202 pathname
= kmalloc(PATH_MAX
, GFP_KERNEL
);
9203 if (pathname
== NULL
) {
9204 cgroup_event
.path
= path_enomem
;
9206 /* just to be sure to have enough space for alignment */
9207 cgroup_path(cgrp
, pathname
, PATH_MAX
- sizeof(u64
));
9208 cgroup_event
.path
= pathname
;
9212 * Since our buffer works in 8 byte units we need to align our string
9213 * size to a multiple of 8. However, we must guarantee the tail end is
9214 * zero'd out to avoid leaking random bits to userspace.
9216 size
= strlen(cgroup_event
.path
) + 1;
9217 while (!IS_ALIGNED(size
, sizeof(u64
)))
9218 cgroup_event
.path
[size
++] = '\0';
9220 cgroup_event
.event_id
.header
.size
+= size
;
9221 cgroup_event
.path_size
= size
;
9223 perf_iterate_sb(perf_event_cgroup_output
,
9236 struct perf_mmap_event
{
9237 struct vm_area_struct
*vma
;
9239 const char *file_name
;
9245 u8 build_id
[BUILD_ID_SIZE_MAX
];
9249 struct perf_event_header header
;
9259 static int perf_event_mmap_match(struct perf_event
*event
,
9262 struct perf_mmap_event
*mmap_event
= data
;
9263 struct vm_area_struct
*vma
= mmap_event
->vma
;
9264 int executable
= vma
->vm_flags
& VM_EXEC
;
9266 return (!executable
&& event
->attr
.mmap_data
) ||
9267 (executable
&& (event
->attr
.mmap
|| event
->attr
.mmap2
));
9270 static void perf_event_mmap_output(struct perf_event
*event
,
9273 struct perf_mmap_event
*mmap_event
= data
;
9274 struct perf_output_handle handle
;
9275 struct perf_sample_data sample
;
9276 int size
= mmap_event
->event_id
.header
.size
;
9277 u32 type
= mmap_event
->event_id
.header
.type
;
9281 if (!perf_event_mmap_match(event
, data
))
9284 if (event
->attr
.mmap2
) {
9285 mmap_event
->event_id
.header
.type
= PERF_RECORD_MMAP2
;
9286 mmap_event
->event_id
.header
.size
+= sizeof(mmap_event
->maj
);
9287 mmap_event
->event_id
.header
.size
+= sizeof(mmap_event
->min
);
9288 mmap_event
->event_id
.header
.size
+= sizeof(mmap_event
->ino
);
9289 mmap_event
->event_id
.header
.size
+= sizeof(mmap_event
->ino_generation
);
9290 mmap_event
->event_id
.header
.size
+= sizeof(mmap_event
->prot
);
9291 mmap_event
->event_id
.header
.size
+= sizeof(mmap_event
->flags
);
9294 perf_event_header__init_id(&mmap_event
->event_id
.header
, &sample
, event
);
9295 ret
= perf_output_begin(&handle
, &sample
, event
,
9296 mmap_event
->event_id
.header
.size
);
9300 mmap_event
->event_id
.pid
= perf_event_pid(event
, current
);
9301 mmap_event
->event_id
.tid
= perf_event_tid(event
, current
);
9303 use_build_id
= event
->attr
.build_id
&& mmap_event
->build_id_size
;
9305 if (event
->attr
.mmap2
&& use_build_id
)
9306 mmap_event
->event_id
.header
.misc
|= PERF_RECORD_MISC_MMAP_BUILD_ID
;
9308 perf_output_put(&handle
, mmap_event
->event_id
);
9310 if (event
->attr
.mmap2
) {
9312 u8 size
[4] = { (u8
) mmap_event
->build_id_size
, 0, 0, 0 };
9314 __output_copy(&handle
, size
, 4);
9315 __output_copy(&handle
, mmap_event
->build_id
, BUILD_ID_SIZE_MAX
);
9317 perf_output_put(&handle
, mmap_event
->maj
);
9318 perf_output_put(&handle
, mmap_event
->min
);
9319 perf_output_put(&handle
, mmap_event
->ino
);
9320 perf_output_put(&handle
, mmap_event
->ino_generation
);
9322 perf_output_put(&handle
, mmap_event
->prot
);
9323 perf_output_put(&handle
, mmap_event
->flags
);
9326 __output_copy(&handle
, mmap_event
->file_name
,
9327 mmap_event
->file_size
);
9329 perf_event__output_id_sample(event
, &handle
, &sample
);
9331 perf_output_end(&handle
);
9333 mmap_event
->event_id
.header
.size
= size
;
9334 mmap_event
->event_id
.header
.type
= type
;
9337 static void perf_event_mmap_event(struct perf_mmap_event
*mmap_event
)
9339 struct vm_area_struct
*vma
= mmap_event
->vma
;
9340 struct file
*file
= vma
->vm_file
;
9341 int maj
= 0, min
= 0;
9342 u64 ino
= 0, gen
= 0;
9343 u32 prot
= 0, flags
= 0;
9349 if (vma
->vm_flags
& VM_READ
)
9351 if (vma
->vm_flags
& VM_WRITE
)
9353 if (vma
->vm_flags
& VM_EXEC
)
9356 if (vma
->vm_flags
& VM_MAYSHARE
)
9359 flags
= MAP_PRIVATE
;
9361 if (vma
->vm_flags
& VM_LOCKED
)
9362 flags
|= MAP_LOCKED
;
9363 if (is_vm_hugetlb_page(vma
))
9364 flags
|= MAP_HUGETLB
;
9367 struct inode
*inode
;
9370 buf
= kmalloc(PATH_MAX
, GFP_KERNEL
);
9376 * d_path() works from the end of the rb backwards, so we
9377 * need to add enough zero bytes after the string to handle
9378 * the 64bit alignment we do later.
9380 name
= file_path(file
, buf
, PATH_MAX
- sizeof(u64
));
9385 inode
= file_inode(vma
->vm_file
);
9386 dev
= inode
->i_sb
->s_dev
;
9388 gen
= inode
->i_generation
;
9394 if (vma
->vm_ops
&& vma
->vm_ops
->name
)
9395 name
= (char *) vma
->vm_ops
->name(vma
);
9397 name
= (char *)arch_vma_name(vma
);
9399 if (vma_is_initial_heap(vma
))
9401 else if (vma_is_initial_stack(vma
))
9413 * Since our buffer works in 8 byte units we need to align our string
9414 * size to a multiple of 8. However, we must guarantee the tail end is
9415 * zero'd out to avoid leaking random bits to userspace.
9417 size
= strlen(name
)+1;
9418 while (!IS_ALIGNED(size
, sizeof(u64
)))
9419 name
[size
++] = '\0';
9421 mmap_event
->file_name
= name
;
9422 mmap_event
->file_size
= size
;
9423 mmap_event
->maj
= maj
;
9424 mmap_event
->min
= min
;
9425 mmap_event
->ino
= ino
;
9426 mmap_event
->ino_generation
= gen
;
9427 mmap_event
->prot
= prot
;
9428 mmap_event
->flags
= flags
;
9430 if (!(vma
->vm_flags
& VM_EXEC
))
9431 mmap_event
->event_id
.header
.misc
|= PERF_RECORD_MISC_MMAP_DATA
;
9433 mmap_event
->event_id
.header
.size
= sizeof(mmap_event
->event_id
) + size
;
9435 if (atomic_read(&nr_build_id_events
))
9436 build_id_parse_nofault(vma
, mmap_event
->build_id
, &mmap_event
->build_id_size
);
9438 perf_iterate_sb(perf_event_mmap_output
,
9446 * Check whether inode and address range match filter criteria.
9448 static bool perf_addr_filter_match(struct perf_addr_filter
*filter
,
9449 struct file
*file
, unsigned long offset
,
9452 /* d_inode(NULL) won't be equal to any mapped user-space file */
9453 if (!filter
->path
.dentry
)
9456 if (d_inode(filter
->path
.dentry
) != file_inode(file
))
9459 if (filter
->offset
> offset
+ size
)
9462 if (filter
->offset
+ filter
->size
< offset
)
9468 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter
*filter
,
9469 struct vm_area_struct
*vma
,
9470 struct perf_addr_filter_range
*fr
)
9472 unsigned long vma_size
= vma
->vm_end
- vma
->vm_start
;
9473 unsigned long off
= vma
->vm_pgoff
<< PAGE_SHIFT
;
9474 struct file
*file
= vma
->vm_file
;
9476 if (!perf_addr_filter_match(filter
, file
, off
, vma_size
))
9479 if (filter
->offset
< off
) {
9480 fr
->start
= vma
->vm_start
;
9481 fr
->size
= min(vma_size
, filter
->size
- (off
- filter
->offset
));
9483 fr
->start
= vma
->vm_start
+ filter
->offset
- off
;
9484 fr
->size
= min(vma
->vm_end
- fr
->start
, filter
->size
);
9490 static void __perf_addr_filters_adjust(struct perf_event
*event
, void *data
)
9492 struct perf_addr_filters_head
*ifh
= perf_event_addr_filters(event
);
9493 struct vm_area_struct
*vma
= data
;
9494 struct perf_addr_filter
*filter
;
9495 unsigned int restart
= 0, count
= 0;
9496 unsigned long flags
;
9498 if (!has_addr_filter(event
))
9504 raw_spin_lock_irqsave(&ifh
->lock
, flags
);
9505 list_for_each_entry(filter
, &ifh
->list
, entry
) {
9506 if (perf_addr_filter_vma_adjust(filter
, vma
,
9507 &event
->addr_filter_ranges
[count
]))
9514 event
->addr_filters_gen
++;
9515 raw_spin_unlock_irqrestore(&ifh
->lock
, flags
);
9518 perf_event_stop(event
, 1);
9522 * Adjust all task's events' filters to the new vma
9524 static void perf_addr_filters_adjust(struct vm_area_struct
*vma
)
9526 struct perf_event_context
*ctx
;
9529 * Data tracing isn't supported yet and as such there is no need
9530 * to keep track of anything that isn't related to executable code:
9532 if (!(vma
->vm_flags
& VM_EXEC
))
9536 ctx
= rcu_dereference(current
->perf_event_ctxp
);
9538 perf_iterate_ctx(ctx
, __perf_addr_filters_adjust
, vma
, true);
9542 void perf_event_mmap(struct vm_area_struct
*vma
)
9544 struct perf_mmap_event mmap_event
;
9546 if (!atomic_read(&nr_mmap_events
))
9549 mmap_event
= (struct perf_mmap_event
){
9555 .type
= PERF_RECORD_MMAP
,
9556 .misc
= PERF_RECORD_MISC_USER
,
9561 .start
= vma
->vm_start
,
9562 .len
= vma
->vm_end
- vma
->vm_start
,
9563 .pgoff
= (u64
)vma
->vm_pgoff
<< PAGE_SHIFT
,
9565 /* .maj (attr_mmap2 only) */
9566 /* .min (attr_mmap2 only) */
9567 /* .ino (attr_mmap2 only) */
9568 /* .ino_generation (attr_mmap2 only) */
9569 /* .prot (attr_mmap2 only) */
9570 /* .flags (attr_mmap2 only) */
9573 perf_addr_filters_adjust(vma
);
9574 perf_event_mmap_event(&mmap_event
);
9577 void perf_event_aux_event(struct perf_event
*event
, unsigned long head
,
9578 unsigned long size
, u64 flags
)
9580 struct perf_output_handle handle
;
9581 struct perf_sample_data sample
;
9582 struct perf_aux_event
{
9583 struct perf_event_header header
;
9589 .type
= PERF_RECORD_AUX
,
9591 .size
= sizeof(rec
),
9599 perf_event_header__init_id(&rec
.header
, &sample
, event
);
9600 ret
= perf_output_begin(&handle
, &sample
, event
, rec
.header
.size
);
9605 perf_output_put(&handle
, rec
);
9606 perf_event__output_id_sample(event
, &handle
, &sample
);
9608 perf_output_end(&handle
);
9612 * Lost/dropped samples logging
9614 void perf_log_lost_samples(struct perf_event
*event
, u64 lost
)
9616 struct perf_output_handle handle
;
9617 struct perf_sample_data sample
;
9621 struct perf_event_header header
;
9623 } lost_samples_event
= {
9625 .type
= PERF_RECORD_LOST_SAMPLES
,
9627 .size
= sizeof(lost_samples_event
),
9632 perf_event_header__init_id(&lost_samples_event
.header
, &sample
, event
);
9634 ret
= perf_output_begin(&handle
, &sample
, event
,
9635 lost_samples_event
.header
.size
);
9639 perf_output_put(&handle
, lost_samples_event
);
9640 perf_event__output_id_sample(event
, &handle
, &sample
);
9641 perf_output_end(&handle
);
9645 * context_switch tracking
9648 struct perf_switch_event
{
9649 struct task_struct
*task
;
9650 struct task_struct
*next_prev
;
9653 struct perf_event_header header
;
9659 static int perf_event_switch_match(struct perf_event
*event
)
9661 return event
->attr
.context_switch
;
9664 static void perf_event_switch_output(struct perf_event
*event
, void *data
)
9666 struct perf_switch_event
*se
= data
;
9667 struct perf_output_handle handle
;
9668 struct perf_sample_data sample
;
9671 if (!perf_event_switch_match(event
))
9674 /* Only CPU-wide events are allowed to see next/prev pid/tid */
9675 if (event
->ctx
->task
) {
9676 se
->event_id
.header
.type
= PERF_RECORD_SWITCH
;
9677 se
->event_id
.header
.size
= sizeof(se
->event_id
.header
);
9679 se
->event_id
.header
.type
= PERF_RECORD_SWITCH_CPU_WIDE
;
9680 se
->event_id
.header
.size
= sizeof(se
->event_id
);
9681 se
->event_id
.next_prev_pid
=
9682 perf_event_pid(event
, se
->next_prev
);
9683 se
->event_id
.next_prev_tid
=
9684 perf_event_tid(event
, se
->next_prev
);
9687 perf_event_header__init_id(&se
->event_id
.header
, &sample
, event
);
9689 ret
= perf_output_begin(&handle
, &sample
, event
, se
->event_id
.header
.size
);
9693 if (event
->ctx
->task
)
9694 perf_output_put(&handle
, se
->event_id
.header
);
9696 perf_output_put(&handle
, se
->event_id
);
9698 perf_event__output_id_sample(event
, &handle
, &sample
);
9700 perf_output_end(&handle
);
9703 static void perf_event_switch(struct task_struct
*task
,
9704 struct task_struct
*next_prev
, bool sched_in
)
9706 struct perf_switch_event switch_event
;
9708 /* N.B. caller checks nr_switch_events != 0 */
9710 switch_event
= (struct perf_switch_event
){
9712 .next_prev
= next_prev
,
9716 .misc
= sched_in
? 0 : PERF_RECORD_MISC_SWITCH_OUT
,
9719 /* .next_prev_pid */
9720 /* .next_prev_tid */
9724 if (!sched_in
&& task_is_runnable(task
)) {
9725 switch_event
.event_id
.header
.misc
|=
9726 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT
;
9729 perf_iterate_sb(perf_event_switch_output
, &switch_event
, NULL
);
9733 * IRQ throttle logging
9736 static void perf_log_throttle(struct perf_event
*event
, int enable
)
9738 struct perf_output_handle handle
;
9739 struct perf_sample_data sample
;
9743 struct perf_event_header header
;
9747 } throttle_event
= {
9749 .type
= PERF_RECORD_THROTTLE
,
9751 .size
= sizeof(throttle_event
),
9753 .time
= perf_event_clock(event
),
9754 .id
= primary_event_id(event
),
9755 .stream_id
= event
->id
,
9759 throttle_event
.header
.type
= PERF_RECORD_UNTHROTTLE
;
9761 perf_event_header__init_id(&throttle_event
.header
, &sample
, event
);
9763 ret
= perf_output_begin(&handle
, &sample
, event
,
9764 throttle_event
.header
.size
);
9768 perf_output_put(&handle
, throttle_event
);
9769 perf_event__output_id_sample(event
, &handle
, &sample
);
9770 perf_output_end(&handle
);
9774 * ksymbol register/unregister tracking
9777 struct perf_ksymbol_event
{
9781 struct perf_event_header header
;
9789 static int perf_event_ksymbol_match(struct perf_event
*event
)
9791 return event
->attr
.ksymbol
;
9794 static void perf_event_ksymbol_output(struct perf_event
*event
, void *data
)
9796 struct perf_ksymbol_event
*ksymbol_event
= data
;
9797 struct perf_output_handle handle
;
9798 struct perf_sample_data sample
;
9801 if (!perf_event_ksymbol_match(event
))
9804 perf_event_header__init_id(&ksymbol_event
->event_id
.header
,
9806 ret
= perf_output_begin(&handle
, &sample
, event
,
9807 ksymbol_event
->event_id
.header
.size
);
9811 perf_output_put(&handle
, ksymbol_event
->event_id
);
9812 __output_copy(&handle
, ksymbol_event
->name
, ksymbol_event
->name_len
);
9813 perf_event__output_id_sample(event
, &handle
, &sample
);
9815 perf_output_end(&handle
);
9818 void perf_event_ksymbol(u16 ksym_type
, u64 addr
, u32 len
, bool unregister
,
9821 struct perf_ksymbol_event ksymbol_event
;
9822 char name
[KSYM_NAME_LEN
];
9826 if (!atomic_read(&nr_ksymbol_events
))
9829 if (ksym_type
>= PERF_RECORD_KSYMBOL_TYPE_MAX
||
9830 ksym_type
== PERF_RECORD_KSYMBOL_TYPE_UNKNOWN
)
9834 name_len
= strlen(name
) + 1;
9835 while (!IS_ALIGNED(name_len
, sizeof(u64
)))
9836 name
[name_len
++] = '\0';
9837 BUILD_BUG_ON(KSYM_NAME_LEN
% sizeof(u64
));
9840 flags
|= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER
;
9842 ksymbol_event
= (struct perf_ksymbol_event
){
9844 .name_len
= name_len
,
9847 .type
= PERF_RECORD_KSYMBOL
,
9848 .size
= sizeof(ksymbol_event
.event_id
) +
9853 .ksym_type
= ksym_type
,
9858 perf_iterate_sb(perf_event_ksymbol_output
, &ksymbol_event
, NULL
);
9861 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__
, ksym_type
);
9865 * bpf program load/unload tracking
9868 struct perf_bpf_event
{
9869 struct bpf_prog
*prog
;
9871 struct perf_event_header header
;
9875 u8 tag
[BPF_TAG_SIZE
];
9879 static int perf_event_bpf_match(struct perf_event
*event
)
9881 return event
->attr
.bpf_event
;
9884 static void perf_event_bpf_output(struct perf_event
*event
, void *data
)
9886 struct perf_bpf_event
*bpf_event
= data
;
9887 struct perf_output_handle handle
;
9888 struct perf_sample_data sample
;
9891 if (!perf_event_bpf_match(event
))
9894 perf_event_header__init_id(&bpf_event
->event_id
.header
,
9896 ret
= perf_output_begin(&handle
, &sample
, event
,
9897 bpf_event
->event_id
.header
.size
);
9901 perf_output_put(&handle
, bpf_event
->event_id
);
9902 perf_event__output_id_sample(event
, &handle
, &sample
);
9904 perf_output_end(&handle
);
9907 static void perf_event_bpf_emit_ksymbols(struct bpf_prog
*prog
,
9908 enum perf_bpf_event_type type
)
9910 bool unregister
= type
== PERF_BPF_EVENT_PROG_UNLOAD
;
9913 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF
,
9914 (u64
)(unsigned long)prog
->bpf_func
,
9915 prog
->jited_len
, unregister
,
9916 prog
->aux
->ksym
.name
);
9918 for (i
= 1; i
< prog
->aux
->func_cnt
; i
++) {
9919 struct bpf_prog
*subprog
= prog
->aux
->func
[i
];
9922 PERF_RECORD_KSYMBOL_TYPE_BPF
,
9923 (u64
)(unsigned long)subprog
->bpf_func
,
9924 subprog
->jited_len
, unregister
,
9925 subprog
->aux
->ksym
.name
);
9929 void perf_event_bpf_event(struct bpf_prog
*prog
,
9930 enum perf_bpf_event_type type
,
9933 struct perf_bpf_event bpf_event
;
9936 case PERF_BPF_EVENT_PROG_LOAD
:
9937 case PERF_BPF_EVENT_PROG_UNLOAD
:
9938 if (atomic_read(&nr_ksymbol_events
))
9939 perf_event_bpf_emit_ksymbols(prog
, type
);
9945 if (!atomic_read(&nr_bpf_events
))
9948 bpf_event
= (struct perf_bpf_event
){
9952 .type
= PERF_RECORD_BPF_EVENT
,
9953 .size
= sizeof(bpf_event
.event_id
),
9957 .id
= prog
->aux
->id
,
9961 BUILD_BUG_ON(BPF_TAG_SIZE
% sizeof(u64
));
9963 memcpy(bpf_event
.event_id
.tag
, prog
->tag
, BPF_TAG_SIZE
);
9964 perf_iterate_sb(perf_event_bpf_output
, &bpf_event
, NULL
);
9967 struct perf_text_poke_event
{
9968 const void *old_bytes
;
9969 const void *new_bytes
;
9975 struct perf_event_header header
;
9981 static int perf_event_text_poke_match(struct perf_event
*event
)
9983 return event
->attr
.text_poke
;
9986 static void perf_event_text_poke_output(struct perf_event
*event
, void *data
)
9988 struct perf_text_poke_event
*text_poke_event
= data
;
9989 struct perf_output_handle handle
;
9990 struct perf_sample_data sample
;
9994 if (!perf_event_text_poke_match(event
))
9997 perf_event_header__init_id(&text_poke_event
->event_id
.header
, &sample
, event
);
9999 ret
= perf_output_begin(&handle
, &sample
, event
,
10000 text_poke_event
->event_id
.header
.size
);
10004 perf_output_put(&handle
, text_poke_event
->event_id
);
10005 perf_output_put(&handle
, text_poke_event
->old_len
);
10006 perf_output_put(&handle
, text_poke_event
->new_len
);
10008 __output_copy(&handle
, text_poke_event
->old_bytes
, text_poke_event
->old_len
);
10009 __output_copy(&handle
, text_poke_event
->new_bytes
, text_poke_event
->new_len
);
10011 if (text_poke_event
->pad
)
10012 __output_copy(&handle
, &padding
, text_poke_event
->pad
);
10014 perf_event__output_id_sample(event
, &handle
, &sample
);
10016 perf_output_end(&handle
);
10019 void perf_event_text_poke(const void *addr
, const void *old_bytes
,
10020 size_t old_len
, const void *new_bytes
, size_t new_len
)
10022 struct perf_text_poke_event text_poke_event
;
10025 if (!atomic_read(&nr_text_poke_events
))
10028 tot
= sizeof(text_poke_event
.old_len
) + old_len
;
10029 tot
+= sizeof(text_poke_event
.new_len
) + new_len
;
10030 pad
= ALIGN(tot
, sizeof(u64
)) - tot
;
10032 text_poke_event
= (struct perf_text_poke_event
){
10033 .old_bytes
= old_bytes
,
10034 .new_bytes
= new_bytes
,
10036 .old_len
= old_len
,
10037 .new_len
= new_len
,
10040 .type
= PERF_RECORD_TEXT_POKE
,
10041 .misc
= PERF_RECORD_MISC_KERNEL
,
10042 .size
= sizeof(text_poke_event
.event_id
) + tot
+ pad
,
10044 .addr
= (unsigned long)addr
,
10048 perf_iterate_sb(perf_event_text_poke_output
, &text_poke_event
, NULL
);
10051 void perf_event_itrace_started(struct perf_event
*event
)
10053 WRITE_ONCE(event
->attach_state
, event
->attach_state
| PERF_ATTACH_ITRACE
);
10056 static void perf_log_itrace_start(struct perf_event
*event
)
10058 struct perf_output_handle handle
;
10059 struct perf_sample_data sample
;
10060 struct perf_aux_event
{
10061 struct perf_event_header header
;
10068 event
= event
->parent
;
10070 if (!(event
->pmu
->capabilities
& PERF_PMU_CAP_ITRACE
) ||
10071 event
->attach_state
& PERF_ATTACH_ITRACE
)
10074 rec
.header
.type
= PERF_RECORD_ITRACE_START
;
10075 rec
.header
.misc
= 0;
10076 rec
.header
.size
= sizeof(rec
);
10077 rec
.pid
= perf_event_pid(event
, current
);
10078 rec
.tid
= perf_event_tid(event
, current
);
10080 perf_event_header__init_id(&rec
.header
, &sample
, event
);
10081 ret
= perf_output_begin(&handle
, &sample
, event
, rec
.header
.size
);
10086 perf_output_put(&handle
, rec
);
10087 perf_event__output_id_sample(event
, &handle
, &sample
);
10089 perf_output_end(&handle
);
10092 void perf_report_aux_output_id(struct perf_event
*event
, u64 hw_id
)
10094 struct perf_output_handle handle
;
10095 struct perf_sample_data sample
;
10096 struct perf_aux_event
{
10097 struct perf_event_header header
;
10103 event
= event
->parent
;
10105 rec
.header
.type
= PERF_RECORD_AUX_OUTPUT_HW_ID
;
10106 rec
.header
.misc
= 0;
10107 rec
.header
.size
= sizeof(rec
);
10110 perf_event_header__init_id(&rec
.header
, &sample
, event
);
10111 ret
= perf_output_begin(&handle
, &sample
, event
, rec
.header
.size
);
10116 perf_output_put(&handle
, rec
);
10117 perf_event__output_id_sample(event
, &handle
, &sample
);
10119 perf_output_end(&handle
);
10121 EXPORT_SYMBOL_GPL(perf_report_aux_output_id
);
10124 __perf_event_account_interrupt(struct perf_event
*event
, int throttle
)
10126 struct hw_perf_event
*hwc
= &event
->hw
;
10130 seq
= __this_cpu_read(perf_throttled_seq
);
10131 if (seq
!= hwc
->interrupts_seq
) {
10132 hwc
->interrupts_seq
= seq
;
10133 hwc
->interrupts
= 1;
10138 if (unlikely(throttle
&& hwc
->interrupts
>= max_samples_per_tick
)) {
10139 __this_cpu_inc(perf_throttled_count
);
10140 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS
);
10141 perf_event_throttle_group(event
);
10145 if (event
->attr
.freq
) {
10146 u64 now
= perf_clock();
10147 s64 delta
= now
- hwc
->freq_time_stamp
;
10149 hwc
->freq_time_stamp
= now
;
10151 if (delta
> 0 && delta
< 2*TICK_NSEC
)
10152 perf_adjust_period(event
, delta
, hwc
->last_period
, true);
10158 int perf_event_account_interrupt(struct perf_event
*event
)
10160 return __perf_event_account_interrupt(event
, 1);
10163 static inline bool sample_is_allowed(struct perf_event
*event
, struct pt_regs
*regs
)
10166 * Due to interrupt latency (AKA "skid"), we may enter the
10167 * kernel before taking an overflow, even if the PMU is only
10168 * counting user events.
10170 if (event
->attr
.exclude_kernel
&& !user_mode(regs
))
10176 #ifdef CONFIG_BPF_SYSCALL
10177 static int bpf_overflow_handler(struct perf_event
*event
,
10178 struct perf_sample_data
*data
,
10179 struct pt_regs
*regs
)
10181 struct bpf_perf_event_data_kern ctx
= {
10185 struct bpf_prog
*prog
;
10188 ctx
.regs
= perf_arch_bpf_user_pt_regs(regs
);
10189 if (unlikely(__this_cpu_inc_return(bpf_prog_active
) != 1))
10192 prog
= READ_ONCE(event
->prog
);
10194 perf_prepare_sample(data
, event
, regs
);
10195 ret
= bpf_prog_run(prog
, &ctx
);
10199 __this_cpu_dec(bpf_prog_active
);
10204 static inline int perf_event_set_bpf_handler(struct perf_event
*event
,
10205 struct bpf_prog
*prog
,
10208 if (event
->overflow_handler_context
)
10209 /* hw breakpoint or kernel counter */
10215 if (prog
->type
!= BPF_PROG_TYPE_PERF_EVENT
)
10218 if (event
->attr
.precise_ip
&&
10219 prog
->call_get_stack
&&
10220 (!(event
->attr
.sample_type
& PERF_SAMPLE_CALLCHAIN
) ||
10221 event
->attr
.exclude_callchain_kernel
||
10222 event
->attr
.exclude_callchain_user
)) {
10224 * On perf_event with precise_ip, calling bpf_get_stack()
10225 * may trigger unwinder warnings and occasional crashes.
10226 * bpf_get_[stack|stackid] works around this issue by using
10227 * callchain attached to perf_sample_data. If the
10228 * perf_event does not full (kernel and user) callchain
10229 * attached to perf_sample_data, do not allow attaching BPF
10230 * program that calls bpf_get_[stack|stackid].
10235 event
->prog
= prog
;
10236 event
->bpf_cookie
= bpf_cookie
;
10240 static inline void perf_event_free_bpf_handler(struct perf_event
*event
)
10242 struct bpf_prog
*prog
= event
->prog
;
10247 event
->prog
= NULL
;
10248 bpf_prog_put(prog
);
10251 static inline int bpf_overflow_handler(struct perf_event
*event
,
10252 struct perf_sample_data
*data
,
10253 struct pt_regs
*regs
)
10258 static inline int perf_event_set_bpf_handler(struct perf_event
*event
,
10259 struct bpf_prog
*prog
,
10262 return -EOPNOTSUPP
;
10265 static inline void perf_event_free_bpf_handler(struct perf_event
*event
)
10271 * Generic event overflow handling, sampling.
10274 static int __perf_event_overflow(struct perf_event
*event
,
10275 int throttle
, struct perf_sample_data
*data
,
10276 struct pt_regs
*regs
)
10278 int events
= atomic_read(&event
->event_limit
);
10282 * Non-sampling counters might still use the PMI to fold short
10283 * hardware counters, ignore those.
10285 if (unlikely(!is_sampling_event(event
)))
10288 ret
= __perf_event_account_interrupt(event
, throttle
);
10290 if (event
->attr
.aux_pause
)
10291 perf_event_aux_pause(event
->aux_event
, true);
10293 if (event
->prog
&& event
->prog
->type
== BPF_PROG_TYPE_PERF_EVENT
&&
10294 !bpf_overflow_handler(event
, data
, regs
))
10298 * XXX event_limit might not quite work as expected on inherited
10302 event
->pending_kill
= POLL_IN
;
10303 if (events
&& atomic_dec_and_test(&event
->event_limit
)) {
10305 event
->pending_kill
= POLL_HUP
;
10306 perf_event_disable_inatomic(event
);
10309 if (event
->attr
.sigtrap
) {
10311 * The desired behaviour of sigtrap vs invalid samples is a bit
10312 * tricky; on the one hand, one should not loose the SIGTRAP if
10313 * it is the first event, on the other hand, we should also not
10314 * trigger the WARN or override the data address.
10316 bool valid_sample
= sample_is_allowed(event
, regs
);
10317 unsigned int pending_id
= 1;
10318 enum task_work_notify_mode notify_mode
;
10321 pending_id
= hash32_ptr((void *)instruction_pointer(regs
)) ?: 1;
10323 notify_mode
= in_nmi() ? TWA_NMI_CURRENT
: TWA_RESUME
;
10325 if (!event
->pending_work
&&
10326 !task_work_add(current
, &event
->pending_task
, notify_mode
)) {
10327 event
->pending_work
= pending_id
;
10328 local_inc(&event
->ctx
->nr_no_switch_fast
);
10329 WARN_ON_ONCE(!atomic_long_inc_not_zero(&event
->refcount
));
10331 event
->pending_addr
= 0;
10332 if (valid_sample
&& (data
->sample_flags
& PERF_SAMPLE_ADDR
))
10333 event
->pending_addr
= data
->addr
;
10335 } else if (event
->attr
.exclude_kernel
&& valid_sample
) {
10337 * Should not be able to return to user space without
10338 * consuming pending_work; with exceptions:
10340 * 1. Where !exclude_kernel, events can overflow again
10341 * in the kernel without returning to user space.
10343 * 2. Events that can overflow again before the IRQ-
10344 * work without user space progress (e.g. hrtimer).
10345 * To approximate progress (with false negatives),
10346 * check 32-bit hash of the current IP.
10348 WARN_ON_ONCE(event
->pending_work
!= pending_id
);
10352 READ_ONCE(event
->overflow_handler
)(event
, data
, regs
);
10354 if (*perf_event_fasync(event
) && event
->pending_kill
) {
10355 event
->pending_wakeup
= 1;
10356 irq_work_queue(&event
->pending_irq
);
10359 if (event
->attr
.aux_resume
)
10360 perf_event_aux_pause(event
->aux_event
, false);
10365 int perf_event_overflow(struct perf_event
*event
,
10366 struct perf_sample_data
*data
,
10367 struct pt_regs
*regs
)
10369 return __perf_event_overflow(event
, 1, data
, regs
);
10373 * Generic software event infrastructure
10376 struct swevent_htable
{
10377 struct swevent_hlist
*swevent_hlist
;
10378 struct mutex hlist_mutex
;
10379 int hlist_refcount
;
10381 static DEFINE_PER_CPU(struct swevent_htable
, swevent_htable
);
10384 * We directly increment event->count and keep a second value in
10385 * event->hw.period_left to count intervals. This period event
10386 * is kept in the range [-sample_period, 0] so that we can use the
10390 u64
perf_swevent_set_period(struct perf_event
*event
)
10392 struct hw_perf_event
*hwc
= &event
->hw
;
10393 u64 period
= hwc
->last_period
;
10397 hwc
->last_period
= hwc
->sample_period
;
10399 old
= local64_read(&hwc
->period_left
);
10405 nr
= div64_u64(period
+ val
, period
);
10406 offset
= nr
* period
;
10408 } while (!local64_try_cmpxchg(&hwc
->period_left
, &old
, val
));
10413 static void perf_swevent_overflow(struct perf_event
*event
, u64 overflow
,
10414 struct perf_sample_data
*data
,
10415 struct pt_regs
*regs
)
10417 struct hw_perf_event
*hwc
= &event
->hw
;
10421 overflow
= perf_swevent_set_period(event
);
10423 if (hwc
->interrupts
== MAX_INTERRUPTS
)
10426 for (; overflow
; overflow
--) {
10427 if (__perf_event_overflow(event
, throttle
,
10430 * We inhibit the overflow from happening when
10431 * hwc->interrupts == MAX_INTERRUPTS.
10439 static void perf_swevent_event(struct perf_event
*event
, u64 nr
,
10440 struct perf_sample_data
*data
,
10441 struct pt_regs
*regs
)
10443 struct hw_perf_event
*hwc
= &event
->hw
;
10445 local64_add(nr
, &event
->count
);
10450 if (!is_sampling_event(event
))
10453 if ((event
->attr
.sample_type
& PERF_SAMPLE_PERIOD
) && !event
->attr
.freq
) {
10455 return perf_swevent_overflow(event
, 1, data
, regs
);
10457 data
->period
= event
->hw
.last_period
;
10459 if (nr
== 1 && hwc
->sample_period
== 1 && !event
->attr
.freq
)
10460 return perf_swevent_overflow(event
, 1, data
, regs
);
10462 if (local64_add_negative(nr
, &hwc
->period_left
))
10465 perf_swevent_overflow(event
, 0, data
, regs
);
10468 int perf_exclude_event(struct perf_event
*event
, struct pt_regs
*regs
)
10470 if (event
->hw
.state
& PERF_HES_STOPPED
)
10474 if (event
->attr
.exclude_user
&& user_mode(regs
))
10477 if (event
->attr
.exclude_kernel
&& !user_mode(regs
))
10484 static int perf_swevent_match(struct perf_event
*event
,
10485 enum perf_type_id type
,
10487 struct perf_sample_data
*data
,
10488 struct pt_regs
*regs
)
10490 if (event
->attr
.type
!= type
)
10493 if (event
->attr
.config
!= event_id
)
10496 if (perf_exclude_event(event
, regs
))
10502 static inline u64
swevent_hash(u64 type
, u32 event_id
)
10504 u64 val
= event_id
| (type
<< 32);
10506 return hash_64(val
, SWEVENT_HLIST_BITS
);
10509 static inline struct hlist_head
*
10510 __find_swevent_head(struct swevent_hlist
*hlist
, u64 type
, u32 event_id
)
10512 u64 hash
= swevent_hash(type
, event_id
);
10514 return &hlist
->heads
[hash
];
10517 /* For the read side: events when they trigger */
10518 static inline struct hlist_head
*
10519 find_swevent_head_rcu(struct swevent_htable
*swhash
, u64 type
, u32 event_id
)
10521 struct swevent_hlist
*hlist
;
10523 hlist
= rcu_dereference(swhash
->swevent_hlist
);
10527 return __find_swevent_head(hlist
, type
, event_id
);
10530 /* For the event head insertion and removal in the hlist */
10531 static inline struct hlist_head
*
10532 find_swevent_head(struct swevent_htable
*swhash
, struct perf_event
*event
)
10534 struct swevent_hlist
*hlist
;
10535 u32 event_id
= event
->attr
.config
;
10536 u64 type
= event
->attr
.type
;
10539 * Event scheduling is always serialized against hlist allocation
10540 * and release. Which makes the protected version suitable here.
10541 * The context lock guarantees that.
10543 hlist
= rcu_dereference_protected(swhash
->swevent_hlist
,
10544 lockdep_is_held(&event
->ctx
->lock
));
10548 return __find_swevent_head(hlist
, type
, event_id
);
10551 static void do_perf_sw_event(enum perf_type_id type
, u32 event_id
,
10553 struct perf_sample_data
*data
,
10554 struct pt_regs
*regs
)
10556 struct swevent_htable
*swhash
= this_cpu_ptr(&swevent_htable
);
10557 struct perf_event
*event
;
10558 struct hlist_head
*head
;
10561 head
= find_swevent_head_rcu(swhash
, type
, event_id
);
10565 hlist_for_each_entry_rcu(event
, head
, hlist_entry
) {
10566 if (perf_swevent_match(event
, type
, event_id
, data
, regs
))
10567 perf_swevent_event(event
, nr
, data
, regs
);
10573 DEFINE_PER_CPU(struct pt_regs
, __perf_regs
[4]);
10575 int perf_swevent_get_recursion_context(void)
10577 return get_recursion_context(current
->perf_recursion
);
10579 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context
);
10581 void perf_swevent_put_recursion_context(int rctx
)
10583 put_recursion_context(current
->perf_recursion
, rctx
);
10586 void ___perf_sw_event(u32 event_id
, u64 nr
, struct pt_regs
*regs
, u64 addr
)
10588 struct perf_sample_data data
;
10590 if (WARN_ON_ONCE(!regs
))
10593 perf_sample_data_init(&data
, addr
, 0);
10594 do_perf_sw_event(PERF_TYPE_SOFTWARE
, event_id
, nr
, &data
, regs
);
10597 void __perf_sw_event(u32 event_id
, u64 nr
, struct pt_regs
*regs
, u64 addr
)
10601 preempt_disable_notrace();
10602 rctx
= perf_swevent_get_recursion_context();
10603 if (unlikely(rctx
< 0))
10606 ___perf_sw_event(event_id
, nr
, regs
, addr
);
10608 perf_swevent_put_recursion_context(rctx
);
10610 preempt_enable_notrace();
10613 static void perf_swevent_read(struct perf_event
*event
)
10617 static int perf_swevent_add(struct perf_event
*event
, int flags
)
10619 struct swevent_htable
*swhash
= this_cpu_ptr(&swevent_htable
);
10620 struct hw_perf_event
*hwc
= &event
->hw
;
10621 struct hlist_head
*head
;
10623 if (is_sampling_event(event
)) {
10624 hwc
->last_period
= hwc
->sample_period
;
10625 perf_swevent_set_period(event
);
10628 hwc
->state
= !(flags
& PERF_EF_START
);
10630 head
= find_swevent_head(swhash
, event
);
10631 if (WARN_ON_ONCE(!head
))
10634 hlist_add_head_rcu(&event
->hlist_entry
, head
);
10635 perf_event_update_userpage(event
);
10640 static void perf_swevent_del(struct perf_event
*event
, int flags
)
10642 hlist_del_rcu(&event
->hlist_entry
);
10645 static void perf_swevent_start(struct perf_event
*event
, int flags
)
10647 event
->hw
.state
= 0;
10650 static void perf_swevent_stop(struct perf_event
*event
, int flags
)
10652 event
->hw
.state
= PERF_HES_STOPPED
;
10655 /* Deref the hlist from the update side */
10656 static inline struct swevent_hlist
*
10657 swevent_hlist_deref(struct swevent_htable
*swhash
)
10659 return rcu_dereference_protected(swhash
->swevent_hlist
,
10660 lockdep_is_held(&swhash
->hlist_mutex
));
10663 static void swevent_hlist_release(struct swevent_htable
*swhash
)
10665 struct swevent_hlist
*hlist
= swevent_hlist_deref(swhash
);
10670 RCU_INIT_POINTER(swhash
->swevent_hlist
, NULL
);
10671 kfree_rcu(hlist
, rcu_head
);
10674 static void swevent_hlist_put_cpu(int cpu
)
10676 struct swevent_htable
*swhash
= &per_cpu(swevent_htable
, cpu
);
10678 mutex_lock(&swhash
->hlist_mutex
);
10680 if (!--swhash
->hlist_refcount
)
10681 swevent_hlist_release(swhash
);
10683 mutex_unlock(&swhash
->hlist_mutex
);
10686 static void swevent_hlist_put(void)
10690 for_each_possible_cpu(cpu
)
10691 swevent_hlist_put_cpu(cpu
);
10694 static int swevent_hlist_get_cpu(int cpu
)
10696 struct swevent_htable
*swhash
= &per_cpu(swevent_htable
, cpu
);
10699 mutex_lock(&swhash
->hlist_mutex
);
10700 if (!swevent_hlist_deref(swhash
) &&
10701 cpumask_test_cpu(cpu
, perf_online_mask
)) {
10702 struct swevent_hlist
*hlist
;
10704 hlist
= kzalloc(sizeof(*hlist
), GFP_KERNEL
);
10709 rcu_assign_pointer(swhash
->swevent_hlist
, hlist
);
10711 swhash
->hlist_refcount
++;
10713 mutex_unlock(&swhash
->hlist_mutex
);
10718 static int swevent_hlist_get(void)
10720 int err
, cpu
, failed_cpu
;
10722 mutex_lock(&pmus_lock
);
10723 for_each_possible_cpu(cpu
) {
10724 err
= swevent_hlist_get_cpu(cpu
);
10730 mutex_unlock(&pmus_lock
);
10733 for_each_possible_cpu(cpu
) {
10734 if (cpu
== failed_cpu
)
10736 swevent_hlist_put_cpu(cpu
);
10738 mutex_unlock(&pmus_lock
);
10742 struct static_key perf_swevent_enabled
[PERF_COUNT_SW_MAX
];
10744 static void sw_perf_event_destroy(struct perf_event
*event
)
10746 u64 event_id
= event
->attr
.config
;
10748 WARN_ON(event
->parent
);
10750 static_key_slow_dec(&perf_swevent_enabled
[event_id
]);
10751 swevent_hlist_put();
10754 static struct pmu perf_cpu_clock
; /* fwd declaration */
10755 static struct pmu perf_task_clock
;
10757 static int perf_swevent_init(struct perf_event
*event
)
10759 u64 event_id
= event
->attr
.config
;
10761 if (event
->attr
.type
!= PERF_TYPE_SOFTWARE
)
10765 * no branch sampling for software events
10767 if (has_branch_stack(event
))
10768 return -EOPNOTSUPP
;
10770 switch (event_id
) {
10771 case PERF_COUNT_SW_CPU_CLOCK
:
10772 event
->attr
.type
= perf_cpu_clock
.type
;
10774 case PERF_COUNT_SW_TASK_CLOCK
:
10775 event
->attr
.type
= perf_task_clock
.type
;
10782 if (event_id
>= PERF_COUNT_SW_MAX
)
10785 if (!event
->parent
) {
10788 err
= swevent_hlist_get();
10792 static_key_slow_inc(&perf_swevent_enabled
[event_id
]);
10793 event
->destroy
= sw_perf_event_destroy
;
10799 static struct pmu perf_swevent
= {
10800 .task_ctx_nr
= perf_sw_context
,
10802 .capabilities
= PERF_PMU_CAP_NO_NMI
,
10804 .event_init
= perf_swevent_init
,
10805 .add
= perf_swevent_add
,
10806 .del
= perf_swevent_del
,
10807 .start
= perf_swevent_start
,
10808 .stop
= perf_swevent_stop
,
10809 .read
= perf_swevent_read
,
10812 #ifdef CONFIG_EVENT_TRACING
10814 static void tp_perf_event_destroy(struct perf_event
*event
)
10816 perf_trace_destroy(event
);
10819 static int perf_tp_event_init(struct perf_event
*event
)
10823 if (event
->attr
.type
!= PERF_TYPE_TRACEPOINT
)
10827 * no branch sampling for tracepoint events
10829 if (has_branch_stack(event
))
10830 return -EOPNOTSUPP
;
10832 err
= perf_trace_init(event
);
10836 event
->destroy
= tp_perf_event_destroy
;
10841 static struct pmu perf_tracepoint
= {
10842 .task_ctx_nr
= perf_sw_context
,
10844 .event_init
= perf_tp_event_init
,
10845 .add
= perf_trace_add
,
10846 .del
= perf_trace_del
,
10847 .start
= perf_swevent_start
,
10848 .stop
= perf_swevent_stop
,
10849 .read
= perf_swevent_read
,
10852 static int perf_tp_filter_match(struct perf_event
*event
,
10853 struct perf_raw_record
*raw
)
10855 void *record
= raw
->frag
.data
;
10857 /* only top level events have filters set */
10859 event
= event
->parent
;
10861 if (likely(!event
->filter
) || filter_match_preds(event
->filter
, record
))
10866 static int perf_tp_event_match(struct perf_event
*event
,
10867 struct perf_raw_record
*raw
,
10868 struct pt_regs
*regs
)
10870 if (event
->hw
.state
& PERF_HES_STOPPED
)
10873 * If exclude_kernel, only trace user-space tracepoints (uprobes)
10875 if (event
->attr
.exclude_kernel
&& !user_mode(regs
))
10878 if (!perf_tp_filter_match(event
, raw
))
10884 void perf_trace_run_bpf_submit(void *raw_data
, int size
, int rctx
,
10885 struct trace_event_call
*call
, u64 count
,
10886 struct pt_regs
*regs
, struct hlist_head
*head
,
10887 struct task_struct
*task
)
10889 if (bpf_prog_array_valid(call
)) {
10890 *(struct pt_regs
**)raw_data
= regs
;
10891 if (!trace_call_bpf(call
, raw_data
) || hlist_empty(head
)) {
10892 perf_swevent_put_recursion_context(rctx
);
10896 perf_tp_event(call
->event
.type
, count
, raw_data
, size
, regs
, head
,
10899 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit
);
10901 static void __perf_tp_event_target_task(u64 count
, void *record
,
10902 struct pt_regs
*regs
,
10903 struct perf_sample_data
*data
,
10904 struct perf_raw_record
*raw
,
10905 struct perf_event
*event
)
10907 struct trace_entry
*entry
= record
;
10909 if (event
->attr
.config
!= entry
->type
)
10911 /* Cannot deliver synchronous signal to other task. */
10912 if (event
->attr
.sigtrap
)
10914 if (perf_tp_event_match(event
, raw
, regs
)) {
10915 perf_sample_data_init(data
, 0, 0);
10916 perf_sample_save_raw_data(data
, event
, raw
);
10917 perf_swevent_event(event
, count
, data
, regs
);
10921 static void perf_tp_event_target_task(u64 count
, void *record
,
10922 struct pt_regs
*regs
,
10923 struct perf_sample_data
*data
,
10924 struct perf_raw_record
*raw
,
10925 struct perf_event_context
*ctx
)
10927 unsigned int cpu
= smp_processor_id();
10928 struct pmu
*pmu
= &perf_tracepoint
;
10929 struct perf_event
*event
, *sibling
;
10931 perf_event_groups_for_cpu_pmu(event
, &ctx
->pinned_groups
, cpu
, pmu
) {
10932 __perf_tp_event_target_task(count
, record
, regs
, data
, raw
, event
);
10933 for_each_sibling_event(sibling
, event
)
10934 __perf_tp_event_target_task(count
, record
, regs
, data
, raw
, sibling
);
10937 perf_event_groups_for_cpu_pmu(event
, &ctx
->flexible_groups
, cpu
, pmu
) {
10938 __perf_tp_event_target_task(count
, record
, regs
, data
, raw
, event
);
10939 for_each_sibling_event(sibling
, event
)
10940 __perf_tp_event_target_task(count
, record
, regs
, data
, raw
, sibling
);
10944 void perf_tp_event(u16 event_type
, u64 count
, void *record
, int entry_size
,
10945 struct pt_regs
*regs
, struct hlist_head
*head
, int rctx
,
10946 struct task_struct
*task
)
10948 struct perf_sample_data data
;
10949 struct perf_event
*event
;
10951 struct perf_raw_record raw
= {
10953 .size
= entry_size
,
10958 perf_trace_buf_update(record
, event_type
);
10960 hlist_for_each_entry_rcu(event
, head
, hlist_entry
) {
10961 if (perf_tp_event_match(event
, &raw
, regs
)) {
10963 * Here use the same on-stack perf_sample_data,
10964 * some members in data are event-specific and
10965 * need to be re-computed for different sweveents.
10966 * Re-initialize data->sample_flags safely to avoid
10967 * the problem that next event skips preparing data
10968 * because data->sample_flags is set.
10970 perf_sample_data_init(&data
, 0, 0);
10971 perf_sample_save_raw_data(&data
, event
, &raw
);
10972 perf_swevent_event(event
, count
, &data
, regs
);
10977 * If we got specified a target task, also iterate its context and
10978 * deliver this event there too.
10980 if (task
&& task
!= current
) {
10981 struct perf_event_context
*ctx
;
10984 ctx
= rcu_dereference(task
->perf_event_ctxp
);
10988 raw_spin_lock(&ctx
->lock
);
10989 perf_tp_event_target_task(count
, record
, regs
, &data
, &raw
, ctx
);
10990 raw_spin_unlock(&ctx
->lock
);
10995 perf_swevent_put_recursion_context(rctx
);
10997 EXPORT_SYMBOL_GPL(perf_tp_event
);
10999 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
11001 * Flags in config, used by dynamic PMU kprobe and uprobe
11002 * The flags should match following PMU_FORMAT_ATTR().
11004 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
11005 * if not set, create kprobe/uprobe
11007 * The following values specify a reference counter (or semaphore in the
11008 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
11009 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
11011 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
11012 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
11014 enum perf_probe_config
{
11015 PERF_PROBE_CONFIG_IS_RETPROBE
= 1U << 0, /* [k,u]retprobe */
11016 PERF_UPROBE_REF_CTR_OFFSET_BITS
= 32,
11017 PERF_UPROBE_REF_CTR_OFFSET_SHIFT
= 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS
,
11020 PMU_FORMAT_ATTR(retprobe
, "config:0");
11023 #ifdef CONFIG_KPROBE_EVENTS
11024 static struct attribute
*kprobe_attrs
[] = {
11025 &format_attr_retprobe
.attr
,
11029 static struct attribute_group kprobe_format_group
= {
11031 .attrs
= kprobe_attrs
,
11034 static const struct attribute_group
*kprobe_attr_groups
[] = {
11035 &kprobe_format_group
,
11039 static int perf_kprobe_event_init(struct perf_event
*event
);
11040 static struct pmu perf_kprobe
= {
11041 .task_ctx_nr
= perf_sw_context
,
11042 .event_init
= perf_kprobe_event_init
,
11043 .add
= perf_trace_add
,
11044 .del
= perf_trace_del
,
11045 .start
= perf_swevent_start
,
11046 .stop
= perf_swevent_stop
,
11047 .read
= perf_swevent_read
,
11048 .attr_groups
= kprobe_attr_groups
,
11051 static int perf_kprobe_event_init(struct perf_event
*event
)
11056 if (event
->attr
.type
!= perf_kprobe
.type
)
11059 if (!perfmon_capable())
11063 * no branch sampling for probe events
11065 if (has_branch_stack(event
))
11066 return -EOPNOTSUPP
;
11068 is_retprobe
= event
->attr
.config
& PERF_PROBE_CONFIG_IS_RETPROBE
;
11069 err
= perf_kprobe_init(event
, is_retprobe
);
11073 event
->destroy
= perf_kprobe_destroy
;
11077 #endif /* CONFIG_KPROBE_EVENTS */
11079 #ifdef CONFIG_UPROBE_EVENTS
11080 PMU_FORMAT_ATTR(ref_ctr_offset
, "config:32-63");
11082 static struct attribute
*uprobe_attrs
[] = {
11083 &format_attr_retprobe
.attr
,
11084 &format_attr_ref_ctr_offset
.attr
,
11088 static struct attribute_group uprobe_format_group
= {
11090 .attrs
= uprobe_attrs
,
11093 static const struct attribute_group
*uprobe_attr_groups
[] = {
11094 &uprobe_format_group
,
11098 static int perf_uprobe_event_init(struct perf_event
*event
);
11099 static struct pmu perf_uprobe
= {
11100 .task_ctx_nr
= perf_sw_context
,
11101 .event_init
= perf_uprobe_event_init
,
11102 .add
= perf_trace_add
,
11103 .del
= perf_trace_del
,
11104 .start
= perf_swevent_start
,
11105 .stop
= perf_swevent_stop
,
11106 .read
= perf_swevent_read
,
11107 .attr_groups
= uprobe_attr_groups
,
11110 static int perf_uprobe_event_init(struct perf_event
*event
)
11113 unsigned long ref_ctr_offset
;
11116 if (event
->attr
.type
!= perf_uprobe
.type
)
11119 if (!perfmon_capable())
11123 * no branch sampling for probe events
11125 if (has_branch_stack(event
))
11126 return -EOPNOTSUPP
;
11128 is_retprobe
= event
->attr
.config
& PERF_PROBE_CONFIG_IS_RETPROBE
;
11129 ref_ctr_offset
= event
->attr
.config
>> PERF_UPROBE_REF_CTR_OFFSET_SHIFT
;
11130 err
= perf_uprobe_init(event
, ref_ctr_offset
, is_retprobe
);
11134 event
->destroy
= perf_uprobe_destroy
;
11138 #endif /* CONFIG_UPROBE_EVENTS */
11140 static inline void perf_tp_register(void)
11142 perf_pmu_register(&perf_tracepoint
, "tracepoint", PERF_TYPE_TRACEPOINT
);
11143 #ifdef CONFIG_KPROBE_EVENTS
11144 perf_pmu_register(&perf_kprobe
, "kprobe", -1);
11146 #ifdef CONFIG_UPROBE_EVENTS
11147 perf_pmu_register(&perf_uprobe
, "uprobe", -1);
11151 static void perf_event_free_filter(struct perf_event
*event
)
11153 ftrace_profile_free_filter(event
);
11157 * returns true if the event is a tracepoint, or a kprobe/upprobe created
11158 * with perf_event_open()
11160 static inline bool perf_event_is_tracing(struct perf_event
*event
)
11162 if (event
->pmu
== &perf_tracepoint
)
11164 #ifdef CONFIG_KPROBE_EVENTS
11165 if (event
->pmu
== &perf_kprobe
)
11168 #ifdef CONFIG_UPROBE_EVENTS
11169 if (event
->pmu
== &perf_uprobe
)
11175 static int __perf_event_set_bpf_prog(struct perf_event
*event
,
11176 struct bpf_prog
*prog
,
11179 bool is_kprobe
, is_uprobe
, is_tracepoint
, is_syscall_tp
;
11181 if (event
->state
<= PERF_EVENT_STATE_REVOKED
)
11184 if (!perf_event_is_tracing(event
))
11185 return perf_event_set_bpf_handler(event
, prog
, bpf_cookie
);
11187 is_kprobe
= event
->tp_event
->flags
& TRACE_EVENT_FL_KPROBE
;
11188 is_uprobe
= event
->tp_event
->flags
& TRACE_EVENT_FL_UPROBE
;
11189 is_tracepoint
= event
->tp_event
->flags
& TRACE_EVENT_FL_TRACEPOINT
;
11190 is_syscall_tp
= is_syscall_trace_event(event
->tp_event
);
11191 if (!is_kprobe
&& !is_uprobe
&& !is_tracepoint
&& !is_syscall_tp
)
11192 /* bpf programs can only be attached to u/kprobe or tracepoint */
11195 if (((is_kprobe
|| is_uprobe
) && prog
->type
!= BPF_PROG_TYPE_KPROBE
) ||
11196 (is_tracepoint
&& prog
->type
!= BPF_PROG_TYPE_TRACEPOINT
) ||
11197 (is_syscall_tp
&& prog
->type
!= BPF_PROG_TYPE_TRACEPOINT
))
11200 if (prog
->type
== BPF_PROG_TYPE_KPROBE
&& prog
->sleepable
&& !is_uprobe
)
11201 /* only uprobe programs are allowed to be sleepable */
11204 /* Kprobe override only works for kprobes, not uprobes. */
11205 if (prog
->kprobe_override
&& !is_kprobe
)
11208 if (is_tracepoint
|| is_syscall_tp
) {
11209 int off
= trace_event_get_offsets(event
->tp_event
);
11211 if (prog
->aux
->max_ctx_offset
> off
)
11215 return perf_event_attach_bpf_prog(event
, prog
, bpf_cookie
);
11218 int perf_event_set_bpf_prog(struct perf_event
*event
,
11219 struct bpf_prog
*prog
,
11222 struct perf_event_context
*ctx
;
11225 ctx
= perf_event_ctx_lock(event
);
11226 ret
= __perf_event_set_bpf_prog(event
, prog
, bpf_cookie
);
11227 perf_event_ctx_unlock(event
, ctx
);
11232 void perf_event_free_bpf_prog(struct perf_event
*event
)
11237 if (!perf_event_is_tracing(event
)) {
11238 perf_event_free_bpf_handler(event
);
11241 perf_event_detach_bpf_prog(event
);
11246 static inline void perf_tp_register(void)
11250 static void perf_event_free_filter(struct perf_event
*event
)
11254 static int __perf_event_set_bpf_prog(struct perf_event
*event
,
11255 struct bpf_prog
*prog
,
11261 int perf_event_set_bpf_prog(struct perf_event
*event
,
11262 struct bpf_prog
*prog
,
11268 void perf_event_free_bpf_prog(struct perf_event
*event
)
11271 #endif /* CONFIG_EVENT_TRACING */
11273 #ifdef CONFIG_HAVE_HW_BREAKPOINT
11274 void perf_bp_event(struct perf_event
*bp
, void *data
)
11276 struct perf_sample_data sample
;
11277 struct pt_regs
*regs
= data
;
11279 perf_sample_data_init(&sample
, bp
->attr
.bp_addr
, 0);
11281 if (!bp
->hw
.state
&& !perf_exclude_event(bp
, regs
))
11282 perf_swevent_event(bp
, 1, &sample
, regs
);
11287 * Allocate a new address filter
11289 static struct perf_addr_filter
*
11290 perf_addr_filter_new(struct perf_event
*event
, struct list_head
*filters
)
11292 int node
= cpu_to_node(event
->cpu
== -1 ? 0 : event
->cpu
);
11293 struct perf_addr_filter
*filter
;
11295 filter
= kzalloc_node(sizeof(*filter
), GFP_KERNEL
, node
);
11299 INIT_LIST_HEAD(&filter
->entry
);
11300 list_add_tail(&filter
->entry
, filters
);
11305 static void free_filters_list(struct list_head
*filters
)
11307 struct perf_addr_filter
*filter
, *iter
;
11309 list_for_each_entry_safe(filter
, iter
, filters
, entry
) {
11310 path_put(&filter
->path
);
11311 list_del(&filter
->entry
);
11317 * Free existing address filters and optionally install new ones
11319 static void perf_addr_filters_splice(struct perf_event
*event
,
11320 struct list_head
*head
)
11322 unsigned long flags
;
11325 if (!has_addr_filter(event
))
11328 /* don't bother with children, they don't have their own filters */
11332 raw_spin_lock_irqsave(&event
->addr_filters
.lock
, flags
);
11334 list_splice_init(&event
->addr_filters
.list
, &list
);
11336 list_splice(head
, &event
->addr_filters
.list
);
11338 raw_spin_unlock_irqrestore(&event
->addr_filters
.lock
, flags
);
11340 free_filters_list(&list
);
11343 static void perf_free_addr_filters(struct perf_event
*event
)
11346 * Used during free paths, there is no concurrency.
11348 if (list_empty(&event
->addr_filters
.list
))
11351 perf_addr_filters_splice(event
, NULL
);
11355 * Scan through mm's vmas and see if one of them matches the
11356 * @filter; if so, adjust filter's address range.
11357 * Called with mm::mmap_lock down for reading.
11359 static void perf_addr_filter_apply(struct perf_addr_filter
*filter
,
11360 struct mm_struct
*mm
,
11361 struct perf_addr_filter_range
*fr
)
11363 struct vm_area_struct
*vma
;
11364 VMA_ITERATOR(vmi
, mm
, 0);
11366 for_each_vma(vmi
, vma
) {
11370 if (perf_addr_filter_vma_adjust(filter
, vma
, fr
))
11376 * Update event's address range filters based on the
11377 * task's existing mappings, if any.
11379 static void perf_event_addr_filters_apply(struct perf_event
*event
)
11381 struct perf_addr_filters_head
*ifh
= perf_event_addr_filters(event
);
11382 struct task_struct
*task
= READ_ONCE(event
->ctx
->task
);
11383 struct perf_addr_filter
*filter
;
11384 struct mm_struct
*mm
= NULL
;
11385 unsigned int count
= 0;
11386 unsigned long flags
;
11389 * We may observe TASK_TOMBSTONE, which means that the event tear-down
11390 * will stop on the parent's child_mutex that our caller is also holding
11392 if (task
== TASK_TOMBSTONE
)
11395 if (ifh
->nr_file_filters
) {
11396 mm
= get_task_mm(task
);
11400 mmap_read_lock(mm
);
11403 raw_spin_lock_irqsave(&ifh
->lock
, flags
);
11404 list_for_each_entry(filter
, &ifh
->list
, entry
) {
11405 if (filter
->path
.dentry
) {
11407 * Adjust base offset if the filter is associated to a
11408 * binary that needs to be mapped:
11410 event
->addr_filter_ranges
[count
].start
= 0;
11411 event
->addr_filter_ranges
[count
].size
= 0;
11413 perf_addr_filter_apply(filter
, mm
, &event
->addr_filter_ranges
[count
]);
11415 event
->addr_filter_ranges
[count
].start
= filter
->offset
;
11416 event
->addr_filter_ranges
[count
].size
= filter
->size
;
11422 event
->addr_filters_gen
++;
11423 raw_spin_unlock_irqrestore(&ifh
->lock
, flags
);
11425 if (ifh
->nr_file_filters
) {
11426 mmap_read_unlock(mm
);
11432 perf_event_stop(event
, 1);
11436 * Address range filtering: limiting the data to certain
11437 * instruction address ranges. Filters are ioctl()ed to us from
11438 * userspace as ascii strings.
11440 * Filter string format:
11442 * ACTION RANGE_SPEC
11443 * where ACTION is one of the
11444 * * "filter": limit the trace to this region
11445 * * "start": start tracing from this address
11446 * * "stop": stop tracing at this address/region;
11448 * * for kernel addresses: <start address>[/<size>]
11449 * * for object files: <start address>[/<size>]@</path/to/object/file>
11451 * if <size> is not specified or is zero, the range is treated as a single
11452 * address; not valid for ACTION=="filter".
11466 IF_STATE_ACTION
= 0,
11471 static const match_table_t if_tokens
= {
11472 { IF_ACT_FILTER
, "filter" },
11473 { IF_ACT_START
, "start" },
11474 { IF_ACT_STOP
, "stop" },
11475 { IF_SRC_FILE
, "%u/%u@%s" },
11476 { IF_SRC_KERNEL
, "%u/%u" },
11477 { IF_SRC_FILEADDR
, "%u@%s" },
11478 { IF_SRC_KERNELADDR
, "%u" },
11479 { IF_ACT_NONE
, NULL
},
11483 * Address filter string parser
11486 perf_event_parse_addr_filter(struct perf_event
*event
, char *fstr
,
11487 struct list_head
*filters
)
11489 struct perf_addr_filter
*filter
= NULL
;
11490 char *start
, *orig
, *filename
= NULL
;
11491 substring_t args
[MAX_OPT_ARGS
];
11492 int state
= IF_STATE_ACTION
, token
;
11493 unsigned int kernel
= 0;
11496 orig
= fstr
= kstrdup(fstr
, GFP_KERNEL
);
11500 while ((start
= strsep(&fstr
, " ,\n")) != NULL
) {
11501 static const enum perf_addr_filter_action_t actions
[] = {
11502 [IF_ACT_FILTER
] = PERF_ADDR_FILTER_ACTION_FILTER
,
11503 [IF_ACT_START
] = PERF_ADDR_FILTER_ACTION_START
,
11504 [IF_ACT_STOP
] = PERF_ADDR_FILTER_ACTION_STOP
,
11511 /* filter definition begins */
11512 if (state
== IF_STATE_ACTION
) {
11513 filter
= perf_addr_filter_new(event
, filters
);
11518 token
= match_token(start
, if_tokens
, args
);
11520 case IF_ACT_FILTER
:
11523 if (state
!= IF_STATE_ACTION
)
11526 filter
->action
= actions
[token
];
11527 state
= IF_STATE_SOURCE
;
11530 case IF_SRC_KERNELADDR
:
11531 case IF_SRC_KERNEL
:
11535 case IF_SRC_FILEADDR
:
11537 if (state
!= IF_STATE_SOURCE
)
11541 ret
= kstrtoul(args
[0].from
, 0, &filter
->offset
);
11545 if (token
== IF_SRC_KERNEL
|| token
== IF_SRC_FILE
) {
11547 ret
= kstrtoul(args
[1].from
, 0, &filter
->size
);
11552 if (token
== IF_SRC_FILE
|| token
== IF_SRC_FILEADDR
) {
11553 int fpos
= token
== IF_SRC_FILE
? 2 : 1;
11556 filename
= match_strdup(&args
[fpos
]);
11563 state
= IF_STATE_END
;
11571 * Filter definition is fully parsed, validate and install it.
11572 * Make sure that it doesn't contradict itself or the event's
11575 if (state
== IF_STATE_END
) {
11579 * ACTION "filter" must have a non-zero length region
11582 if (filter
->action
== PERF_ADDR_FILTER_ACTION_FILTER
&&
11591 * For now, we only support file-based filters
11592 * in per-task events; doing so for CPU-wide
11593 * events requires additional context switching
11594 * trickery, since same object code will be
11595 * mapped at different virtual addresses in
11596 * different processes.
11599 if (!event
->ctx
->task
)
11602 /* look up the path and grab its inode */
11603 ret
= kern_path(filename
, LOOKUP_FOLLOW
,
11609 if (!filter
->path
.dentry
||
11610 !S_ISREG(d_inode(filter
->path
.dentry
)
11614 event
->addr_filters
.nr_file_filters
++;
11617 /* ready to consume more filters */
11620 state
= IF_STATE_ACTION
;
11626 if (state
!= IF_STATE_ACTION
)
11636 free_filters_list(filters
);
11643 perf_event_set_addr_filter(struct perf_event
*event
, char *filter_str
)
11645 LIST_HEAD(filters
);
11649 * Since this is called in perf_ioctl() path, we're already holding
11652 lockdep_assert_held(&event
->ctx
->mutex
);
11654 if (WARN_ON_ONCE(event
->parent
))
11657 ret
= perf_event_parse_addr_filter(event
, filter_str
, &filters
);
11659 goto fail_clear_files
;
11661 ret
= event
->pmu
->addr_filters_validate(&filters
);
11663 goto fail_free_filters
;
11665 /* remove existing filters, if any */
11666 perf_addr_filters_splice(event
, &filters
);
11668 /* install new filters */
11669 perf_event_for_each_child(event
, perf_event_addr_filters_apply
);
11674 free_filters_list(&filters
);
11677 event
->addr_filters
.nr_file_filters
= 0;
11682 static int perf_event_set_filter(struct perf_event
*event
, void __user
*arg
)
11687 filter_str
= strndup_user(arg
, PAGE_SIZE
);
11688 if (IS_ERR(filter_str
))
11689 return PTR_ERR(filter_str
);
11691 #ifdef CONFIG_EVENT_TRACING
11692 if (perf_event_is_tracing(event
)) {
11693 struct perf_event_context
*ctx
= event
->ctx
;
11696 * Beware, here be dragons!!
11698 * the tracepoint muck will deadlock against ctx->mutex, but
11699 * the tracepoint stuff does not actually need it. So
11700 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
11701 * already have a reference on ctx.
11703 * This can result in event getting moved to a different ctx,
11704 * but that does not affect the tracepoint state.
11706 mutex_unlock(&ctx
->mutex
);
11707 ret
= ftrace_profile_set_filter(event
, event
->attr
.config
, filter_str
);
11708 mutex_lock(&ctx
->mutex
);
11711 if (has_addr_filter(event
))
11712 ret
= perf_event_set_addr_filter(event
, filter_str
);
11719 * hrtimer based swevent callback
11722 static enum hrtimer_restart
perf_swevent_hrtimer(struct hrtimer
*hrtimer
)
11724 enum hrtimer_restart ret
= HRTIMER_RESTART
;
11725 struct perf_sample_data data
;
11726 struct pt_regs
*regs
;
11727 struct perf_event
*event
;
11730 event
= container_of(hrtimer
, struct perf_event
, hw
.hrtimer
);
11732 if (event
->state
!= PERF_EVENT_STATE_ACTIVE
)
11733 return HRTIMER_NORESTART
;
11735 event
->pmu
->read(event
);
11737 perf_sample_data_init(&data
, 0, event
->hw
.last_period
);
11738 regs
= get_irq_regs();
11740 if (regs
&& !perf_exclude_event(event
, regs
)) {
11741 if (!(event
->attr
.exclude_idle
&& is_idle_task(current
)))
11742 if (__perf_event_overflow(event
, 1, &data
, regs
))
11743 ret
= HRTIMER_NORESTART
;
11746 period
= max_t(u64
, 10000, event
->hw
.sample_period
);
11747 hrtimer_forward_now(hrtimer
, ns_to_ktime(period
));
11752 static void perf_swevent_start_hrtimer(struct perf_event
*event
)
11754 struct hw_perf_event
*hwc
= &event
->hw
;
11757 if (!is_sampling_event(event
))
11760 period
= local64_read(&hwc
->period_left
);
11765 local64_set(&hwc
->period_left
, 0);
11767 period
= max_t(u64
, 10000, hwc
->sample_period
);
11769 hrtimer_start(&hwc
->hrtimer
, ns_to_ktime(period
),
11770 HRTIMER_MODE_REL_PINNED_HARD
);
11773 static void perf_swevent_cancel_hrtimer(struct perf_event
*event
)
11775 struct hw_perf_event
*hwc
= &event
->hw
;
11778 * The throttle can be triggered in the hrtimer handler.
11779 * The HRTIMER_NORESTART should be used to stop the timer,
11780 * rather than hrtimer_cancel(). See perf_swevent_hrtimer()
11782 if (is_sampling_event(event
) && (hwc
->interrupts
!= MAX_INTERRUPTS
)) {
11783 ktime_t remaining
= hrtimer_get_remaining(&hwc
->hrtimer
);
11784 local64_set(&hwc
->period_left
, ktime_to_ns(remaining
));
11786 hrtimer_cancel(&hwc
->hrtimer
);
11790 static void perf_swevent_init_hrtimer(struct perf_event
*event
)
11792 struct hw_perf_event
*hwc
= &event
->hw
;
11794 if (!is_sampling_event(event
))
11797 hrtimer_setup(&hwc
->hrtimer
, perf_swevent_hrtimer
, CLOCK_MONOTONIC
, HRTIMER_MODE_REL_HARD
);
11800 * Since hrtimers have a fixed rate, we can do a static freq->period
11801 * mapping and avoid the whole period adjust feedback stuff.
11803 if (event
->attr
.freq
) {
11804 long freq
= event
->attr
.sample_freq
;
11806 event
->attr
.sample_period
= NSEC_PER_SEC
/ freq
;
11807 hwc
->sample_period
= event
->attr
.sample_period
;
11808 local64_set(&hwc
->period_left
, hwc
->sample_period
);
11809 hwc
->last_period
= hwc
->sample_period
;
11810 event
->attr
.freq
= 0;
11815 * Software event: cpu wall time clock
11818 static void cpu_clock_event_update(struct perf_event
*event
)
11823 now
= local_clock();
11824 prev
= local64_xchg(&event
->hw
.prev_count
, now
);
11825 local64_add(now
- prev
, &event
->count
);
11828 static void cpu_clock_event_start(struct perf_event
*event
, int flags
)
11830 local64_set(&event
->hw
.prev_count
, local_clock());
11831 perf_swevent_start_hrtimer(event
);
11834 static void cpu_clock_event_stop(struct perf_event
*event
, int flags
)
11836 perf_swevent_cancel_hrtimer(event
);
11837 if (flags
& PERF_EF_UPDATE
)
11838 cpu_clock_event_update(event
);
11841 static int cpu_clock_event_add(struct perf_event
*event
, int flags
)
11843 if (flags
& PERF_EF_START
)
11844 cpu_clock_event_start(event
, flags
);
11845 perf_event_update_userpage(event
);
11850 static void cpu_clock_event_del(struct perf_event
*event
, int flags
)
11852 cpu_clock_event_stop(event
, flags
);
11855 static void cpu_clock_event_read(struct perf_event
*event
)
11857 cpu_clock_event_update(event
);
11860 static int cpu_clock_event_init(struct perf_event
*event
)
11862 if (event
->attr
.type
!= perf_cpu_clock
.type
)
11865 if (event
->attr
.config
!= PERF_COUNT_SW_CPU_CLOCK
)
11869 * no branch sampling for software events
11871 if (has_branch_stack(event
))
11872 return -EOPNOTSUPP
;
11874 perf_swevent_init_hrtimer(event
);
11879 static struct pmu perf_cpu_clock
= {
11880 .task_ctx_nr
= perf_sw_context
,
11882 .capabilities
= PERF_PMU_CAP_NO_NMI
,
11883 .dev
= PMU_NULL_DEV
,
11885 .event_init
= cpu_clock_event_init
,
11886 .add
= cpu_clock_event_add
,
11887 .del
= cpu_clock_event_del
,
11888 .start
= cpu_clock_event_start
,
11889 .stop
= cpu_clock_event_stop
,
11890 .read
= cpu_clock_event_read
,
11894 * Software event: task time clock
11897 static void task_clock_event_update(struct perf_event
*event
, u64 now
)
11902 prev
= local64_xchg(&event
->hw
.prev_count
, now
);
11903 delta
= now
- prev
;
11904 local64_add(delta
, &event
->count
);
11907 static void task_clock_event_start(struct perf_event
*event
, int flags
)
11909 local64_set(&event
->hw
.prev_count
, event
->ctx
->time
);
11910 perf_swevent_start_hrtimer(event
);
11913 static void task_clock_event_stop(struct perf_event
*event
, int flags
)
11915 perf_swevent_cancel_hrtimer(event
);
11916 if (flags
& PERF_EF_UPDATE
)
11917 task_clock_event_update(event
, event
->ctx
->time
);
11920 static int task_clock_event_add(struct perf_event
*event
, int flags
)
11922 if (flags
& PERF_EF_START
)
11923 task_clock_event_start(event
, flags
);
11924 perf_event_update_userpage(event
);
11929 static void task_clock_event_del(struct perf_event
*event
, int flags
)
11931 task_clock_event_stop(event
, PERF_EF_UPDATE
);
11934 static void task_clock_event_read(struct perf_event
*event
)
11936 u64 now
= perf_clock();
11937 u64 delta
= now
- event
->ctx
->timestamp
;
11938 u64 time
= event
->ctx
->time
+ delta
;
11940 task_clock_event_update(event
, time
);
11943 static int task_clock_event_init(struct perf_event
*event
)
11945 if (event
->attr
.type
!= perf_task_clock
.type
)
11948 if (event
->attr
.config
!= PERF_COUNT_SW_TASK_CLOCK
)
11952 * no branch sampling for software events
11954 if (has_branch_stack(event
))
11955 return -EOPNOTSUPP
;
11957 perf_swevent_init_hrtimer(event
);
11962 static struct pmu perf_task_clock
= {
11963 .task_ctx_nr
= perf_sw_context
,
11965 .capabilities
= PERF_PMU_CAP_NO_NMI
,
11966 .dev
= PMU_NULL_DEV
,
11968 .event_init
= task_clock_event_init
,
11969 .add
= task_clock_event_add
,
11970 .del
= task_clock_event_del
,
11971 .start
= task_clock_event_start
,
11972 .stop
= task_clock_event_stop
,
11973 .read
= task_clock_event_read
,
11976 static void perf_pmu_nop_void(struct pmu
*pmu
)
11980 static void perf_pmu_nop_txn(struct pmu
*pmu
, unsigned int flags
)
11984 static int perf_pmu_nop_int(struct pmu
*pmu
)
11989 static int perf_event_nop_int(struct perf_event
*event
, u64 value
)
11994 static DEFINE_PER_CPU(unsigned int, nop_txn_flags
);
11996 static void perf_pmu_start_txn(struct pmu
*pmu
, unsigned int flags
)
11998 __this_cpu_write(nop_txn_flags
, flags
);
12000 if (flags
& ~PERF_PMU_TXN_ADD
)
12003 perf_pmu_disable(pmu
);
12006 static int perf_pmu_commit_txn(struct pmu
*pmu
)
12008 unsigned int flags
= __this_cpu_read(nop_txn_flags
);
12010 __this_cpu_write(nop_txn_flags
, 0);
12012 if (flags
& ~PERF_PMU_TXN_ADD
)
12015 perf_pmu_enable(pmu
);
12019 static void perf_pmu_cancel_txn(struct pmu
*pmu
)
12021 unsigned int flags
= __this_cpu_read(nop_txn_flags
);
12023 __this_cpu_write(nop_txn_flags
, 0);
12025 if (flags
& ~PERF_PMU_TXN_ADD
)
12028 perf_pmu_enable(pmu
);
12031 static int perf_event_idx_default(struct perf_event
*event
)
12037 * Let userspace know that this PMU supports address range filtering:
12039 static ssize_t
nr_addr_filters_show(struct device
*dev
,
12040 struct device_attribute
*attr
,
12043 struct pmu
*pmu
= dev_get_drvdata(dev
);
12045 return sysfs_emit(page
, "%d\n", pmu
->nr_addr_filters
);
12047 DEVICE_ATTR_RO(nr_addr_filters
);
12049 static struct idr pmu_idr
;
12052 type_show(struct device
*dev
, struct device_attribute
*attr
, char *page
)
12054 struct pmu
*pmu
= dev_get_drvdata(dev
);
12056 return sysfs_emit(page
, "%d\n", pmu
->type
);
12058 static DEVICE_ATTR_RO(type
);
12061 perf_event_mux_interval_ms_show(struct device
*dev
,
12062 struct device_attribute
*attr
,
12065 struct pmu
*pmu
= dev_get_drvdata(dev
);
12067 return sysfs_emit(page
, "%d\n", pmu
->hrtimer_interval_ms
);
12070 static DEFINE_MUTEX(mux_interval_mutex
);
12073 perf_event_mux_interval_ms_store(struct device
*dev
,
12074 struct device_attribute
*attr
,
12075 const char *buf
, size_t count
)
12077 struct pmu
*pmu
= dev_get_drvdata(dev
);
12078 int timer
, cpu
, ret
;
12080 ret
= kstrtoint(buf
, 0, &timer
);
12087 /* same value, noting to do */
12088 if (timer
== pmu
->hrtimer_interval_ms
)
12091 mutex_lock(&mux_interval_mutex
);
12092 pmu
->hrtimer_interval_ms
= timer
;
12094 /* update all cpuctx for this PMU */
12096 for_each_online_cpu(cpu
) {
12097 struct perf_cpu_pmu_context
*cpc
;
12098 cpc
= *per_cpu_ptr(pmu
->cpu_pmu_context
, cpu
);
12099 cpc
->hrtimer_interval
= ns_to_ktime(NSEC_PER_MSEC
* timer
);
12101 cpu_function_call(cpu
, perf_mux_hrtimer_restart_ipi
, cpc
);
12103 cpus_read_unlock();
12104 mutex_unlock(&mux_interval_mutex
);
12108 static DEVICE_ATTR_RW(perf_event_mux_interval_ms
);
12110 static inline const struct cpumask
*perf_scope_cpu_topology_cpumask(unsigned int scope
, int cpu
)
12113 case PERF_PMU_SCOPE_CORE
:
12114 return topology_sibling_cpumask(cpu
);
12115 case PERF_PMU_SCOPE_DIE
:
12116 return topology_die_cpumask(cpu
);
12117 case PERF_PMU_SCOPE_CLUSTER
:
12118 return topology_cluster_cpumask(cpu
);
12119 case PERF_PMU_SCOPE_PKG
:
12120 return topology_core_cpumask(cpu
);
12121 case PERF_PMU_SCOPE_SYS_WIDE
:
12122 return cpu_online_mask
;
12128 static inline struct cpumask
*perf_scope_cpumask(unsigned int scope
)
12131 case PERF_PMU_SCOPE_CORE
:
12132 return perf_online_core_mask
;
12133 case PERF_PMU_SCOPE_DIE
:
12134 return perf_online_die_mask
;
12135 case PERF_PMU_SCOPE_CLUSTER
:
12136 return perf_online_cluster_mask
;
12137 case PERF_PMU_SCOPE_PKG
:
12138 return perf_online_pkg_mask
;
12139 case PERF_PMU_SCOPE_SYS_WIDE
:
12140 return perf_online_sys_mask
;
12146 static ssize_t
cpumask_show(struct device
*dev
, struct device_attribute
*attr
,
12149 struct pmu
*pmu
= dev_get_drvdata(dev
);
12150 struct cpumask
*mask
= perf_scope_cpumask(pmu
->scope
);
12153 return cpumap_print_to_pagebuf(true, buf
, mask
);
12157 static DEVICE_ATTR_RO(cpumask
);
12159 static struct attribute
*pmu_dev_attrs
[] = {
12160 &dev_attr_type
.attr
,
12161 &dev_attr_perf_event_mux_interval_ms
.attr
,
12162 &dev_attr_nr_addr_filters
.attr
,
12163 &dev_attr_cpumask
.attr
,
12167 static umode_t
pmu_dev_is_visible(struct kobject
*kobj
, struct attribute
*a
, int n
)
12169 struct device
*dev
= kobj_to_dev(kobj
);
12170 struct pmu
*pmu
= dev_get_drvdata(dev
);
12172 if (n
== 2 && !pmu
->nr_addr_filters
)
12176 if (n
== 3 && pmu
->scope
== PERF_PMU_SCOPE_NONE
)
12182 static struct attribute_group pmu_dev_attr_group
= {
12183 .is_visible
= pmu_dev_is_visible
,
12184 .attrs
= pmu_dev_attrs
,
12187 static const struct attribute_group
*pmu_dev_groups
[] = {
12188 &pmu_dev_attr_group
,
12192 static int pmu_bus_running
;
12193 static struct bus_type pmu_bus
= {
12194 .name
= "event_source",
12195 .dev_groups
= pmu_dev_groups
,
12198 static void pmu_dev_release(struct device
*dev
)
12203 static int pmu_dev_alloc(struct pmu
*pmu
)
12207 pmu
->dev
= kzalloc(sizeof(struct device
), GFP_KERNEL
);
12211 pmu
->dev
->groups
= pmu
->attr_groups
;
12212 device_initialize(pmu
->dev
);
12214 dev_set_drvdata(pmu
->dev
, pmu
);
12215 pmu
->dev
->bus
= &pmu_bus
;
12216 pmu
->dev
->parent
= pmu
->parent
;
12217 pmu
->dev
->release
= pmu_dev_release
;
12219 ret
= dev_set_name(pmu
->dev
, "%s", pmu
->name
);
12223 ret
= device_add(pmu
->dev
);
12227 if (pmu
->attr_update
) {
12228 ret
= sysfs_update_groups(&pmu
->dev
->kobj
, pmu
->attr_update
);
12237 device_del(pmu
->dev
);
12240 put_device(pmu
->dev
);
12245 static struct lock_class_key cpuctx_mutex
;
12246 static struct lock_class_key cpuctx_lock
;
12248 static bool idr_cmpxchg(struct idr
*idr
, unsigned long id
, void *old
, void *new)
12250 void *tmp
, *val
= idr_find(idr
, id
);
12255 tmp
= idr_replace(idr
, new, id
);
12259 WARN_ON_ONCE(tmp
!= val
);
12263 static void perf_pmu_free(struct pmu
*pmu
)
12265 if (pmu_bus_running
&& pmu
->dev
&& pmu
->dev
!= PMU_NULL_DEV
) {
12266 if (pmu
->nr_addr_filters
)
12267 device_remove_file(pmu
->dev
, &dev_attr_nr_addr_filters
);
12268 device_del(pmu
->dev
);
12269 put_device(pmu
->dev
);
12272 if (pmu
->cpu_pmu_context
) {
12275 for_each_possible_cpu(cpu
) {
12276 struct perf_cpu_pmu_context
*cpc
;
12278 cpc
= *per_cpu_ptr(pmu
->cpu_pmu_context
, cpu
);
12281 if (cpc
->epc
.embedded
) {
12282 /* refcount managed */
12283 put_pmu_ctx(&cpc
->epc
);
12288 free_percpu(pmu
->cpu_pmu_context
);
12292 DEFINE_FREE(pmu_unregister
, struct pmu
*, if (_T
) perf_pmu_free(_T
))
12294 int perf_pmu_register(struct pmu
*_pmu
, const char *name
, int type
)
12296 int cpu
, max
= PERF_TYPE_MAX
;
12298 struct pmu
*pmu
__free(pmu_unregister
) = _pmu
;
12299 guard(mutex
)(&pmus_lock
);
12301 if (WARN_ONCE(!name
, "Can not register anonymous pmu.\n"))
12304 if (WARN_ONCE(pmu
->scope
>= PERF_PMU_MAX_SCOPE
,
12305 "Can not register a pmu with an invalid scope.\n"))
12313 CLASS(idr_alloc
, pmu_type
)(&pmu_idr
, NULL
, max
, 0, GFP_KERNEL
);
12314 if (pmu_type
.id
< 0)
12315 return pmu_type
.id
;
12317 WARN_ON(type
>= 0 && pmu_type
.id
!= type
);
12319 pmu
->type
= pmu_type
.id
;
12320 atomic_set(&pmu
->exclusive_cnt
, 0);
12322 if (pmu_bus_running
&& !pmu
->dev
) {
12323 int ret
= pmu_dev_alloc(pmu
);
12328 pmu
->cpu_pmu_context
= alloc_percpu(struct perf_cpu_pmu_context
*);
12329 if (!pmu
->cpu_pmu_context
)
12332 for_each_possible_cpu(cpu
) {
12333 struct perf_cpu_pmu_context
*cpc
=
12334 kmalloc_node(sizeof(struct perf_cpu_pmu_context
),
12335 GFP_KERNEL
| __GFP_ZERO
,
12341 *per_cpu_ptr(pmu
->cpu_pmu_context
, cpu
) = cpc
;
12342 __perf_init_event_pmu_context(&cpc
->epc
, pmu
);
12343 __perf_mux_hrtimer_init(cpc
, cpu
);
12346 if (!pmu
->start_txn
) {
12347 if (pmu
->pmu_enable
) {
12349 * If we have pmu_enable/pmu_disable calls, install
12350 * transaction stubs that use that to try and batch
12351 * hardware accesses.
12353 pmu
->start_txn
= perf_pmu_start_txn
;
12354 pmu
->commit_txn
= perf_pmu_commit_txn
;
12355 pmu
->cancel_txn
= perf_pmu_cancel_txn
;
12357 pmu
->start_txn
= perf_pmu_nop_txn
;
12358 pmu
->commit_txn
= perf_pmu_nop_int
;
12359 pmu
->cancel_txn
= perf_pmu_nop_void
;
12363 if (!pmu
->pmu_enable
) {
12364 pmu
->pmu_enable
= perf_pmu_nop_void
;
12365 pmu
->pmu_disable
= perf_pmu_nop_void
;
12368 if (!pmu
->check_period
)
12369 pmu
->check_period
= perf_event_nop_int
;
12371 if (!pmu
->event_idx
)
12372 pmu
->event_idx
= perf_event_idx_default
;
12374 INIT_LIST_HEAD(&pmu
->events
);
12375 spin_lock_init(&pmu
->events_lock
);
12378 * Now that the PMU is complete, make it visible to perf_try_init_event().
12380 if (!idr_cmpxchg(&pmu_idr
, pmu
->type
, NULL
, pmu
))
12382 list_add_rcu(&pmu
->entry
, &pmus
);
12384 take_idr_id(pmu_type
);
12385 _pmu
= no_free_ptr(pmu
); // let it rip
12388 EXPORT_SYMBOL_GPL(perf_pmu_register
);
12390 static void __pmu_detach_event(struct pmu
*pmu
, struct perf_event
*event
,
12391 struct perf_event_context
*ctx
)
12394 * De-schedule the event and mark it REVOKED.
12396 perf_event_exit_event(event
, ctx
, true);
12399 * All _free_event() bits that rely on event->pmu:
12401 * Notably, perf_mmap() relies on the ordering here.
12403 scoped_guard (mutex
, &event
->mmap_mutex
) {
12404 WARN_ON_ONCE(pmu
->event_unmapped
);
12406 * Mostly an empty lock sequence, such that perf_mmap(), which
12407 * relies on mmap_mutex, is sure to observe the state change.
12411 perf_event_free_bpf_prog(event
);
12412 perf_free_addr_filters(event
);
12414 if (event
->destroy
) {
12415 event
->destroy(event
);
12416 event
->destroy
= NULL
;
12419 if (event
->pmu_ctx
) {
12420 put_pmu_ctx(event
->pmu_ctx
);
12421 event
->pmu_ctx
= NULL
;
12424 exclusive_event_destroy(event
);
12425 module_put(pmu
->module
);
12427 event
->pmu
= NULL
; /* force fault instead of UAF */
12430 static void pmu_detach_event(struct pmu
*pmu
, struct perf_event
*event
)
12432 struct perf_event_context
*ctx
;
12434 ctx
= perf_event_ctx_lock(event
);
12435 __pmu_detach_event(pmu
, event
, ctx
);
12436 perf_event_ctx_unlock(event
, ctx
);
12438 scoped_guard (spinlock
, &pmu
->events_lock
)
12439 list_del(&event
->pmu_list
);
12442 static struct perf_event
*pmu_get_event(struct pmu
*pmu
)
12444 struct perf_event
*event
;
12446 guard(spinlock
)(&pmu
->events_lock
);
12447 list_for_each_entry(event
, &pmu
->events
, pmu_list
) {
12448 if (atomic_long_inc_not_zero(&event
->refcount
))
12455 static bool pmu_empty(struct pmu
*pmu
)
12457 guard(spinlock
)(&pmu
->events_lock
);
12458 return list_empty(&pmu
->events
);
12461 static void pmu_detach_events(struct pmu
*pmu
)
12463 struct perf_event
*event
;
12466 event
= pmu_get_event(pmu
);
12470 pmu_detach_event(pmu
, event
);
12475 * wait for pending _free_event()s
12477 wait_var_event(pmu
, pmu_empty(pmu
));
12480 int perf_pmu_unregister(struct pmu
*pmu
)
12482 scoped_guard (mutex
, &pmus_lock
) {
12483 if (!idr_cmpxchg(&pmu_idr
, pmu
->type
, pmu
, NULL
))
12486 list_del_rcu(&pmu
->entry
);
12490 * We dereference the pmu list under both SRCU and regular RCU, so
12491 * synchronize against both of those.
12493 * Notably, the entirety of event creation, from perf_init_event()
12494 * (which will now fail, because of the above) until
12495 * perf_install_in_context() should be under SRCU such that
12496 * this synchronizes against event creation. This avoids trying to
12497 * detach events that are not fully formed.
12499 synchronize_srcu(&pmus_srcu
);
12502 if (pmu
->event_unmapped
&& !pmu_empty(pmu
)) {
12504 * Can't force remove events when pmu::event_unmapped()
12505 * is used in perf_mmap_close().
12507 guard(mutex
)(&pmus_lock
);
12508 idr_cmpxchg(&pmu_idr
, pmu
->type
, NULL
, pmu
);
12509 list_add_rcu(&pmu
->entry
, &pmus
);
12513 scoped_guard (mutex
, &pmus_lock
)
12514 idr_remove(&pmu_idr
, pmu
->type
);
12517 * PMU is removed from the pmus list, so no new events will
12518 * be created, now take care of the existing ones.
12520 pmu_detach_events(pmu
);
12523 * PMU is unused, make it go away.
12525 perf_pmu_free(pmu
);
12528 EXPORT_SYMBOL_GPL(perf_pmu_unregister
);
12530 static inline bool has_extended_regs(struct perf_event
*event
)
12532 return (event
->attr
.sample_regs_user
& PERF_REG_EXTENDED_MASK
) ||
12533 (event
->attr
.sample_regs_intr
& PERF_REG_EXTENDED_MASK
);
12536 static int perf_try_init_event(struct pmu
*pmu
, struct perf_event
*event
)
12538 struct perf_event_context
*ctx
= NULL
;
12541 if (!try_module_get(pmu
->module
))
12545 * A number of pmu->event_init() methods iterate the sibling_list to,
12546 * for example, validate if the group fits on the PMU. Therefore,
12547 * if this is a sibling event, acquire the ctx->mutex to protect
12548 * the sibling_list.
12550 if (event
->group_leader
!= event
&& pmu
->task_ctx_nr
!= perf_sw_context
) {
12552 * This ctx->mutex can nest when we're called through
12553 * inheritance. See the perf_event_ctx_lock_nested() comment.
12555 ctx
= perf_event_ctx_lock_nested(event
->group_leader
,
12556 SINGLE_DEPTH_NESTING
);
12561 ret
= pmu
->event_init(event
);
12564 perf_event_ctx_unlock(event
->group_leader
, ctx
);
12569 if (!(pmu
->capabilities
& PERF_PMU_CAP_EXTENDED_REGS
) &&
12570 has_extended_regs(event
)) {
12575 if (pmu
->capabilities
& PERF_PMU_CAP_NO_EXCLUDE
&&
12576 event_has_any_exclude_flag(event
)) {
12581 if (pmu
->scope
!= PERF_PMU_SCOPE_NONE
&& event
->cpu
>= 0) {
12582 const struct cpumask
*cpumask
;
12583 struct cpumask
*pmu_cpumask
;
12586 cpumask
= perf_scope_cpu_topology_cpumask(pmu
->scope
, event
->cpu
);
12587 pmu_cpumask
= perf_scope_cpumask(pmu
->scope
);
12590 if (!pmu_cpumask
|| !cpumask
)
12593 cpu
= cpumask_any_and(pmu_cpumask
, cpumask
);
12594 if (cpu
>= nr_cpu_ids
)
12597 event
->event_caps
|= PERF_EV_CAP_READ_SCOPE
;
12603 if (event
->destroy
) {
12604 event
->destroy(event
);
12605 event
->destroy
= NULL
;
12610 module_put(pmu
->module
);
12614 static struct pmu
*perf_init_event(struct perf_event
*event
)
12616 bool extended_type
= false;
12620 guard(srcu
)(&pmus_srcu
); /* pmu idr/list access */
12623 * Save original type before calling pmu->event_init() since certain
12624 * pmus overwrites event->attr.type to forward event to another pmu.
12626 event
->orig_type
= event
->attr
.type
;
12628 /* Try parent's PMU first: */
12629 if (event
->parent
&& event
->parent
->pmu
) {
12630 pmu
= event
->parent
->pmu
;
12631 ret
= perf_try_init_event(pmu
, event
);
12637 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
12638 * are often aliases for PERF_TYPE_RAW.
12640 type
= event
->attr
.type
;
12641 if (type
== PERF_TYPE_HARDWARE
|| type
== PERF_TYPE_HW_CACHE
) {
12642 type
= event
->attr
.config
>> PERF_PMU_TYPE_SHIFT
;
12644 type
= PERF_TYPE_RAW
;
12646 extended_type
= true;
12647 event
->attr
.config
&= PERF_HW_EVENT_MASK
;
12653 pmu
= idr_find(&pmu_idr
, type
);
12655 if (event
->attr
.type
!= type
&& type
!= PERF_TYPE_RAW
&&
12656 !(pmu
->capabilities
& PERF_PMU_CAP_EXTENDED_HW_TYPE
))
12657 return ERR_PTR(-ENOENT
);
12659 ret
= perf_try_init_event(pmu
, event
);
12660 if (ret
== -ENOENT
&& event
->attr
.type
!= type
&& !extended_type
) {
12661 type
= event
->attr
.type
;
12666 return ERR_PTR(ret
);
12671 list_for_each_entry_rcu(pmu
, &pmus
, entry
, lockdep_is_held(&pmus_srcu
)) {
12672 ret
= perf_try_init_event(pmu
, event
);
12676 if (ret
!= -ENOENT
)
12677 return ERR_PTR(ret
);
12680 return ERR_PTR(-ENOENT
);
12683 static void attach_sb_event(struct perf_event
*event
)
12685 struct pmu_event_list
*pel
= per_cpu_ptr(&pmu_sb_events
, event
->cpu
);
12687 raw_spin_lock(&pel
->lock
);
12688 list_add_rcu(&event
->sb_list
, &pel
->list
);
12689 raw_spin_unlock(&pel
->lock
);
12693 * We keep a list of all !task (and therefore per-cpu) events
12694 * that need to receive side-band records.
12696 * This avoids having to scan all the various PMU per-cpu contexts
12697 * looking for them.
12699 static void account_pmu_sb_event(struct perf_event
*event
)
12701 if (is_sb_event(event
))
12702 attach_sb_event(event
);
12705 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
12706 static void account_freq_event_nohz(void)
12708 #ifdef CONFIG_NO_HZ_FULL
12709 /* Lock so we don't race with concurrent unaccount */
12710 spin_lock(&nr_freq_lock
);
12711 if (atomic_inc_return(&nr_freq_events
) == 1)
12712 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS
);
12713 spin_unlock(&nr_freq_lock
);
12717 static void account_freq_event(void)
12719 if (tick_nohz_full_enabled())
12720 account_freq_event_nohz();
12722 atomic_inc(&nr_freq_events
);
12726 static void account_event(struct perf_event
*event
)
12733 if (event
->attach_state
& (PERF_ATTACH_TASK
| PERF_ATTACH_SCHED_CB
))
12735 if (event
->attr
.mmap
|| event
->attr
.mmap_data
)
12736 atomic_inc(&nr_mmap_events
);
12737 if (event
->attr
.build_id
)
12738 atomic_inc(&nr_build_id_events
);
12739 if (event
->attr
.comm
)
12740 atomic_inc(&nr_comm_events
);
12741 if (event
->attr
.namespaces
)
12742 atomic_inc(&nr_namespaces_events
);
12743 if (event
->attr
.cgroup
)
12744 atomic_inc(&nr_cgroup_events
);
12745 if (event
->attr
.task
)
12746 atomic_inc(&nr_task_events
);
12747 if (event
->attr
.freq
)
12748 account_freq_event();
12749 if (event
->attr
.context_switch
) {
12750 atomic_inc(&nr_switch_events
);
12753 if (has_branch_stack(event
))
12755 if (is_cgroup_event(event
))
12757 if (event
->attr
.ksymbol
)
12758 atomic_inc(&nr_ksymbol_events
);
12759 if (event
->attr
.bpf_event
)
12760 atomic_inc(&nr_bpf_events
);
12761 if (event
->attr
.text_poke
)
12762 atomic_inc(&nr_text_poke_events
);
12766 * We need the mutex here because static_branch_enable()
12767 * must complete *before* the perf_sched_count increment
12770 if (atomic_inc_not_zero(&perf_sched_count
))
12773 mutex_lock(&perf_sched_mutex
);
12774 if (!atomic_read(&perf_sched_count
)) {
12775 static_branch_enable(&perf_sched_events
);
12777 * Guarantee that all CPUs observe they key change and
12778 * call the perf scheduling hooks before proceeding to
12779 * install events that need them.
12784 * Now that we have waited for the sync_sched(), allow further
12785 * increments to by-pass the mutex.
12787 atomic_inc(&perf_sched_count
);
12788 mutex_unlock(&perf_sched_mutex
);
12792 account_pmu_sb_event(event
);
12796 * Allocate and initialize an event structure
12798 static struct perf_event
*
12799 perf_event_alloc(struct perf_event_attr
*attr
, int cpu
,
12800 struct task_struct
*task
,
12801 struct perf_event
*group_leader
,
12802 struct perf_event
*parent_event
,
12803 perf_overflow_handler_t overflow_handler
,
12804 void *context
, int cgroup_fd
)
12807 struct hw_perf_event
*hwc
;
12808 long err
= -EINVAL
;
12811 if ((unsigned)cpu
>= nr_cpu_ids
) {
12812 if (!task
|| cpu
!= -1)
12813 return ERR_PTR(-EINVAL
);
12815 if (attr
->sigtrap
&& !task
) {
12816 /* Requires a task: avoid signalling random tasks. */
12817 return ERR_PTR(-EINVAL
);
12820 node
= (cpu
>= 0) ? cpu_to_node(cpu
) : -1;
12821 struct perf_event
*event
__free(__free_event
) =
12822 kmem_cache_alloc_node(perf_event_cache
, GFP_KERNEL
| __GFP_ZERO
, node
);
12824 return ERR_PTR(-ENOMEM
);
12827 * Single events are their own group leaders, with an
12828 * empty sibling list:
12831 group_leader
= event
;
12833 mutex_init(&event
->child_mutex
);
12834 INIT_LIST_HEAD(&event
->child_list
);
12836 INIT_LIST_HEAD(&event
->event_entry
);
12837 INIT_LIST_HEAD(&event
->sibling_list
);
12838 INIT_LIST_HEAD(&event
->active_list
);
12839 init_event_group(event
);
12840 INIT_LIST_HEAD(&event
->rb_entry
);
12841 INIT_LIST_HEAD(&event
->active_entry
);
12842 INIT_LIST_HEAD(&event
->addr_filters
.list
);
12843 INIT_HLIST_NODE(&event
->hlist_entry
);
12844 INIT_LIST_HEAD(&event
->pmu_list
);
12847 init_waitqueue_head(&event
->waitq
);
12848 init_irq_work(&event
->pending_irq
, perf_pending_irq
);
12849 event
->pending_disable_irq
= IRQ_WORK_INIT_HARD(perf_pending_disable
);
12850 init_task_work(&event
->pending_task
, perf_pending_task
);
12852 mutex_init(&event
->mmap_mutex
);
12853 raw_spin_lock_init(&event
->addr_filters
.lock
);
12855 atomic_long_set(&event
->refcount
, 1);
12857 event
->attr
= *attr
;
12858 event
->group_leader
= group_leader
;
12862 event
->parent
= parent_event
;
12864 event
->ns
= get_pid_ns(task_active_pid_ns(current
));
12865 event
->id
= atomic64_inc_return(&perf_event_id
);
12867 event
->state
= PERF_EVENT_STATE_INACTIVE
;
12870 event
->event_caps
= parent_event
->event_caps
;
12873 event
->attach_state
= PERF_ATTACH_TASK
;
12875 * XXX pmu::event_init needs to know what task to account to
12876 * and we cannot use the ctx information because we need the
12877 * pmu before we get a ctx.
12879 event
->hw
.target
= get_task_struct(task
);
12882 event
->clock
= &local_clock
;
12884 event
->clock
= parent_event
->clock
;
12886 if (!overflow_handler
&& parent_event
) {
12887 overflow_handler
= parent_event
->overflow_handler
;
12888 context
= parent_event
->overflow_handler_context
;
12889 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
12890 if (parent_event
->prog
) {
12891 struct bpf_prog
*prog
= parent_event
->prog
;
12893 bpf_prog_inc(prog
);
12894 event
->prog
= prog
;
12899 if (overflow_handler
) {
12900 event
->overflow_handler
= overflow_handler
;
12901 event
->overflow_handler_context
= context
;
12902 } else if (is_write_backward(event
)){
12903 event
->overflow_handler
= perf_event_output_backward
;
12904 event
->overflow_handler_context
= NULL
;
12906 event
->overflow_handler
= perf_event_output_forward
;
12907 event
->overflow_handler_context
= NULL
;
12910 perf_event__state_init(event
);
12915 hwc
->sample_period
= attr
->sample_period
;
12916 if (is_event_in_freq_mode(event
))
12917 hwc
->sample_period
= 1;
12918 hwc
->last_period
= hwc
->sample_period
;
12920 local64_set(&hwc
->period_left
, hwc
->sample_period
);
12923 * We do not support PERF_SAMPLE_READ on inherited events unless
12924 * PERF_SAMPLE_TID is also selected, which allows inherited events to
12925 * collect per-thread samples.
12926 * See perf_output_read().
12928 if (has_inherit_and_sample_read(attr
) && !(attr
->sample_type
& PERF_SAMPLE_TID
))
12929 return ERR_PTR(-EINVAL
);
12931 if (!has_branch_stack(event
))
12932 event
->attr
.branch_sample_type
= 0;
12934 pmu
= perf_init_event(event
);
12939 * The PERF_ATTACH_TASK_DATA is set in the event_init()->hw_config().
12940 * The attach should be right after the perf_init_event().
12941 * Otherwise, the __free_event() would mistakenly detach the non-exist
12942 * perf_ctx_data because of the other errors between them.
12944 if (event
->attach_state
& PERF_ATTACH_TASK_DATA
) {
12945 err
= attach_perf_ctx_data(event
);
12947 return ERR_PTR(err
);
12951 * Disallow uncore-task events. Similarly, disallow uncore-cgroup
12952 * events (they don't make sense as the cgroup will be different
12953 * on other CPUs in the uncore mask).
12955 if (pmu
->task_ctx_nr
== perf_invalid_context
&& (task
|| cgroup_fd
!= -1))
12956 return ERR_PTR(-EINVAL
);
12958 if (event
->attr
.aux_output
&&
12959 (!(pmu
->capabilities
& PERF_PMU_CAP_AUX_OUTPUT
) ||
12960 event
->attr
.aux_pause
|| event
->attr
.aux_resume
))
12961 return ERR_PTR(-EOPNOTSUPP
);
12963 if (event
->attr
.aux_pause
&& event
->attr
.aux_resume
)
12964 return ERR_PTR(-EINVAL
);
12966 if (event
->attr
.aux_start_paused
) {
12967 if (!(pmu
->capabilities
& PERF_PMU_CAP_AUX_PAUSE
))
12968 return ERR_PTR(-EOPNOTSUPP
);
12969 event
->hw
.aux_paused
= 1;
12972 if (cgroup_fd
!= -1) {
12973 err
= perf_cgroup_connect(cgroup_fd
, event
, attr
, group_leader
);
12975 return ERR_PTR(err
);
12978 err
= exclusive_event_init(event
);
12980 return ERR_PTR(err
);
12982 if (has_addr_filter(event
)) {
12983 event
->addr_filter_ranges
= kcalloc(pmu
->nr_addr_filters
,
12984 sizeof(struct perf_addr_filter_range
),
12986 if (!event
->addr_filter_ranges
)
12987 return ERR_PTR(-ENOMEM
);
12990 * Clone the parent's vma offsets: they are valid until exec()
12991 * even if the mm is not shared with the parent.
12993 if (event
->parent
) {
12994 struct perf_addr_filters_head
*ifh
= perf_event_addr_filters(event
);
12996 raw_spin_lock_irq(&ifh
->lock
);
12997 memcpy(event
->addr_filter_ranges
,
12998 event
->parent
->addr_filter_ranges
,
12999 pmu
->nr_addr_filters
* sizeof(struct perf_addr_filter_range
));
13000 raw_spin_unlock_irq(&ifh
->lock
);
13003 /* force hw sync on the address filters */
13004 event
->addr_filters_gen
= 1;
13007 if (!event
->parent
) {
13008 if (event
->attr
.sample_type
& PERF_SAMPLE_CALLCHAIN
) {
13009 err
= get_callchain_buffers(attr
->sample_max_stack
);
13011 return ERR_PTR(err
);
13012 event
->attach_state
|= PERF_ATTACH_CALLCHAIN
;
13016 err
= security_perf_event_alloc(event
);
13018 return ERR_PTR(err
);
13020 /* symmetric to unaccount_event() in _free_event() */
13021 account_event(event
);
13024 * Event creation should be under SRCU, see perf_pmu_unregister().
13026 lockdep_assert_held(&pmus_srcu
);
13027 scoped_guard (spinlock
, &pmu
->events_lock
)
13028 list_add(&event
->pmu_list
, &pmu
->events
);
13033 static int perf_copy_attr(struct perf_event_attr __user
*uattr
,
13034 struct perf_event_attr
*attr
)
13039 /* Zero the full structure, so that a short copy will be nice. */
13040 memset(attr
, 0, sizeof(*attr
));
13042 ret
= get_user(size
, &uattr
->size
);
13046 /* ABI compatibility quirk: */
13048 size
= PERF_ATTR_SIZE_VER0
;
13049 if (size
< PERF_ATTR_SIZE_VER0
|| size
> PAGE_SIZE
)
13052 ret
= copy_struct_from_user(attr
, sizeof(*attr
), uattr
, size
);
13061 if (attr
->__reserved_1
|| attr
->__reserved_2
|| attr
->__reserved_3
)
13064 if (attr
->sample_type
& ~(PERF_SAMPLE_MAX
-1))
13067 if (attr
->read_format
& ~(PERF_FORMAT_MAX
-1))
13070 if (attr
->sample_type
& PERF_SAMPLE_BRANCH_STACK
) {
13071 u64 mask
= attr
->branch_sample_type
;
13073 /* only using defined bits */
13074 if (mask
& ~(PERF_SAMPLE_BRANCH_MAX
-1))
13077 /* at least one branch bit must be set */
13078 if (!(mask
& ~PERF_SAMPLE_BRANCH_PLM_ALL
))
13081 /* propagate priv level, when not set for branch */
13082 if (!(mask
& PERF_SAMPLE_BRANCH_PLM_ALL
)) {
13084 /* exclude_kernel checked on syscall entry */
13085 if (!attr
->exclude_kernel
)
13086 mask
|= PERF_SAMPLE_BRANCH_KERNEL
;
13088 if (!attr
->exclude_user
)
13089 mask
|= PERF_SAMPLE_BRANCH_USER
;
13091 if (!attr
->exclude_hv
)
13092 mask
|= PERF_SAMPLE_BRANCH_HV
;
13094 * adjust user setting (for HW filter setup)
13096 attr
->branch_sample_type
= mask
;
13098 /* privileged levels capture (kernel, hv): check permissions */
13099 if (mask
& PERF_SAMPLE_BRANCH_PERM_PLM
) {
13100 ret
= perf_allow_kernel();
13106 if (attr
->sample_type
& PERF_SAMPLE_REGS_USER
) {
13107 ret
= perf_reg_validate(attr
->sample_regs_user
);
13112 if (attr
->sample_type
& PERF_SAMPLE_STACK_USER
) {
13113 if (!arch_perf_have_user_stack_dump())
13117 * We have __u32 type for the size, but so far
13118 * we can only use __u16 as maximum due to the
13119 * __u16 sample size limit.
13121 if (attr
->sample_stack_user
>= USHRT_MAX
)
13123 else if (!IS_ALIGNED(attr
->sample_stack_user
, sizeof(u64
)))
13127 if (!attr
->sample_max_stack
)
13128 attr
->sample_max_stack
= sysctl_perf_event_max_stack
;
13130 if (attr
->sample_type
& PERF_SAMPLE_REGS_INTR
)
13131 ret
= perf_reg_validate(attr
->sample_regs_intr
);
13133 #ifndef CONFIG_CGROUP_PERF
13134 if (attr
->sample_type
& PERF_SAMPLE_CGROUP
)
13137 if ((attr
->sample_type
& PERF_SAMPLE_WEIGHT
) &&
13138 (attr
->sample_type
& PERF_SAMPLE_WEIGHT_STRUCT
))
13141 if (!attr
->inherit
&& attr
->inherit_thread
)
13144 if (attr
->remove_on_exec
&& attr
->enable_on_exec
)
13147 if (attr
->sigtrap
&& !attr
->remove_on_exec
)
13154 put_user(sizeof(*attr
), &uattr
->size
);
13159 static void mutex_lock_double(struct mutex
*a
, struct mutex
*b
)
13165 mutex_lock_nested(b
, SINGLE_DEPTH_NESTING
);
13169 perf_event_set_output(struct perf_event
*event
, struct perf_event
*output_event
)
13171 struct perf_buffer
*rb
= NULL
;
13174 if (!output_event
) {
13175 mutex_lock(&event
->mmap_mutex
);
13179 /* don't allow circular references */
13180 if (event
== output_event
)
13184 * Don't allow cross-cpu buffers
13186 if (output_event
->cpu
!= event
->cpu
)
13190 * If its not a per-cpu rb, it must be the same task.
13192 if (output_event
->cpu
== -1 && output_event
->hw
.target
!= event
->hw
.target
)
13196 * Mixing clocks in the same buffer is trouble you don't need.
13198 if (output_event
->clock
!= event
->clock
)
13202 * Either writing ring buffer from beginning or from end.
13203 * Mixing is not allowed.
13205 if (is_write_backward(output_event
) != is_write_backward(event
))
13209 * If both events generate aux data, they must be on the same PMU
13211 if (has_aux(event
) && has_aux(output_event
) &&
13212 event
->pmu
!= output_event
->pmu
)
13216 * Hold both mmap_mutex to serialize against perf_mmap_close(). Since
13217 * output_event is already on rb->event_list, and the list iteration
13218 * restarts after every removal, it is guaranteed this new event is
13219 * observed *OR* if output_event is already removed, it's guaranteed we
13220 * observe !rb->mmap_count.
13222 mutex_lock_double(&event
->mmap_mutex
, &output_event
->mmap_mutex
);
13224 /* Can't redirect output if we've got an active mmap() */
13225 if (atomic_read(&event
->mmap_count
))
13228 if (output_event
) {
13229 if (output_event
->state
<= PERF_EVENT_STATE_REVOKED
)
13232 /* get the rb we want to redirect to */
13233 rb
= ring_buffer_get(output_event
);
13237 /* did we race against perf_mmap_close() */
13238 if (!atomic_read(&rb
->mmap_count
)) {
13239 ring_buffer_put(rb
);
13244 ring_buffer_attach(event
, rb
);
13248 mutex_unlock(&event
->mmap_mutex
);
13250 mutex_unlock(&output_event
->mmap_mutex
);
13256 static int perf_event_set_clock(struct perf_event
*event
, clockid_t clk_id
)
13258 bool nmi_safe
= false;
13261 case CLOCK_MONOTONIC
:
13262 event
->clock
= &ktime_get_mono_fast_ns
;
13266 case CLOCK_MONOTONIC_RAW
:
13267 event
->clock
= &ktime_get_raw_fast_ns
;
13271 case CLOCK_REALTIME
:
13272 event
->clock
= &ktime_get_real_ns
;
13275 case CLOCK_BOOTTIME
:
13276 event
->clock
= &ktime_get_boottime_ns
;
13280 event
->clock
= &ktime_get_clocktai_ns
;
13287 if (!nmi_safe
&& !(event
->pmu
->capabilities
& PERF_PMU_CAP_NO_NMI
))
13294 perf_check_permission(struct perf_event_attr
*attr
, struct task_struct
*task
)
13296 unsigned int ptrace_mode
= PTRACE_MODE_READ_REALCREDS
;
13297 bool is_capable
= perfmon_capable();
13299 if (attr
->sigtrap
) {
13301 * perf_event_attr::sigtrap sends signals to the other task.
13302 * Require the current task to also have CAP_KILL.
13305 is_capable
&= ns_capable(__task_cred(task
)->user_ns
, CAP_KILL
);
13309 * If the required capabilities aren't available, checks for
13310 * ptrace permissions: upgrade to ATTACH, since sending signals
13311 * can effectively change the target task.
13313 ptrace_mode
= PTRACE_MODE_ATTACH_REALCREDS
;
13317 * Preserve ptrace permission check for backwards compatibility. The
13318 * ptrace check also includes checks that the current task and other
13319 * task have matching uids, and is therefore not done here explicitly.
13321 return is_capable
|| ptrace_may_access(task
, ptrace_mode
);
13325 * sys_perf_event_open - open a performance event, associate it to a task/cpu
13327 * @attr_uptr: event_id type attributes for monitoring/sampling
13330 * @group_fd: group leader event fd
13331 * @flags: perf event open flags
13333 SYSCALL_DEFINE5(perf_event_open
,
13334 struct perf_event_attr __user
*, attr_uptr
,
13335 pid_t
, pid
, int, cpu
, int, group_fd
, unsigned long, flags
)
13337 struct perf_event
*group_leader
= NULL
, *output_event
= NULL
;
13338 struct perf_event_pmu_context
*pmu_ctx
;
13339 struct perf_event
*event
, *sibling
;
13340 struct perf_event_attr attr
;
13341 struct perf_event_context
*ctx
;
13342 struct file
*event_file
= NULL
;
13343 struct task_struct
*task
= NULL
;
13346 int move_group
= 0;
13348 int f_flags
= O_RDWR
;
13349 int cgroup_fd
= -1;
13351 /* for future expandability... */
13352 if (flags
& ~PERF_FLAG_ALL
)
13355 err
= perf_copy_attr(attr_uptr
, &attr
);
13359 /* Do we allow access to perf_event_open(2) ? */
13360 err
= security_perf_event_open(PERF_SECURITY_OPEN
);
13364 if (!attr
.exclude_kernel
) {
13365 err
= perf_allow_kernel();
13370 if (attr
.namespaces
) {
13371 if (!perfmon_capable())
13376 if (attr
.sample_freq
> sysctl_perf_event_sample_rate
)
13379 if (attr
.sample_period
& (1ULL << 63))
13383 /* Only privileged users can get physical addresses */
13384 if ((attr
.sample_type
& PERF_SAMPLE_PHYS_ADDR
)) {
13385 err
= perf_allow_kernel();
13390 /* REGS_INTR can leak data, lockdown must prevent this */
13391 if (attr
.sample_type
& PERF_SAMPLE_REGS_INTR
) {
13392 err
= security_locked_down(LOCKDOWN_PERF
);
13398 * In cgroup mode, the pid argument is used to pass the fd
13399 * opened to the cgroup directory in cgroupfs. The cpu argument
13400 * designates the cpu on which to monitor threads from that
13403 if ((flags
& PERF_FLAG_PID_CGROUP
) && (pid
== -1 || cpu
== -1))
13406 if (flags
& PERF_FLAG_FD_CLOEXEC
)
13407 f_flags
|= O_CLOEXEC
;
13409 event_fd
= get_unused_fd_flags(f_flags
);
13414 * Event creation should be under SRCU, see perf_pmu_unregister().
13416 guard(srcu
)(&pmus_srcu
);
13418 CLASS(fd
, group
)(group_fd
); // group_fd == -1 => empty
13419 if (group_fd
!= -1) {
13420 if (!is_perf_file(group
)) {
13424 group_leader
= fd_file(group
)->private_data
;
13425 if (group_leader
->state
<= PERF_EVENT_STATE_REVOKED
) {
13429 if (flags
& PERF_FLAG_FD_OUTPUT
)
13430 output_event
= group_leader
;
13431 if (flags
& PERF_FLAG_FD_NO_GROUP
)
13432 group_leader
= NULL
;
13435 if (pid
!= -1 && !(flags
& PERF_FLAG_PID_CGROUP
)) {
13436 task
= find_lively_task_by_vpid(pid
);
13437 if (IS_ERR(task
)) {
13438 err
= PTR_ERR(task
);
13443 if (task
&& group_leader
&&
13444 group_leader
->attr
.inherit
!= attr
.inherit
) {
13449 if (flags
& PERF_FLAG_PID_CGROUP
)
13452 event
= perf_event_alloc(&attr
, cpu
, task
, group_leader
, NULL
,
13453 NULL
, NULL
, cgroup_fd
);
13454 if (IS_ERR(event
)) {
13455 err
= PTR_ERR(event
);
13459 if (is_sampling_event(event
)) {
13460 if (event
->pmu
->capabilities
& PERF_PMU_CAP_NO_INTERRUPT
) {
13467 * Special case software events and allow them to be part of
13468 * any hardware group.
13472 if (attr
.use_clockid
) {
13473 err
= perf_event_set_clock(event
, attr
.clockid
);
13478 if (pmu
->task_ctx_nr
== perf_sw_context
)
13479 event
->event_caps
|= PERF_EV_CAP_SOFTWARE
;
13482 err
= down_read_interruptible(&task
->signal
->exec_update_lock
);
13487 * We must hold exec_update_lock across this and any potential
13488 * perf_install_in_context() call for this new event to
13489 * serialize against exec() altering our credentials (and the
13490 * perf_event_exit_task() that could imply).
13493 if (!perf_check_permission(&attr
, task
))
13498 * Get the target context (task or percpu):
13500 ctx
= find_get_context(task
, event
);
13502 err
= PTR_ERR(ctx
);
13506 mutex_lock(&ctx
->mutex
);
13508 if (ctx
->task
== TASK_TOMBSTONE
) {
13515 * Check if the @cpu we're creating an event for is online.
13517 * We use the perf_cpu_context::ctx::mutex to serialize against
13518 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
13520 struct perf_cpu_context
*cpuctx
= per_cpu_ptr(&perf_cpu_context
, event
->cpu
);
13522 if (!cpuctx
->online
) {
13528 if (group_leader
) {
13532 * Do not allow a recursive hierarchy (this new sibling
13533 * becoming part of another group-sibling):
13535 if (group_leader
->group_leader
!= group_leader
)
13538 /* All events in a group should have the same clock */
13539 if (group_leader
->clock
!= event
->clock
)
13543 * Make sure we're both events for the same CPU;
13544 * grouping events for different CPUs is broken; since
13545 * you can never concurrently schedule them anyhow.
13547 if (group_leader
->cpu
!= event
->cpu
)
13551 * Make sure we're both on the same context; either task or cpu.
13553 if (group_leader
->ctx
!= ctx
)
13557 * Only a group leader can be exclusive or pinned
13559 if (attr
.exclusive
|| attr
.pinned
)
13562 if (is_software_event(event
) &&
13563 !in_software_context(group_leader
)) {
13565 * If the event is a sw event, but the group_leader
13566 * is on hw context.
13568 * Allow the addition of software events to hw
13569 * groups, this is safe because software events
13570 * never fail to schedule.
13572 * Note the comment that goes with struct
13573 * perf_event_pmu_context.
13575 pmu
= group_leader
->pmu_ctx
->pmu
;
13576 } else if (!is_software_event(event
)) {
13577 if (is_software_event(group_leader
) &&
13578 (group_leader
->group_caps
& PERF_EV_CAP_SOFTWARE
)) {
13580 * In case the group is a pure software group, and we
13581 * try to add a hardware event, move the whole group to
13582 * the hardware context.
13587 /* Don't allow group of multiple hw events from different pmus */
13588 if (!in_software_context(group_leader
) &&
13589 group_leader
->pmu_ctx
->pmu
!= pmu
)
13595 * Now that we're certain of the pmu; find the pmu_ctx.
13597 pmu_ctx
= find_get_pmu_context(pmu
, ctx
, event
);
13598 if (IS_ERR(pmu_ctx
)) {
13599 err
= PTR_ERR(pmu_ctx
);
13602 event
->pmu_ctx
= pmu_ctx
;
13604 if (output_event
) {
13605 err
= perf_event_set_output(event
, output_event
);
13610 if (!perf_event_validate_size(event
)) {
13615 if (perf_need_aux_event(event
) && !perf_get_aux_event(event
, group_leader
)) {
13621 * Must be under the same ctx::mutex as perf_install_in_context(),
13622 * because we need to serialize with concurrent event creation.
13624 if (!exclusive_event_installable(event
, ctx
)) {
13629 WARN_ON_ONCE(ctx
->parent_ctx
);
13631 event_file
= anon_inode_getfile("[perf_event]", &perf_fops
, event
, f_flags
);
13632 if (IS_ERR(event_file
)) {
13633 err
= PTR_ERR(event_file
);
13639 * This is the point on no return; we cannot fail hereafter. This is
13640 * where we start modifying current state.
13644 perf_remove_from_context(group_leader
, 0);
13645 put_pmu_ctx(group_leader
->pmu_ctx
);
13647 for_each_sibling_event(sibling
, group_leader
) {
13648 perf_remove_from_context(sibling
, 0);
13649 put_pmu_ctx(sibling
->pmu_ctx
);
13653 * Install the group siblings before the group leader.
13655 * Because a group leader will try and install the entire group
13656 * (through the sibling list, which is still in-tact), we can
13657 * end up with siblings installed in the wrong context.
13659 * By installing siblings first we NO-OP because they're not
13660 * reachable through the group lists.
13662 for_each_sibling_event(sibling
, group_leader
) {
13663 sibling
->pmu_ctx
= pmu_ctx
;
13664 get_pmu_ctx(pmu_ctx
);
13665 perf_event__state_init(sibling
);
13666 perf_install_in_context(ctx
, sibling
, sibling
->cpu
);
13670 * Removing from the context ends up with disabled
13671 * event. What we want here is event in the initial
13672 * startup state, ready to be add into new context.
13674 group_leader
->pmu_ctx
= pmu_ctx
;
13675 get_pmu_ctx(pmu_ctx
);
13676 perf_event__state_init(group_leader
);
13677 perf_install_in_context(ctx
, group_leader
, group_leader
->cpu
);
13681 * Precalculate sample_data sizes; do while holding ctx::mutex such
13682 * that we're serialized against further additions and before
13683 * perf_install_in_context() which is the point the event is active and
13684 * can use these values.
13686 perf_event__header_size(event
);
13687 perf_event__id_header_size(event
);
13689 event
->owner
= current
;
13691 perf_install_in_context(ctx
, event
, event
->cpu
);
13692 perf_unpin_context(ctx
);
13694 mutex_unlock(&ctx
->mutex
);
13697 up_read(&task
->signal
->exec_update_lock
);
13698 put_task_struct(task
);
13701 mutex_lock(¤t
->perf_event_mutex
);
13702 list_add_tail(&event
->owner_entry
, ¤t
->perf_event_list
);
13703 mutex_unlock(¤t
->perf_event_mutex
);
13706 * File reference in group guarantees that group_leader has been
13707 * kept alive until we place the new event on the sibling_list.
13708 * This ensures destruction of the group leader will find
13709 * the pointer to itself in perf_group_detach().
13711 fd_install(event_fd
, event_file
);
13715 put_pmu_ctx(event
->pmu_ctx
);
13716 event
->pmu_ctx
= NULL
; /* _free_event() */
13718 mutex_unlock(&ctx
->mutex
);
13719 perf_unpin_context(ctx
);
13723 up_read(&task
->signal
->exec_update_lock
);
13728 put_task_struct(task
);
13730 put_unused_fd(event_fd
);
13735 * perf_event_create_kernel_counter
13737 * @attr: attributes of the counter to create
13738 * @cpu: cpu in which the counter is bound
13739 * @task: task to profile (NULL for percpu)
13740 * @overflow_handler: callback to trigger when we hit the event
13741 * @context: context data could be used in overflow_handler callback
13743 struct perf_event
*
13744 perf_event_create_kernel_counter(struct perf_event_attr
*attr
, int cpu
,
13745 struct task_struct
*task
,
13746 perf_overflow_handler_t overflow_handler
,
13749 struct perf_event_pmu_context
*pmu_ctx
;
13750 struct perf_event_context
*ctx
;
13751 struct perf_event
*event
;
13756 * Grouping is not supported for kernel events, neither is 'AUX',
13757 * make sure the caller's intentions are adjusted.
13759 if (attr
->aux_output
|| attr
->aux_action
)
13760 return ERR_PTR(-EINVAL
);
13763 * Event creation should be under SRCU, see perf_pmu_unregister().
13765 guard(srcu
)(&pmus_srcu
);
13767 event
= perf_event_alloc(attr
, cpu
, task
, NULL
, NULL
,
13768 overflow_handler
, context
, -1);
13769 if (IS_ERR(event
)) {
13770 err
= PTR_ERR(event
);
13774 /* Mark owner so we could distinguish it from user events. */
13775 event
->owner
= TASK_TOMBSTONE
;
13778 if (pmu
->task_ctx_nr
== perf_sw_context
)
13779 event
->event_caps
|= PERF_EV_CAP_SOFTWARE
;
13782 * Get the target context (task or percpu):
13784 ctx
= find_get_context(task
, event
);
13786 err
= PTR_ERR(ctx
);
13790 WARN_ON_ONCE(ctx
->parent_ctx
);
13791 mutex_lock(&ctx
->mutex
);
13792 if (ctx
->task
== TASK_TOMBSTONE
) {
13797 pmu_ctx
= find_get_pmu_context(pmu
, ctx
, event
);
13798 if (IS_ERR(pmu_ctx
)) {
13799 err
= PTR_ERR(pmu_ctx
);
13802 event
->pmu_ctx
= pmu_ctx
;
13806 * Check if the @cpu we're creating an event for is online.
13808 * We use the perf_cpu_context::ctx::mutex to serialize against
13809 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
13811 struct perf_cpu_context
*cpuctx
=
13812 container_of(ctx
, struct perf_cpu_context
, ctx
);
13813 if (!cpuctx
->online
) {
13819 if (!exclusive_event_installable(event
, ctx
)) {
13824 perf_install_in_context(ctx
, event
, event
->cpu
);
13825 perf_unpin_context(ctx
);
13826 mutex_unlock(&ctx
->mutex
);
13831 put_pmu_ctx(pmu_ctx
);
13832 event
->pmu_ctx
= NULL
; /* _free_event() */
13834 mutex_unlock(&ctx
->mutex
);
13835 perf_unpin_context(ctx
);
13840 return ERR_PTR(err
);
13842 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter
);
13844 static void __perf_pmu_remove(struct perf_event_context
*ctx
,
13845 int cpu
, struct pmu
*pmu
,
13846 struct perf_event_groups
*groups
,
13847 struct list_head
*events
)
13849 struct perf_event
*event
, *sibling
;
13851 perf_event_groups_for_cpu_pmu(event
, groups
, cpu
, pmu
) {
13852 perf_remove_from_context(event
, 0);
13853 put_pmu_ctx(event
->pmu_ctx
);
13854 list_add(&event
->migrate_entry
, events
);
13856 for_each_sibling_event(sibling
, event
) {
13857 perf_remove_from_context(sibling
, 0);
13858 put_pmu_ctx(sibling
->pmu_ctx
);
13859 list_add(&sibling
->migrate_entry
, events
);
13864 static void __perf_pmu_install_event(struct pmu
*pmu
,
13865 struct perf_event_context
*ctx
,
13866 int cpu
, struct perf_event
*event
)
13868 struct perf_event_pmu_context
*epc
;
13869 struct perf_event_context
*old_ctx
= event
->ctx
;
13871 get_ctx(ctx
); /* normally find_get_context() */
13874 epc
= find_get_pmu_context(pmu
, ctx
, event
);
13875 event
->pmu_ctx
= epc
;
13877 if (event
->state
>= PERF_EVENT_STATE_OFF
)
13878 event
->state
= PERF_EVENT_STATE_INACTIVE
;
13879 perf_install_in_context(ctx
, event
, cpu
);
13882 * Now that event->ctx is updated and visible, put the old ctx.
13887 static void __perf_pmu_install(struct perf_event_context
*ctx
,
13888 int cpu
, struct pmu
*pmu
, struct list_head
*events
)
13890 struct perf_event
*event
, *tmp
;
13893 * Re-instate events in 2 passes.
13895 * Skip over group leaders and only install siblings on this first
13896 * pass, siblings will not get enabled without a leader, however a
13897 * leader will enable its siblings, even if those are still on the old
13900 list_for_each_entry_safe(event
, tmp
, events
, migrate_entry
) {
13901 if (event
->group_leader
== event
)
13904 list_del(&event
->migrate_entry
);
13905 __perf_pmu_install_event(pmu
, ctx
, cpu
, event
);
13909 * Once all the siblings are setup properly, install the group leaders
13912 list_for_each_entry_safe(event
, tmp
, events
, migrate_entry
) {
13913 list_del(&event
->migrate_entry
);
13914 __perf_pmu_install_event(pmu
, ctx
, cpu
, event
);
13918 void perf_pmu_migrate_context(struct pmu
*pmu
, int src_cpu
, int dst_cpu
)
13920 struct perf_event_context
*src_ctx
, *dst_ctx
;
13924 * Since per-cpu context is persistent, no need to grab an extra
13927 src_ctx
= &per_cpu_ptr(&perf_cpu_context
, src_cpu
)->ctx
;
13928 dst_ctx
= &per_cpu_ptr(&perf_cpu_context
, dst_cpu
)->ctx
;
13931 * See perf_event_ctx_lock() for comments on the details
13932 * of swizzling perf_event::ctx.
13934 mutex_lock_double(&src_ctx
->mutex
, &dst_ctx
->mutex
);
13936 __perf_pmu_remove(src_ctx
, src_cpu
, pmu
, &src_ctx
->pinned_groups
, &events
);
13937 __perf_pmu_remove(src_ctx
, src_cpu
, pmu
, &src_ctx
->flexible_groups
, &events
);
13939 if (!list_empty(&events
)) {
13941 * Wait for the events to quiesce before re-instating them.
13945 __perf_pmu_install(dst_ctx
, dst_cpu
, pmu
, &events
);
13948 mutex_unlock(&dst_ctx
->mutex
);
13949 mutex_unlock(&src_ctx
->mutex
);
13951 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context
);
13953 static void sync_child_event(struct perf_event
*child_event
)
13955 struct perf_event
*parent_event
= child_event
->parent
;
13958 if (child_event
->attr
.inherit_stat
) {
13959 struct task_struct
*task
= child_event
->ctx
->task
;
13961 if (task
&& task
!= TASK_TOMBSTONE
)
13962 perf_event_read_event(child_event
, task
);
13965 child_val
= perf_event_count(child_event
, false);
13968 * Add back the child's count to the parent's count:
13970 atomic64_add(child_val
, &parent_event
->child_count
);
13971 atomic64_add(child_event
->total_time_enabled
,
13972 &parent_event
->child_total_time_enabled
);
13973 atomic64_add(child_event
->total_time_running
,
13974 &parent_event
->child_total_time_running
);
13978 perf_event_exit_event(struct perf_event
*event
,
13979 struct perf_event_context
*ctx
, bool revoke
)
13981 struct perf_event
*parent_event
= event
->parent
;
13982 unsigned long detach_flags
= DETACH_EXIT
;
13983 unsigned int attach_state
;
13985 if (parent_event
) {
13987 * Do not destroy the 'original' grouping; because of the
13988 * context switch optimization the original events could've
13989 * ended up in a random child task.
13991 * If we were to destroy the original group, all group related
13992 * operations would cease to function properly after this
13993 * random child dies.
13995 * Do destroy all inherited groups, we don't care about those
13996 * and being thorough is better.
13998 detach_flags
|= DETACH_GROUP
| DETACH_CHILD
;
13999 mutex_lock(&parent_event
->child_mutex
);
14000 /* PERF_ATTACH_ITRACE might be set concurrently */
14001 attach_state
= READ_ONCE(event
->attach_state
);
14005 detach_flags
|= DETACH_GROUP
| DETACH_REVOKE
;
14007 perf_remove_from_context(event
, detach_flags
);
14009 * Child events can be freed.
14011 if (parent_event
) {
14012 mutex_unlock(&parent_event
->child_mutex
);
14015 * Match the refcount initialization. Make sure it doesn't happen
14016 * twice if pmu_detach_event() calls it on an already exited task.
14018 if (attach_state
& PERF_ATTACH_CHILD
) {
14020 * Kick perf_poll() for is_event_hup();
14022 perf_event_wakeup(parent_event
);
14024 * pmu_detach_event() will have an extra refcount.
14025 * perf_pending_task() might have one too.
14034 * Parent events are governed by their filedesc, retain them.
14036 perf_event_wakeup(event
);
14039 static void perf_event_exit_task_context(struct task_struct
*task
, bool exit
)
14041 struct perf_event_context
*ctx
, *clone_ctx
= NULL
;
14042 struct perf_event
*child_event
, *next
;
14044 ctx
= perf_pin_task_context(task
);
14049 * In order to reduce the amount of tricky in ctx tear-down, we hold
14050 * ctx::mutex over the entire thing. This serializes against almost
14051 * everything that wants to access the ctx.
14053 * The exception is sys_perf_event_open() /
14054 * perf_event_create_kernel_count() which does find_get_context()
14055 * without ctx::mutex (it cannot because of the move_group double mutex
14056 * lock thing). See the comments in perf_install_in_context().
14058 mutex_lock(&ctx
->mutex
);
14061 * In a single ctx::lock section, de-schedule the events and detach the
14062 * context from the task such that we cannot ever get it scheduled back
14065 raw_spin_lock_irq(&ctx
->lock
);
14067 task_ctx_sched_out(ctx
, NULL
, EVENT_ALL
);
14070 * Now that the context is inactive, destroy the task <-> ctx relation
14071 * and mark the context dead.
14073 RCU_INIT_POINTER(task
->perf_event_ctxp
, NULL
);
14074 put_ctx(ctx
); /* cannot be last */
14075 WRITE_ONCE(ctx
->task
, TASK_TOMBSTONE
);
14076 put_task_struct(task
); /* cannot be last */
14078 clone_ctx
= unclone_ctx(ctx
);
14079 raw_spin_unlock_irq(&ctx
->lock
);
14082 put_ctx(clone_ctx
);
14085 * Report the task dead after unscheduling the events so that we
14086 * won't get any samples after PERF_RECORD_EXIT. We can however still
14087 * get a few PERF_RECORD_READ events.
14090 perf_event_task(task
, ctx
, 0);
14092 list_for_each_entry_safe(child_event
, next
, &ctx
->event_list
, event_entry
)
14093 perf_event_exit_event(child_event
, ctx
, false);
14095 mutex_unlock(&ctx
->mutex
);
14099 * perf_event_release_kernel() could still have a reference on
14100 * this context. In that case we must wait for these events to
14101 * have been freed (in particular all their references to this
14102 * task must've been dropped).
14104 * Without this copy_process() will unconditionally free this
14105 * task (irrespective of its reference count) and
14106 * _free_event()'s put_task_struct(event->hw.target) will be a
14109 * Wait for all events to drop their context reference.
14111 wait_var_event(&ctx
->refcount
,
14112 refcount_read(&ctx
->refcount
) == 1);
14118 * When a task exits, feed back event values to parent events.
14120 * Can be called with exec_update_lock held when called from
14121 * setup_new_exec().
14123 void perf_event_exit_task(struct task_struct
*task
)
14125 struct perf_event
*event
, *tmp
;
14127 WARN_ON_ONCE(task
!= current
);
14129 mutex_lock(&task
->perf_event_mutex
);
14130 list_for_each_entry_safe(event
, tmp
, &task
->perf_event_list
,
14132 list_del_init(&event
->owner_entry
);
14135 * Ensure the list deletion is visible before we clear
14136 * the owner, closes a race against perf_release() where
14137 * we need to serialize on the owner->perf_event_mutex.
14139 smp_store_release(&event
->owner
, NULL
);
14141 mutex_unlock(&task
->perf_event_mutex
);
14143 perf_event_exit_task_context(task
, true);
14146 * The perf_event_exit_task_context calls perf_event_task
14147 * with task's task_ctx, which generates EXIT events for
14148 * task contexts and sets task->perf_event_ctxp[] to NULL.
14149 * At this point we need to send EXIT events to cpu contexts.
14151 perf_event_task(task
, NULL
, 0);
14154 * Detach the perf_ctx_data for the system-wide event.
14156 guard(percpu_read
)(&global_ctx_data_rwsem
);
14157 detach_task_ctx_data(task
);
14161 * Free a context as created by inheritance by perf_event_init_task() below,
14162 * used by fork() in case of fail.
14164 * Even though the task has never lived, the context and events have been
14165 * exposed through the child_list, so we must take care tearing it all down.
14167 void perf_event_free_task(struct task_struct
*task
)
14169 perf_event_exit_task_context(task
, false);
14172 void perf_event_delayed_put(struct task_struct
*task
)
14174 WARN_ON_ONCE(task
->perf_event_ctxp
);
14177 struct file
*perf_event_get(unsigned int fd
)
14179 struct file
*file
= fget(fd
);
14181 return ERR_PTR(-EBADF
);
14183 if (file
->f_op
!= &perf_fops
) {
14185 return ERR_PTR(-EBADF
);
14191 const struct perf_event
*perf_get_event(struct file
*file
)
14193 if (file
->f_op
!= &perf_fops
)
14194 return ERR_PTR(-EINVAL
);
14196 return file
->private_data
;
14199 const struct perf_event_attr
*perf_event_attrs(struct perf_event
*event
)
14202 return ERR_PTR(-EINVAL
);
14204 return &event
->attr
;
14207 int perf_allow_kernel(void)
14209 if (sysctl_perf_event_paranoid
> 1 && !perfmon_capable())
14212 return security_perf_event_open(PERF_SECURITY_KERNEL
);
14214 EXPORT_SYMBOL_GPL(perf_allow_kernel
);
14217 * Inherit an event from parent task to child task.
14220 * - valid pointer on success
14221 * - NULL for orphaned events
14222 * - IS_ERR() on error
14224 static struct perf_event
*
14225 inherit_event(struct perf_event
*parent_event
,
14226 struct task_struct
*parent
,
14227 struct perf_event_context
*parent_ctx
,
14228 struct task_struct
*child
,
14229 struct perf_event
*group_leader
,
14230 struct perf_event_context
*child_ctx
)
14232 enum perf_event_state parent_state
= parent_event
->state
;
14233 struct perf_event_pmu_context
*pmu_ctx
;
14234 struct perf_event
*child_event
;
14235 unsigned long flags
;
14238 * Instead of creating recursive hierarchies of events,
14239 * we link inherited events back to the original parent,
14240 * which has a filp for sure, which we use as the reference
14243 if (parent_event
->parent
)
14244 parent_event
= parent_event
->parent
;
14246 if (parent_event
->state
<= PERF_EVENT_STATE_REVOKED
)
14250 * Event creation should be under SRCU, see perf_pmu_unregister().
14252 guard(srcu
)(&pmus_srcu
);
14254 child_event
= perf_event_alloc(&parent_event
->attr
,
14257 group_leader
, parent_event
,
14259 if (IS_ERR(child_event
))
14260 return child_event
;
14262 get_ctx(child_ctx
);
14263 child_event
->ctx
= child_ctx
;
14265 pmu_ctx
= find_get_pmu_context(child_event
->pmu
, child_ctx
, child_event
);
14266 if (IS_ERR(pmu_ctx
)) {
14267 free_event(child_event
);
14268 return ERR_CAST(pmu_ctx
);
14270 child_event
->pmu_ctx
= pmu_ctx
;
14273 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
14274 * must be under the same lock in order to serialize against
14275 * perf_event_release_kernel(), such that either we must observe
14276 * is_orphaned_event() or they will observe us on the child_list.
14278 mutex_lock(&parent_event
->child_mutex
);
14279 if (is_orphaned_event(parent_event
) ||
14280 !atomic_long_inc_not_zero(&parent_event
->refcount
)) {
14281 mutex_unlock(&parent_event
->child_mutex
);
14282 free_event(child_event
);
14287 * Make the child state follow the state of the parent event,
14288 * not its attr.disabled bit. We hold the parent's mutex,
14289 * so we won't race with perf_event_{en, dis}able_family.
14291 if (parent_state
>= PERF_EVENT_STATE_INACTIVE
)
14292 child_event
->state
= PERF_EVENT_STATE_INACTIVE
;
14294 child_event
->state
= PERF_EVENT_STATE_OFF
;
14296 if (parent_event
->attr
.freq
) {
14297 u64 sample_period
= parent_event
->hw
.sample_period
;
14298 struct hw_perf_event
*hwc
= &child_event
->hw
;
14300 hwc
->sample_period
= sample_period
;
14301 hwc
->last_period
= sample_period
;
14303 local64_set(&hwc
->period_left
, sample_period
);
14306 child_event
->overflow_handler
= parent_event
->overflow_handler
;
14307 child_event
->overflow_handler_context
14308 = parent_event
->overflow_handler_context
;
14311 * Precalculate sample_data sizes
14313 perf_event__header_size(child_event
);
14314 perf_event__id_header_size(child_event
);
14317 * Link it up in the child's context:
14319 raw_spin_lock_irqsave(&child_ctx
->lock
, flags
);
14320 add_event_to_ctx(child_event
, child_ctx
);
14321 child_event
->attach_state
|= PERF_ATTACH_CHILD
;
14322 raw_spin_unlock_irqrestore(&child_ctx
->lock
, flags
);
14325 * Link this into the parent event's child list
14327 list_add_tail(&child_event
->child_list
, &parent_event
->child_list
);
14328 mutex_unlock(&parent_event
->child_mutex
);
14330 return child_event
;
14334 * Inherits an event group.
14336 * This will quietly suppress orphaned events; !inherit_event() is not an error.
14337 * This matches with perf_event_release_kernel() removing all child events.
14343 static int inherit_group(struct perf_event
*parent_event
,
14344 struct task_struct
*parent
,
14345 struct perf_event_context
*parent_ctx
,
14346 struct task_struct
*child
,
14347 struct perf_event_context
*child_ctx
)
14349 struct perf_event
*leader
;
14350 struct perf_event
*sub
;
14351 struct perf_event
*child_ctr
;
14353 leader
= inherit_event(parent_event
, parent
, parent_ctx
,
14354 child
, NULL
, child_ctx
);
14355 if (IS_ERR(leader
))
14356 return PTR_ERR(leader
);
14358 * @leader can be NULL here because of is_orphaned_event(). In this
14359 * case inherit_event() will create individual events, similar to what
14360 * perf_group_detach() would do anyway.
14362 for_each_sibling_event(sub
, parent_event
) {
14363 child_ctr
= inherit_event(sub
, parent
, parent_ctx
,
14364 child
, leader
, child_ctx
);
14365 if (IS_ERR(child_ctr
))
14366 return PTR_ERR(child_ctr
);
14368 if (sub
->aux_event
== parent_event
&& child_ctr
&&
14369 !perf_get_aux_event(child_ctr
, leader
))
14373 leader
->group_generation
= parent_event
->group_generation
;
14378 * Creates the child task context and tries to inherit the event-group.
14380 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
14381 * inherited_all set when we 'fail' to inherit an orphaned event; this is
14382 * consistent with perf_event_release_kernel() removing all child events.
14389 inherit_task_group(struct perf_event
*event
, struct task_struct
*parent
,
14390 struct perf_event_context
*parent_ctx
,
14391 struct task_struct
*child
,
14392 u64 clone_flags
, int *inherited_all
)
14394 struct perf_event_context
*child_ctx
;
14397 if (!event
->attr
.inherit
||
14398 (event
->attr
.inherit_thread
&& !(clone_flags
& CLONE_THREAD
)) ||
14399 /* Do not inherit if sigtrap and signal handlers were cleared. */
14400 (event
->attr
.sigtrap
&& (clone_flags
& CLONE_CLEAR_SIGHAND
))) {
14401 *inherited_all
= 0;
14405 child_ctx
= child
->perf_event_ctxp
;
14408 * This is executed from the parent task context, so
14409 * inherit events that have been marked for cloning.
14410 * First allocate and initialize a context for the
14413 child_ctx
= alloc_perf_context(child
);
14417 child
->perf_event_ctxp
= child_ctx
;
14420 ret
= inherit_group(event
, parent
, parent_ctx
, child
, child_ctx
);
14422 *inherited_all
= 0;
14428 * Initialize the perf_event context in task_struct
14430 static int perf_event_init_context(struct task_struct
*child
, u64 clone_flags
)
14432 struct perf_event_context
*child_ctx
, *parent_ctx
;
14433 struct perf_event_context
*cloned_ctx
;
14434 struct perf_event
*event
;
14435 struct task_struct
*parent
= current
;
14436 int inherited_all
= 1;
14437 unsigned long flags
;
14440 if (likely(!parent
->perf_event_ctxp
))
14444 * If the parent's context is a clone, pin it so it won't get
14445 * swapped under us.
14447 parent_ctx
= perf_pin_task_context(parent
);
14452 * No need to check if parent_ctx != NULL here; since we saw
14453 * it non-NULL earlier, the only reason for it to become NULL
14454 * is if we exit, and since we're currently in the middle of
14455 * a fork we can't be exiting at the same time.
14459 * Lock the parent list. No need to lock the child - not PID
14460 * hashed yet and not running, so nobody can access it.
14462 mutex_lock(&parent_ctx
->mutex
);
14465 * We dont have to disable NMIs - we are only looking at
14466 * the list, not manipulating it:
14468 perf_event_groups_for_each(event
, &parent_ctx
->pinned_groups
) {
14469 ret
= inherit_task_group(event
, parent
, parent_ctx
,
14470 child
, clone_flags
, &inherited_all
);
14476 * We can't hold ctx->lock when iterating the ->flexible_group list due
14477 * to allocations, but we need to prevent rotation because
14478 * rotate_ctx() will change the list from interrupt context.
14480 raw_spin_lock_irqsave(&parent_ctx
->lock
, flags
);
14481 parent_ctx
->rotate_disable
= 1;
14482 raw_spin_unlock_irqrestore(&parent_ctx
->lock
, flags
);
14484 perf_event_groups_for_each(event
, &parent_ctx
->flexible_groups
) {
14485 ret
= inherit_task_group(event
, parent
, parent_ctx
,
14486 child
, clone_flags
, &inherited_all
);
14491 raw_spin_lock_irqsave(&parent_ctx
->lock
, flags
);
14492 parent_ctx
->rotate_disable
= 0;
14494 child_ctx
= child
->perf_event_ctxp
;
14496 if (child_ctx
&& inherited_all
) {
14498 * Mark the child context as a clone of the parent
14499 * context, or of whatever the parent is a clone of.
14501 * Note that if the parent is a clone, the holding of
14502 * parent_ctx->lock avoids it from being uncloned.
14504 cloned_ctx
= parent_ctx
->parent_ctx
;
14506 child_ctx
->parent_ctx
= cloned_ctx
;
14507 child_ctx
->parent_gen
= parent_ctx
->parent_gen
;
14509 child_ctx
->parent_ctx
= parent_ctx
;
14510 child_ctx
->parent_gen
= parent_ctx
->generation
;
14512 get_ctx(child_ctx
->parent_ctx
);
14515 raw_spin_unlock_irqrestore(&parent_ctx
->lock
, flags
);
14517 mutex_unlock(&parent_ctx
->mutex
);
14519 perf_unpin_context(parent_ctx
);
14520 put_ctx(parent_ctx
);
14526 * Initialize the perf_event context in task_struct
14528 int perf_event_init_task(struct task_struct
*child
, u64 clone_flags
)
14532 memset(child
->perf_recursion
, 0, sizeof(child
->perf_recursion
));
14533 child
->perf_event_ctxp
= NULL
;
14534 mutex_init(&child
->perf_event_mutex
);
14535 INIT_LIST_HEAD(&child
->perf_event_list
);
14536 child
->perf_ctx_data
= NULL
;
14538 ret
= perf_event_init_context(child
, clone_flags
);
14540 perf_event_free_task(child
);
14547 static void __init
perf_event_init_all_cpus(void)
14549 struct swevent_htable
*swhash
;
14550 struct perf_cpu_context
*cpuctx
;
14553 zalloc_cpumask_var(&perf_online_mask
, GFP_KERNEL
);
14554 zalloc_cpumask_var(&perf_online_core_mask
, GFP_KERNEL
);
14555 zalloc_cpumask_var(&perf_online_die_mask
, GFP_KERNEL
);
14556 zalloc_cpumask_var(&perf_online_cluster_mask
, GFP_KERNEL
);
14557 zalloc_cpumask_var(&perf_online_pkg_mask
, GFP_KERNEL
);
14558 zalloc_cpumask_var(&perf_online_sys_mask
, GFP_KERNEL
);
14561 for_each_possible_cpu(cpu
) {
14562 swhash
= &per_cpu(swevent_htable
, cpu
);
14563 mutex_init(&swhash
->hlist_mutex
);
14565 INIT_LIST_HEAD(&per_cpu(pmu_sb_events
.list
, cpu
));
14566 raw_spin_lock_init(&per_cpu(pmu_sb_events
.lock
, cpu
));
14568 INIT_LIST_HEAD(&per_cpu(sched_cb_list
, cpu
));
14570 cpuctx
= per_cpu_ptr(&perf_cpu_context
, cpu
);
14571 __perf_event_init_context(&cpuctx
->ctx
);
14572 lockdep_set_class(&cpuctx
->ctx
.mutex
, &cpuctx_mutex
);
14573 lockdep_set_class(&cpuctx
->ctx
.lock
, &cpuctx_lock
);
14574 cpuctx
->online
= cpumask_test_cpu(cpu
, perf_online_mask
);
14575 cpuctx
->heap_size
= ARRAY_SIZE(cpuctx
->heap_default
);
14576 cpuctx
->heap
= cpuctx
->heap_default
;
14580 static void perf_swevent_init_cpu(unsigned int cpu
)
14582 struct swevent_htable
*swhash
= &per_cpu(swevent_htable
, cpu
);
14584 mutex_lock(&swhash
->hlist_mutex
);
14585 if (swhash
->hlist_refcount
> 0 && !swevent_hlist_deref(swhash
)) {
14586 struct swevent_hlist
*hlist
;
14588 hlist
= kzalloc_node(sizeof(*hlist
), GFP_KERNEL
, cpu_to_node(cpu
));
14590 rcu_assign_pointer(swhash
->swevent_hlist
, hlist
);
14592 mutex_unlock(&swhash
->hlist_mutex
);
14595 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
14596 static void __perf_event_exit_context(void *__info
)
14598 struct perf_cpu_context
*cpuctx
= this_cpu_ptr(&perf_cpu_context
);
14599 struct perf_event_context
*ctx
= __info
;
14600 struct perf_event
*event
;
14602 raw_spin_lock(&ctx
->lock
);
14603 ctx_sched_out(ctx
, NULL
, EVENT_TIME
);
14604 list_for_each_entry(event
, &ctx
->event_list
, event_entry
)
14605 __perf_remove_from_context(event
, cpuctx
, ctx
, (void *)DETACH_GROUP
);
14606 raw_spin_unlock(&ctx
->lock
);
14609 static void perf_event_clear_cpumask(unsigned int cpu
)
14611 int target
[PERF_PMU_MAX_SCOPE
];
14612 unsigned int scope
;
14615 cpumask_clear_cpu(cpu
, perf_online_mask
);
14617 for (scope
= PERF_PMU_SCOPE_NONE
+ 1; scope
< PERF_PMU_MAX_SCOPE
; scope
++) {
14618 const struct cpumask
*cpumask
= perf_scope_cpu_topology_cpumask(scope
, cpu
);
14619 struct cpumask
*pmu_cpumask
= perf_scope_cpumask(scope
);
14621 target
[scope
] = -1;
14622 if (WARN_ON_ONCE(!pmu_cpumask
|| !cpumask
))
14625 if (!cpumask_test_and_clear_cpu(cpu
, pmu_cpumask
))
14627 target
[scope
] = cpumask_any_but(cpumask
, cpu
);
14628 if (target
[scope
] < nr_cpu_ids
)
14629 cpumask_set_cpu(target
[scope
], pmu_cpumask
);
14633 list_for_each_entry(pmu
, &pmus
, entry
) {
14634 if (pmu
->scope
== PERF_PMU_SCOPE_NONE
||
14635 WARN_ON_ONCE(pmu
->scope
>= PERF_PMU_MAX_SCOPE
))
14638 if (target
[pmu
->scope
] >= 0 && target
[pmu
->scope
] < nr_cpu_ids
)
14639 perf_pmu_migrate_context(pmu
, cpu
, target
[pmu
->scope
]);
14643 static void perf_event_exit_cpu_context(int cpu
)
14645 struct perf_cpu_context
*cpuctx
;
14646 struct perf_event_context
*ctx
;
14648 // XXX simplify cpuctx->online
14649 mutex_lock(&pmus_lock
);
14651 * Clear the cpumasks, and migrate to other CPUs if possible.
14652 * Must be invoked before the __perf_event_exit_context.
14654 perf_event_clear_cpumask(cpu
);
14655 cpuctx
= per_cpu_ptr(&perf_cpu_context
, cpu
);
14656 ctx
= &cpuctx
->ctx
;
14658 mutex_lock(&ctx
->mutex
);
14659 smp_call_function_single(cpu
, __perf_event_exit_context
, ctx
, 1);
14660 cpuctx
->online
= 0;
14661 mutex_unlock(&ctx
->mutex
);
14662 mutex_unlock(&pmus_lock
);
14666 static void perf_event_exit_cpu_context(int cpu
) { }
14670 static void perf_event_setup_cpumask(unsigned int cpu
)
14672 struct cpumask
*pmu_cpumask
;
14673 unsigned int scope
;
14676 * Early boot stage, the cpumask hasn't been set yet.
14677 * The perf_online_<domain>_masks includes the first CPU of each domain.
14678 * Always unconditionally set the boot CPU for the perf_online_<domain>_masks.
14680 if (cpumask_empty(perf_online_mask
)) {
14681 for (scope
= PERF_PMU_SCOPE_NONE
+ 1; scope
< PERF_PMU_MAX_SCOPE
; scope
++) {
14682 pmu_cpumask
= perf_scope_cpumask(scope
);
14683 if (WARN_ON_ONCE(!pmu_cpumask
))
14685 cpumask_set_cpu(cpu
, pmu_cpumask
);
14690 for (scope
= PERF_PMU_SCOPE_NONE
+ 1; scope
< PERF_PMU_MAX_SCOPE
; scope
++) {
14691 const struct cpumask
*cpumask
= perf_scope_cpu_topology_cpumask(scope
, cpu
);
14693 pmu_cpumask
= perf_scope_cpumask(scope
);
14695 if (WARN_ON_ONCE(!pmu_cpumask
|| !cpumask
))
14698 if (!cpumask_empty(cpumask
) &&
14699 cpumask_any_and(pmu_cpumask
, cpumask
) >= nr_cpu_ids
)
14700 cpumask_set_cpu(cpu
, pmu_cpumask
);
14703 cpumask_set_cpu(cpu
, perf_online_mask
);
14706 int perf_event_init_cpu(unsigned int cpu
)
14708 struct perf_cpu_context
*cpuctx
;
14709 struct perf_event_context
*ctx
;
14711 perf_swevent_init_cpu(cpu
);
14713 mutex_lock(&pmus_lock
);
14714 perf_event_setup_cpumask(cpu
);
14715 cpuctx
= per_cpu_ptr(&perf_cpu_context
, cpu
);
14716 ctx
= &cpuctx
->ctx
;
14718 mutex_lock(&ctx
->mutex
);
14719 cpuctx
->online
= 1;
14720 mutex_unlock(&ctx
->mutex
);
14721 mutex_unlock(&pmus_lock
);
14726 int perf_event_exit_cpu(unsigned int cpu
)
14728 perf_event_exit_cpu_context(cpu
);
14733 perf_reboot(struct notifier_block
*notifier
, unsigned long val
, void *v
)
14737 for_each_online_cpu(cpu
)
14738 perf_event_exit_cpu(cpu
);
14744 * Run the perf reboot notifier at the very last possible moment so that
14745 * the generic watchdog code runs as long as possible.
14747 static struct notifier_block perf_reboot_notifier
= {
14748 .notifier_call
= perf_reboot
,
14749 .priority
= INT_MIN
,
14752 void __init
perf_event_init(void)
14756 idr_init(&pmu_idr
);
14758 perf_event_init_all_cpus();
14759 init_srcu_struct(&pmus_srcu
);
14760 perf_pmu_register(&perf_swevent
, "software", PERF_TYPE_SOFTWARE
);
14761 perf_pmu_register(&perf_cpu_clock
, "cpu_clock", -1);
14762 perf_pmu_register(&perf_task_clock
, "task_clock", -1);
14763 perf_tp_register();
14764 perf_event_init_cpu(smp_processor_id());
14765 register_reboot_notifier(&perf_reboot_notifier
);
14767 ret
= init_hw_breakpoint();
14768 WARN(ret
, "hw_breakpoint initialization failed with: %d", ret
);
14770 perf_event_cache
= KMEM_CACHE(perf_event
, SLAB_PANIC
);
14773 * Build time assertion that we keep the data_head at the intended
14774 * location. IOW, validation we got the __reserved[] size right.
14776 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page
, data_head
))
14780 ssize_t
perf_event_sysfs_show(struct device
*dev
, struct device_attribute
*attr
,
14783 struct perf_pmu_events_attr
*pmu_attr
=
14784 container_of(attr
, struct perf_pmu_events_attr
, attr
);
14786 if (pmu_attr
->event_str
)
14787 return sprintf(page
, "%s\n", pmu_attr
->event_str
);
14791 EXPORT_SYMBOL_GPL(perf_event_sysfs_show
);
14793 static int __init
perf_event_sysfs_init(void)
14798 mutex_lock(&pmus_lock
);
14800 ret
= bus_register(&pmu_bus
);
14804 list_for_each_entry(pmu
, &pmus
, entry
) {
14808 ret
= pmu_dev_alloc(pmu
);
14809 WARN(ret
, "Failed to register pmu: %s, reason %d\n", pmu
->name
, ret
);
14811 pmu_bus_running
= 1;
14815 mutex_unlock(&pmus_lock
);
14819 device_initcall(perf_event_sysfs_init
);
14821 #ifdef CONFIG_CGROUP_PERF
14822 static struct cgroup_subsys_state
*
14823 perf_cgroup_css_alloc(struct cgroup_subsys_state
*parent_css
)
14825 struct perf_cgroup
*jc
;
14827 jc
= kzalloc(sizeof(*jc
), GFP_KERNEL
);
14829 return ERR_PTR(-ENOMEM
);
14831 jc
->info
= alloc_percpu(struct perf_cgroup_info
);
14834 return ERR_PTR(-ENOMEM
);
14840 static void perf_cgroup_css_free(struct cgroup_subsys_state
*css
)
14842 struct perf_cgroup
*jc
= container_of(css
, struct perf_cgroup
, css
);
14844 free_percpu(jc
->info
);
14848 static int perf_cgroup_css_online(struct cgroup_subsys_state
*css
)
14850 perf_event_cgroup(css
->cgroup
);
14854 static int __perf_cgroup_move(void *info
)
14856 struct task_struct
*task
= info
;
14859 perf_cgroup_switch(task
);
14865 static void perf_cgroup_attach(struct cgroup_taskset
*tset
)
14867 struct task_struct
*task
;
14868 struct cgroup_subsys_state
*css
;
14870 cgroup_taskset_for_each(task
, css
, tset
)
14871 task_function_call(task
, __perf_cgroup_move
, task
);
14874 struct cgroup_subsys perf_event_cgrp_subsys
= {
14875 .css_alloc
= perf_cgroup_css_alloc
,
14876 .css_free
= perf_cgroup_css_free
,
14877 .css_online
= perf_cgroup_css_online
,
14878 .attach
= perf_cgroup_attach
,
14880 * Implicitly enable on dfl hierarchy so that perf events can
14881 * always be filtered by cgroup2 path as long as perf_event
14882 * controller is not mounted on a legacy hierarchy.
14884 .implicit_on_dfl
= true,
14887 #endif /* CONFIG_CGROUP_PERF */
14889 DEFINE_STATIC_CALL_RET0(perf_snapshot_branch_stack
, perf_snapshot_branch_stack_t
);