2 * Performance events core code:
4 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
5 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
6 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
7 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
9 * For licensing details see kernel-base/COPYING
14 #include <linux/cpu.h>
15 #include <linux/smp.h>
16 #include <linux/idr.h>
17 #include <linux/file.h>
18 #include <linux/poll.h>
19 #include <linux/slab.h>
20 #include <linux/hash.h>
21 #include <linux/tick.h>
22 #include <linux/sysfs.h>
23 #include <linux/dcache.h>
24 #include <linux/percpu.h>
25 #include <linux/ptrace.h>
26 #include <linux/reboot.h>
27 #include <linux/vmstat.h>
28 #include <linux/device.h>
29 #include <linux/export.h>
30 #include <linux/vmalloc.h>
31 #include <linux/hardirq.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>
50 #include <asm/irq_regs.h>
52 typedef int (*remote_function_f)(void *);
54 struct remote_function_call {
55 struct task_struct *p;
56 remote_function_f func;
61 static void remote_function(void *data)
63 struct remote_function_call *tfc = data;
64 struct task_struct *p = tfc->p;
68 if (task_cpu(p) != smp_processor_id() || !task_curr(p))
72 tfc->ret = tfc->func(tfc->info);
76 * task_function_call - call a function on the cpu on which a task runs
77 * @p: the task to evaluate
78 * @func: the function to be called
79 * @info: the function call argument
81 * Calls the function @func when the task is currently running. This might
82 * be on the current CPU, which just calls the function directly
84 * returns: @func return value, or
85 * -ESRCH - when the process isn't running
86 * -EAGAIN - when the process moved away
89 task_function_call(struct task_struct *p, remote_function_f func, void *info)
91 struct remote_function_call data = {
95 .ret = -ESRCH, /* No such (running) process */
99 smp_call_function_single(task_cpu(p), remote_function, &data, 1);
105 * cpu_function_call - call a function on the cpu
106 * @func: the function to be called
107 * @info: the function call argument
109 * Calls the function @func on the remote cpu.
111 * returns: @func return value or -ENXIO when the cpu is offline
113 static int cpu_function_call(int cpu, remote_function_f func, void *info)
115 struct remote_function_call data = {
119 .ret = -ENXIO, /* No such CPU */
122 smp_call_function_single(cpu, remote_function, &data, 1);
127 static inline struct perf_cpu_context *
128 __get_cpu_context(struct perf_event_context *ctx)
130 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
133 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
134 struct perf_event_context *ctx)
136 raw_spin_lock(&cpuctx->ctx.lock);
138 raw_spin_lock(&ctx->lock);
141 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
142 struct perf_event_context *ctx)
145 raw_spin_unlock(&ctx->lock);
146 raw_spin_unlock(&cpuctx->ctx.lock);
149 #define TASK_TOMBSTONE ((void *)-1L)
151 static bool is_kernel_event(struct perf_event *event)
153 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
157 * On task ctx scheduling...
159 * When !ctx->nr_events a task context will not be scheduled. This means
160 * we can disable the scheduler hooks (for performance) without leaving
161 * pending task ctx state.
163 * This however results in two special cases:
165 * - removing the last event from a task ctx; this is relatively straight
166 * forward and is done in __perf_remove_from_context.
168 * - adding the first event to a task ctx; this is tricky because we cannot
169 * rely on ctx->is_active and therefore cannot use event_function_call().
170 * See perf_install_in_context().
172 * This is because we need a ctx->lock serialized variable (ctx->is_active)
173 * to reliably determine if a particular task/context is scheduled in. The
174 * task_curr() use in task_function_call() is racy in that a remote context
175 * switch is not a single atomic operation.
177 * As is, the situation is 'safe' because we set rq->curr before we do the
178 * actual context switch. This means that task_curr() will fail early, but
179 * we'll continue spinning on ctx->is_active until we've passed
180 * perf_event_task_sched_out().
182 * Without this ctx->lock serialized variable we could have race where we find
183 * the task (and hence the context) would not be active while in fact they are.
185 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
188 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
189 struct perf_event_context *, void *);
191 struct event_function_struct {
192 struct perf_event *event;
197 static int event_function(void *info)
199 struct event_function_struct *efs = info;
200 struct perf_event *event = efs->event;
201 struct perf_event_context *ctx = event->ctx;
202 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
203 struct perf_event_context *task_ctx = cpuctx->task_ctx;
206 WARN_ON_ONCE(!irqs_disabled());
208 perf_ctx_lock(cpuctx, task_ctx);
210 * Since we do the IPI call without holding ctx->lock things can have
211 * changed, double check we hit the task we set out to hit.
214 if (ctx->task != current) {
220 * We only use event_function_call() on established contexts,
221 * and event_function() is only ever called when active (or
222 * rather, we'll have bailed in task_function_call() or the
223 * above ctx->task != current test), therefore we must have
224 * ctx->is_active here.
226 WARN_ON_ONCE(!ctx->is_active);
228 * And since we have ctx->is_active, cpuctx->task_ctx must
231 WARN_ON_ONCE(task_ctx != ctx);
233 WARN_ON_ONCE(&cpuctx->ctx != ctx);
236 efs->func(event, cpuctx, ctx, efs->data);
238 perf_ctx_unlock(cpuctx, task_ctx);
243 static void event_function_local(struct perf_event *event, event_f func, void *data)
245 struct event_function_struct efs = {
251 int ret = event_function(&efs);
255 static void event_function_call(struct perf_event *event, event_f func, void *data)
257 struct perf_event_context *ctx = event->ctx;
258 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
259 struct event_function_struct efs = {
265 if (!event->parent) {
267 * If this is a !child event, we must hold ctx::mutex to
268 * stabilize the the event->ctx relation. See
269 * perf_event_ctx_lock().
271 lockdep_assert_held(&ctx->mutex);
275 cpu_function_call(event->cpu, event_function, &efs);
280 if (task == TASK_TOMBSTONE)
283 if (!task_function_call(task, event_function, &efs))
286 raw_spin_lock_irq(&ctx->lock);
288 * Reload the task pointer, it might have been changed by
289 * a concurrent perf_event_context_sched_out().
292 if (task != TASK_TOMBSTONE) {
293 if (ctx->is_active) {
294 raw_spin_unlock_irq(&ctx->lock);
297 func(event, NULL, ctx, data);
299 raw_spin_unlock_irq(&ctx->lock);
302 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
303 PERF_FLAG_FD_OUTPUT |\
304 PERF_FLAG_PID_CGROUP |\
305 PERF_FLAG_FD_CLOEXEC)
308 * branch priv levels that need permission checks
310 #define PERF_SAMPLE_BRANCH_PERM_PLM \
311 (PERF_SAMPLE_BRANCH_KERNEL |\
312 PERF_SAMPLE_BRANCH_HV)
315 EVENT_FLEXIBLE = 0x1,
318 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
322 * perf_sched_events : >0 events exist
323 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
326 static void perf_sched_delayed(struct work_struct *work);
327 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
328 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
329 static DEFINE_MUTEX(perf_sched_mutex);
330 static atomic_t perf_sched_count;
332 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
333 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
335 static atomic_t nr_mmap_events __read_mostly;
336 static atomic_t nr_comm_events __read_mostly;
337 static atomic_t nr_task_events __read_mostly;
338 static atomic_t nr_freq_events __read_mostly;
339 static atomic_t nr_switch_events __read_mostly;
341 static LIST_HEAD(pmus);
342 static DEFINE_MUTEX(pmus_lock);
343 static struct srcu_struct pmus_srcu;
346 * perf event paranoia level:
347 * -1 - not paranoid at all
348 * 0 - disallow raw tracepoint access for unpriv
349 * 1 - disallow cpu events for unpriv
350 * 2 - disallow kernel profiling for unpriv
352 int sysctl_perf_event_paranoid __read_mostly = 1;
354 /* Minimum for 512 kiB + 1 user control page */
355 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
358 * max perf event sample rate
360 #define DEFAULT_MAX_SAMPLE_RATE 100000
361 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
362 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
364 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
366 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
367 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
369 static int perf_sample_allowed_ns __read_mostly =
370 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
372 static void update_perf_cpu_limits(void)
374 u64 tmp = perf_sample_period_ns;
376 tmp *= sysctl_perf_cpu_time_max_percent;
378 ACCESS_ONCE(perf_sample_allowed_ns) = tmp;
381 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
383 int perf_proc_update_handler(struct ctl_table *table, int write,
384 void __user *buffer, size_t *lenp,
387 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
392 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
393 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
394 update_perf_cpu_limits();
399 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
401 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
402 void __user *buffer, size_t *lenp,
405 int ret = proc_dointvec(table, write, buffer, lenp, ppos);
410 update_perf_cpu_limits();
416 * perf samples are done in some very critical code paths (NMIs).
417 * If they take too much CPU time, the system can lock up and not
418 * get any real work done. This will drop the sample rate when
419 * we detect that events are taking too long.
421 #define NR_ACCUMULATED_SAMPLES 128
422 static DEFINE_PER_CPU(u64, running_sample_length);
424 static void perf_duration_warn(struct irq_work *w)
426 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
427 u64 avg_local_sample_len;
428 u64 local_samples_len;
430 local_samples_len = __this_cpu_read(running_sample_length);
431 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
433 printk_ratelimited(KERN_WARNING
434 "perf interrupt took too long (%lld > %lld), lowering "
435 "kernel.perf_event_max_sample_rate to %d\n",
436 avg_local_sample_len, allowed_ns >> 1,
437 sysctl_perf_event_sample_rate);
440 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
442 void perf_sample_event_took(u64 sample_len_ns)
444 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
445 u64 avg_local_sample_len;
446 u64 local_samples_len;
451 /* decay the counter by 1 average sample */
452 local_samples_len = __this_cpu_read(running_sample_length);
453 local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES;
454 local_samples_len += sample_len_ns;
455 __this_cpu_write(running_sample_length, local_samples_len);
458 * note: this will be biased artifically low until we have
459 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
460 * from having to maintain a count.
462 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
464 if (avg_local_sample_len <= allowed_ns)
467 if (max_samples_per_tick <= 1)
470 max_samples_per_tick = DIV_ROUND_UP(max_samples_per_tick, 2);
471 sysctl_perf_event_sample_rate = max_samples_per_tick * HZ;
472 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
474 update_perf_cpu_limits();
476 if (!irq_work_queue(&perf_duration_work)) {
477 early_printk("perf interrupt took too long (%lld > %lld), lowering "
478 "kernel.perf_event_max_sample_rate to %d\n",
479 avg_local_sample_len, allowed_ns >> 1,
480 sysctl_perf_event_sample_rate);
484 static atomic64_t perf_event_id;
486 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
487 enum event_type_t event_type);
489 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
490 enum event_type_t event_type,
491 struct task_struct *task);
493 static void update_context_time(struct perf_event_context *ctx);
494 static u64 perf_event_time(struct perf_event *event);
496 void __weak perf_event_print_debug(void) { }
498 extern __weak const char *perf_pmu_name(void)
503 static inline u64 perf_clock(void)
505 return local_clock();
508 static inline u64 perf_event_clock(struct perf_event *event)
510 return event->clock();
513 #ifdef CONFIG_CGROUP_PERF
516 perf_cgroup_match(struct perf_event *event)
518 struct perf_event_context *ctx = event->ctx;
519 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
521 /* @event doesn't care about cgroup */
525 /* wants specific cgroup scope but @cpuctx isn't associated with any */
530 * Cgroup scoping is recursive. An event enabled for a cgroup is
531 * also enabled for all its descendant cgroups. If @cpuctx's
532 * cgroup is a descendant of @event's (the test covers identity
533 * case), it's a match.
535 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
536 event->cgrp->css.cgroup);
539 static inline void perf_detach_cgroup(struct perf_event *event)
541 css_put(&event->cgrp->css);
545 static inline int is_cgroup_event(struct perf_event *event)
547 return event->cgrp != NULL;
550 static inline u64 perf_cgroup_event_time(struct perf_event *event)
552 struct perf_cgroup_info *t;
554 t = per_cpu_ptr(event->cgrp->info, event->cpu);
558 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
560 struct perf_cgroup_info *info;
565 info = this_cpu_ptr(cgrp->info);
567 info->time += now - info->timestamp;
568 info->timestamp = now;
571 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
573 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
575 __update_cgrp_time(cgrp_out);
578 static inline void update_cgrp_time_from_event(struct perf_event *event)
580 struct perf_cgroup *cgrp;
583 * ensure we access cgroup data only when needed and
584 * when we know the cgroup is pinned (css_get)
586 if (!is_cgroup_event(event))
589 cgrp = perf_cgroup_from_task(current, event->ctx);
591 * Do not update time when cgroup is not active
593 if (cgrp == event->cgrp)
594 __update_cgrp_time(event->cgrp);
598 perf_cgroup_set_timestamp(struct task_struct *task,
599 struct perf_event_context *ctx)
601 struct perf_cgroup *cgrp;
602 struct perf_cgroup_info *info;
605 * ctx->lock held by caller
606 * ensure we do not access cgroup data
607 * unless we have the cgroup pinned (css_get)
609 if (!task || !ctx->nr_cgroups)
612 cgrp = perf_cgroup_from_task(task, ctx);
613 info = this_cpu_ptr(cgrp->info);
614 info->timestamp = ctx->timestamp;
617 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
618 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
621 * reschedule events based on the cgroup constraint of task.
623 * mode SWOUT : schedule out everything
624 * mode SWIN : schedule in based on cgroup for next
626 static void perf_cgroup_switch(struct task_struct *task, int mode)
628 struct perf_cpu_context *cpuctx;
633 * disable interrupts to avoid geting nr_cgroup
634 * changes via __perf_event_disable(). Also
637 local_irq_save(flags);
640 * we reschedule only in the presence of cgroup
641 * constrained events.
644 list_for_each_entry_rcu(pmu, &pmus, entry) {
645 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
646 if (cpuctx->unique_pmu != pmu)
647 continue; /* ensure we process each cpuctx once */
650 * perf_cgroup_events says at least one
651 * context on this CPU has cgroup events.
653 * ctx->nr_cgroups reports the number of cgroup
654 * events for a context.
656 if (cpuctx->ctx.nr_cgroups > 0) {
657 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
658 perf_pmu_disable(cpuctx->ctx.pmu);
660 if (mode & PERF_CGROUP_SWOUT) {
661 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
663 * must not be done before ctxswout due
664 * to event_filter_match() in event_sched_out()
669 if (mode & PERF_CGROUP_SWIN) {
670 WARN_ON_ONCE(cpuctx->cgrp);
672 * set cgrp before ctxsw in to allow
673 * event_filter_match() to not have to pass
675 * we pass the cpuctx->ctx to perf_cgroup_from_task()
676 * because cgorup events are only per-cpu
678 cpuctx->cgrp = perf_cgroup_from_task(task, &cpuctx->ctx);
679 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
681 perf_pmu_enable(cpuctx->ctx.pmu);
682 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
686 local_irq_restore(flags);
689 static inline void perf_cgroup_sched_out(struct task_struct *task,
690 struct task_struct *next)
692 struct perf_cgroup *cgrp1;
693 struct perf_cgroup *cgrp2 = NULL;
697 * we come here when we know perf_cgroup_events > 0
698 * we do not need to pass the ctx here because we know
699 * we are holding the rcu lock
701 cgrp1 = perf_cgroup_from_task(task, NULL);
702 cgrp2 = perf_cgroup_from_task(next, NULL);
705 * only schedule out current cgroup events if we know
706 * that we are switching to a different cgroup. Otherwise,
707 * do no touch the cgroup events.
710 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
715 static inline void perf_cgroup_sched_in(struct task_struct *prev,
716 struct task_struct *task)
718 struct perf_cgroup *cgrp1;
719 struct perf_cgroup *cgrp2 = NULL;
723 * we come here when we know perf_cgroup_events > 0
724 * we do not need to pass the ctx here because we know
725 * we are holding the rcu lock
727 cgrp1 = perf_cgroup_from_task(task, NULL);
728 cgrp2 = perf_cgroup_from_task(prev, NULL);
731 * only need to schedule in cgroup events if we are changing
732 * cgroup during ctxsw. Cgroup events were not scheduled
733 * out of ctxsw out if that was not the case.
736 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
741 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
742 struct perf_event_attr *attr,
743 struct perf_event *group_leader)
745 struct perf_cgroup *cgrp;
746 struct cgroup_subsys_state *css;
747 struct fd f = fdget(fd);
753 css = css_tryget_online_from_dir(f.file->f_path.dentry,
754 &perf_event_cgrp_subsys);
760 cgrp = container_of(css, struct perf_cgroup, css);
764 * all events in a group must monitor
765 * the same cgroup because a task belongs
766 * to only one perf cgroup at a time
768 if (group_leader && group_leader->cgrp != cgrp) {
769 perf_detach_cgroup(event);
778 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
780 struct perf_cgroup_info *t;
781 t = per_cpu_ptr(event->cgrp->info, event->cpu);
782 event->shadow_ctx_time = now - t->timestamp;
786 perf_cgroup_defer_enabled(struct perf_event *event)
789 * when the current task's perf cgroup does not match
790 * the event's, we need to remember to call the
791 * perf_mark_enable() function the first time a task with
792 * a matching perf cgroup is scheduled in.
794 if (is_cgroup_event(event) && !perf_cgroup_match(event))
795 event->cgrp_defer_enabled = 1;
799 perf_cgroup_mark_enabled(struct perf_event *event,
800 struct perf_event_context *ctx)
802 struct perf_event *sub;
803 u64 tstamp = perf_event_time(event);
805 if (!event->cgrp_defer_enabled)
808 event->cgrp_defer_enabled = 0;
810 event->tstamp_enabled = tstamp - event->total_time_enabled;
811 list_for_each_entry(sub, &event->sibling_list, group_entry) {
812 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
813 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
814 sub->cgrp_defer_enabled = 0;
818 #else /* !CONFIG_CGROUP_PERF */
821 perf_cgroup_match(struct perf_event *event)
826 static inline void perf_detach_cgroup(struct perf_event *event)
829 static inline int is_cgroup_event(struct perf_event *event)
834 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
839 static inline void update_cgrp_time_from_event(struct perf_event *event)
843 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
847 static inline void perf_cgroup_sched_out(struct task_struct *task,
848 struct task_struct *next)
852 static inline void perf_cgroup_sched_in(struct task_struct *prev,
853 struct task_struct *task)
857 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
858 struct perf_event_attr *attr,
859 struct perf_event *group_leader)
865 perf_cgroup_set_timestamp(struct task_struct *task,
866 struct perf_event_context *ctx)
871 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
876 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
880 static inline u64 perf_cgroup_event_time(struct perf_event *event)
886 perf_cgroup_defer_enabled(struct perf_event *event)
891 perf_cgroup_mark_enabled(struct perf_event *event,
892 struct perf_event_context *ctx)
898 * set default to be dependent on timer tick just
901 #define PERF_CPU_HRTIMER (1000 / HZ)
903 * function must be called with interrupts disbled
905 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
907 struct perf_cpu_context *cpuctx;
910 WARN_ON(!irqs_disabled());
912 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
913 rotations = perf_rotate_context(cpuctx);
915 raw_spin_lock(&cpuctx->hrtimer_lock);
917 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
919 cpuctx->hrtimer_active = 0;
920 raw_spin_unlock(&cpuctx->hrtimer_lock);
922 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
925 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
927 struct hrtimer *timer = &cpuctx->hrtimer;
928 struct pmu *pmu = cpuctx->ctx.pmu;
931 /* no multiplexing needed for SW PMU */
932 if (pmu->task_ctx_nr == perf_sw_context)
936 * check default is sane, if not set then force to
937 * default interval (1/tick)
939 interval = pmu->hrtimer_interval_ms;
941 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
943 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
945 raw_spin_lock_init(&cpuctx->hrtimer_lock);
946 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
947 timer->function = perf_mux_hrtimer_handler;
950 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
952 struct hrtimer *timer = &cpuctx->hrtimer;
953 struct pmu *pmu = cpuctx->ctx.pmu;
957 if (pmu->task_ctx_nr == perf_sw_context)
960 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
961 if (!cpuctx->hrtimer_active) {
962 cpuctx->hrtimer_active = 1;
963 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
964 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
966 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
971 void perf_pmu_disable(struct pmu *pmu)
973 int *count = this_cpu_ptr(pmu->pmu_disable_count);
975 pmu->pmu_disable(pmu);
978 void perf_pmu_enable(struct pmu *pmu)
980 int *count = this_cpu_ptr(pmu->pmu_disable_count);
982 pmu->pmu_enable(pmu);
985 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
988 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
989 * perf_event_task_tick() are fully serialized because they're strictly cpu
990 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
991 * disabled, while perf_event_task_tick is called from IRQ context.
993 static void perf_event_ctx_activate(struct perf_event_context *ctx)
995 struct list_head *head = this_cpu_ptr(&active_ctx_list);
997 WARN_ON(!irqs_disabled());
999 WARN_ON(!list_empty(&ctx->active_ctx_list));
1001 list_add(&ctx->active_ctx_list, head);
1004 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1006 WARN_ON(!irqs_disabled());
1008 WARN_ON(list_empty(&ctx->active_ctx_list));
1010 list_del_init(&ctx->active_ctx_list);
1013 static void get_ctx(struct perf_event_context *ctx)
1015 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
1018 static void free_ctx(struct rcu_head *head)
1020 struct perf_event_context *ctx;
1022 ctx = container_of(head, struct perf_event_context, rcu_head);
1023 kfree(ctx->task_ctx_data);
1027 static void put_ctx(struct perf_event_context *ctx)
1029 if (atomic_dec_and_test(&ctx->refcount)) {
1030 if (ctx->parent_ctx)
1031 put_ctx(ctx->parent_ctx);
1032 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1033 put_task_struct(ctx->task);
1034 call_rcu(&ctx->rcu_head, free_ctx);
1039 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1040 * perf_pmu_migrate_context() we need some magic.
1042 * Those places that change perf_event::ctx will hold both
1043 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1045 * Lock ordering is by mutex address. There are two other sites where
1046 * perf_event_context::mutex nests and those are:
1048 * - perf_event_exit_task_context() [ child , 0 ]
1049 * perf_event_exit_event()
1050 * put_event() [ parent, 1 ]
1052 * - perf_event_init_context() [ parent, 0 ]
1053 * inherit_task_group()
1056 * perf_event_alloc()
1058 * perf_try_init_event() [ child , 1 ]
1060 * While it appears there is an obvious deadlock here -- the parent and child
1061 * nesting levels are inverted between the two. This is in fact safe because
1062 * life-time rules separate them. That is an exiting task cannot fork, and a
1063 * spawning task cannot (yet) exit.
1065 * But remember that that these are parent<->child context relations, and
1066 * migration does not affect children, therefore these two orderings should not
1069 * The change in perf_event::ctx does not affect children (as claimed above)
1070 * because the sys_perf_event_open() case will install a new event and break
1071 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1072 * concerned with cpuctx and that doesn't have children.
1074 * The places that change perf_event::ctx will issue:
1076 * perf_remove_from_context();
1077 * synchronize_rcu();
1078 * perf_install_in_context();
1080 * to affect the change. The remove_from_context() + synchronize_rcu() should
1081 * quiesce the event, after which we can install it in the new location. This
1082 * means that only external vectors (perf_fops, prctl) can perturb the event
1083 * while in transit. Therefore all such accessors should also acquire
1084 * perf_event_context::mutex to serialize against this.
1086 * However; because event->ctx can change while we're waiting to acquire
1087 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1091 * task_struct::perf_event_mutex
1092 * perf_event_context::mutex
1093 * perf_event::child_mutex;
1094 * perf_event_context::lock
1095 * perf_event::mmap_mutex
1098 static struct perf_event_context *
1099 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1101 struct perf_event_context *ctx;
1105 ctx = ACCESS_ONCE(event->ctx);
1106 if (!atomic_inc_not_zero(&ctx->refcount)) {
1112 mutex_lock_nested(&ctx->mutex, nesting);
1113 if (event->ctx != ctx) {
1114 mutex_unlock(&ctx->mutex);
1122 static inline struct perf_event_context *
1123 perf_event_ctx_lock(struct perf_event *event)
1125 return perf_event_ctx_lock_nested(event, 0);
1128 static void perf_event_ctx_unlock(struct perf_event *event,
1129 struct perf_event_context *ctx)
1131 mutex_unlock(&ctx->mutex);
1136 * This must be done under the ctx->lock, such as to serialize against
1137 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1138 * calling scheduler related locks and ctx->lock nests inside those.
1140 static __must_check struct perf_event_context *
1141 unclone_ctx(struct perf_event_context *ctx)
1143 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1145 lockdep_assert_held(&ctx->lock);
1148 ctx->parent_ctx = NULL;
1154 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1157 * only top level events have the pid namespace they were created in
1160 event = event->parent;
1162 return task_tgid_nr_ns(p, event->ns);
1165 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1168 * only top level events have the pid namespace they were created in
1171 event = event->parent;
1173 return task_pid_nr_ns(p, event->ns);
1177 * If we inherit events we want to return the parent event id
1180 static u64 primary_event_id(struct perf_event *event)
1185 id = event->parent->id;
1191 * Get the perf_event_context for a task and lock it.
1193 * This has to cope with with the fact that until it is locked,
1194 * the context could get moved to another task.
1196 static struct perf_event_context *
1197 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1199 struct perf_event_context *ctx;
1203 * One of the few rules of preemptible RCU is that one cannot do
1204 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1205 * part of the read side critical section was irqs-enabled -- see
1206 * rcu_read_unlock_special().
1208 * Since ctx->lock nests under rq->lock we must ensure the entire read
1209 * side critical section has interrupts disabled.
1211 local_irq_save(*flags);
1213 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1216 * If this context is a clone of another, it might
1217 * get swapped for another underneath us by
1218 * perf_event_task_sched_out, though the
1219 * rcu_read_lock() protects us from any context
1220 * getting freed. Lock the context and check if it
1221 * got swapped before we could get the lock, and retry
1222 * if so. If we locked the right context, then it
1223 * can't get swapped on us any more.
1225 raw_spin_lock(&ctx->lock);
1226 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1227 raw_spin_unlock(&ctx->lock);
1229 local_irq_restore(*flags);
1233 if (ctx->task == TASK_TOMBSTONE ||
1234 !atomic_inc_not_zero(&ctx->refcount)) {
1235 raw_spin_unlock(&ctx->lock);
1238 WARN_ON_ONCE(ctx->task != task);
1243 local_irq_restore(*flags);
1248 * Get the context for a task and increment its pin_count so it
1249 * can't get swapped to another task. This also increments its
1250 * reference count so that the context can't get freed.
1252 static struct perf_event_context *
1253 perf_pin_task_context(struct task_struct *task, int ctxn)
1255 struct perf_event_context *ctx;
1256 unsigned long flags;
1258 ctx = perf_lock_task_context(task, ctxn, &flags);
1261 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1266 static void perf_unpin_context(struct perf_event_context *ctx)
1268 unsigned long flags;
1270 raw_spin_lock_irqsave(&ctx->lock, flags);
1272 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1276 * Update the record of the current time in a context.
1278 static void update_context_time(struct perf_event_context *ctx)
1280 u64 now = perf_clock();
1282 ctx->time += now - ctx->timestamp;
1283 ctx->timestamp = now;
1286 static u64 perf_event_time(struct perf_event *event)
1288 struct perf_event_context *ctx = event->ctx;
1290 if (is_cgroup_event(event))
1291 return perf_cgroup_event_time(event);
1293 return ctx ? ctx->time : 0;
1297 * Update the total_time_enabled and total_time_running fields for a event.
1299 static void update_event_times(struct perf_event *event)
1301 struct perf_event_context *ctx = event->ctx;
1304 lockdep_assert_held(&ctx->lock);
1306 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1307 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1311 * in cgroup mode, time_enabled represents
1312 * the time the event was enabled AND active
1313 * tasks were in the monitored cgroup. This is
1314 * independent of the activity of the context as
1315 * there may be a mix of cgroup and non-cgroup events.
1317 * That is why we treat cgroup events differently
1320 if (is_cgroup_event(event))
1321 run_end = perf_cgroup_event_time(event);
1322 else if (ctx->is_active)
1323 run_end = ctx->time;
1325 run_end = event->tstamp_stopped;
1327 event->total_time_enabled = run_end - event->tstamp_enabled;
1329 if (event->state == PERF_EVENT_STATE_INACTIVE)
1330 run_end = event->tstamp_stopped;
1332 run_end = perf_event_time(event);
1334 event->total_time_running = run_end - event->tstamp_running;
1339 * Update total_time_enabled and total_time_running for all events in a group.
1341 static void update_group_times(struct perf_event *leader)
1343 struct perf_event *event;
1345 update_event_times(leader);
1346 list_for_each_entry(event, &leader->sibling_list, group_entry)
1347 update_event_times(event);
1350 static struct list_head *
1351 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1353 if (event->attr.pinned)
1354 return &ctx->pinned_groups;
1356 return &ctx->flexible_groups;
1360 * Add a event from the lists for its context.
1361 * Must be called with ctx->mutex and ctx->lock held.
1364 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1366 lockdep_assert_held(&ctx->lock);
1368 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1369 event->attach_state |= PERF_ATTACH_CONTEXT;
1372 * If we're a stand alone event or group leader, we go to the context
1373 * list, group events are kept attached to the group so that
1374 * perf_group_detach can, at all times, locate all siblings.
1376 if (event->group_leader == event) {
1377 struct list_head *list;
1379 if (is_software_event(event))
1380 event->group_flags |= PERF_GROUP_SOFTWARE;
1382 list = ctx_group_list(event, ctx);
1383 list_add_tail(&event->group_entry, list);
1386 if (is_cgroup_event(event))
1389 list_add_rcu(&event->event_entry, &ctx->event_list);
1391 if (event->attr.inherit_stat)
1398 * Initialize event state based on the perf_event_attr::disabled.
1400 static inline void perf_event__state_init(struct perf_event *event)
1402 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1403 PERF_EVENT_STATE_INACTIVE;
1406 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1408 int entry = sizeof(u64); /* value */
1412 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1413 size += sizeof(u64);
1415 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1416 size += sizeof(u64);
1418 if (event->attr.read_format & PERF_FORMAT_ID)
1419 entry += sizeof(u64);
1421 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1423 size += sizeof(u64);
1427 event->read_size = size;
1430 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1432 struct perf_sample_data *data;
1435 if (sample_type & PERF_SAMPLE_IP)
1436 size += sizeof(data->ip);
1438 if (sample_type & PERF_SAMPLE_ADDR)
1439 size += sizeof(data->addr);
1441 if (sample_type & PERF_SAMPLE_PERIOD)
1442 size += sizeof(data->period);
1444 if (sample_type & PERF_SAMPLE_WEIGHT)
1445 size += sizeof(data->weight);
1447 if (sample_type & PERF_SAMPLE_READ)
1448 size += event->read_size;
1450 if (sample_type & PERF_SAMPLE_DATA_SRC)
1451 size += sizeof(data->data_src.val);
1453 if (sample_type & PERF_SAMPLE_TRANSACTION)
1454 size += sizeof(data->txn);
1456 event->header_size = size;
1460 * Called at perf_event creation and when events are attached/detached from a
1463 static void perf_event__header_size(struct perf_event *event)
1465 __perf_event_read_size(event,
1466 event->group_leader->nr_siblings);
1467 __perf_event_header_size(event, event->attr.sample_type);
1470 static void perf_event__id_header_size(struct perf_event *event)
1472 struct perf_sample_data *data;
1473 u64 sample_type = event->attr.sample_type;
1476 if (sample_type & PERF_SAMPLE_TID)
1477 size += sizeof(data->tid_entry);
1479 if (sample_type & PERF_SAMPLE_TIME)
1480 size += sizeof(data->time);
1482 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1483 size += sizeof(data->id);
1485 if (sample_type & PERF_SAMPLE_ID)
1486 size += sizeof(data->id);
1488 if (sample_type & PERF_SAMPLE_STREAM_ID)
1489 size += sizeof(data->stream_id);
1491 if (sample_type & PERF_SAMPLE_CPU)
1492 size += sizeof(data->cpu_entry);
1494 event->id_header_size = size;
1497 static bool perf_event_validate_size(struct perf_event *event)
1500 * The values computed here will be over-written when we actually
1503 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1504 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1505 perf_event__id_header_size(event);
1508 * Sum the lot; should not exceed the 64k limit we have on records.
1509 * Conservative limit to allow for callchains and other variable fields.
1511 if (event->read_size + event->header_size +
1512 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1518 static void perf_group_attach(struct perf_event *event)
1520 struct perf_event *group_leader = event->group_leader, *pos;
1523 * We can have double attach due to group movement in perf_event_open.
1525 if (event->attach_state & PERF_ATTACH_GROUP)
1528 event->attach_state |= PERF_ATTACH_GROUP;
1530 if (group_leader == event)
1533 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1535 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1536 !is_software_event(event))
1537 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1539 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1540 group_leader->nr_siblings++;
1542 perf_event__header_size(group_leader);
1544 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1545 perf_event__header_size(pos);
1549 * Remove a event from the lists for its context.
1550 * Must be called with ctx->mutex and ctx->lock held.
1553 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1555 struct perf_cpu_context *cpuctx;
1557 WARN_ON_ONCE(event->ctx != ctx);
1558 lockdep_assert_held(&ctx->lock);
1561 * We can have double detach due to exit/hot-unplug + close.
1563 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1566 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1568 if (is_cgroup_event(event)) {
1571 * Because cgroup events are always per-cpu events, this will
1572 * always be called from the right CPU.
1574 cpuctx = __get_cpu_context(ctx);
1576 * If there are no more cgroup events then clear cgrp to avoid
1577 * stale pointer in update_cgrp_time_from_cpuctx().
1579 if (!ctx->nr_cgroups)
1580 cpuctx->cgrp = NULL;
1584 if (event->attr.inherit_stat)
1587 list_del_rcu(&event->event_entry);
1589 if (event->group_leader == event)
1590 list_del_init(&event->group_entry);
1592 update_group_times(event);
1595 * If event was in error state, then keep it
1596 * that way, otherwise bogus counts will be
1597 * returned on read(). The only way to get out
1598 * of error state is by explicit re-enabling
1601 if (event->state > PERF_EVENT_STATE_OFF)
1602 event->state = PERF_EVENT_STATE_OFF;
1607 static void perf_group_detach(struct perf_event *event)
1609 struct perf_event *sibling, *tmp;
1610 struct list_head *list = NULL;
1613 * We can have double detach due to exit/hot-unplug + close.
1615 if (!(event->attach_state & PERF_ATTACH_GROUP))
1618 event->attach_state &= ~PERF_ATTACH_GROUP;
1621 * If this is a sibling, remove it from its group.
1623 if (event->group_leader != event) {
1624 list_del_init(&event->group_entry);
1625 event->group_leader->nr_siblings--;
1629 if (!list_empty(&event->group_entry))
1630 list = &event->group_entry;
1633 * If this was a group event with sibling events then
1634 * upgrade the siblings to singleton events by adding them
1635 * to whatever list we are on.
1637 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1639 list_move_tail(&sibling->group_entry, list);
1640 sibling->group_leader = sibling;
1642 /* Inherit group flags from the previous leader */
1643 sibling->group_flags = event->group_flags;
1645 WARN_ON_ONCE(sibling->ctx != event->ctx);
1649 perf_event__header_size(event->group_leader);
1651 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1652 perf_event__header_size(tmp);
1655 static bool is_orphaned_event(struct perf_event *event)
1657 return event->state == PERF_EVENT_STATE_DEAD;
1660 static inline int pmu_filter_match(struct perf_event *event)
1662 struct pmu *pmu = event->pmu;
1663 return pmu->filter_match ? pmu->filter_match(event) : 1;
1667 event_filter_match(struct perf_event *event)
1669 return (event->cpu == -1 || event->cpu == smp_processor_id())
1670 && perf_cgroup_match(event) && pmu_filter_match(event);
1674 event_sched_out(struct perf_event *event,
1675 struct perf_cpu_context *cpuctx,
1676 struct perf_event_context *ctx)
1678 u64 tstamp = perf_event_time(event);
1681 WARN_ON_ONCE(event->ctx != ctx);
1682 lockdep_assert_held(&ctx->lock);
1685 * An event which could not be activated because of
1686 * filter mismatch still needs to have its timings
1687 * maintained, otherwise bogus information is return
1688 * via read() for time_enabled, time_running:
1690 if (event->state == PERF_EVENT_STATE_INACTIVE
1691 && !event_filter_match(event)) {
1692 delta = tstamp - event->tstamp_stopped;
1693 event->tstamp_running += delta;
1694 event->tstamp_stopped = tstamp;
1697 if (event->state != PERF_EVENT_STATE_ACTIVE)
1700 perf_pmu_disable(event->pmu);
1702 event->tstamp_stopped = tstamp;
1703 event->pmu->del(event, 0);
1705 event->state = PERF_EVENT_STATE_INACTIVE;
1706 if (event->pending_disable) {
1707 event->pending_disable = 0;
1708 event->state = PERF_EVENT_STATE_OFF;
1711 if (!is_software_event(event))
1712 cpuctx->active_oncpu--;
1713 if (!--ctx->nr_active)
1714 perf_event_ctx_deactivate(ctx);
1715 if (event->attr.freq && event->attr.sample_freq)
1717 if (event->attr.exclusive || !cpuctx->active_oncpu)
1718 cpuctx->exclusive = 0;
1720 perf_pmu_enable(event->pmu);
1724 group_sched_out(struct perf_event *group_event,
1725 struct perf_cpu_context *cpuctx,
1726 struct perf_event_context *ctx)
1728 struct perf_event *event;
1729 int state = group_event->state;
1731 event_sched_out(group_event, cpuctx, ctx);
1734 * Schedule out siblings (if any):
1736 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1737 event_sched_out(event, cpuctx, ctx);
1739 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1740 cpuctx->exclusive = 0;
1743 #define DETACH_GROUP 0x01UL
1746 * Cross CPU call to remove a performance event
1748 * We disable the event on the hardware level first. After that we
1749 * remove it from the context list.
1752 __perf_remove_from_context(struct perf_event *event,
1753 struct perf_cpu_context *cpuctx,
1754 struct perf_event_context *ctx,
1757 unsigned long flags = (unsigned long)info;
1759 event_sched_out(event, cpuctx, ctx);
1760 if (flags & DETACH_GROUP)
1761 perf_group_detach(event);
1762 list_del_event(event, ctx);
1764 if (!ctx->nr_events && ctx->is_active) {
1767 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
1768 cpuctx->task_ctx = NULL;
1774 * Remove the event from a task's (or a CPU's) list of events.
1776 * If event->ctx is a cloned context, callers must make sure that
1777 * every task struct that event->ctx->task could possibly point to
1778 * remains valid. This is OK when called from perf_release since
1779 * that only calls us on the top-level context, which can't be a clone.
1780 * When called from perf_event_exit_task, it's OK because the
1781 * context has been detached from its task.
1783 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
1785 lockdep_assert_held(&event->ctx->mutex);
1787 event_function_call(event, __perf_remove_from_context, (void *)flags);
1791 * Cross CPU call to disable a performance event
1793 static void __perf_event_disable(struct perf_event *event,
1794 struct perf_cpu_context *cpuctx,
1795 struct perf_event_context *ctx,
1798 if (event->state < PERF_EVENT_STATE_INACTIVE)
1801 update_context_time(ctx);
1802 update_cgrp_time_from_event(event);
1803 update_group_times(event);
1804 if (event == event->group_leader)
1805 group_sched_out(event, cpuctx, ctx);
1807 event_sched_out(event, cpuctx, ctx);
1808 event->state = PERF_EVENT_STATE_OFF;
1814 * If event->ctx is a cloned context, callers must make sure that
1815 * every task struct that event->ctx->task could possibly point to
1816 * remains valid. This condition is satisifed when called through
1817 * perf_event_for_each_child or perf_event_for_each because they
1818 * hold the top-level event's child_mutex, so any descendant that
1819 * goes to exit will block in perf_event_exit_event().
1821 * When called from perf_pending_event it's OK because event->ctx
1822 * is the current context on this CPU and preemption is disabled,
1823 * hence we can't get into perf_event_task_sched_out for this context.
1825 static void _perf_event_disable(struct perf_event *event)
1827 struct perf_event_context *ctx = event->ctx;
1829 raw_spin_lock_irq(&ctx->lock);
1830 if (event->state <= PERF_EVENT_STATE_OFF) {
1831 raw_spin_unlock_irq(&ctx->lock);
1834 raw_spin_unlock_irq(&ctx->lock);
1836 event_function_call(event, __perf_event_disable, NULL);
1839 void perf_event_disable_local(struct perf_event *event)
1841 event_function_local(event, __perf_event_disable, NULL);
1845 * Strictly speaking kernel users cannot create groups and therefore this
1846 * interface does not need the perf_event_ctx_lock() magic.
1848 void perf_event_disable(struct perf_event *event)
1850 struct perf_event_context *ctx;
1852 ctx = perf_event_ctx_lock(event);
1853 _perf_event_disable(event);
1854 perf_event_ctx_unlock(event, ctx);
1856 EXPORT_SYMBOL_GPL(perf_event_disable);
1858 static void perf_set_shadow_time(struct perf_event *event,
1859 struct perf_event_context *ctx,
1863 * use the correct time source for the time snapshot
1865 * We could get by without this by leveraging the
1866 * fact that to get to this function, the caller
1867 * has most likely already called update_context_time()
1868 * and update_cgrp_time_xx() and thus both timestamp
1869 * are identical (or very close). Given that tstamp is,
1870 * already adjusted for cgroup, we could say that:
1871 * tstamp - ctx->timestamp
1873 * tstamp - cgrp->timestamp.
1875 * Then, in perf_output_read(), the calculation would
1876 * work with no changes because:
1877 * - event is guaranteed scheduled in
1878 * - no scheduled out in between
1879 * - thus the timestamp would be the same
1881 * But this is a bit hairy.
1883 * So instead, we have an explicit cgroup call to remain
1884 * within the time time source all along. We believe it
1885 * is cleaner and simpler to understand.
1887 if (is_cgroup_event(event))
1888 perf_cgroup_set_shadow_time(event, tstamp);
1890 event->shadow_ctx_time = tstamp - ctx->timestamp;
1893 #define MAX_INTERRUPTS (~0ULL)
1895 static void perf_log_throttle(struct perf_event *event, int enable);
1896 static void perf_log_itrace_start(struct perf_event *event);
1899 event_sched_in(struct perf_event *event,
1900 struct perf_cpu_context *cpuctx,
1901 struct perf_event_context *ctx)
1903 u64 tstamp = perf_event_time(event);
1906 lockdep_assert_held(&ctx->lock);
1908 if (event->state <= PERF_EVENT_STATE_OFF)
1911 event->state = PERF_EVENT_STATE_ACTIVE;
1912 event->oncpu = smp_processor_id();
1915 * Unthrottle events, since we scheduled we might have missed several
1916 * ticks already, also for a heavily scheduling task there is little
1917 * guarantee it'll get a tick in a timely manner.
1919 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1920 perf_log_throttle(event, 1);
1921 event->hw.interrupts = 0;
1925 * The new state must be visible before we turn it on in the hardware:
1929 perf_pmu_disable(event->pmu);
1931 perf_set_shadow_time(event, ctx, tstamp);
1933 perf_log_itrace_start(event);
1935 if (event->pmu->add(event, PERF_EF_START)) {
1936 event->state = PERF_EVENT_STATE_INACTIVE;
1942 event->tstamp_running += tstamp - event->tstamp_stopped;
1944 if (!is_software_event(event))
1945 cpuctx->active_oncpu++;
1946 if (!ctx->nr_active++)
1947 perf_event_ctx_activate(ctx);
1948 if (event->attr.freq && event->attr.sample_freq)
1951 if (event->attr.exclusive)
1952 cpuctx->exclusive = 1;
1955 perf_pmu_enable(event->pmu);
1961 group_sched_in(struct perf_event *group_event,
1962 struct perf_cpu_context *cpuctx,
1963 struct perf_event_context *ctx)
1965 struct perf_event *event, *partial_group = NULL;
1966 struct pmu *pmu = ctx->pmu;
1967 u64 now = ctx->time;
1968 bool simulate = false;
1970 if (group_event->state == PERF_EVENT_STATE_OFF)
1973 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
1975 if (event_sched_in(group_event, cpuctx, ctx)) {
1976 pmu->cancel_txn(pmu);
1977 perf_mux_hrtimer_restart(cpuctx);
1982 * Schedule in siblings as one group (if any):
1984 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1985 if (event_sched_in(event, cpuctx, ctx)) {
1986 partial_group = event;
1991 if (!pmu->commit_txn(pmu))
1996 * Groups can be scheduled in as one unit only, so undo any
1997 * partial group before returning:
1998 * The events up to the failed event are scheduled out normally,
1999 * tstamp_stopped will be updated.
2001 * The failed events and the remaining siblings need to have
2002 * their timings updated as if they had gone thru event_sched_in()
2003 * and event_sched_out(). This is required to get consistent timings
2004 * across the group. This also takes care of the case where the group
2005 * could never be scheduled by ensuring tstamp_stopped is set to mark
2006 * the time the event was actually stopped, such that time delta
2007 * calculation in update_event_times() is correct.
2009 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2010 if (event == partial_group)
2014 event->tstamp_running += now - event->tstamp_stopped;
2015 event->tstamp_stopped = now;
2017 event_sched_out(event, cpuctx, ctx);
2020 event_sched_out(group_event, cpuctx, ctx);
2022 pmu->cancel_txn(pmu);
2024 perf_mux_hrtimer_restart(cpuctx);
2030 * Work out whether we can put this event group on the CPU now.
2032 static int group_can_go_on(struct perf_event *event,
2033 struct perf_cpu_context *cpuctx,
2037 * Groups consisting entirely of software events can always go on.
2039 if (event->group_flags & PERF_GROUP_SOFTWARE)
2042 * If an exclusive group is already on, no other hardware
2045 if (cpuctx->exclusive)
2048 * If this group is exclusive and there are already
2049 * events on the CPU, it can't go on.
2051 if (event->attr.exclusive && cpuctx->active_oncpu)
2054 * Otherwise, try to add it if all previous groups were able
2060 static void add_event_to_ctx(struct perf_event *event,
2061 struct perf_event_context *ctx)
2063 u64 tstamp = perf_event_time(event);
2065 list_add_event(event, ctx);
2066 perf_group_attach(event);
2067 event->tstamp_enabled = tstamp;
2068 event->tstamp_running = tstamp;
2069 event->tstamp_stopped = tstamp;
2072 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2073 struct perf_event_context *ctx);
2075 ctx_sched_in(struct perf_event_context *ctx,
2076 struct perf_cpu_context *cpuctx,
2077 enum event_type_t event_type,
2078 struct task_struct *task);
2080 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2081 struct perf_event_context *ctx,
2082 struct task_struct *task)
2084 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2086 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2087 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2089 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2092 static void ctx_resched(struct perf_cpu_context *cpuctx,
2093 struct perf_event_context *task_ctx)
2095 perf_pmu_disable(cpuctx->ctx.pmu);
2097 task_ctx_sched_out(cpuctx, task_ctx);
2098 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
2099 perf_event_sched_in(cpuctx, task_ctx, current);
2100 perf_pmu_enable(cpuctx->ctx.pmu);
2104 * Cross CPU call to install and enable a performance event
2106 * Must be called with ctx->mutex held
2108 static int __perf_install_in_context(void *info)
2110 struct perf_event_context *ctx = info;
2111 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2112 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2114 raw_spin_lock(&cpuctx->ctx.lock);
2116 raw_spin_lock(&ctx->lock);
2118 * If we hit the 'wrong' task, we've since scheduled and
2119 * everything should be sorted, nothing to do!
2122 if (ctx->task != current)
2126 * If task_ctx is set, it had better be to us.
2128 WARN_ON_ONCE(cpuctx->task_ctx != ctx && cpuctx->task_ctx);
2129 } else if (task_ctx) {
2130 raw_spin_lock(&task_ctx->lock);
2133 ctx_resched(cpuctx, task_ctx);
2135 perf_ctx_unlock(cpuctx, task_ctx);
2141 * Attach a performance event to a context
2144 perf_install_in_context(struct perf_event_context *ctx,
2145 struct perf_event *event,
2148 struct task_struct *task = NULL;
2150 lockdep_assert_held(&ctx->mutex);
2153 if (event->cpu != -1)
2157 * Installing events is tricky because we cannot rely on ctx->is_active
2158 * to be set in case this is the nr_events 0 -> 1 transition.
2160 * So what we do is we add the event to the list here, which will allow
2161 * a future context switch to DTRT and then send a racy IPI. If the IPI
2162 * fails to hit the right task, this means a context switch must have
2163 * happened and that will have taken care of business.
2165 raw_spin_lock_irq(&ctx->lock);
2169 * If between ctx = find_get_context() and mutex_lock(&ctx->mutex) the
2170 * ctx gets destroyed, we must not install an event into it.
2172 * This is normally tested for after we acquire the mutex, so this is
2175 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2176 raw_spin_unlock_irq(&ctx->lock);
2180 if (ctx->is_active) {
2181 update_context_time(ctx);
2182 update_cgrp_time_from_event(event);
2185 add_event_to_ctx(event, ctx);
2186 raw_spin_unlock_irq(&ctx->lock);
2189 task_function_call(task, __perf_install_in_context, ctx);
2191 cpu_function_call(cpu, __perf_install_in_context, ctx);
2195 * Put a event into inactive state and update time fields.
2196 * Enabling the leader of a group effectively enables all
2197 * the group members that aren't explicitly disabled, so we
2198 * have to update their ->tstamp_enabled also.
2199 * Note: this works for group members as well as group leaders
2200 * since the non-leader members' sibling_lists will be empty.
2202 static void __perf_event_mark_enabled(struct perf_event *event)
2204 struct perf_event *sub;
2205 u64 tstamp = perf_event_time(event);
2207 event->state = PERF_EVENT_STATE_INACTIVE;
2208 event->tstamp_enabled = tstamp - event->total_time_enabled;
2209 list_for_each_entry(sub, &event->sibling_list, group_entry) {
2210 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2211 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2216 * Cross CPU call to enable a performance event
2218 static void __perf_event_enable(struct perf_event *event,
2219 struct perf_cpu_context *cpuctx,
2220 struct perf_event_context *ctx,
2223 struct perf_event *leader = event->group_leader;
2224 struct perf_event_context *task_ctx;
2226 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2227 event->state <= PERF_EVENT_STATE_ERROR)
2230 update_context_time(ctx);
2231 __perf_event_mark_enabled(event);
2233 if (!ctx->is_active)
2236 if (!event_filter_match(event)) {
2237 if (is_cgroup_event(event)) {
2238 perf_cgroup_set_timestamp(current, ctx); // XXX ?
2239 perf_cgroup_defer_enabled(event);
2245 * If the event is in a group and isn't the group leader,
2246 * then don't put it on unless the group is on.
2248 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
2251 task_ctx = cpuctx->task_ctx;
2253 WARN_ON_ONCE(task_ctx != ctx);
2255 ctx_resched(cpuctx, task_ctx);
2261 * If event->ctx is a cloned context, callers must make sure that
2262 * every task struct that event->ctx->task could possibly point to
2263 * remains valid. This condition is satisfied when called through
2264 * perf_event_for_each_child or perf_event_for_each as described
2265 * for perf_event_disable.
2267 static void _perf_event_enable(struct perf_event *event)
2269 struct perf_event_context *ctx = event->ctx;
2271 raw_spin_lock_irq(&ctx->lock);
2272 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2273 event->state < PERF_EVENT_STATE_ERROR) {
2274 raw_spin_unlock_irq(&ctx->lock);
2279 * If the event is in error state, clear that first.
2281 * That way, if we see the event in error state below, we know that it
2282 * has gone back into error state, as distinct from the task having
2283 * been scheduled away before the cross-call arrived.
2285 if (event->state == PERF_EVENT_STATE_ERROR)
2286 event->state = PERF_EVENT_STATE_OFF;
2287 raw_spin_unlock_irq(&ctx->lock);
2289 event_function_call(event, __perf_event_enable, NULL);
2293 * See perf_event_disable();
2295 void perf_event_enable(struct perf_event *event)
2297 struct perf_event_context *ctx;
2299 ctx = perf_event_ctx_lock(event);
2300 _perf_event_enable(event);
2301 perf_event_ctx_unlock(event, ctx);
2303 EXPORT_SYMBOL_GPL(perf_event_enable);
2305 static int _perf_event_refresh(struct perf_event *event, int refresh)
2308 * not supported on inherited events
2310 if (event->attr.inherit || !is_sampling_event(event))
2313 atomic_add(refresh, &event->event_limit);
2314 _perf_event_enable(event);
2320 * See perf_event_disable()
2322 int perf_event_refresh(struct perf_event *event, int refresh)
2324 struct perf_event_context *ctx;
2327 ctx = perf_event_ctx_lock(event);
2328 ret = _perf_event_refresh(event, refresh);
2329 perf_event_ctx_unlock(event, ctx);
2333 EXPORT_SYMBOL_GPL(perf_event_refresh);
2335 static void ctx_sched_out(struct perf_event_context *ctx,
2336 struct perf_cpu_context *cpuctx,
2337 enum event_type_t event_type)
2339 int is_active = ctx->is_active;
2340 struct perf_event *event;
2342 lockdep_assert_held(&ctx->lock);
2344 if (likely(!ctx->nr_events)) {
2346 * See __perf_remove_from_context().
2348 WARN_ON_ONCE(ctx->is_active);
2350 WARN_ON_ONCE(cpuctx->task_ctx);
2354 ctx->is_active &= ~event_type;
2355 if (!(ctx->is_active & EVENT_ALL))
2359 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2360 if (!ctx->is_active)
2361 cpuctx->task_ctx = NULL;
2364 is_active ^= ctx->is_active; /* changed bits */
2366 if (is_active & EVENT_TIME) {
2367 /* update (and stop) ctx time */
2368 update_context_time(ctx);
2369 update_cgrp_time_from_cpuctx(cpuctx);
2372 if (!ctx->nr_active || !(is_active & EVENT_ALL))
2375 perf_pmu_disable(ctx->pmu);
2376 if (is_active & EVENT_PINNED) {
2377 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2378 group_sched_out(event, cpuctx, ctx);
2381 if (is_active & EVENT_FLEXIBLE) {
2382 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2383 group_sched_out(event, cpuctx, ctx);
2385 perf_pmu_enable(ctx->pmu);
2389 * Test whether two contexts are equivalent, i.e. whether they have both been
2390 * cloned from the same version of the same context.
2392 * Equivalence is measured using a generation number in the context that is
2393 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2394 * and list_del_event().
2396 static int context_equiv(struct perf_event_context *ctx1,
2397 struct perf_event_context *ctx2)
2399 lockdep_assert_held(&ctx1->lock);
2400 lockdep_assert_held(&ctx2->lock);
2402 /* Pinning disables the swap optimization */
2403 if (ctx1->pin_count || ctx2->pin_count)
2406 /* If ctx1 is the parent of ctx2 */
2407 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2410 /* If ctx2 is the parent of ctx1 */
2411 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2415 * If ctx1 and ctx2 have the same parent; we flatten the parent
2416 * hierarchy, see perf_event_init_context().
2418 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2419 ctx1->parent_gen == ctx2->parent_gen)
2426 static void __perf_event_sync_stat(struct perf_event *event,
2427 struct perf_event *next_event)
2431 if (!event->attr.inherit_stat)
2435 * Update the event value, we cannot use perf_event_read()
2436 * because we're in the middle of a context switch and have IRQs
2437 * disabled, which upsets smp_call_function_single(), however
2438 * we know the event must be on the current CPU, therefore we
2439 * don't need to use it.
2441 switch (event->state) {
2442 case PERF_EVENT_STATE_ACTIVE:
2443 event->pmu->read(event);
2446 case PERF_EVENT_STATE_INACTIVE:
2447 update_event_times(event);
2455 * In order to keep per-task stats reliable we need to flip the event
2456 * values when we flip the contexts.
2458 value = local64_read(&next_event->count);
2459 value = local64_xchg(&event->count, value);
2460 local64_set(&next_event->count, value);
2462 swap(event->total_time_enabled, next_event->total_time_enabled);
2463 swap(event->total_time_running, next_event->total_time_running);
2466 * Since we swizzled the values, update the user visible data too.
2468 perf_event_update_userpage(event);
2469 perf_event_update_userpage(next_event);
2472 static void perf_event_sync_stat(struct perf_event_context *ctx,
2473 struct perf_event_context *next_ctx)
2475 struct perf_event *event, *next_event;
2480 update_context_time(ctx);
2482 event = list_first_entry(&ctx->event_list,
2483 struct perf_event, event_entry);
2485 next_event = list_first_entry(&next_ctx->event_list,
2486 struct perf_event, event_entry);
2488 while (&event->event_entry != &ctx->event_list &&
2489 &next_event->event_entry != &next_ctx->event_list) {
2491 __perf_event_sync_stat(event, next_event);
2493 event = list_next_entry(event, event_entry);
2494 next_event = list_next_entry(next_event, event_entry);
2498 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2499 struct task_struct *next)
2501 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2502 struct perf_event_context *next_ctx;
2503 struct perf_event_context *parent, *next_parent;
2504 struct perf_cpu_context *cpuctx;
2510 cpuctx = __get_cpu_context(ctx);
2511 if (!cpuctx->task_ctx)
2515 next_ctx = next->perf_event_ctxp[ctxn];
2519 parent = rcu_dereference(ctx->parent_ctx);
2520 next_parent = rcu_dereference(next_ctx->parent_ctx);
2522 /* If neither context have a parent context; they cannot be clones. */
2523 if (!parent && !next_parent)
2526 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2528 * Looks like the two contexts are clones, so we might be
2529 * able to optimize the context switch. We lock both
2530 * contexts and check that they are clones under the
2531 * lock (including re-checking that neither has been
2532 * uncloned in the meantime). It doesn't matter which
2533 * order we take the locks because no other cpu could
2534 * be trying to lock both of these tasks.
2536 raw_spin_lock(&ctx->lock);
2537 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2538 if (context_equiv(ctx, next_ctx)) {
2539 WRITE_ONCE(ctx->task, next);
2540 WRITE_ONCE(next_ctx->task, task);
2542 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
2545 * RCU_INIT_POINTER here is safe because we've not
2546 * modified the ctx and the above modification of
2547 * ctx->task and ctx->task_ctx_data are immaterial
2548 * since those values are always verified under
2549 * ctx->lock which we're now holding.
2551 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
2552 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
2556 perf_event_sync_stat(ctx, next_ctx);
2558 raw_spin_unlock(&next_ctx->lock);
2559 raw_spin_unlock(&ctx->lock);
2565 raw_spin_lock(&ctx->lock);
2566 task_ctx_sched_out(cpuctx, ctx);
2567 raw_spin_unlock(&ctx->lock);
2571 void perf_sched_cb_dec(struct pmu *pmu)
2573 this_cpu_dec(perf_sched_cb_usages);
2576 void perf_sched_cb_inc(struct pmu *pmu)
2578 this_cpu_inc(perf_sched_cb_usages);
2582 * This function provides the context switch callback to the lower code
2583 * layer. It is invoked ONLY when the context switch callback is enabled.
2585 static void perf_pmu_sched_task(struct task_struct *prev,
2586 struct task_struct *next,
2589 struct perf_cpu_context *cpuctx;
2591 unsigned long flags;
2596 local_irq_save(flags);
2600 list_for_each_entry_rcu(pmu, &pmus, entry) {
2601 if (pmu->sched_task) {
2602 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2604 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2606 perf_pmu_disable(pmu);
2608 pmu->sched_task(cpuctx->task_ctx, sched_in);
2610 perf_pmu_enable(pmu);
2612 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2618 local_irq_restore(flags);
2621 static void perf_event_switch(struct task_struct *task,
2622 struct task_struct *next_prev, bool sched_in);
2624 #define for_each_task_context_nr(ctxn) \
2625 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2628 * Called from scheduler to remove the events of the current task,
2629 * with interrupts disabled.
2631 * We stop each event and update the event value in event->count.
2633 * This does not protect us against NMI, but disable()
2634 * sets the disabled bit in the control field of event _before_
2635 * accessing the event control register. If a NMI hits, then it will
2636 * not restart the event.
2638 void __perf_event_task_sched_out(struct task_struct *task,
2639 struct task_struct *next)
2643 if (__this_cpu_read(perf_sched_cb_usages))
2644 perf_pmu_sched_task(task, next, false);
2646 if (atomic_read(&nr_switch_events))
2647 perf_event_switch(task, next, false);
2649 for_each_task_context_nr(ctxn)
2650 perf_event_context_sched_out(task, ctxn, next);
2653 * if cgroup events exist on this CPU, then we need
2654 * to check if we have to switch out PMU state.
2655 * cgroup event are system-wide mode only
2657 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2658 perf_cgroup_sched_out(task, next);
2661 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2662 struct perf_event_context *ctx)
2664 if (!cpuctx->task_ctx)
2667 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2670 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2674 * Called with IRQs disabled
2676 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2677 enum event_type_t event_type)
2679 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2683 ctx_pinned_sched_in(struct perf_event_context *ctx,
2684 struct perf_cpu_context *cpuctx)
2686 struct perf_event *event;
2688 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2689 if (event->state <= PERF_EVENT_STATE_OFF)
2691 if (!event_filter_match(event))
2694 /* may need to reset tstamp_enabled */
2695 if (is_cgroup_event(event))
2696 perf_cgroup_mark_enabled(event, ctx);
2698 if (group_can_go_on(event, cpuctx, 1))
2699 group_sched_in(event, cpuctx, ctx);
2702 * If this pinned group hasn't been scheduled,
2703 * put it in error state.
2705 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2706 update_group_times(event);
2707 event->state = PERF_EVENT_STATE_ERROR;
2713 ctx_flexible_sched_in(struct perf_event_context *ctx,
2714 struct perf_cpu_context *cpuctx)
2716 struct perf_event *event;
2719 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2720 /* Ignore events in OFF or ERROR state */
2721 if (event->state <= PERF_EVENT_STATE_OFF)
2724 * Listen to the 'cpu' scheduling filter constraint
2727 if (!event_filter_match(event))
2730 /* may need to reset tstamp_enabled */
2731 if (is_cgroup_event(event))
2732 perf_cgroup_mark_enabled(event, ctx);
2734 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2735 if (group_sched_in(event, cpuctx, ctx))
2742 ctx_sched_in(struct perf_event_context *ctx,
2743 struct perf_cpu_context *cpuctx,
2744 enum event_type_t event_type,
2745 struct task_struct *task)
2747 int is_active = ctx->is_active;
2750 lockdep_assert_held(&ctx->lock);
2752 if (likely(!ctx->nr_events))
2755 ctx->is_active |= (event_type | EVENT_TIME);
2758 cpuctx->task_ctx = ctx;
2760 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2763 is_active ^= ctx->is_active; /* changed bits */
2765 if (is_active & EVENT_TIME) {
2766 /* start ctx time */
2768 ctx->timestamp = now;
2769 perf_cgroup_set_timestamp(task, ctx);
2773 * First go through the list and put on any pinned groups
2774 * in order to give them the best chance of going on.
2776 if (is_active & EVENT_PINNED)
2777 ctx_pinned_sched_in(ctx, cpuctx);
2779 /* Then walk through the lower prio flexible groups */
2780 if (is_active & EVENT_FLEXIBLE)
2781 ctx_flexible_sched_in(ctx, cpuctx);
2784 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2785 enum event_type_t event_type,
2786 struct task_struct *task)
2788 struct perf_event_context *ctx = &cpuctx->ctx;
2790 ctx_sched_in(ctx, cpuctx, event_type, task);
2793 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2794 struct task_struct *task)
2796 struct perf_cpu_context *cpuctx;
2798 cpuctx = __get_cpu_context(ctx);
2799 if (cpuctx->task_ctx == ctx)
2802 perf_ctx_lock(cpuctx, ctx);
2803 perf_pmu_disable(ctx->pmu);
2805 * We want to keep the following priority order:
2806 * cpu pinned (that don't need to move), task pinned,
2807 * cpu flexible, task flexible.
2809 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2810 perf_event_sched_in(cpuctx, ctx, task);
2811 perf_pmu_enable(ctx->pmu);
2812 perf_ctx_unlock(cpuctx, ctx);
2816 * Called from scheduler to add the events of the current task
2817 * with interrupts disabled.
2819 * We restore the event value and then enable it.
2821 * This does not protect us against NMI, but enable()
2822 * sets the enabled bit in the control field of event _before_
2823 * accessing the event control register. If a NMI hits, then it will
2824 * keep the event running.
2826 void __perf_event_task_sched_in(struct task_struct *prev,
2827 struct task_struct *task)
2829 struct perf_event_context *ctx;
2833 * If cgroup events exist on this CPU, then we need to check if we have
2834 * to switch in PMU state; cgroup event are system-wide mode only.
2836 * Since cgroup events are CPU events, we must schedule these in before
2837 * we schedule in the task events.
2839 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2840 perf_cgroup_sched_in(prev, task);
2842 for_each_task_context_nr(ctxn) {
2843 ctx = task->perf_event_ctxp[ctxn];
2847 perf_event_context_sched_in(ctx, task);
2850 if (atomic_read(&nr_switch_events))
2851 perf_event_switch(task, prev, true);
2853 if (__this_cpu_read(perf_sched_cb_usages))
2854 perf_pmu_sched_task(prev, task, true);
2857 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2859 u64 frequency = event->attr.sample_freq;
2860 u64 sec = NSEC_PER_SEC;
2861 u64 divisor, dividend;
2863 int count_fls, nsec_fls, frequency_fls, sec_fls;
2865 count_fls = fls64(count);
2866 nsec_fls = fls64(nsec);
2867 frequency_fls = fls64(frequency);
2871 * We got @count in @nsec, with a target of sample_freq HZ
2872 * the target period becomes:
2875 * period = -------------------
2876 * @nsec * sample_freq
2881 * Reduce accuracy by one bit such that @a and @b converge
2882 * to a similar magnitude.
2884 #define REDUCE_FLS(a, b) \
2886 if (a##_fls > b##_fls) { \
2896 * Reduce accuracy until either term fits in a u64, then proceed with
2897 * the other, so that finally we can do a u64/u64 division.
2899 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2900 REDUCE_FLS(nsec, frequency);
2901 REDUCE_FLS(sec, count);
2904 if (count_fls + sec_fls > 64) {
2905 divisor = nsec * frequency;
2907 while (count_fls + sec_fls > 64) {
2908 REDUCE_FLS(count, sec);
2912 dividend = count * sec;
2914 dividend = count * sec;
2916 while (nsec_fls + frequency_fls > 64) {
2917 REDUCE_FLS(nsec, frequency);
2921 divisor = nsec * frequency;
2927 return div64_u64(dividend, divisor);
2930 static DEFINE_PER_CPU(int, perf_throttled_count);
2931 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2933 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2935 struct hw_perf_event *hwc = &event->hw;
2936 s64 period, sample_period;
2939 period = perf_calculate_period(event, nsec, count);
2941 delta = (s64)(period - hwc->sample_period);
2942 delta = (delta + 7) / 8; /* low pass filter */
2944 sample_period = hwc->sample_period + delta;
2949 hwc->sample_period = sample_period;
2951 if (local64_read(&hwc->period_left) > 8*sample_period) {
2953 event->pmu->stop(event, PERF_EF_UPDATE);
2955 local64_set(&hwc->period_left, 0);
2958 event->pmu->start(event, PERF_EF_RELOAD);
2963 * combine freq adjustment with unthrottling to avoid two passes over the
2964 * events. At the same time, make sure, having freq events does not change
2965 * the rate of unthrottling as that would introduce bias.
2967 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
2970 struct perf_event *event;
2971 struct hw_perf_event *hwc;
2972 u64 now, period = TICK_NSEC;
2976 * only need to iterate over all events iff:
2977 * - context have events in frequency mode (needs freq adjust)
2978 * - there are events to unthrottle on this cpu
2980 if (!(ctx->nr_freq || needs_unthr))
2983 raw_spin_lock(&ctx->lock);
2984 perf_pmu_disable(ctx->pmu);
2986 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
2987 if (event->state != PERF_EVENT_STATE_ACTIVE)
2990 if (!event_filter_match(event))
2993 perf_pmu_disable(event->pmu);
2997 if (hwc->interrupts == MAX_INTERRUPTS) {
2998 hwc->interrupts = 0;
2999 perf_log_throttle(event, 1);
3000 event->pmu->start(event, 0);
3003 if (!event->attr.freq || !event->attr.sample_freq)
3007 * stop the event and update event->count
3009 event->pmu->stop(event, PERF_EF_UPDATE);
3011 now = local64_read(&event->count);
3012 delta = now - hwc->freq_count_stamp;
3013 hwc->freq_count_stamp = now;
3017 * reload only if value has changed
3018 * we have stopped the event so tell that
3019 * to perf_adjust_period() to avoid stopping it
3023 perf_adjust_period(event, period, delta, false);
3025 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3027 perf_pmu_enable(event->pmu);
3030 perf_pmu_enable(ctx->pmu);
3031 raw_spin_unlock(&ctx->lock);
3035 * Round-robin a context's events:
3037 static void rotate_ctx(struct perf_event_context *ctx)
3040 * Rotate the first entry last of non-pinned groups. Rotation might be
3041 * disabled by the inheritance code.
3043 if (!ctx->rotate_disable)
3044 list_rotate_left(&ctx->flexible_groups);
3047 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
3049 struct perf_event_context *ctx = NULL;
3052 if (cpuctx->ctx.nr_events) {
3053 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
3057 ctx = cpuctx->task_ctx;
3058 if (ctx && ctx->nr_events) {
3059 if (ctx->nr_events != ctx->nr_active)
3066 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3067 perf_pmu_disable(cpuctx->ctx.pmu);
3069 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3071 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
3073 rotate_ctx(&cpuctx->ctx);
3077 perf_event_sched_in(cpuctx, ctx, current);
3079 perf_pmu_enable(cpuctx->ctx.pmu);
3080 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3086 #ifdef CONFIG_NO_HZ_FULL
3087 bool perf_event_can_stop_tick(void)
3089 if (atomic_read(&nr_freq_events) ||
3090 __this_cpu_read(perf_throttled_count))
3097 void perf_event_task_tick(void)
3099 struct list_head *head = this_cpu_ptr(&active_ctx_list);
3100 struct perf_event_context *ctx, *tmp;
3103 WARN_ON(!irqs_disabled());
3105 __this_cpu_inc(perf_throttled_seq);
3106 throttled = __this_cpu_xchg(perf_throttled_count, 0);
3108 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
3109 perf_adjust_freq_unthr_context(ctx, throttled);
3112 static int event_enable_on_exec(struct perf_event *event,
3113 struct perf_event_context *ctx)
3115 if (!event->attr.enable_on_exec)
3118 event->attr.enable_on_exec = 0;
3119 if (event->state >= PERF_EVENT_STATE_INACTIVE)
3122 __perf_event_mark_enabled(event);
3128 * Enable all of a task's events that have been marked enable-on-exec.
3129 * This expects task == current.
3131 static void perf_event_enable_on_exec(int ctxn)
3133 struct perf_event_context *ctx, *clone_ctx = NULL;
3134 struct perf_cpu_context *cpuctx;
3135 struct perf_event *event;
3136 unsigned long flags;
3139 local_irq_save(flags);
3140 ctx = current->perf_event_ctxp[ctxn];
3141 if (!ctx || !ctx->nr_events)
3144 cpuctx = __get_cpu_context(ctx);
3145 perf_ctx_lock(cpuctx, ctx);
3146 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
3147 list_for_each_entry(event, &ctx->event_list, event_entry)
3148 enabled |= event_enable_on_exec(event, ctx);
3151 * Unclone and reschedule this context if we enabled any event.
3154 clone_ctx = unclone_ctx(ctx);
3155 ctx_resched(cpuctx, ctx);
3157 perf_ctx_unlock(cpuctx, ctx);
3160 local_irq_restore(flags);
3166 void perf_event_exec(void)
3171 for_each_task_context_nr(ctxn)
3172 perf_event_enable_on_exec(ctxn);
3176 struct perf_read_data {
3177 struct perf_event *event;
3183 * Cross CPU call to read the hardware event
3185 static void __perf_event_read(void *info)
3187 struct perf_read_data *data = info;
3188 struct perf_event *sub, *event = data->event;
3189 struct perf_event_context *ctx = event->ctx;
3190 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3191 struct pmu *pmu = event->pmu;
3194 * If this is a task context, we need to check whether it is
3195 * the current task context of this cpu. If not it has been
3196 * scheduled out before the smp call arrived. In that case
3197 * event->count would have been updated to a recent sample
3198 * when the event was scheduled out.
3200 if (ctx->task && cpuctx->task_ctx != ctx)
3203 raw_spin_lock(&ctx->lock);
3204 if (ctx->is_active) {
3205 update_context_time(ctx);
3206 update_cgrp_time_from_event(event);
3209 update_event_times(event);
3210 if (event->state != PERF_EVENT_STATE_ACTIVE)
3219 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
3223 list_for_each_entry(sub, &event->sibling_list, group_entry) {
3224 update_event_times(sub);
3225 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
3227 * Use sibling's PMU rather than @event's since
3228 * sibling could be on different (eg: software) PMU.
3230 sub->pmu->read(sub);
3234 data->ret = pmu->commit_txn(pmu);
3237 raw_spin_unlock(&ctx->lock);
3240 static inline u64 perf_event_count(struct perf_event *event)
3242 if (event->pmu->count)
3243 return event->pmu->count(event);
3245 return __perf_event_count(event);
3249 * NMI-safe method to read a local event, that is an event that
3251 * - either for the current task, or for this CPU
3252 * - does not have inherit set, for inherited task events
3253 * will not be local and we cannot read them atomically
3254 * - must not have a pmu::count method
3256 u64 perf_event_read_local(struct perf_event *event)
3258 unsigned long flags;
3262 * Disabling interrupts avoids all counter scheduling (context
3263 * switches, timer based rotation and IPIs).
3265 local_irq_save(flags);
3267 /* If this is a per-task event, it must be for current */
3268 WARN_ON_ONCE((event->attach_state & PERF_ATTACH_TASK) &&
3269 event->hw.target != current);
3271 /* If this is a per-CPU event, it must be for this CPU */
3272 WARN_ON_ONCE(!(event->attach_state & PERF_ATTACH_TASK) &&
3273 event->cpu != smp_processor_id());
3276 * It must not be an event with inherit set, we cannot read
3277 * all child counters from atomic context.
3279 WARN_ON_ONCE(event->attr.inherit);
3282 * It must not have a pmu::count method, those are not
3285 WARN_ON_ONCE(event->pmu->count);
3288 * If the event is currently on this CPU, its either a per-task event,
3289 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
3292 if (event->oncpu == smp_processor_id())
3293 event->pmu->read(event);
3295 val = local64_read(&event->count);
3296 local_irq_restore(flags);
3301 static int perf_event_read(struct perf_event *event, bool group)
3306 * If event is enabled and currently active on a CPU, update the
3307 * value in the event structure:
3309 if (event->state == PERF_EVENT_STATE_ACTIVE) {
3310 struct perf_read_data data = {
3315 smp_call_function_single(event->oncpu,
3316 __perf_event_read, &data, 1);
3318 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3319 struct perf_event_context *ctx = event->ctx;
3320 unsigned long flags;
3322 raw_spin_lock_irqsave(&ctx->lock, flags);
3324 * may read while context is not active
3325 * (e.g., thread is blocked), in that case
3326 * we cannot update context time
3328 if (ctx->is_active) {
3329 update_context_time(ctx);
3330 update_cgrp_time_from_event(event);
3333 update_group_times(event);
3335 update_event_times(event);
3336 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3343 * Initialize the perf_event context in a task_struct:
3345 static void __perf_event_init_context(struct perf_event_context *ctx)
3347 raw_spin_lock_init(&ctx->lock);
3348 mutex_init(&ctx->mutex);
3349 INIT_LIST_HEAD(&ctx->active_ctx_list);
3350 INIT_LIST_HEAD(&ctx->pinned_groups);
3351 INIT_LIST_HEAD(&ctx->flexible_groups);
3352 INIT_LIST_HEAD(&ctx->event_list);
3353 atomic_set(&ctx->refcount, 1);
3356 static struct perf_event_context *
3357 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3359 struct perf_event_context *ctx;
3361 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3365 __perf_event_init_context(ctx);
3368 get_task_struct(task);
3375 static struct task_struct *
3376 find_lively_task_by_vpid(pid_t vpid)
3378 struct task_struct *task;
3385 task = find_task_by_vpid(vpid);
3387 get_task_struct(task);
3391 return ERR_PTR(-ESRCH);
3393 /* Reuse ptrace permission checks for now. */
3395 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
3400 put_task_struct(task);
3401 return ERR_PTR(err);
3406 * Returns a matching context with refcount and pincount.
3408 static struct perf_event_context *
3409 find_get_context(struct pmu *pmu, struct task_struct *task,
3410 struct perf_event *event)
3412 struct perf_event_context *ctx, *clone_ctx = NULL;
3413 struct perf_cpu_context *cpuctx;
3414 void *task_ctx_data = NULL;
3415 unsigned long flags;
3417 int cpu = event->cpu;
3420 /* Must be root to operate on a CPU event: */
3421 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3422 return ERR_PTR(-EACCES);
3425 * We could be clever and allow to attach a event to an
3426 * offline CPU and activate it when the CPU comes up, but
3429 if (!cpu_online(cpu))
3430 return ERR_PTR(-ENODEV);
3432 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3441 ctxn = pmu->task_ctx_nr;
3445 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
3446 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
3447 if (!task_ctx_data) {
3454 ctx = perf_lock_task_context(task, ctxn, &flags);
3456 clone_ctx = unclone_ctx(ctx);
3459 if (task_ctx_data && !ctx->task_ctx_data) {
3460 ctx->task_ctx_data = task_ctx_data;
3461 task_ctx_data = NULL;
3463 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3468 ctx = alloc_perf_context(pmu, task);
3473 if (task_ctx_data) {
3474 ctx->task_ctx_data = task_ctx_data;
3475 task_ctx_data = NULL;
3479 mutex_lock(&task->perf_event_mutex);
3481 * If it has already passed perf_event_exit_task().
3482 * we must see PF_EXITING, it takes this mutex too.
3484 if (task->flags & PF_EXITING)
3486 else if (task->perf_event_ctxp[ctxn])
3491 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3493 mutex_unlock(&task->perf_event_mutex);
3495 if (unlikely(err)) {
3504 kfree(task_ctx_data);
3508 kfree(task_ctx_data);
3509 return ERR_PTR(err);
3512 static void perf_event_free_filter(struct perf_event *event);
3513 static void perf_event_free_bpf_prog(struct perf_event *event);
3515 static void free_event_rcu(struct rcu_head *head)
3517 struct perf_event *event;
3519 event = container_of(head, struct perf_event, rcu_head);
3521 put_pid_ns(event->ns);
3522 perf_event_free_filter(event);
3526 static void ring_buffer_attach(struct perf_event *event,
3527 struct ring_buffer *rb);
3529 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3534 if (is_cgroup_event(event))
3535 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3538 static void unaccount_event(struct perf_event *event)
3545 if (event->attach_state & PERF_ATTACH_TASK)
3547 if (event->attr.mmap || event->attr.mmap_data)
3548 atomic_dec(&nr_mmap_events);
3549 if (event->attr.comm)
3550 atomic_dec(&nr_comm_events);
3551 if (event->attr.task)
3552 atomic_dec(&nr_task_events);
3553 if (event->attr.freq)
3554 atomic_dec(&nr_freq_events);
3555 if (event->attr.context_switch) {
3557 atomic_dec(&nr_switch_events);
3559 if (is_cgroup_event(event))
3561 if (has_branch_stack(event))
3565 if (!atomic_add_unless(&perf_sched_count, -1, 1))
3566 schedule_delayed_work(&perf_sched_work, HZ);
3569 unaccount_event_cpu(event, event->cpu);
3572 static void perf_sched_delayed(struct work_struct *work)
3574 mutex_lock(&perf_sched_mutex);
3575 if (atomic_dec_and_test(&perf_sched_count))
3576 static_branch_disable(&perf_sched_events);
3577 mutex_unlock(&perf_sched_mutex);
3581 * The following implement mutual exclusion of events on "exclusive" pmus
3582 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
3583 * at a time, so we disallow creating events that might conflict, namely:
3585 * 1) cpu-wide events in the presence of per-task events,
3586 * 2) per-task events in the presence of cpu-wide events,
3587 * 3) two matching events on the same context.
3589 * The former two cases are handled in the allocation path (perf_event_alloc(),
3590 * _free_event()), the latter -- before the first perf_install_in_context().
3592 static int exclusive_event_init(struct perf_event *event)
3594 struct pmu *pmu = event->pmu;
3596 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3600 * Prevent co-existence of per-task and cpu-wide events on the
3601 * same exclusive pmu.
3603 * Negative pmu::exclusive_cnt means there are cpu-wide
3604 * events on this "exclusive" pmu, positive means there are
3607 * Since this is called in perf_event_alloc() path, event::ctx
3608 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
3609 * to mean "per-task event", because unlike other attach states it
3610 * never gets cleared.
3612 if (event->attach_state & PERF_ATTACH_TASK) {
3613 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
3616 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
3623 static void exclusive_event_destroy(struct perf_event *event)
3625 struct pmu *pmu = event->pmu;
3627 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3630 /* see comment in exclusive_event_init() */
3631 if (event->attach_state & PERF_ATTACH_TASK)
3632 atomic_dec(&pmu->exclusive_cnt);
3634 atomic_inc(&pmu->exclusive_cnt);
3637 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
3639 if ((e1->pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) &&
3640 (e1->cpu == e2->cpu ||
3647 /* Called under the same ctx::mutex as perf_install_in_context() */
3648 static bool exclusive_event_installable(struct perf_event *event,
3649 struct perf_event_context *ctx)
3651 struct perf_event *iter_event;
3652 struct pmu *pmu = event->pmu;
3654 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3657 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
3658 if (exclusive_event_match(iter_event, event))
3665 static void _free_event(struct perf_event *event)
3667 irq_work_sync(&event->pending);
3669 unaccount_event(event);
3673 * Can happen when we close an event with re-directed output.
3675 * Since we have a 0 refcount, perf_mmap_close() will skip
3676 * over us; possibly making our ring_buffer_put() the last.
3678 mutex_lock(&event->mmap_mutex);
3679 ring_buffer_attach(event, NULL);
3680 mutex_unlock(&event->mmap_mutex);
3683 if (is_cgroup_event(event))
3684 perf_detach_cgroup(event);
3686 if (!event->parent) {
3687 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3688 put_callchain_buffers();
3691 perf_event_free_bpf_prog(event);
3694 event->destroy(event);
3697 put_ctx(event->ctx);
3700 exclusive_event_destroy(event);
3701 module_put(event->pmu->module);
3704 call_rcu(&event->rcu_head, free_event_rcu);
3708 * Used to free events which have a known refcount of 1, such as in error paths
3709 * where the event isn't exposed yet and inherited events.
3711 static void free_event(struct perf_event *event)
3713 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3714 "unexpected event refcount: %ld; ptr=%p\n",
3715 atomic_long_read(&event->refcount), event)) {
3716 /* leak to avoid use-after-free */
3724 * Remove user event from the owner task.
3726 static void perf_remove_from_owner(struct perf_event *event)
3728 struct task_struct *owner;
3732 * Matches the smp_store_release() in perf_event_exit_task(). If we
3733 * observe !owner it means the list deletion is complete and we can
3734 * indeed free this event, otherwise we need to serialize on
3735 * owner->perf_event_mutex.
3737 owner = lockless_dereference(event->owner);
3740 * Since delayed_put_task_struct() also drops the last
3741 * task reference we can safely take a new reference
3742 * while holding the rcu_read_lock().
3744 get_task_struct(owner);
3750 * If we're here through perf_event_exit_task() we're already
3751 * holding ctx->mutex which would be an inversion wrt. the
3752 * normal lock order.
3754 * However we can safely take this lock because its the child
3757 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
3760 * We have to re-check the event->owner field, if it is cleared
3761 * we raced with perf_event_exit_task(), acquiring the mutex
3762 * ensured they're done, and we can proceed with freeing the
3766 list_del_init(&event->owner_entry);
3767 smp_store_release(&event->owner, NULL);
3769 mutex_unlock(&owner->perf_event_mutex);
3770 put_task_struct(owner);
3774 static void put_event(struct perf_event *event)
3776 if (!atomic_long_dec_and_test(&event->refcount))
3783 * Kill an event dead; while event:refcount will preserve the event
3784 * object, it will not preserve its functionality. Once the last 'user'
3785 * gives up the object, we'll destroy the thing.
3787 int perf_event_release_kernel(struct perf_event *event)
3789 struct perf_event_context *ctx = event->ctx;
3790 struct perf_event *child, *tmp;
3793 * If we got here through err_file: fput(event_file); we will not have
3794 * attached to a context yet.
3797 WARN_ON_ONCE(event->attach_state &
3798 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
3802 if (!is_kernel_event(event))
3803 perf_remove_from_owner(event);
3805 ctx = perf_event_ctx_lock(event);
3806 WARN_ON_ONCE(ctx->parent_ctx);
3807 perf_remove_from_context(event, DETACH_GROUP);
3809 raw_spin_lock_irq(&ctx->lock);
3811 * Mark this even as STATE_DEAD, there is no external reference to it
3814 * Anybody acquiring event->child_mutex after the below loop _must_
3815 * also see this, most importantly inherit_event() which will avoid
3816 * placing more children on the list.
3818 * Thus this guarantees that we will in fact observe and kill _ALL_
3821 event->state = PERF_EVENT_STATE_DEAD;
3822 raw_spin_unlock_irq(&ctx->lock);
3824 perf_event_ctx_unlock(event, ctx);
3827 mutex_lock(&event->child_mutex);
3828 list_for_each_entry(child, &event->child_list, child_list) {
3831 * Cannot change, child events are not migrated, see the
3832 * comment with perf_event_ctx_lock_nested().
3834 ctx = lockless_dereference(child->ctx);
3836 * Since child_mutex nests inside ctx::mutex, we must jump
3837 * through hoops. We start by grabbing a reference on the ctx.
3839 * Since the event cannot get freed while we hold the
3840 * child_mutex, the context must also exist and have a !0
3846 * Now that we have a ctx ref, we can drop child_mutex, and
3847 * acquire ctx::mutex without fear of it going away. Then we
3848 * can re-acquire child_mutex.
3850 mutex_unlock(&event->child_mutex);
3851 mutex_lock(&ctx->mutex);
3852 mutex_lock(&event->child_mutex);
3855 * Now that we hold ctx::mutex and child_mutex, revalidate our
3856 * state, if child is still the first entry, it didn't get freed
3857 * and we can continue doing so.
3859 tmp = list_first_entry_or_null(&event->child_list,
3860 struct perf_event, child_list);
3862 perf_remove_from_context(child, DETACH_GROUP);
3863 list_del(&child->child_list);
3866 * This matches the refcount bump in inherit_event();
3867 * this can't be the last reference.
3872 mutex_unlock(&event->child_mutex);
3873 mutex_unlock(&ctx->mutex);
3877 mutex_unlock(&event->child_mutex);
3880 put_event(event); /* Must be the 'last' reference */
3883 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3886 * Called when the last reference to the file is gone.
3888 static int perf_release(struct inode *inode, struct file *file)
3890 perf_event_release_kernel(file->private_data);
3894 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3896 struct perf_event *child;
3902 mutex_lock(&event->child_mutex);
3904 (void)perf_event_read(event, false);
3905 total += perf_event_count(event);
3907 *enabled += event->total_time_enabled +
3908 atomic64_read(&event->child_total_time_enabled);
3909 *running += event->total_time_running +
3910 atomic64_read(&event->child_total_time_running);
3912 list_for_each_entry(child, &event->child_list, child_list) {
3913 (void)perf_event_read(child, false);
3914 total += perf_event_count(child);
3915 *enabled += child->total_time_enabled;
3916 *running += child->total_time_running;
3918 mutex_unlock(&event->child_mutex);
3922 EXPORT_SYMBOL_GPL(perf_event_read_value);
3924 static int __perf_read_group_add(struct perf_event *leader,
3925 u64 read_format, u64 *values)
3927 struct perf_event *sub;
3928 int n = 1; /* skip @nr */
3931 ret = perf_event_read(leader, true);
3936 * Since we co-schedule groups, {enabled,running} times of siblings
3937 * will be identical to those of the leader, so we only publish one
3940 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
3941 values[n++] += leader->total_time_enabled +
3942 atomic64_read(&leader->child_total_time_enabled);
3945 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
3946 values[n++] += leader->total_time_running +
3947 atomic64_read(&leader->child_total_time_running);
3951 * Write {count,id} tuples for every sibling.
3953 values[n++] += perf_event_count(leader);
3954 if (read_format & PERF_FORMAT_ID)
3955 values[n++] = primary_event_id(leader);
3957 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3958 values[n++] += perf_event_count(sub);
3959 if (read_format & PERF_FORMAT_ID)
3960 values[n++] = primary_event_id(sub);
3966 static int perf_read_group(struct perf_event *event,
3967 u64 read_format, char __user *buf)
3969 struct perf_event *leader = event->group_leader, *child;
3970 struct perf_event_context *ctx = leader->ctx;
3974 lockdep_assert_held(&ctx->mutex);
3976 values = kzalloc(event->read_size, GFP_KERNEL);
3980 values[0] = 1 + leader->nr_siblings;
3983 * By locking the child_mutex of the leader we effectively
3984 * lock the child list of all siblings.. XXX explain how.
3986 mutex_lock(&leader->child_mutex);
3988 ret = __perf_read_group_add(leader, read_format, values);
3992 list_for_each_entry(child, &leader->child_list, child_list) {
3993 ret = __perf_read_group_add(child, read_format, values);
3998 mutex_unlock(&leader->child_mutex);
4000 ret = event->read_size;
4001 if (copy_to_user(buf, values, event->read_size))
4006 mutex_unlock(&leader->child_mutex);
4012 static int perf_read_one(struct perf_event *event,
4013 u64 read_format, char __user *buf)
4015 u64 enabled, running;
4019 values[n++] = perf_event_read_value(event, &enabled, &running);
4020 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4021 values[n++] = enabled;
4022 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4023 values[n++] = running;
4024 if (read_format & PERF_FORMAT_ID)
4025 values[n++] = primary_event_id(event);
4027 if (copy_to_user(buf, values, n * sizeof(u64)))
4030 return n * sizeof(u64);
4033 static bool is_event_hup(struct perf_event *event)
4037 if (event->state > PERF_EVENT_STATE_EXIT)
4040 mutex_lock(&event->child_mutex);
4041 no_children = list_empty(&event->child_list);
4042 mutex_unlock(&event->child_mutex);
4047 * Read the performance event - simple non blocking version for now
4050 __perf_read(struct perf_event *event, char __user *buf, size_t count)
4052 u64 read_format = event->attr.read_format;
4056 * Return end-of-file for a read on a event that is in
4057 * error state (i.e. because it was pinned but it couldn't be
4058 * scheduled on to the CPU at some point).
4060 if (event->state == PERF_EVENT_STATE_ERROR)
4063 if (count < event->read_size)
4066 WARN_ON_ONCE(event->ctx->parent_ctx);
4067 if (read_format & PERF_FORMAT_GROUP)
4068 ret = perf_read_group(event, read_format, buf);
4070 ret = perf_read_one(event, read_format, buf);
4076 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
4078 struct perf_event *event = file->private_data;
4079 struct perf_event_context *ctx;
4082 ctx = perf_event_ctx_lock(event);
4083 ret = __perf_read(event, buf, count);
4084 perf_event_ctx_unlock(event, ctx);
4089 static unsigned int perf_poll(struct file *file, poll_table *wait)
4091 struct perf_event *event = file->private_data;
4092 struct ring_buffer *rb;
4093 unsigned int events = POLLHUP;
4095 poll_wait(file, &event->waitq, wait);
4097 if (is_event_hup(event))
4101 * Pin the event->rb by taking event->mmap_mutex; otherwise
4102 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
4104 mutex_lock(&event->mmap_mutex);
4107 events = atomic_xchg(&rb->poll, 0);
4108 mutex_unlock(&event->mmap_mutex);
4112 static void _perf_event_reset(struct perf_event *event)
4114 (void)perf_event_read(event, false);
4115 local64_set(&event->count, 0);
4116 perf_event_update_userpage(event);
4120 * Holding the top-level event's child_mutex means that any
4121 * descendant process that has inherited this event will block
4122 * in perf_event_exit_event() if it goes to exit, thus satisfying the
4123 * task existence requirements of perf_event_enable/disable.
4125 static void perf_event_for_each_child(struct perf_event *event,
4126 void (*func)(struct perf_event *))
4128 struct perf_event *child;
4130 WARN_ON_ONCE(event->ctx->parent_ctx);
4132 mutex_lock(&event->child_mutex);
4134 list_for_each_entry(child, &event->child_list, child_list)
4136 mutex_unlock(&event->child_mutex);
4139 static void perf_event_for_each(struct perf_event *event,
4140 void (*func)(struct perf_event *))
4142 struct perf_event_context *ctx = event->ctx;
4143 struct perf_event *sibling;
4145 lockdep_assert_held(&ctx->mutex);
4147 event = event->group_leader;
4149 perf_event_for_each_child(event, func);
4150 list_for_each_entry(sibling, &event->sibling_list, group_entry)
4151 perf_event_for_each_child(sibling, func);
4154 static void __perf_event_period(struct perf_event *event,
4155 struct perf_cpu_context *cpuctx,
4156 struct perf_event_context *ctx,
4159 u64 value = *((u64 *)info);
4162 if (event->attr.freq) {
4163 event->attr.sample_freq = value;
4165 event->attr.sample_period = value;
4166 event->hw.sample_period = value;
4169 active = (event->state == PERF_EVENT_STATE_ACTIVE);
4171 perf_pmu_disable(ctx->pmu);
4172 event->pmu->stop(event, PERF_EF_UPDATE);
4175 local64_set(&event->hw.period_left, 0);
4178 event->pmu->start(event, PERF_EF_RELOAD);
4179 perf_pmu_enable(ctx->pmu);
4183 static int perf_event_period(struct perf_event *event, u64 __user *arg)
4187 if (!is_sampling_event(event))
4190 if (copy_from_user(&value, arg, sizeof(value)))
4196 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
4199 event_function_call(event, __perf_event_period, &value);
4204 static const struct file_operations perf_fops;
4206 static inline int perf_fget_light(int fd, struct fd *p)
4208 struct fd f = fdget(fd);
4212 if (f.file->f_op != &perf_fops) {
4220 static int perf_event_set_output(struct perf_event *event,
4221 struct perf_event *output_event);
4222 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
4223 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
4225 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
4227 void (*func)(struct perf_event *);
4231 case PERF_EVENT_IOC_ENABLE:
4232 func = _perf_event_enable;
4234 case PERF_EVENT_IOC_DISABLE:
4235 func = _perf_event_disable;
4237 case PERF_EVENT_IOC_RESET:
4238 func = _perf_event_reset;
4241 case PERF_EVENT_IOC_REFRESH:
4242 return _perf_event_refresh(event, arg);
4244 case PERF_EVENT_IOC_PERIOD:
4245 return perf_event_period(event, (u64 __user *)arg);
4247 case PERF_EVENT_IOC_ID:
4249 u64 id = primary_event_id(event);
4251 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
4256 case PERF_EVENT_IOC_SET_OUTPUT:
4260 struct perf_event *output_event;
4262 ret = perf_fget_light(arg, &output);
4265 output_event = output.file->private_data;
4266 ret = perf_event_set_output(event, output_event);
4269 ret = perf_event_set_output(event, NULL);
4274 case PERF_EVENT_IOC_SET_FILTER:
4275 return perf_event_set_filter(event, (void __user *)arg);
4277 case PERF_EVENT_IOC_SET_BPF:
4278 return perf_event_set_bpf_prog(event, arg);
4284 if (flags & PERF_IOC_FLAG_GROUP)
4285 perf_event_for_each(event, func);
4287 perf_event_for_each_child(event, func);
4292 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4294 struct perf_event *event = file->private_data;
4295 struct perf_event_context *ctx;
4298 ctx = perf_event_ctx_lock(event);
4299 ret = _perf_ioctl(event, cmd, arg);
4300 perf_event_ctx_unlock(event, ctx);
4305 #ifdef CONFIG_COMPAT
4306 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
4309 switch (_IOC_NR(cmd)) {
4310 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
4311 case _IOC_NR(PERF_EVENT_IOC_ID):
4312 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
4313 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
4314 cmd &= ~IOCSIZE_MASK;
4315 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
4319 return perf_ioctl(file, cmd, arg);
4322 # define perf_compat_ioctl NULL
4325 int perf_event_task_enable(void)
4327 struct perf_event_context *ctx;
4328 struct perf_event *event;
4330 mutex_lock(¤t->perf_event_mutex);
4331 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4332 ctx = perf_event_ctx_lock(event);
4333 perf_event_for_each_child(event, _perf_event_enable);
4334 perf_event_ctx_unlock(event, ctx);
4336 mutex_unlock(¤t->perf_event_mutex);
4341 int perf_event_task_disable(void)
4343 struct perf_event_context *ctx;
4344 struct perf_event *event;
4346 mutex_lock(¤t->perf_event_mutex);
4347 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4348 ctx = perf_event_ctx_lock(event);
4349 perf_event_for_each_child(event, _perf_event_disable);
4350 perf_event_ctx_unlock(event, ctx);
4352 mutex_unlock(¤t->perf_event_mutex);
4357 static int perf_event_index(struct perf_event *event)
4359 if (event->hw.state & PERF_HES_STOPPED)
4362 if (event->state != PERF_EVENT_STATE_ACTIVE)
4365 return event->pmu->event_idx(event);
4368 static void calc_timer_values(struct perf_event *event,
4375 *now = perf_clock();
4376 ctx_time = event->shadow_ctx_time + *now;
4377 *enabled = ctx_time - event->tstamp_enabled;
4378 *running = ctx_time - event->tstamp_running;
4381 static void perf_event_init_userpage(struct perf_event *event)
4383 struct perf_event_mmap_page *userpg;
4384 struct ring_buffer *rb;
4387 rb = rcu_dereference(event->rb);
4391 userpg = rb->user_page;
4393 /* Allow new userspace to detect that bit 0 is deprecated */
4394 userpg->cap_bit0_is_deprecated = 1;
4395 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
4396 userpg->data_offset = PAGE_SIZE;
4397 userpg->data_size = perf_data_size(rb);
4403 void __weak arch_perf_update_userpage(
4404 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
4409 * Callers need to ensure there can be no nesting of this function, otherwise
4410 * the seqlock logic goes bad. We can not serialize this because the arch
4411 * code calls this from NMI context.
4413 void perf_event_update_userpage(struct perf_event *event)
4415 struct perf_event_mmap_page *userpg;
4416 struct ring_buffer *rb;
4417 u64 enabled, running, now;
4420 rb = rcu_dereference(event->rb);
4425 * compute total_time_enabled, total_time_running
4426 * based on snapshot values taken when the event
4427 * was last scheduled in.
4429 * we cannot simply called update_context_time()
4430 * because of locking issue as we can be called in
4433 calc_timer_values(event, &now, &enabled, &running);
4435 userpg = rb->user_page;
4437 * Disable preemption so as to not let the corresponding user-space
4438 * spin too long if we get preempted.
4443 userpg->index = perf_event_index(event);
4444 userpg->offset = perf_event_count(event);
4446 userpg->offset -= local64_read(&event->hw.prev_count);
4448 userpg->time_enabled = enabled +
4449 atomic64_read(&event->child_total_time_enabled);
4451 userpg->time_running = running +
4452 atomic64_read(&event->child_total_time_running);
4454 arch_perf_update_userpage(event, userpg, now);
4463 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
4465 struct perf_event *event = vma->vm_file->private_data;
4466 struct ring_buffer *rb;
4467 int ret = VM_FAULT_SIGBUS;
4469 if (vmf->flags & FAULT_FLAG_MKWRITE) {
4470 if (vmf->pgoff == 0)
4476 rb = rcu_dereference(event->rb);
4480 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
4483 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
4487 get_page(vmf->page);
4488 vmf->page->mapping = vma->vm_file->f_mapping;
4489 vmf->page->index = vmf->pgoff;
4498 static void ring_buffer_attach(struct perf_event *event,
4499 struct ring_buffer *rb)
4501 struct ring_buffer *old_rb = NULL;
4502 unsigned long flags;
4506 * Should be impossible, we set this when removing
4507 * event->rb_entry and wait/clear when adding event->rb_entry.
4509 WARN_ON_ONCE(event->rcu_pending);
4512 spin_lock_irqsave(&old_rb->event_lock, flags);
4513 list_del_rcu(&event->rb_entry);
4514 spin_unlock_irqrestore(&old_rb->event_lock, flags);
4516 event->rcu_batches = get_state_synchronize_rcu();
4517 event->rcu_pending = 1;
4521 if (event->rcu_pending) {
4522 cond_synchronize_rcu(event->rcu_batches);
4523 event->rcu_pending = 0;
4526 spin_lock_irqsave(&rb->event_lock, flags);
4527 list_add_rcu(&event->rb_entry, &rb->event_list);
4528 spin_unlock_irqrestore(&rb->event_lock, flags);
4531 rcu_assign_pointer(event->rb, rb);
4534 ring_buffer_put(old_rb);
4536 * Since we detached before setting the new rb, so that we
4537 * could attach the new rb, we could have missed a wakeup.
4540 wake_up_all(&event->waitq);
4544 static void ring_buffer_wakeup(struct perf_event *event)
4546 struct ring_buffer *rb;
4549 rb = rcu_dereference(event->rb);
4551 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
4552 wake_up_all(&event->waitq);
4557 struct ring_buffer *ring_buffer_get(struct perf_event *event)
4559 struct ring_buffer *rb;
4562 rb = rcu_dereference(event->rb);
4564 if (!atomic_inc_not_zero(&rb->refcount))
4572 void ring_buffer_put(struct ring_buffer *rb)
4574 if (!atomic_dec_and_test(&rb->refcount))
4577 WARN_ON_ONCE(!list_empty(&rb->event_list));
4579 call_rcu(&rb->rcu_head, rb_free_rcu);
4582 static void perf_mmap_open(struct vm_area_struct *vma)
4584 struct perf_event *event = vma->vm_file->private_data;
4586 atomic_inc(&event->mmap_count);
4587 atomic_inc(&event->rb->mmap_count);
4590 atomic_inc(&event->rb->aux_mmap_count);
4592 if (event->pmu->event_mapped)
4593 event->pmu->event_mapped(event);
4597 * A buffer can be mmap()ed multiple times; either directly through the same
4598 * event, or through other events by use of perf_event_set_output().
4600 * In order to undo the VM accounting done by perf_mmap() we need to destroy
4601 * the buffer here, where we still have a VM context. This means we need
4602 * to detach all events redirecting to us.
4604 static void perf_mmap_close(struct vm_area_struct *vma)
4606 struct perf_event *event = vma->vm_file->private_data;
4608 struct ring_buffer *rb = ring_buffer_get(event);
4609 struct user_struct *mmap_user = rb->mmap_user;
4610 int mmap_locked = rb->mmap_locked;
4611 unsigned long size = perf_data_size(rb);
4613 if (event->pmu->event_unmapped)
4614 event->pmu->event_unmapped(event);
4617 * rb->aux_mmap_count will always drop before rb->mmap_count and
4618 * event->mmap_count, so it is ok to use event->mmap_mutex to
4619 * serialize with perf_mmap here.
4621 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
4622 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
4623 atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
4624 vma->vm_mm->pinned_vm -= rb->aux_mmap_locked;
4627 mutex_unlock(&event->mmap_mutex);
4630 atomic_dec(&rb->mmap_count);
4632 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
4635 ring_buffer_attach(event, NULL);
4636 mutex_unlock(&event->mmap_mutex);
4638 /* If there's still other mmap()s of this buffer, we're done. */
4639 if (atomic_read(&rb->mmap_count))
4643 * No other mmap()s, detach from all other events that might redirect
4644 * into the now unreachable buffer. Somewhat complicated by the
4645 * fact that rb::event_lock otherwise nests inside mmap_mutex.
4649 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4650 if (!atomic_long_inc_not_zero(&event->refcount)) {
4652 * This event is en-route to free_event() which will
4653 * detach it and remove it from the list.
4659 mutex_lock(&event->mmap_mutex);
4661 * Check we didn't race with perf_event_set_output() which can
4662 * swizzle the rb from under us while we were waiting to
4663 * acquire mmap_mutex.
4665 * If we find a different rb; ignore this event, a next
4666 * iteration will no longer find it on the list. We have to
4667 * still restart the iteration to make sure we're not now
4668 * iterating the wrong list.
4670 if (event->rb == rb)
4671 ring_buffer_attach(event, NULL);
4673 mutex_unlock(&event->mmap_mutex);
4677 * Restart the iteration; either we're on the wrong list or
4678 * destroyed its integrity by doing a deletion.
4685 * It could be there's still a few 0-ref events on the list; they'll
4686 * get cleaned up by free_event() -- they'll also still have their
4687 * ref on the rb and will free it whenever they are done with it.
4689 * Aside from that, this buffer is 'fully' detached and unmapped,
4690 * undo the VM accounting.
4693 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4694 vma->vm_mm->pinned_vm -= mmap_locked;
4695 free_uid(mmap_user);
4698 ring_buffer_put(rb); /* could be last */
4701 static const struct vm_operations_struct perf_mmap_vmops = {
4702 .open = perf_mmap_open,
4703 .close = perf_mmap_close, /* non mergable */
4704 .fault = perf_mmap_fault,
4705 .page_mkwrite = perf_mmap_fault,
4708 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
4710 struct perf_event *event = file->private_data;
4711 unsigned long user_locked, user_lock_limit;
4712 struct user_struct *user = current_user();
4713 unsigned long locked, lock_limit;
4714 struct ring_buffer *rb = NULL;
4715 unsigned long vma_size;
4716 unsigned long nr_pages;
4717 long user_extra = 0, extra = 0;
4718 int ret = 0, flags = 0;
4721 * Don't allow mmap() of inherited per-task counters. This would
4722 * create a performance issue due to all children writing to the
4725 if (event->cpu == -1 && event->attr.inherit)
4728 if (!(vma->vm_flags & VM_SHARED))
4731 vma_size = vma->vm_end - vma->vm_start;
4733 if (vma->vm_pgoff == 0) {
4734 nr_pages = (vma_size / PAGE_SIZE) - 1;
4737 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
4738 * mapped, all subsequent mappings should have the same size
4739 * and offset. Must be above the normal perf buffer.
4741 u64 aux_offset, aux_size;
4746 nr_pages = vma_size / PAGE_SIZE;
4748 mutex_lock(&event->mmap_mutex);
4755 aux_offset = ACCESS_ONCE(rb->user_page->aux_offset);
4756 aux_size = ACCESS_ONCE(rb->user_page->aux_size);
4758 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
4761 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
4764 /* already mapped with a different offset */
4765 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
4768 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
4771 /* already mapped with a different size */
4772 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
4775 if (!is_power_of_2(nr_pages))
4778 if (!atomic_inc_not_zero(&rb->mmap_count))
4781 if (rb_has_aux(rb)) {
4782 atomic_inc(&rb->aux_mmap_count);
4787 atomic_set(&rb->aux_mmap_count, 1);
4788 user_extra = nr_pages;
4794 * If we have rb pages ensure they're a power-of-two number, so we
4795 * can do bitmasks instead of modulo.
4797 if (nr_pages != 0 && !is_power_of_2(nr_pages))
4800 if (vma_size != PAGE_SIZE * (1 + nr_pages))
4803 WARN_ON_ONCE(event->ctx->parent_ctx);
4805 mutex_lock(&event->mmap_mutex);
4807 if (event->rb->nr_pages != nr_pages) {
4812 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4814 * Raced against perf_mmap_close() through
4815 * perf_event_set_output(). Try again, hope for better
4818 mutex_unlock(&event->mmap_mutex);
4825 user_extra = nr_pages + 1;
4828 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
4831 * Increase the limit linearly with more CPUs:
4833 user_lock_limit *= num_online_cpus();
4835 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
4837 if (user_locked > user_lock_limit)
4838 extra = user_locked - user_lock_limit;
4840 lock_limit = rlimit(RLIMIT_MEMLOCK);
4841 lock_limit >>= PAGE_SHIFT;
4842 locked = vma->vm_mm->pinned_vm + extra;
4844 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
4845 !capable(CAP_IPC_LOCK)) {
4850 WARN_ON(!rb && event->rb);
4852 if (vma->vm_flags & VM_WRITE)
4853 flags |= RING_BUFFER_WRITABLE;
4856 rb = rb_alloc(nr_pages,
4857 event->attr.watermark ? event->attr.wakeup_watermark : 0,
4865 atomic_set(&rb->mmap_count, 1);
4866 rb->mmap_user = get_current_user();
4867 rb->mmap_locked = extra;
4869 ring_buffer_attach(event, rb);
4871 perf_event_init_userpage(event);
4872 perf_event_update_userpage(event);
4874 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
4875 event->attr.aux_watermark, flags);
4877 rb->aux_mmap_locked = extra;
4882 atomic_long_add(user_extra, &user->locked_vm);
4883 vma->vm_mm->pinned_vm += extra;
4885 atomic_inc(&event->mmap_count);
4887 atomic_dec(&rb->mmap_count);
4890 mutex_unlock(&event->mmap_mutex);
4893 * Since pinned accounting is per vm we cannot allow fork() to copy our
4896 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
4897 vma->vm_ops = &perf_mmap_vmops;
4899 if (event->pmu->event_mapped)
4900 event->pmu->event_mapped(event);
4905 static int perf_fasync(int fd, struct file *filp, int on)
4907 struct inode *inode = file_inode(filp);
4908 struct perf_event *event = filp->private_data;
4912 retval = fasync_helper(fd, filp, on, &event->fasync);
4913 inode_unlock(inode);
4921 static const struct file_operations perf_fops = {
4922 .llseek = no_llseek,
4923 .release = perf_release,
4926 .unlocked_ioctl = perf_ioctl,
4927 .compat_ioctl = perf_compat_ioctl,
4929 .fasync = perf_fasync,
4935 * If there's data, ensure we set the poll() state and publish everything
4936 * to user-space before waking everybody up.
4939 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
4941 /* only the parent has fasync state */
4943 event = event->parent;
4944 return &event->fasync;
4947 void perf_event_wakeup(struct perf_event *event)
4949 ring_buffer_wakeup(event);
4951 if (event->pending_kill) {
4952 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
4953 event->pending_kill = 0;
4957 static void perf_pending_event(struct irq_work *entry)
4959 struct perf_event *event = container_of(entry,
4960 struct perf_event, pending);
4963 rctx = perf_swevent_get_recursion_context();
4965 * If we 'fail' here, that's OK, it means recursion is already disabled
4966 * and we won't recurse 'further'.
4969 if (event->pending_disable) {
4970 event->pending_disable = 0;
4971 perf_event_disable_local(event);
4974 if (event->pending_wakeup) {
4975 event->pending_wakeup = 0;
4976 perf_event_wakeup(event);
4980 perf_swevent_put_recursion_context(rctx);
4984 * We assume there is only KVM supporting the callbacks.
4985 * Later on, we might change it to a list if there is
4986 * another virtualization implementation supporting the callbacks.
4988 struct perf_guest_info_callbacks *perf_guest_cbs;
4990 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4992 perf_guest_cbs = cbs;
4995 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
4997 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4999 perf_guest_cbs = NULL;
5002 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
5005 perf_output_sample_regs(struct perf_output_handle *handle,
5006 struct pt_regs *regs, u64 mask)
5010 for_each_set_bit(bit, (const unsigned long *) &mask,
5011 sizeof(mask) * BITS_PER_BYTE) {
5014 val = perf_reg_value(regs, bit);
5015 perf_output_put(handle, val);
5019 static void perf_sample_regs_user(struct perf_regs *regs_user,
5020 struct pt_regs *regs,
5021 struct pt_regs *regs_user_copy)
5023 if (user_mode(regs)) {
5024 regs_user->abi = perf_reg_abi(current);
5025 regs_user->regs = regs;
5026 } else if (current->mm) {
5027 perf_get_regs_user(regs_user, regs, regs_user_copy);
5029 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
5030 regs_user->regs = NULL;
5034 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
5035 struct pt_regs *regs)
5037 regs_intr->regs = regs;
5038 regs_intr->abi = perf_reg_abi(current);
5043 * Get remaining task size from user stack pointer.
5045 * It'd be better to take stack vma map and limit this more
5046 * precisly, but there's no way to get it safely under interrupt,
5047 * so using TASK_SIZE as limit.
5049 static u64 perf_ustack_task_size(struct pt_regs *regs)
5051 unsigned long addr = perf_user_stack_pointer(regs);
5053 if (!addr || addr >= TASK_SIZE)
5056 return TASK_SIZE - addr;
5060 perf_sample_ustack_size(u16 stack_size, u16 header_size,
5061 struct pt_regs *regs)
5065 /* No regs, no stack pointer, no dump. */
5070 * Check if we fit in with the requested stack size into the:
5072 * If we don't, we limit the size to the TASK_SIZE.
5074 * - remaining sample size
5075 * If we don't, we customize the stack size to
5076 * fit in to the remaining sample size.
5079 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
5080 stack_size = min(stack_size, (u16) task_size);
5082 /* Current header size plus static size and dynamic size. */
5083 header_size += 2 * sizeof(u64);
5085 /* Do we fit in with the current stack dump size? */
5086 if ((u16) (header_size + stack_size) < header_size) {
5088 * If we overflow the maximum size for the sample,
5089 * we customize the stack dump size to fit in.
5091 stack_size = USHRT_MAX - header_size - sizeof(u64);
5092 stack_size = round_up(stack_size, sizeof(u64));
5099 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
5100 struct pt_regs *regs)
5102 /* Case of a kernel thread, nothing to dump */
5105 perf_output_put(handle, size);
5114 * - the size requested by user or the best one we can fit
5115 * in to the sample max size
5117 * - user stack dump data
5119 * - the actual dumped size
5123 perf_output_put(handle, dump_size);
5126 sp = perf_user_stack_pointer(regs);
5127 rem = __output_copy_user(handle, (void *) sp, dump_size);
5128 dyn_size = dump_size - rem;
5130 perf_output_skip(handle, rem);
5133 perf_output_put(handle, dyn_size);
5137 static void __perf_event_header__init_id(struct perf_event_header *header,
5138 struct perf_sample_data *data,
5139 struct perf_event *event)
5141 u64 sample_type = event->attr.sample_type;
5143 data->type = sample_type;
5144 header->size += event->id_header_size;
5146 if (sample_type & PERF_SAMPLE_TID) {
5147 /* namespace issues */
5148 data->tid_entry.pid = perf_event_pid(event, current);
5149 data->tid_entry.tid = perf_event_tid(event, current);
5152 if (sample_type & PERF_SAMPLE_TIME)
5153 data->time = perf_event_clock(event);
5155 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
5156 data->id = primary_event_id(event);
5158 if (sample_type & PERF_SAMPLE_STREAM_ID)
5159 data->stream_id = event->id;
5161 if (sample_type & PERF_SAMPLE_CPU) {
5162 data->cpu_entry.cpu = raw_smp_processor_id();
5163 data->cpu_entry.reserved = 0;
5167 void perf_event_header__init_id(struct perf_event_header *header,
5168 struct perf_sample_data *data,
5169 struct perf_event *event)
5171 if (event->attr.sample_id_all)
5172 __perf_event_header__init_id(header, data, event);
5175 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
5176 struct perf_sample_data *data)
5178 u64 sample_type = data->type;
5180 if (sample_type & PERF_SAMPLE_TID)
5181 perf_output_put(handle, data->tid_entry);
5183 if (sample_type & PERF_SAMPLE_TIME)
5184 perf_output_put(handle, data->time);
5186 if (sample_type & PERF_SAMPLE_ID)
5187 perf_output_put(handle, data->id);
5189 if (sample_type & PERF_SAMPLE_STREAM_ID)
5190 perf_output_put(handle, data->stream_id);
5192 if (sample_type & PERF_SAMPLE_CPU)
5193 perf_output_put(handle, data->cpu_entry);
5195 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5196 perf_output_put(handle, data->id);
5199 void perf_event__output_id_sample(struct perf_event *event,
5200 struct perf_output_handle *handle,
5201 struct perf_sample_data *sample)
5203 if (event->attr.sample_id_all)
5204 __perf_event__output_id_sample(handle, sample);
5207 static void perf_output_read_one(struct perf_output_handle *handle,
5208 struct perf_event *event,
5209 u64 enabled, u64 running)
5211 u64 read_format = event->attr.read_format;
5215 values[n++] = perf_event_count(event);
5216 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5217 values[n++] = enabled +
5218 atomic64_read(&event->child_total_time_enabled);
5220 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5221 values[n++] = running +
5222 atomic64_read(&event->child_total_time_running);
5224 if (read_format & PERF_FORMAT_ID)
5225 values[n++] = primary_event_id(event);
5227 __output_copy(handle, values, n * sizeof(u64));
5231 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
5233 static void perf_output_read_group(struct perf_output_handle *handle,
5234 struct perf_event *event,
5235 u64 enabled, u64 running)
5237 struct perf_event *leader = event->group_leader, *sub;
5238 u64 read_format = event->attr.read_format;
5242 values[n++] = 1 + leader->nr_siblings;
5244 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5245 values[n++] = enabled;
5247 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5248 values[n++] = running;
5250 if (leader != event)
5251 leader->pmu->read(leader);
5253 values[n++] = perf_event_count(leader);
5254 if (read_format & PERF_FORMAT_ID)
5255 values[n++] = primary_event_id(leader);
5257 __output_copy(handle, values, n * sizeof(u64));
5259 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
5262 if ((sub != event) &&
5263 (sub->state == PERF_EVENT_STATE_ACTIVE))
5264 sub->pmu->read(sub);
5266 values[n++] = perf_event_count(sub);
5267 if (read_format & PERF_FORMAT_ID)
5268 values[n++] = primary_event_id(sub);
5270 __output_copy(handle, values, n * sizeof(u64));
5274 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
5275 PERF_FORMAT_TOTAL_TIME_RUNNING)
5277 static void perf_output_read(struct perf_output_handle *handle,
5278 struct perf_event *event)
5280 u64 enabled = 0, running = 0, now;
5281 u64 read_format = event->attr.read_format;
5284 * compute total_time_enabled, total_time_running
5285 * based on snapshot values taken when the event
5286 * was last scheduled in.
5288 * we cannot simply called update_context_time()
5289 * because of locking issue as we are called in
5292 if (read_format & PERF_FORMAT_TOTAL_TIMES)
5293 calc_timer_values(event, &now, &enabled, &running);
5295 if (event->attr.read_format & PERF_FORMAT_GROUP)
5296 perf_output_read_group(handle, event, enabled, running);
5298 perf_output_read_one(handle, event, enabled, running);
5301 void perf_output_sample(struct perf_output_handle *handle,
5302 struct perf_event_header *header,
5303 struct perf_sample_data *data,
5304 struct perf_event *event)
5306 u64 sample_type = data->type;
5308 perf_output_put(handle, *header);
5310 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5311 perf_output_put(handle, data->id);
5313 if (sample_type & PERF_SAMPLE_IP)
5314 perf_output_put(handle, data->ip);
5316 if (sample_type & PERF_SAMPLE_TID)
5317 perf_output_put(handle, data->tid_entry);
5319 if (sample_type & PERF_SAMPLE_TIME)
5320 perf_output_put(handle, data->time);
5322 if (sample_type & PERF_SAMPLE_ADDR)
5323 perf_output_put(handle, data->addr);
5325 if (sample_type & PERF_SAMPLE_ID)
5326 perf_output_put(handle, data->id);
5328 if (sample_type & PERF_SAMPLE_STREAM_ID)
5329 perf_output_put(handle, data->stream_id);
5331 if (sample_type & PERF_SAMPLE_CPU)
5332 perf_output_put(handle, data->cpu_entry);
5334 if (sample_type & PERF_SAMPLE_PERIOD)
5335 perf_output_put(handle, data->period);
5337 if (sample_type & PERF_SAMPLE_READ)
5338 perf_output_read(handle, event);
5340 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5341 if (data->callchain) {
5344 if (data->callchain)
5345 size += data->callchain->nr;
5347 size *= sizeof(u64);
5349 __output_copy(handle, data->callchain, size);
5352 perf_output_put(handle, nr);
5356 if (sample_type & PERF_SAMPLE_RAW) {
5358 u32 raw_size = data->raw->size;
5359 u32 real_size = round_up(raw_size + sizeof(u32),
5360 sizeof(u64)) - sizeof(u32);
5363 perf_output_put(handle, real_size);
5364 __output_copy(handle, data->raw->data, raw_size);
5365 if (real_size - raw_size)
5366 __output_copy(handle, &zero, real_size - raw_size);
5372 .size = sizeof(u32),
5375 perf_output_put(handle, raw);
5379 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5380 if (data->br_stack) {
5383 size = data->br_stack->nr
5384 * sizeof(struct perf_branch_entry);
5386 perf_output_put(handle, data->br_stack->nr);
5387 perf_output_copy(handle, data->br_stack->entries, size);
5390 * we always store at least the value of nr
5393 perf_output_put(handle, nr);
5397 if (sample_type & PERF_SAMPLE_REGS_USER) {
5398 u64 abi = data->regs_user.abi;
5401 * If there are no regs to dump, notice it through
5402 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5404 perf_output_put(handle, abi);
5407 u64 mask = event->attr.sample_regs_user;
5408 perf_output_sample_regs(handle,
5409 data->regs_user.regs,
5414 if (sample_type & PERF_SAMPLE_STACK_USER) {
5415 perf_output_sample_ustack(handle,
5416 data->stack_user_size,
5417 data->regs_user.regs);
5420 if (sample_type & PERF_SAMPLE_WEIGHT)
5421 perf_output_put(handle, data->weight);
5423 if (sample_type & PERF_SAMPLE_DATA_SRC)
5424 perf_output_put(handle, data->data_src.val);
5426 if (sample_type & PERF_SAMPLE_TRANSACTION)
5427 perf_output_put(handle, data->txn);
5429 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5430 u64 abi = data->regs_intr.abi;
5432 * If there are no regs to dump, notice it through
5433 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5435 perf_output_put(handle, abi);
5438 u64 mask = event->attr.sample_regs_intr;
5440 perf_output_sample_regs(handle,
5441 data->regs_intr.regs,
5446 if (!event->attr.watermark) {
5447 int wakeup_events = event->attr.wakeup_events;
5449 if (wakeup_events) {
5450 struct ring_buffer *rb = handle->rb;
5451 int events = local_inc_return(&rb->events);
5453 if (events >= wakeup_events) {
5454 local_sub(wakeup_events, &rb->events);
5455 local_inc(&rb->wakeup);
5461 void perf_prepare_sample(struct perf_event_header *header,
5462 struct perf_sample_data *data,
5463 struct perf_event *event,
5464 struct pt_regs *regs)
5466 u64 sample_type = event->attr.sample_type;
5468 header->type = PERF_RECORD_SAMPLE;
5469 header->size = sizeof(*header) + event->header_size;
5472 header->misc |= perf_misc_flags(regs);
5474 __perf_event_header__init_id(header, data, event);
5476 if (sample_type & PERF_SAMPLE_IP)
5477 data->ip = perf_instruction_pointer(regs);
5479 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5482 data->callchain = perf_callchain(event, regs);
5484 if (data->callchain)
5485 size += data->callchain->nr;
5487 header->size += size * sizeof(u64);
5490 if (sample_type & PERF_SAMPLE_RAW) {
5491 int size = sizeof(u32);
5494 size += data->raw->size;
5496 size += sizeof(u32);
5498 header->size += round_up(size, sizeof(u64));
5501 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5502 int size = sizeof(u64); /* nr */
5503 if (data->br_stack) {
5504 size += data->br_stack->nr
5505 * sizeof(struct perf_branch_entry);
5507 header->size += size;
5510 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
5511 perf_sample_regs_user(&data->regs_user, regs,
5512 &data->regs_user_copy);
5514 if (sample_type & PERF_SAMPLE_REGS_USER) {
5515 /* regs dump ABI info */
5516 int size = sizeof(u64);
5518 if (data->regs_user.regs) {
5519 u64 mask = event->attr.sample_regs_user;
5520 size += hweight64(mask) * sizeof(u64);
5523 header->size += size;
5526 if (sample_type & PERF_SAMPLE_STACK_USER) {
5528 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
5529 * processed as the last one or have additional check added
5530 * in case new sample type is added, because we could eat
5531 * up the rest of the sample size.
5533 u16 stack_size = event->attr.sample_stack_user;
5534 u16 size = sizeof(u64);
5536 stack_size = perf_sample_ustack_size(stack_size, header->size,
5537 data->regs_user.regs);
5540 * If there is something to dump, add space for the dump
5541 * itself and for the field that tells the dynamic size,
5542 * which is how many have been actually dumped.
5545 size += sizeof(u64) + stack_size;
5547 data->stack_user_size = stack_size;
5548 header->size += size;
5551 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5552 /* regs dump ABI info */
5553 int size = sizeof(u64);
5555 perf_sample_regs_intr(&data->regs_intr, regs);
5557 if (data->regs_intr.regs) {
5558 u64 mask = event->attr.sample_regs_intr;
5560 size += hweight64(mask) * sizeof(u64);
5563 header->size += size;
5567 void perf_event_output(struct perf_event *event,
5568 struct perf_sample_data *data,
5569 struct pt_regs *regs)
5571 struct perf_output_handle handle;
5572 struct perf_event_header header;
5574 /* protect the callchain buffers */
5577 perf_prepare_sample(&header, data, event, regs);
5579 if (perf_output_begin(&handle, event, header.size))
5582 perf_output_sample(&handle, &header, data, event);
5584 perf_output_end(&handle);
5594 struct perf_read_event {
5595 struct perf_event_header header;
5602 perf_event_read_event(struct perf_event *event,
5603 struct task_struct *task)
5605 struct perf_output_handle handle;
5606 struct perf_sample_data sample;
5607 struct perf_read_event read_event = {
5609 .type = PERF_RECORD_READ,
5611 .size = sizeof(read_event) + event->read_size,
5613 .pid = perf_event_pid(event, task),
5614 .tid = perf_event_tid(event, task),
5618 perf_event_header__init_id(&read_event.header, &sample, event);
5619 ret = perf_output_begin(&handle, event, read_event.header.size);
5623 perf_output_put(&handle, read_event);
5624 perf_output_read(&handle, event);
5625 perf_event__output_id_sample(event, &handle, &sample);
5627 perf_output_end(&handle);
5630 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
5633 perf_event_aux_ctx(struct perf_event_context *ctx,
5634 perf_event_aux_output_cb output,
5637 struct perf_event *event;
5639 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5640 if (event->state < PERF_EVENT_STATE_INACTIVE)
5642 if (!event_filter_match(event))
5644 output(event, data);
5649 perf_event_aux_task_ctx(perf_event_aux_output_cb output, void *data,
5650 struct perf_event_context *task_ctx)
5654 perf_event_aux_ctx(task_ctx, output, data);
5660 perf_event_aux(perf_event_aux_output_cb output, void *data,
5661 struct perf_event_context *task_ctx)
5663 struct perf_cpu_context *cpuctx;
5664 struct perf_event_context *ctx;
5669 * If we have task_ctx != NULL we only notify
5670 * the task context itself. The task_ctx is set
5671 * only for EXIT events before releasing task
5675 perf_event_aux_task_ctx(output, data, task_ctx);
5680 list_for_each_entry_rcu(pmu, &pmus, entry) {
5681 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
5682 if (cpuctx->unique_pmu != pmu)
5684 perf_event_aux_ctx(&cpuctx->ctx, output, data);
5685 ctxn = pmu->task_ctx_nr;
5688 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
5690 perf_event_aux_ctx(ctx, output, data);
5692 put_cpu_ptr(pmu->pmu_cpu_context);
5698 * task tracking -- fork/exit
5700 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
5703 struct perf_task_event {
5704 struct task_struct *task;
5705 struct perf_event_context *task_ctx;
5708 struct perf_event_header header;
5718 static int perf_event_task_match(struct perf_event *event)
5720 return event->attr.comm || event->attr.mmap ||
5721 event->attr.mmap2 || event->attr.mmap_data ||
5725 static void perf_event_task_output(struct perf_event *event,
5728 struct perf_task_event *task_event = data;
5729 struct perf_output_handle handle;
5730 struct perf_sample_data sample;
5731 struct task_struct *task = task_event->task;
5732 int ret, size = task_event->event_id.header.size;
5734 if (!perf_event_task_match(event))
5737 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
5739 ret = perf_output_begin(&handle, event,
5740 task_event->event_id.header.size);
5744 task_event->event_id.pid = perf_event_pid(event, task);
5745 task_event->event_id.ppid = perf_event_pid(event, current);
5747 task_event->event_id.tid = perf_event_tid(event, task);
5748 task_event->event_id.ptid = perf_event_tid(event, current);
5750 task_event->event_id.time = perf_event_clock(event);
5752 perf_output_put(&handle, task_event->event_id);
5754 perf_event__output_id_sample(event, &handle, &sample);
5756 perf_output_end(&handle);
5758 task_event->event_id.header.size = size;
5761 static void perf_event_task(struct task_struct *task,
5762 struct perf_event_context *task_ctx,
5765 struct perf_task_event task_event;
5767 if (!atomic_read(&nr_comm_events) &&
5768 !atomic_read(&nr_mmap_events) &&
5769 !atomic_read(&nr_task_events))
5772 task_event = (struct perf_task_event){
5774 .task_ctx = task_ctx,
5777 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
5779 .size = sizeof(task_event.event_id),
5789 perf_event_aux(perf_event_task_output,
5794 void perf_event_fork(struct task_struct *task)
5796 perf_event_task(task, NULL, 1);
5803 struct perf_comm_event {
5804 struct task_struct *task;
5809 struct perf_event_header header;
5816 static int perf_event_comm_match(struct perf_event *event)
5818 return event->attr.comm;
5821 static void perf_event_comm_output(struct perf_event *event,
5824 struct perf_comm_event *comm_event = data;
5825 struct perf_output_handle handle;
5826 struct perf_sample_data sample;
5827 int size = comm_event->event_id.header.size;
5830 if (!perf_event_comm_match(event))
5833 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
5834 ret = perf_output_begin(&handle, event,
5835 comm_event->event_id.header.size);
5840 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
5841 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
5843 perf_output_put(&handle, comm_event->event_id);
5844 __output_copy(&handle, comm_event->comm,
5845 comm_event->comm_size);
5847 perf_event__output_id_sample(event, &handle, &sample);
5849 perf_output_end(&handle);
5851 comm_event->event_id.header.size = size;
5854 static void perf_event_comm_event(struct perf_comm_event *comm_event)
5856 char comm[TASK_COMM_LEN];
5859 memset(comm, 0, sizeof(comm));
5860 strlcpy(comm, comm_event->task->comm, sizeof(comm));
5861 size = ALIGN(strlen(comm)+1, sizeof(u64));
5863 comm_event->comm = comm;
5864 comm_event->comm_size = size;
5866 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
5868 perf_event_aux(perf_event_comm_output,
5873 void perf_event_comm(struct task_struct *task, bool exec)
5875 struct perf_comm_event comm_event;
5877 if (!atomic_read(&nr_comm_events))
5880 comm_event = (struct perf_comm_event){
5886 .type = PERF_RECORD_COMM,
5887 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
5895 perf_event_comm_event(&comm_event);
5902 struct perf_mmap_event {
5903 struct vm_area_struct *vma;
5905 const char *file_name;
5913 struct perf_event_header header;
5923 static int perf_event_mmap_match(struct perf_event *event,
5926 struct perf_mmap_event *mmap_event = data;
5927 struct vm_area_struct *vma = mmap_event->vma;
5928 int executable = vma->vm_flags & VM_EXEC;
5930 return (!executable && event->attr.mmap_data) ||
5931 (executable && (event->attr.mmap || event->attr.mmap2));
5934 static void perf_event_mmap_output(struct perf_event *event,
5937 struct perf_mmap_event *mmap_event = data;
5938 struct perf_output_handle handle;
5939 struct perf_sample_data sample;
5940 int size = mmap_event->event_id.header.size;
5943 if (!perf_event_mmap_match(event, data))
5946 if (event->attr.mmap2) {
5947 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
5948 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
5949 mmap_event->event_id.header.size += sizeof(mmap_event->min);
5950 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
5951 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
5952 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
5953 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
5956 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
5957 ret = perf_output_begin(&handle, event,
5958 mmap_event->event_id.header.size);
5962 mmap_event->event_id.pid = perf_event_pid(event, current);
5963 mmap_event->event_id.tid = perf_event_tid(event, current);
5965 perf_output_put(&handle, mmap_event->event_id);
5967 if (event->attr.mmap2) {
5968 perf_output_put(&handle, mmap_event->maj);
5969 perf_output_put(&handle, mmap_event->min);
5970 perf_output_put(&handle, mmap_event->ino);
5971 perf_output_put(&handle, mmap_event->ino_generation);
5972 perf_output_put(&handle, mmap_event->prot);
5973 perf_output_put(&handle, mmap_event->flags);
5976 __output_copy(&handle, mmap_event->file_name,
5977 mmap_event->file_size);
5979 perf_event__output_id_sample(event, &handle, &sample);
5981 perf_output_end(&handle);
5983 mmap_event->event_id.header.size = size;
5986 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
5988 struct vm_area_struct *vma = mmap_event->vma;
5989 struct file *file = vma->vm_file;
5990 int maj = 0, min = 0;
5991 u64 ino = 0, gen = 0;
5992 u32 prot = 0, flags = 0;
5999 struct inode *inode;
6002 buf = kmalloc(PATH_MAX, GFP_KERNEL);
6008 * d_path() works from the end of the rb backwards, so we
6009 * need to add enough zero bytes after the string to handle
6010 * the 64bit alignment we do later.
6012 name = file_path(file, buf, PATH_MAX - sizeof(u64));
6017 inode = file_inode(vma->vm_file);
6018 dev = inode->i_sb->s_dev;
6020 gen = inode->i_generation;
6024 if (vma->vm_flags & VM_READ)
6026 if (vma->vm_flags & VM_WRITE)
6028 if (vma->vm_flags & VM_EXEC)
6031 if (vma->vm_flags & VM_MAYSHARE)
6034 flags = MAP_PRIVATE;
6036 if (vma->vm_flags & VM_DENYWRITE)
6037 flags |= MAP_DENYWRITE;
6038 if (vma->vm_flags & VM_MAYEXEC)
6039 flags |= MAP_EXECUTABLE;
6040 if (vma->vm_flags & VM_LOCKED)
6041 flags |= MAP_LOCKED;
6042 if (vma->vm_flags & VM_HUGETLB)
6043 flags |= MAP_HUGETLB;
6047 if (vma->vm_ops && vma->vm_ops->name) {
6048 name = (char *) vma->vm_ops->name(vma);
6053 name = (char *)arch_vma_name(vma);
6057 if (vma->vm_start <= vma->vm_mm->start_brk &&
6058 vma->vm_end >= vma->vm_mm->brk) {
6062 if (vma->vm_start <= vma->vm_mm->start_stack &&
6063 vma->vm_end >= vma->vm_mm->start_stack) {
6073 strlcpy(tmp, name, sizeof(tmp));
6077 * Since our buffer works in 8 byte units we need to align our string
6078 * size to a multiple of 8. However, we must guarantee the tail end is
6079 * zero'd out to avoid leaking random bits to userspace.
6081 size = strlen(name)+1;
6082 while (!IS_ALIGNED(size, sizeof(u64)))
6083 name[size++] = '\0';
6085 mmap_event->file_name = name;
6086 mmap_event->file_size = size;
6087 mmap_event->maj = maj;
6088 mmap_event->min = min;
6089 mmap_event->ino = ino;
6090 mmap_event->ino_generation = gen;
6091 mmap_event->prot = prot;
6092 mmap_event->flags = flags;
6094 if (!(vma->vm_flags & VM_EXEC))
6095 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
6097 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
6099 perf_event_aux(perf_event_mmap_output,
6106 void perf_event_mmap(struct vm_area_struct *vma)
6108 struct perf_mmap_event mmap_event;
6110 if (!atomic_read(&nr_mmap_events))
6113 mmap_event = (struct perf_mmap_event){
6119 .type = PERF_RECORD_MMAP,
6120 .misc = PERF_RECORD_MISC_USER,
6125 .start = vma->vm_start,
6126 .len = vma->vm_end - vma->vm_start,
6127 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
6129 /* .maj (attr_mmap2 only) */
6130 /* .min (attr_mmap2 only) */
6131 /* .ino (attr_mmap2 only) */
6132 /* .ino_generation (attr_mmap2 only) */
6133 /* .prot (attr_mmap2 only) */
6134 /* .flags (attr_mmap2 only) */
6137 perf_event_mmap_event(&mmap_event);
6140 void perf_event_aux_event(struct perf_event *event, unsigned long head,
6141 unsigned long size, u64 flags)
6143 struct perf_output_handle handle;
6144 struct perf_sample_data sample;
6145 struct perf_aux_event {
6146 struct perf_event_header header;
6152 .type = PERF_RECORD_AUX,
6154 .size = sizeof(rec),
6162 perf_event_header__init_id(&rec.header, &sample, event);
6163 ret = perf_output_begin(&handle, event, rec.header.size);
6168 perf_output_put(&handle, rec);
6169 perf_event__output_id_sample(event, &handle, &sample);
6171 perf_output_end(&handle);
6175 * Lost/dropped samples logging
6177 void perf_log_lost_samples(struct perf_event *event, u64 lost)
6179 struct perf_output_handle handle;
6180 struct perf_sample_data sample;
6184 struct perf_event_header header;
6186 } lost_samples_event = {
6188 .type = PERF_RECORD_LOST_SAMPLES,
6190 .size = sizeof(lost_samples_event),
6195 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
6197 ret = perf_output_begin(&handle, event,
6198 lost_samples_event.header.size);
6202 perf_output_put(&handle, lost_samples_event);
6203 perf_event__output_id_sample(event, &handle, &sample);
6204 perf_output_end(&handle);
6208 * context_switch tracking
6211 struct perf_switch_event {
6212 struct task_struct *task;
6213 struct task_struct *next_prev;
6216 struct perf_event_header header;
6222 static int perf_event_switch_match(struct perf_event *event)
6224 return event->attr.context_switch;
6227 static void perf_event_switch_output(struct perf_event *event, void *data)
6229 struct perf_switch_event *se = data;
6230 struct perf_output_handle handle;
6231 struct perf_sample_data sample;
6234 if (!perf_event_switch_match(event))
6237 /* Only CPU-wide events are allowed to see next/prev pid/tid */
6238 if (event->ctx->task) {
6239 se->event_id.header.type = PERF_RECORD_SWITCH;
6240 se->event_id.header.size = sizeof(se->event_id.header);
6242 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
6243 se->event_id.header.size = sizeof(se->event_id);
6244 se->event_id.next_prev_pid =
6245 perf_event_pid(event, se->next_prev);
6246 se->event_id.next_prev_tid =
6247 perf_event_tid(event, se->next_prev);
6250 perf_event_header__init_id(&se->event_id.header, &sample, event);
6252 ret = perf_output_begin(&handle, event, se->event_id.header.size);
6256 if (event->ctx->task)
6257 perf_output_put(&handle, se->event_id.header);
6259 perf_output_put(&handle, se->event_id);
6261 perf_event__output_id_sample(event, &handle, &sample);
6263 perf_output_end(&handle);
6266 static void perf_event_switch(struct task_struct *task,
6267 struct task_struct *next_prev, bool sched_in)
6269 struct perf_switch_event switch_event;
6271 /* N.B. caller checks nr_switch_events != 0 */
6273 switch_event = (struct perf_switch_event){
6275 .next_prev = next_prev,
6279 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
6282 /* .next_prev_pid */
6283 /* .next_prev_tid */
6287 perf_event_aux(perf_event_switch_output,
6293 * IRQ throttle logging
6296 static void perf_log_throttle(struct perf_event *event, int enable)
6298 struct perf_output_handle handle;
6299 struct perf_sample_data sample;
6303 struct perf_event_header header;
6307 } throttle_event = {
6309 .type = PERF_RECORD_THROTTLE,
6311 .size = sizeof(throttle_event),
6313 .time = perf_event_clock(event),
6314 .id = primary_event_id(event),
6315 .stream_id = event->id,
6319 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
6321 perf_event_header__init_id(&throttle_event.header, &sample, event);
6323 ret = perf_output_begin(&handle, event,
6324 throttle_event.header.size);
6328 perf_output_put(&handle, throttle_event);
6329 perf_event__output_id_sample(event, &handle, &sample);
6330 perf_output_end(&handle);
6333 static void perf_log_itrace_start(struct perf_event *event)
6335 struct perf_output_handle handle;
6336 struct perf_sample_data sample;
6337 struct perf_aux_event {
6338 struct perf_event_header header;
6345 event = event->parent;
6347 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
6348 event->hw.itrace_started)
6351 rec.header.type = PERF_RECORD_ITRACE_START;
6352 rec.header.misc = 0;
6353 rec.header.size = sizeof(rec);
6354 rec.pid = perf_event_pid(event, current);
6355 rec.tid = perf_event_tid(event, current);
6357 perf_event_header__init_id(&rec.header, &sample, event);
6358 ret = perf_output_begin(&handle, event, rec.header.size);
6363 perf_output_put(&handle, rec);
6364 perf_event__output_id_sample(event, &handle, &sample);
6366 perf_output_end(&handle);
6370 * Generic event overflow handling, sampling.
6373 static int __perf_event_overflow(struct perf_event *event,
6374 int throttle, struct perf_sample_data *data,
6375 struct pt_regs *regs)
6377 int events = atomic_read(&event->event_limit);
6378 struct hw_perf_event *hwc = &event->hw;
6383 * Non-sampling counters might still use the PMI to fold short
6384 * hardware counters, ignore those.
6386 if (unlikely(!is_sampling_event(event)))
6389 seq = __this_cpu_read(perf_throttled_seq);
6390 if (seq != hwc->interrupts_seq) {
6391 hwc->interrupts_seq = seq;
6392 hwc->interrupts = 1;
6395 if (unlikely(throttle
6396 && hwc->interrupts >= max_samples_per_tick)) {
6397 __this_cpu_inc(perf_throttled_count);
6398 hwc->interrupts = MAX_INTERRUPTS;
6399 perf_log_throttle(event, 0);
6400 tick_nohz_full_kick();
6405 if (event->attr.freq) {
6406 u64 now = perf_clock();
6407 s64 delta = now - hwc->freq_time_stamp;
6409 hwc->freq_time_stamp = now;
6411 if (delta > 0 && delta < 2*TICK_NSEC)
6412 perf_adjust_period(event, delta, hwc->last_period, true);
6416 * XXX event_limit might not quite work as expected on inherited
6420 event->pending_kill = POLL_IN;
6421 if (events && atomic_dec_and_test(&event->event_limit)) {
6423 event->pending_kill = POLL_HUP;
6424 event->pending_disable = 1;
6425 irq_work_queue(&event->pending);
6428 if (event->overflow_handler)
6429 event->overflow_handler(event, data, regs);
6431 perf_event_output(event, data, regs);
6433 if (*perf_event_fasync(event) && event->pending_kill) {
6434 event->pending_wakeup = 1;
6435 irq_work_queue(&event->pending);
6441 int perf_event_overflow(struct perf_event *event,
6442 struct perf_sample_data *data,
6443 struct pt_regs *regs)
6445 return __perf_event_overflow(event, 1, data, regs);
6449 * Generic software event infrastructure
6452 struct swevent_htable {
6453 struct swevent_hlist *swevent_hlist;
6454 struct mutex hlist_mutex;
6457 /* Recursion avoidance in each contexts */
6458 int recursion[PERF_NR_CONTEXTS];
6461 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
6464 * We directly increment event->count and keep a second value in
6465 * event->hw.period_left to count intervals. This period event
6466 * is kept in the range [-sample_period, 0] so that we can use the
6470 u64 perf_swevent_set_period(struct perf_event *event)
6472 struct hw_perf_event *hwc = &event->hw;
6473 u64 period = hwc->last_period;
6477 hwc->last_period = hwc->sample_period;
6480 old = val = local64_read(&hwc->period_left);
6484 nr = div64_u64(period + val, period);
6485 offset = nr * period;
6487 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
6493 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
6494 struct perf_sample_data *data,
6495 struct pt_regs *regs)
6497 struct hw_perf_event *hwc = &event->hw;
6501 overflow = perf_swevent_set_period(event);
6503 if (hwc->interrupts == MAX_INTERRUPTS)
6506 for (; overflow; overflow--) {
6507 if (__perf_event_overflow(event, throttle,
6510 * We inhibit the overflow from happening when
6511 * hwc->interrupts == MAX_INTERRUPTS.
6519 static void perf_swevent_event(struct perf_event *event, u64 nr,
6520 struct perf_sample_data *data,
6521 struct pt_regs *regs)
6523 struct hw_perf_event *hwc = &event->hw;
6525 local64_add(nr, &event->count);
6530 if (!is_sampling_event(event))
6533 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
6535 return perf_swevent_overflow(event, 1, data, regs);
6537 data->period = event->hw.last_period;
6539 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
6540 return perf_swevent_overflow(event, 1, data, regs);
6542 if (local64_add_negative(nr, &hwc->period_left))
6545 perf_swevent_overflow(event, 0, data, regs);
6548 static int perf_exclude_event(struct perf_event *event,
6549 struct pt_regs *regs)
6551 if (event->hw.state & PERF_HES_STOPPED)
6555 if (event->attr.exclude_user && user_mode(regs))
6558 if (event->attr.exclude_kernel && !user_mode(regs))
6565 static int perf_swevent_match(struct perf_event *event,
6566 enum perf_type_id type,
6568 struct perf_sample_data *data,
6569 struct pt_regs *regs)
6571 if (event->attr.type != type)
6574 if (event->attr.config != event_id)
6577 if (perf_exclude_event(event, regs))
6583 static inline u64 swevent_hash(u64 type, u32 event_id)
6585 u64 val = event_id | (type << 32);
6587 return hash_64(val, SWEVENT_HLIST_BITS);
6590 static inline struct hlist_head *
6591 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
6593 u64 hash = swevent_hash(type, event_id);
6595 return &hlist->heads[hash];
6598 /* For the read side: events when they trigger */
6599 static inline struct hlist_head *
6600 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
6602 struct swevent_hlist *hlist;
6604 hlist = rcu_dereference(swhash->swevent_hlist);
6608 return __find_swevent_head(hlist, type, event_id);
6611 /* For the event head insertion and removal in the hlist */
6612 static inline struct hlist_head *
6613 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
6615 struct swevent_hlist *hlist;
6616 u32 event_id = event->attr.config;
6617 u64 type = event->attr.type;
6620 * Event scheduling is always serialized against hlist allocation
6621 * and release. Which makes the protected version suitable here.
6622 * The context lock guarantees that.
6624 hlist = rcu_dereference_protected(swhash->swevent_hlist,
6625 lockdep_is_held(&event->ctx->lock));
6629 return __find_swevent_head(hlist, type, event_id);
6632 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
6634 struct perf_sample_data *data,
6635 struct pt_regs *regs)
6637 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6638 struct perf_event *event;
6639 struct hlist_head *head;
6642 head = find_swevent_head_rcu(swhash, type, event_id);
6646 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6647 if (perf_swevent_match(event, type, event_id, data, regs))
6648 perf_swevent_event(event, nr, data, regs);
6654 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
6656 int perf_swevent_get_recursion_context(void)
6658 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6660 return get_recursion_context(swhash->recursion);
6662 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
6664 inline void perf_swevent_put_recursion_context(int rctx)
6666 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6668 put_recursion_context(swhash->recursion, rctx);
6671 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6673 struct perf_sample_data data;
6675 if (WARN_ON_ONCE(!regs))
6678 perf_sample_data_init(&data, addr, 0);
6679 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
6682 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6686 preempt_disable_notrace();
6687 rctx = perf_swevent_get_recursion_context();
6688 if (unlikely(rctx < 0))
6691 ___perf_sw_event(event_id, nr, regs, addr);
6693 perf_swevent_put_recursion_context(rctx);
6695 preempt_enable_notrace();
6698 static void perf_swevent_read(struct perf_event *event)
6702 static int perf_swevent_add(struct perf_event *event, int flags)
6704 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6705 struct hw_perf_event *hwc = &event->hw;
6706 struct hlist_head *head;
6708 if (is_sampling_event(event)) {
6709 hwc->last_period = hwc->sample_period;
6710 perf_swevent_set_period(event);
6713 hwc->state = !(flags & PERF_EF_START);
6715 head = find_swevent_head(swhash, event);
6716 if (WARN_ON_ONCE(!head))
6719 hlist_add_head_rcu(&event->hlist_entry, head);
6720 perf_event_update_userpage(event);
6725 static void perf_swevent_del(struct perf_event *event, int flags)
6727 hlist_del_rcu(&event->hlist_entry);
6730 static void perf_swevent_start(struct perf_event *event, int flags)
6732 event->hw.state = 0;
6735 static void perf_swevent_stop(struct perf_event *event, int flags)
6737 event->hw.state = PERF_HES_STOPPED;
6740 /* Deref the hlist from the update side */
6741 static inline struct swevent_hlist *
6742 swevent_hlist_deref(struct swevent_htable *swhash)
6744 return rcu_dereference_protected(swhash->swevent_hlist,
6745 lockdep_is_held(&swhash->hlist_mutex));
6748 static void swevent_hlist_release(struct swevent_htable *swhash)
6750 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
6755 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
6756 kfree_rcu(hlist, rcu_head);
6759 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
6761 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6763 mutex_lock(&swhash->hlist_mutex);
6765 if (!--swhash->hlist_refcount)
6766 swevent_hlist_release(swhash);
6768 mutex_unlock(&swhash->hlist_mutex);
6771 static void swevent_hlist_put(struct perf_event *event)
6775 for_each_possible_cpu(cpu)
6776 swevent_hlist_put_cpu(event, cpu);
6779 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
6781 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6784 mutex_lock(&swhash->hlist_mutex);
6785 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
6786 struct swevent_hlist *hlist;
6788 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
6793 rcu_assign_pointer(swhash->swevent_hlist, hlist);
6795 swhash->hlist_refcount++;
6797 mutex_unlock(&swhash->hlist_mutex);
6802 static int swevent_hlist_get(struct perf_event *event)
6805 int cpu, failed_cpu;
6808 for_each_possible_cpu(cpu) {
6809 err = swevent_hlist_get_cpu(event, cpu);
6819 for_each_possible_cpu(cpu) {
6820 if (cpu == failed_cpu)
6822 swevent_hlist_put_cpu(event, cpu);
6829 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
6831 static void sw_perf_event_destroy(struct perf_event *event)
6833 u64 event_id = event->attr.config;
6835 WARN_ON(event->parent);
6837 static_key_slow_dec(&perf_swevent_enabled[event_id]);
6838 swevent_hlist_put(event);
6841 static int perf_swevent_init(struct perf_event *event)
6843 u64 event_id = event->attr.config;
6845 if (event->attr.type != PERF_TYPE_SOFTWARE)
6849 * no branch sampling for software events
6851 if (has_branch_stack(event))
6855 case PERF_COUNT_SW_CPU_CLOCK:
6856 case PERF_COUNT_SW_TASK_CLOCK:
6863 if (event_id >= PERF_COUNT_SW_MAX)
6866 if (!event->parent) {
6869 err = swevent_hlist_get(event);
6873 static_key_slow_inc(&perf_swevent_enabled[event_id]);
6874 event->destroy = sw_perf_event_destroy;
6880 static struct pmu perf_swevent = {
6881 .task_ctx_nr = perf_sw_context,
6883 .capabilities = PERF_PMU_CAP_NO_NMI,
6885 .event_init = perf_swevent_init,
6886 .add = perf_swevent_add,
6887 .del = perf_swevent_del,
6888 .start = perf_swevent_start,
6889 .stop = perf_swevent_stop,
6890 .read = perf_swevent_read,
6893 #ifdef CONFIG_EVENT_TRACING
6895 static int perf_tp_filter_match(struct perf_event *event,
6896 struct perf_sample_data *data)
6898 void *record = data->raw->data;
6900 /* only top level events have filters set */
6902 event = event->parent;
6904 if (likely(!event->filter) || filter_match_preds(event->filter, record))
6909 static int perf_tp_event_match(struct perf_event *event,
6910 struct perf_sample_data *data,
6911 struct pt_regs *regs)
6913 if (event->hw.state & PERF_HES_STOPPED)
6916 * All tracepoints are from kernel-space.
6918 if (event->attr.exclude_kernel)
6921 if (!perf_tp_filter_match(event, data))
6927 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
6928 struct pt_regs *regs, struct hlist_head *head, int rctx,
6929 struct task_struct *task)
6931 struct perf_sample_data data;
6932 struct perf_event *event;
6934 struct perf_raw_record raw = {
6939 perf_sample_data_init(&data, addr, 0);
6942 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6943 if (perf_tp_event_match(event, &data, regs))
6944 perf_swevent_event(event, count, &data, regs);
6948 * If we got specified a target task, also iterate its context and
6949 * deliver this event there too.
6951 if (task && task != current) {
6952 struct perf_event_context *ctx;
6953 struct trace_entry *entry = record;
6956 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
6960 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
6961 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6963 if (event->attr.config != entry->type)
6965 if (perf_tp_event_match(event, &data, regs))
6966 perf_swevent_event(event, count, &data, regs);
6972 perf_swevent_put_recursion_context(rctx);
6974 EXPORT_SYMBOL_GPL(perf_tp_event);
6976 static void tp_perf_event_destroy(struct perf_event *event)
6978 perf_trace_destroy(event);
6981 static int perf_tp_event_init(struct perf_event *event)
6985 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6989 * no branch sampling for tracepoint events
6991 if (has_branch_stack(event))
6994 err = perf_trace_init(event);
6998 event->destroy = tp_perf_event_destroy;
7003 static struct pmu perf_tracepoint = {
7004 .task_ctx_nr = perf_sw_context,
7006 .event_init = perf_tp_event_init,
7007 .add = perf_trace_add,
7008 .del = perf_trace_del,
7009 .start = perf_swevent_start,
7010 .stop = perf_swevent_stop,
7011 .read = perf_swevent_read,
7014 static inline void perf_tp_register(void)
7016 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
7019 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7024 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7027 filter_str = strndup_user(arg, PAGE_SIZE);
7028 if (IS_ERR(filter_str))
7029 return PTR_ERR(filter_str);
7031 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
7037 static void perf_event_free_filter(struct perf_event *event)
7039 ftrace_profile_free_filter(event);
7042 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7044 struct bpf_prog *prog;
7046 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7049 if (event->tp_event->prog)
7052 if (!(event->tp_event->flags & TRACE_EVENT_FL_UKPROBE))
7053 /* bpf programs can only be attached to u/kprobes */
7056 prog = bpf_prog_get(prog_fd);
7058 return PTR_ERR(prog);
7060 if (prog->type != BPF_PROG_TYPE_KPROBE) {
7061 /* valid fd, but invalid bpf program type */
7066 event->tp_event->prog = prog;
7071 static void perf_event_free_bpf_prog(struct perf_event *event)
7073 struct bpf_prog *prog;
7075 if (!event->tp_event)
7078 prog = event->tp_event->prog;
7080 event->tp_event->prog = NULL;
7087 static inline void perf_tp_register(void)
7091 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7096 static void perf_event_free_filter(struct perf_event *event)
7100 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7105 static void perf_event_free_bpf_prog(struct perf_event *event)
7108 #endif /* CONFIG_EVENT_TRACING */
7110 #ifdef CONFIG_HAVE_HW_BREAKPOINT
7111 void perf_bp_event(struct perf_event *bp, void *data)
7113 struct perf_sample_data sample;
7114 struct pt_regs *regs = data;
7116 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
7118 if (!bp->hw.state && !perf_exclude_event(bp, regs))
7119 perf_swevent_event(bp, 1, &sample, regs);
7124 * hrtimer based swevent callback
7127 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
7129 enum hrtimer_restart ret = HRTIMER_RESTART;
7130 struct perf_sample_data data;
7131 struct pt_regs *regs;
7132 struct perf_event *event;
7135 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
7137 if (event->state != PERF_EVENT_STATE_ACTIVE)
7138 return HRTIMER_NORESTART;
7140 event->pmu->read(event);
7142 perf_sample_data_init(&data, 0, event->hw.last_period);
7143 regs = get_irq_regs();
7145 if (regs && !perf_exclude_event(event, regs)) {
7146 if (!(event->attr.exclude_idle && is_idle_task(current)))
7147 if (__perf_event_overflow(event, 1, &data, regs))
7148 ret = HRTIMER_NORESTART;
7151 period = max_t(u64, 10000, event->hw.sample_period);
7152 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
7157 static void perf_swevent_start_hrtimer(struct perf_event *event)
7159 struct hw_perf_event *hwc = &event->hw;
7162 if (!is_sampling_event(event))
7165 period = local64_read(&hwc->period_left);
7170 local64_set(&hwc->period_left, 0);
7172 period = max_t(u64, 10000, hwc->sample_period);
7174 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
7175 HRTIMER_MODE_REL_PINNED);
7178 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
7180 struct hw_perf_event *hwc = &event->hw;
7182 if (is_sampling_event(event)) {
7183 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
7184 local64_set(&hwc->period_left, ktime_to_ns(remaining));
7186 hrtimer_cancel(&hwc->hrtimer);
7190 static void perf_swevent_init_hrtimer(struct perf_event *event)
7192 struct hw_perf_event *hwc = &event->hw;
7194 if (!is_sampling_event(event))
7197 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7198 hwc->hrtimer.function = perf_swevent_hrtimer;
7201 * Since hrtimers have a fixed rate, we can do a static freq->period
7202 * mapping and avoid the whole period adjust feedback stuff.
7204 if (event->attr.freq) {
7205 long freq = event->attr.sample_freq;
7207 event->attr.sample_period = NSEC_PER_SEC / freq;
7208 hwc->sample_period = event->attr.sample_period;
7209 local64_set(&hwc->period_left, hwc->sample_period);
7210 hwc->last_period = hwc->sample_period;
7211 event->attr.freq = 0;
7216 * Software event: cpu wall time clock
7219 static void cpu_clock_event_update(struct perf_event *event)
7224 now = local_clock();
7225 prev = local64_xchg(&event->hw.prev_count, now);
7226 local64_add(now - prev, &event->count);
7229 static void cpu_clock_event_start(struct perf_event *event, int flags)
7231 local64_set(&event->hw.prev_count, local_clock());
7232 perf_swevent_start_hrtimer(event);
7235 static void cpu_clock_event_stop(struct perf_event *event, int flags)
7237 perf_swevent_cancel_hrtimer(event);
7238 cpu_clock_event_update(event);
7241 static int cpu_clock_event_add(struct perf_event *event, int flags)
7243 if (flags & PERF_EF_START)
7244 cpu_clock_event_start(event, flags);
7245 perf_event_update_userpage(event);
7250 static void cpu_clock_event_del(struct perf_event *event, int flags)
7252 cpu_clock_event_stop(event, flags);
7255 static void cpu_clock_event_read(struct perf_event *event)
7257 cpu_clock_event_update(event);
7260 static int cpu_clock_event_init(struct perf_event *event)
7262 if (event->attr.type != PERF_TYPE_SOFTWARE)
7265 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
7269 * no branch sampling for software events
7271 if (has_branch_stack(event))
7274 perf_swevent_init_hrtimer(event);
7279 static struct pmu perf_cpu_clock = {
7280 .task_ctx_nr = perf_sw_context,
7282 .capabilities = PERF_PMU_CAP_NO_NMI,
7284 .event_init = cpu_clock_event_init,
7285 .add = cpu_clock_event_add,
7286 .del = cpu_clock_event_del,
7287 .start = cpu_clock_event_start,
7288 .stop = cpu_clock_event_stop,
7289 .read = cpu_clock_event_read,
7293 * Software event: task time clock
7296 static void task_clock_event_update(struct perf_event *event, u64 now)
7301 prev = local64_xchg(&event->hw.prev_count, now);
7303 local64_add(delta, &event->count);
7306 static void task_clock_event_start(struct perf_event *event, int flags)
7308 local64_set(&event->hw.prev_count, event->ctx->time);
7309 perf_swevent_start_hrtimer(event);
7312 static void task_clock_event_stop(struct perf_event *event, int flags)
7314 perf_swevent_cancel_hrtimer(event);
7315 task_clock_event_update(event, event->ctx->time);
7318 static int task_clock_event_add(struct perf_event *event, int flags)
7320 if (flags & PERF_EF_START)
7321 task_clock_event_start(event, flags);
7322 perf_event_update_userpage(event);
7327 static void task_clock_event_del(struct perf_event *event, int flags)
7329 task_clock_event_stop(event, PERF_EF_UPDATE);
7332 static void task_clock_event_read(struct perf_event *event)
7334 u64 now = perf_clock();
7335 u64 delta = now - event->ctx->timestamp;
7336 u64 time = event->ctx->time + delta;
7338 task_clock_event_update(event, time);
7341 static int task_clock_event_init(struct perf_event *event)
7343 if (event->attr.type != PERF_TYPE_SOFTWARE)
7346 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
7350 * no branch sampling for software events
7352 if (has_branch_stack(event))
7355 perf_swevent_init_hrtimer(event);
7360 static struct pmu perf_task_clock = {
7361 .task_ctx_nr = perf_sw_context,
7363 .capabilities = PERF_PMU_CAP_NO_NMI,
7365 .event_init = task_clock_event_init,
7366 .add = task_clock_event_add,
7367 .del = task_clock_event_del,
7368 .start = task_clock_event_start,
7369 .stop = task_clock_event_stop,
7370 .read = task_clock_event_read,
7373 static void perf_pmu_nop_void(struct pmu *pmu)
7377 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
7381 static int perf_pmu_nop_int(struct pmu *pmu)
7386 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
7388 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
7390 __this_cpu_write(nop_txn_flags, flags);
7392 if (flags & ~PERF_PMU_TXN_ADD)
7395 perf_pmu_disable(pmu);
7398 static int perf_pmu_commit_txn(struct pmu *pmu)
7400 unsigned int flags = __this_cpu_read(nop_txn_flags);
7402 __this_cpu_write(nop_txn_flags, 0);
7404 if (flags & ~PERF_PMU_TXN_ADD)
7407 perf_pmu_enable(pmu);
7411 static void perf_pmu_cancel_txn(struct pmu *pmu)
7413 unsigned int flags = __this_cpu_read(nop_txn_flags);
7415 __this_cpu_write(nop_txn_flags, 0);
7417 if (flags & ~PERF_PMU_TXN_ADD)
7420 perf_pmu_enable(pmu);
7423 static int perf_event_idx_default(struct perf_event *event)
7429 * Ensures all contexts with the same task_ctx_nr have the same
7430 * pmu_cpu_context too.
7432 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
7439 list_for_each_entry(pmu, &pmus, entry) {
7440 if (pmu->task_ctx_nr == ctxn)
7441 return pmu->pmu_cpu_context;
7447 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
7451 for_each_possible_cpu(cpu) {
7452 struct perf_cpu_context *cpuctx;
7454 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7456 if (cpuctx->unique_pmu == old_pmu)
7457 cpuctx->unique_pmu = pmu;
7461 static void free_pmu_context(struct pmu *pmu)
7465 mutex_lock(&pmus_lock);
7467 * Like a real lame refcount.
7469 list_for_each_entry(i, &pmus, entry) {
7470 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
7471 update_pmu_context(i, pmu);
7476 free_percpu(pmu->pmu_cpu_context);
7478 mutex_unlock(&pmus_lock);
7480 static struct idr pmu_idr;
7483 type_show(struct device *dev, struct device_attribute *attr, char *page)
7485 struct pmu *pmu = dev_get_drvdata(dev);
7487 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
7489 static DEVICE_ATTR_RO(type);
7492 perf_event_mux_interval_ms_show(struct device *dev,
7493 struct device_attribute *attr,
7496 struct pmu *pmu = dev_get_drvdata(dev);
7498 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
7501 static DEFINE_MUTEX(mux_interval_mutex);
7504 perf_event_mux_interval_ms_store(struct device *dev,
7505 struct device_attribute *attr,
7506 const char *buf, size_t count)
7508 struct pmu *pmu = dev_get_drvdata(dev);
7509 int timer, cpu, ret;
7511 ret = kstrtoint(buf, 0, &timer);
7518 /* same value, noting to do */
7519 if (timer == pmu->hrtimer_interval_ms)
7522 mutex_lock(&mux_interval_mutex);
7523 pmu->hrtimer_interval_ms = timer;
7525 /* update all cpuctx for this PMU */
7527 for_each_online_cpu(cpu) {
7528 struct perf_cpu_context *cpuctx;
7529 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7530 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
7532 cpu_function_call(cpu,
7533 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
7536 mutex_unlock(&mux_interval_mutex);
7540 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
7542 static struct attribute *pmu_dev_attrs[] = {
7543 &dev_attr_type.attr,
7544 &dev_attr_perf_event_mux_interval_ms.attr,
7547 ATTRIBUTE_GROUPS(pmu_dev);
7549 static int pmu_bus_running;
7550 static struct bus_type pmu_bus = {
7551 .name = "event_source",
7552 .dev_groups = pmu_dev_groups,
7555 static void pmu_dev_release(struct device *dev)
7560 static int pmu_dev_alloc(struct pmu *pmu)
7564 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
7568 pmu->dev->groups = pmu->attr_groups;
7569 device_initialize(pmu->dev);
7570 ret = dev_set_name(pmu->dev, "%s", pmu->name);
7574 dev_set_drvdata(pmu->dev, pmu);
7575 pmu->dev->bus = &pmu_bus;
7576 pmu->dev->release = pmu_dev_release;
7577 ret = device_add(pmu->dev);
7585 put_device(pmu->dev);
7589 static struct lock_class_key cpuctx_mutex;
7590 static struct lock_class_key cpuctx_lock;
7592 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
7596 mutex_lock(&pmus_lock);
7598 pmu->pmu_disable_count = alloc_percpu(int);
7599 if (!pmu->pmu_disable_count)
7608 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
7616 if (pmu_bus_running) {
7617 ret = pmu_dev_alloc(pmu);
7623 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
7624 if (pmu->pmu_cpu_context)
7625 goto got_cpu_context;
7628 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
7629 if (!pmu->pmu_cpu_context)
7632 for_each_possible_cpu(cpu) {
7633 struct perf_cpu_context *cpuctx;
7635 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7636 __perf_event_init_context(&cpuctx->ctx);
7637 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
7638 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
7639 cpuctx->ctx.pmu = pmu;
7641 __perf_mux_hrtimer_init(cpuctx, cpu);
7643 cpuctx->unique_pmu = pmu;
7647 if (!pmu->start_txn) {
7648 if (pmu->pmu_enable) {
7650 * If we have pmu_enable/pmu_disable calls, install
7651 * transaction stubs that use that to try and batch
7652 * hardware accesses.
7654 pmu->start_txn = perf_pmu_start_txn;
7655 pmu->commit_txn = perf_pmu_commit_txn;
7656 pmu->cancel_txn = perf_pmu_cancel_txn;
7658 pmu->start_txn = perf_pmu_nop_txn;
7659 pmu->commit_txn = perf_pmu_nop_int;
7660 pmu->cancel_txn = perf_pmu_nop_void;
7664 if (!pmu->pmu_enable) {
7665 pmu->pmu_enable = perf_pmu_nop_void;
7666 pmu->pmu_disable = perf_pmu_nop_void;
7669 if (!pmu->event_idx)
7670 pmu->event_idx = perf_event_idx_default;
7672 list_add_rcu(&pmu->entry, &pmus);
7673 atomic_set(&pmu->exclusive_cnt, 0);
7676 mutex_unlock(&pmus_lock);
7681 device_del(pmu->dev);
7682 put_device(pmu->dev);
7685 if (pmu->type >= PERF_TYPE_MAX)
7686 idr_remove(&pmu_idr, pmu->type);
7689 free_percpu(pmu->pmu_disable_count);
7692 EXPORT_SYMBOL_GPL(perf_pmu_register);
7694 void perf_pmu_unregister(struct pmu *pmu)
7696 mutex_lock(&pmus_lock);
7697 list_del_rcu(&pmu->entry);
7698 mutex_unlock(&pmus_lock);
7701 * We dereference the pmu list under both SRCU and regular RCU, so
7702 * synchronize against both of those.
7704 synchronize_srcu(&pmus_srcu);
7707 free_percpu(pmu->pmu_disable_count);
7708 if (pmu->type >= PERF_TYPE_MAX)
7709 idr_remove(&pmu_idr, pmu->type);
7710 device_del(pmu->dev);
7711 put_device(pmu->dev);
7712 free_pmu_context(pmu);
7714 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
7716 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
7718 struct perf_event_context *ctx = NULL;
7721 if (!try_module_get(pmu->module))
7724 if (event->group_leader != event) {
7726 * This ctx->mutex can nest when we're called through
7727 * inheritance. See the perf_event_ctx_lock_nested() comment.
7729 ctx = perf_event_ctx_lock_nested(event->group_leader,
7730 SINGLE_DEPTH_NESTING);
7735 ret = pmu->event_init(event);
7738 perf_event_ctx_unlock(event->group_leader, ctx);
7741 module_put(pmu->module);
7746 static struct pmu *perf_init_event(struct perf_event *event)
7748 struct pmu *pmu = NULL;
7752 idx = srcu_read_lock(&pmus_srcu);
7755 pmu = idr_find(&pmu_idr, event->attr.type);
7758 ret = perf_try_init_event(pmu, event);
7764 list_for_each_entry_rcu(pmu, &pmus, entry) {
7765 ret = perf_try_init_event(pmu, event);
7769 if (ret != -ENOENT) {
7774 pmu = ERR_PTR(-ENOENT);
7776 srcu_read_unlock(&pmus_srcu, idx);
7781 static void account_event_cpu(struct perf_event *event, int cpu)
7786 if (is_cgroup_event(event))
7787 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
7790 static void account_event(struct perf_event *event)
7797 if (event->attach_state & PERF_ATTACH_TASK)
7799 if (event->attr.mmap || event->attr.mmap_data)
7800 atomic_inc(&nr_mmap_events);
7801 if (event->attr.comm)
7802 atomic_inc(&nr_comm_events);
7803 if (event->attr.task)
7804 atomic_inc(&nr_task_events);
7805 if (event->attr.freq) {
7806 if (atomic_inc_return(&nr_freq_events) == 1)
7807 tick_nohz_full_kick_all();
7809 if (event->attr.context_switch) {
7810 atomic_inc(&nr_switch_events);
7813 if (has_branch_stack(event))
7815 if (is_cgroup_event(event))
7819 if (atomic_inc_not_zero(&perf_sched_count))
7822 mutex_lock(&perf_sched_mutex);
7823 if (!atomic_read(&perf_sched_count)) {
7824 static_branch_enable(&perf_sched_events);
7826 * Guarantee that all CPUs observe they key change and
7827 * call the perf scheduling hooks before proceeding to
7828 * install events that need them.
7830 synchronize_sched();
7833 * Now that we have waited for the sync_sched(), allow further
7834 * increments to by-pass the mutex.
7836 atomic_inc(&perf_sched_count);
7837 mutex_unlock(&perf_sched_mutex);
7841 account_event_cpu(event, event->cpu);
7845 * Allocate and initialize a event structure
7847 static struct perf_event *
7848 perf_event_alloc(struct perf_event_attr *attr, int cpu,
7849 struct task_struct *task,
7850 struct perf_event *group_leader,
7851 struct perf_event *parent_event,
7852 perf_overflow_handler_t overflow_handler,
7853 void *context, int cgroup_fd)
7856 struct perf_event *event;
7857 struct hw_perf_event *hwc;
7860 if ((unsigned)cpu >= nr_cpu_ids) {
7861 if (!task || cpu != -1)
7862 return ERR_PTR(-EINVAL);
7865 event = kzalloc(sizeof(*event), GFP_KERNEL);
7867 return ERR_PTR(-ENOMEM);
7870 * Single events are their own group leaders, with an
7871 * empty sibling list:
7874 group_leader = event;
7876 mutex_init(&event->child_mutex);
7877 INIT_LIST_HEAD(&event->child_list);
7879 INIT_LIST_HEAD(&event->group_entry);
7880 INIT_LIST_HEAD(&event->event_entry);
7881 INIT_LIST_HEAD(&event->sibling_list);
7882 INIT_LIST_HEAD(&event->rb_entry);
7883 INIT_LIST_HEAD(&event->active_entry);
7884 INIT_HLIST_NODE(&event->hlist_entry);
7887 init_waitqueue_head(&event->waitq);
7888 init_irq_work(&event->pending, perf_pending_event);
7890 mutex_init(&event->mmap_mutex);
7892 atomic_long_set(&event->refcount, 1);
7894 event->attr = *attr;
7895 event->group_leader = group_leader;
7899 event->parent = parent_event;
7901 event->ns = get_pid_ns(task_active_pid_ns(current));
7902 event->id = atomic64_inc_return(&perf_event_id);
7904 event->state = PERF_EVENT_STATE_INACTIVE;
7907 event->attach_state = PERF_ATTACH_TASK;
7909 * XXX pmu::event_init needs to know what task to account to
7910 * and we cannot use the ctx information because we need the
7911 * pmu before we get a ctx.
7913 event->hw.target = task;
7916 event->clock = &local_clock;
7918 event->clock = parent_event->clock;
7920 if (!overflow_handler && parent_event) {
7921 overflow_handler = parent_event->overflow_handler;
7922 context = parent_event->overflow_handler_context;
7925 event->overflow_handler = overflow_handler;
7926 event->overflow_handler_context = context;
7928 perf_event__state_init(event);
7933 hwc->sample_period = attr->sample_period;
7934 if (attr->freq && attr->sample_freq)
7935 hwc->sample_period = 1;
7936 hwc->last_period = hwc->sample_period;
7938 local64_set(&hwc->period_left, hwc->sample_period);
7941 * we currently do not support PERF_FORMAT_GROUP on inherited events
7943 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
7946 if (!has_branch_stack(event))
7947 event->attr.branch_sample_type = 0;
7949 if (cgroup_fd != -1) {
7950 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
7955 pmu = perf_init_event(event);
7958 else if (IS_ERR(pmu)) {
7963 err = exclusive_event_init(event);
7967 if (!event->parent) {
7968 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
7969 err = get_callchain_buffers();
7978 exclusive_event_destroy(event);
7982 event->destroy(event);
7983 module_put(pmu->module);
7985 if (is_cgroup_event(event))
7986 perf_detach_cgroup(event);
7988 put_pid_ns(event->ns);
7991 return ERR_PTR(err);
7994 static int perf_copy_attr(struct perf_event_attr __user *uattr,
7995 struct perf_event_attr *attr)
8000 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
8004 * zero the full structure, so that a short copy will be nice.
8006 memset(attr, 0, sizeof(*attr));
8008 ret = get_user(size, &uattr->size);
8012 if (size > PAGE_SIZE) /* silly large */
8015 if (!size) /* abi compat */
8016 size = PERF_ATTR_SIZE_VER0;
8018 if (size < PERF_ATTR_SIZE_VER0)
8022 * If we're handed a bigger struct than we know of,
8023 * ensure all the unknown bits are 0 - i.e. new
8024 * user-space does not rely on any kernel feature
8025 * extensions we dont know about yet.
8027 if (size > sizeof(*attr)) {
8028 unsigned char __user *addr;
8029 unsigned char __user *end;
8032 addr = (void __user *)uattr + sizeof(*attr);
8033 end = (void __user *)uattr + size;
8035 for (; addr < end; addr++) {
8036 ret = get_user(val, addr);
8042 size = sizeof(*attr);
8045 ret = copy_from_user(attr, uattr, size);
8049 if (attr->__reserved_1)
8052 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
8055 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
8058 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
8059 u64 mask = attr->branch_sample_type;
8061 /* only using defined bits */
8062 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
8065 /* at least one branch bit must be set */
8066 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
8069 /* propagate priv level, when not set for branch */
8070 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
8072 /* exclude_kernel checked on syscall entry */
8073 if (!attr->exclude_kernel)
8074 mask |= PERF_SAMPLE_BRANCH_KERNEL;
8076 if (!attr->exclude_user)
8077 mask |= PERF_SAMPLE_BRANCH_USER;
8079 if (!attr->exclude_hv)
8080 mask |= PERF_SAMPLE_BRANCH_HV;
8082 * adjust user setting (for HW filter setup)
8084 attr->branch_sample_type = mask;
8086 /* privileged levels capture (kernel, hv): check permissions */
8087 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
8088 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8092 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
8093 ret = perf_reg_validate(attr->sample_regs_user);
8098 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
8099 if (!arch_perf_have_user_stack_dump())
8103 * We have __u32 type for the size, but so far
8104 * we can only use __u16 as maximum due to the
8105 * __u16 sample size limit.
8107 if (attr->sample_stack_user >= USHRT_MAX)
8109 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
8113 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
8114 ret = perf_reg_validate(attr->sample_regs_intr);
8119 put_user(sizeof(*attr), &uattr->size);
8125 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
8127 struct ring_buffer *rb = NULL;
8133 /* don't allow circular references */
8134 if (event == output_event)
8138 * Don't allow cross-cpu buffers
8140 if (output_event->cpu != event->cpu)
8144 * If its not a per-cpu rb, it must be the same task.
8146 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
8150 * Mixing clocks in the same buffer is trouble you don't need.
8152 if (output_event->clock != event->clock)
8156 * If both events generate aux data, they must be on the same PMU
8158 if (has_aux(event) && has_aux(output_event) &&
8159 event->pmu != output_event->pmu)
8163 mutex_lock(&event->mmap_mutex);
8164 /* Can't redirect output if we've got an active mmap() */
8165 if (atomic_read(&event->mmap_count))
8169 /* get the rb we want to redirect to */
8170 rb = ring_buffer_get(output_event);
8175 ring_buffer_attach(event, rb);
8179 mutex_unlock(&event->mmap_mutex);
8185 static void mutex_lock_double(struct mutex *a, struct mutex *b)
8191 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
8194 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
8196 bool nmi_safe = false;
8199 case CLOCK_MONOTONIC:
8200 event->clock = &ktime_get_mono_fast_ns;
8204 case CLOCK_MONOTONIC_RAW:
8205 event->clock = &ktime_get_raw_fast_ns;
8209 case CLOCK_REALTIME:
8210 event->clock = &ktime_get_real_ns;
8213 case CLOCK_BOOTTIME:
8214 event->clock = &ktime_get_boot_ns;
8218 event->clock = &ktime_get_tai_ns;
8225 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
8232 * sys_perf_event_open - open a performance event, associate it to a task/cpu
8234 * @attr_uptr: event_id type attributes for monitoring/sampling
8237 * @group_fd: group leader event fd
8239 SYSCALL_DEFINE5(perf_event_open,
8240 struct perf_event_attr __user *, attr_uptr,
8241 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
8243 struct perf_event *group_leader = NULL, *output_event = NULL;
8244 struct perf_event *event, *sibling;
8245 struct perf_event_attr attr;
8246 struct perf_event_context *ctx, *uninitialized_var(gctx);
8247 struct file *event_file = NULL;
8248 struct fd group = {NULL, 0};
8249 struct task_struct *task = NULL;
8254 int f_flags = O_RDWR;
8257 /* for future expandability... */
8258 if (flags & ~PERF_FLAG_ALL)
8261 err = perf_copy_attr(attr_uptr, &attr);
8265 if (!attr.exclude_kernel) {
8266 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8271 if (attr.sample_freq > sysctl_perf_event_sample_rate)
8274 if (attr.sample_period & (1ULL << 63))
8279 * In cgroup mode, the pid argument is used to pass the fd
8280 * opened to the cgroup directory in cgroupfs. The cpu argument
8281 * designates the cpu on which to monitor threads from that
8284 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
8287 if (flags & PERF_FLAG_FD_CLOEXEC)
8288 f_flags |= O_CLOEXEC;
8290 event_fd = get_unused_fd_flags(f_flags);
8294 if (group_fd != -1) {
8295 err = perf_fget_light(group_fd, &group);
8298 group_leader = group.file->private_data;
8299 if (flags & PERF_FLAG_FD_OUTPUT)
8300 output_event = group_leader;
8301 if (flags & PERF_FLAG_FD_NO_GROUP)
8302 group_leader = NULL;
8305 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
8306 task = find_lively_task_by_vpid(pid);
8308 err = PTR_ERR(task);
8313 if (task && group_leader &&
8314 group_leader->attr.inherit != attr.inherit) {
8321 if (flags & PERF_FLAG_PID_CGROUP)
8324 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
8325 NULL, NULL, cgroup_fd);
8326 if (IS_ERR(event)) {
8327 err = PTR_ERR(event);
8331 if (is_sampling_event(event)) {
8332 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
8338 account_event(event);
8341 * Special case software events and allow them to be part of
8342 * any hardware group.
8346 if (attr.use_clockid) {
8347 err = perf_event_set_clock(event, attr.clockid);
8353 (is_software_event(event) != is_software_event(group_leader))) {
8354 if (is_software_event(event)) {
8356 * If event and group_leader are not both a software
8357 * event, and event is, then group leader is not.
8359 * Allow the addition of software events to !software
8360 * groups, this is safe because software events never
8363 pmu = group_leader->pmu;
8364 } else if (is_software_event(group_leader) &&
8365 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
8367 * In case the group is a pure software group, and we
8368 * try to add a hardware event, move the whole group to
8369 * the hardware context.
8376 * Get the target context (task or percpu):
8378 ctx = find_get_context(pmu, task, event);
8384 if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
8390 put_task_struct(task);
8395 * Look up the group leader (we will attach this event to it):
8401 * Do not allow a recursive hierarchy (this new sibling
8402 * becoming part of another group-sibling):
8404 if (group_leader->group_leader != group_leader)
8407 /* All events in a group should have the same clock */
8408 if (group_leader->clock != event->clock)
8412 * Do not allow to attach to a group in a different
8413 * task or CPU context:
8417 * Make sure we're both on the same task, or both
8420 if (group_leader->ctx->task != ctx->task)
8424 * Make sure we're both events for the same CPU;
8425 * grouping events for different CPUs is broken; since
8426 * you can never concurrently schedule them anyhow.
8428 if (group_leader->cpu != event->cpu)
8431 if (group_leader->ctx != ctx)
8436 * Only a group leader can be exclusive or pinned
8438 if (attr.exclusive || attr.pinned)
8443 err = perf_event_set_output(event, output_event);
8448 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
8450 if (IS_ERR(event_file)) {
8451 err = PTR_ERR(event_file);
8456 gctx = group_leader->ctx;
8457 mutex_lock_double(&gctx->mutex, &ctx->mutex);
8458 if (gctx->task == TASK_TOMBSTONE) {
8463 mutex_lock(&ctx->mutex);
8466 if (ctx->task == TASK_TOMBSTONE) {
8471 if (!perf_event_validate_size(event)) {
8477 * Must be under the same ctx::mutex as perf_install_in_context(),
8478 * because we need to serialize with concurrent event creation.
8480 if (!exclusive_event_installable(event, ctx)) {
8481 /* exclusive and group stuff are assumed mutually exclusive */
8482 WARN_ON_ONCE(move_group);
8488 WARN_ON_ONCE(ctx->parent_ctx);
8492 * See perf_event_ctx_lock() for comments on the details
8493 * of swizzling perf_event::ctx.
8495 perf_remove_from_context(group_leader, 0);
8497 list_for_each_entry(sibling, &group_leader->sibling_list,
8499 perf_remove_from_context(sibling, 0);
8504 * Wait for everybody to stop referencing the events through
8505 * the old lists, before installing it on new lists.
8510 * Install the group siblings before the group leader.
8512 * Because a group leader will try and install the entire group
8513 * (through the sibling list, which is still in-tact), we can
8514 * end up with siblings installed in the wrong context.
8516 * By installing siblings first we NO-OP because they're not
8517 * reachable through the group lists.
8519 list_for_each_entry(sibling, &group_leader->sibling_list,
8521 perf_event__state_init(sibling);
8522 perf_install_in_context(ctx, sibling, sibling->cpu);
8527 * Removing from the context ends up with disabled
8528 * event. What we want here is event in the initial
8529 * startup state, ready to be add into new context.
8531 perf_event__state_init(group_leader);
8532 perf_install_in_context(ctx, group_leader, group_leader->cpu);
8536 * Now that all events are installed in @ctx, nothing
8537 * references @gctx anymore, so drop the last reference we have
8544 * Precalculate sample_data sizes; do while holding ctx::mutex such
8545 * that we're serialized against further additions and before
8546 * perf_install_in_context() which is the point the event is active and
8547 * can use these values.
8549 perf_event__header_size(event);
8550 perf_event__id_header_size(event);
8552 event->owner = current;
8554 perf_install_in_context(ctx, event, event->cpu);
8555 perf_unpin_context(ctx);
8558 mutex_unlock(&gctx->mutex);
8559 mutex_unlock(&ctx->mutex);
8563 mutex_lock(¤t->perf_event_mutex);
8564 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
8565 mutex_unlock(¤t->perf_event_mutex);
8568 * Drop the reference on the group_event after placing the
8569 * new event on the sibling_list. This ensures destruction
8570 * of the group leader will find the pointer to itself in
8571 * perf_group_detach().
8574 fd_install(event_fd, event_file);
8579 mutex_unlock(&gctx->mutex);
8580 mutex_unlock(&ctx->mutex);
8584 perf_unpin_context(ctx);
8588 * If event_file is set, the fput() above will have called ->release()
8589 * and that will take care of freeing the event.
8597 put_task_struct(task);
8601 put_unused_fd(event_fd);
8606 * perf_event_create_kernel_counter
8608 * @attr: attributes of the counter to create
8609 * @cpu: cpu in which the counter is bound
8610 * @task: task to profile (NULL for percpu)
8613 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
8614 struct task_struct *task,
8615 perf_overflow_handler_t overflow_handler,
8618 struct perf_event_context *ctx;
8619 struct perf_event *event;
8623 * Get the target context (task or percpu):
8626 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
8627 overflow_handler, context, -1);
8628 if (IS_ERR(event)) {
8629 err = PTR_ERR(event);
8633 /* Mark owner so we could distinguish it from user events. */
8634 event->owner = TASK_TOMBSTONE;
8636 account_event(event);
8638 ctx = find_get_context(event->pmu, task, event);
8644 WARN_ON_ONCE(ctx->parent_ctx);
8645 mutex_lock(&ctx->mutex);
8646 if (ctx->task == TASK_TOMBSTONE) {
8651 if (!exclusive_event_installable(event, ctx)) {
8656 perf_install_in_context(ctx, event, cpu);
8657 perf_unpin_context(ctx);
8658 mutex_unlock(&ctx->mutex);
8663 mutex_unlock(&ctx->mutex);
8664 perf_unpin_context(ctx);
8669 return ERR_PTR(err);
8671 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
8673 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
8675 struct perf_event_context *src_ctx;
8676 struct perf_event_context *dst_ctx;
8677 struct perf_event *event, *tmp;
8680 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
8681 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
8684 * See perf_event_ctx_lock() for comments on the details
8685 * of swizzling perf_event::ctx.
8687 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
8688 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
8690 perf_remove_from_context(event, 0);
8691 unaccount_event_cpu(event, src_cpu);
8693 list_add(&event->migrate_entry, &events);
8697 * Wait for the events to quiesce before re-instating them.
8702 * Re-instate events in 2 passes.
8704 * Skip over group leaders and only install siblings on this first
8705 * pass, siblings will not get enabled without a leader, however a
8706 * leader will enable its siblings, even if those are still on the old
8709 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
8710 if (event->group_leader == event)
8713 list_del(&event->migrate_entry);
8714 if (event->state >= PERF_EVENT_STATE_OFF)
8715 event->state = PERF_EVENT_STATE_INACTIVE;
8716 account_event_cpu(event, dst_cpu);
8717 perf_install_in_context(dst_ctx, event, dst_cpu);
8722 * Once all the siblings are setup properly, install the group leaders
8725 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
8726 list_del(&event->migrate_entry);
8727 if (event->state >= PERF_EVENT_STATE_OFF)
8728 event->state = PERF_EVENT_STATE_INACTIVE;
8729 account_event_cpu(event, dst_cpu);
8730 perf_install_in_context(dst_ctx, event, dst_cpu);
8733 mutex_unlock(&dst_ctx->mutex);
8734 mutex_unlock(&src_ctx->mutex);
8736 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
8738 static void sync_child_event(struct perf_event *child_event,
8739 struct task_struct *child)
8741 struct perf_event *parent_event = child_event->parent;
8744 if (child_event->attr.inherit_stat)
8745 perf_event_read_event(child_event, child);
8747 child_val = perf_event_count(child_event);
8750 * Add back the child's count to the parent's count:
8752 atomic64_add(child_val, &parent_event->child_count);
8753 atomic64_add(child_event->total_time_enabled,
8754 &parent_event->child_total_time_enabled);
8755 atomic64_add(child_event->total_time_running,
8756 &parent_event->child_total_time_running);
8760 perf_event_exit_event(struct perf_event *child_event,
8761 struct perf_event_context *child_ctx,
8762 struct task_struct *child)
8764 struct perf_event *parent_event = child_event->parent;
8767 * Do not destroy the 'original' grouping; because of the context
8768 * switch optimization the original events could've ended up in a
8769 * random child task.
8771 * If we were to destroy the original group, all group related
8772 * operations would cease to function properly after this random
8775 * Do destroy all inherited groups, we don't care about those
8776 * and being thorough is better.
8778 raw_spin_lock_irq(&child_ctx->lock);
8779 WARN_ON_ONCE(child_ctx->is_active);
8782 perf_group_detach(child_event);
8783 list_del_event(child_event, child_ctx);
8784 child_event->state = PERF_EVENT_STATE_EXIT; /* is_event_hup() */
8785 raw_spin_unlock_irq(&child_ctx->lock);
8788 * Parent events are governed by their filedesc, retain them.
8790 if (!parent_event) {
8791 perf_event_wakeup(child_event);
8795 * Child events can be cleaned up.
8798 sync_child_event(child_event, child);
8801 * Remove this event from the parent's list
8803 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
8804 mutex_lock(&parent_event->child_mutex);
8805 list_del_init(&child_event->child_list);
8806 mutex_unlock(&parent_event->child_mutex);
8809 * Kick perf_poll() for is_event_hup().
8811 perf_event_wakeup(parent_event);
8812 free_event(child_event);
8813 put_event(parent_event);
8816 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
8818 struct perf_event_context *child_ctx, *clone_ctx = NULL;
8819 struct perf_event *child_event, *next;
8821 WARN_ON_ONCE(child != current);
8823 child_ctx = perf_pin_task_context(child, ctxn);
8828 * In order to reduce the amount of tricky in ctx tear-down, we hold
8829 * ctx::mutex over the entire thing. This serializes against almost
8830 * everything that wants to access the ctx.
8832 * The exception is sys_perf_event_open() /
8833 * perf_event_create_kernel_count() which does find_get_context()
8834 * without ctx::mutex (it cannot because of the move_group double mutex
8835 * lock thing). See the comments in perf_install_in_context().
8837 mutex_lock(&child_ctx->mutex);
8840 * In a single ctx::lock section, de-schedule the events and detach the
8841 * context from the task such that we cannot ever get it scheduled back
8844 raw_spin_lock_irq(&child_ctx->lock);
8845 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx);
8848 * Now that the context is inactive, destroy the task <-> ctx relation
8849 * and mark the context dead.
8851 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
8852 put_ctx(child_ctx); /* cannot be last */
8853 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
8854 put_task_struct(current); /* cannot be last */
8856 clone_ctx = unclone_ctx(child_ctx);
8857 raw_spin_unlock_irq(&child_ctx->lock);
8863 * Report the task dead after unscheduling the events so that we
8864 * won't get any samples after PERF_RECORD_EXIT. We can however still
8865 * get a few PERF_RECORD_READ events.
8867 perf_event_task(child, child_ctx, 0);
8869 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
8870 perf_event_exit_event(child_event, child_ctx, child);
8872 mutex_unlock(&child_ctx->mutex);
8878 * When a child task exits, feed back event values to parent events.
8880 void perf_event_exit_task(struct task_struct *child)
8882 struct perf_event *event, *tmp;
8885 mutex_lock(&child->perf_event_mutex);
8886 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
8888 list_del_init(&event->owner_entry);
8891 * Ensure the list deletion is visible before we clear
8892 * the owner, closes a race against perf_release() where
8893 * we need to serialize on the owner->perf_event_mutex.
8895 smp_store_release(&event->owner, NULL);
8897 mutex_unlock(&child->perf_event_mutex);
8899 for_each_task_context_nr(ctxn)
8900 perf_event_exit_task_context(child, ctxn);
8903 * The perf_event_exit_task_context calls perf_event_task
8904 * with child's task_ctx, which generates EXIT events for
8905 * child contexts and sets child->perf_event_ctxp[] to NULL.
8906 * At this point we need to send EXIT events to cpu contexts.
8908 perf_event_task(child, NULL, 0);
8911 static void perf_free_event(struct perf_event *event,
8912 struct perf_event_context *ctx)
8914 struct perf_event *parent = event->parent;
8916 if (WARN_ON_ONCE(!parent))
8919 mutex_lock(&parent->child_mutex);
8920 list_del_init(&event->child_list);
8921 mutex_unlock(&parent->child_mutex);
8925 raw_spin_lock_irq(&ctx->lock);
8926 perf_group_detach(event);
8927 list_del_event(event, ctx);
8928 raw_spin_unlock_irq(&ctx->lock);
8933 * Free an unexposed, unused context as created by inheritance by
8934 * perf_event_init_task below, used by fork() in case of fail.
8936 * Not all locks are strictly required, but take them anyway to be nice and
8937 * help out with the lockdep assertions.
8939 void perf_event_free_task(struct task_struct *task)
8941 struct perf_event_context *ctx;
8942 struct perf_event *event, *tmp;
8945 for_each_task_context_nr(ctxn) {
8946 ctx = task->perf_event_ctxp[ctxn];
8950 mutex_lock(&ctx->mutex);
8952 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
8954 perf_free_event(event, ctx);
8956 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
8958 perf_free_event(event, ctx);
8960 if (!list_empty(&ctx->pinned_groups) ||
8961 !list_empty(&ctx->flexible_groups))
8964 mutex_unlock(&ctx->mutex);
8970 void perf_event_delayed_put(struct task_struct *task)
8974 for_each_task_context_nr(ctxn)
8975 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
8978 struct file *perf_event_get(unsigned int fd)
8982 file = fget_raw(fd);
8984 return ERR_PTR(-EBADF);
8986 if (file->f_op != &perf_fops) {
8988 return ERR_PTR(-EBADF);
8994 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
8997 return ERR_PTR(-EINVAL);
8999 return &event->attr;
9003 * inherit a event from parent task to child task:
9005 static struct perf_event *
9006 inherit_event(struct perf_event *parent_event,
9007 struct task_struct *parent,
9008 struct perf_event_context *parent_ctx,
9009 struct task_struct *child,
9010 struct perf_event *group_leader,
9011 struct perf_event_context *child_ctx)
9013 enum perf_event_active_state parent_state = parent_event->state;
9014 struct perf_event *child_event;
9015 unsigned long flags;
9018 * Instead of creating recursive hierarchies of events,
9019 * we link inherited events back to the original parent,
9020 * which has a filp for sure, which we use as the reference
9023 if (parent_event->parent)
9024 parent_event = parent_event->parent;
9026 child_event = perf_event_alloc(&parent_event->attr,
9029 group_leader, parent_event,
9031 if (IS_ERR(child_event))
9035 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
9036 * must be under the same lock in order to serialize against
9037 * perf_event_release_kernel(), such that either we must observe
9038 * is_orphaned_event() or they will observe us on the child_list.
9040 mutex_lock(&parent_event->child_mutex);
9041 if (is_orphaned_event(parent_event) ||
9042 !atomic_long_inc_not_zero(&parent_event->refcount)) {
9043 mutex_unlock(&parent_event->child_mutex);
9044 free_event(child_event);
9051 * Make the child state follow the state of the parent event,
9052 * not its attr.disabled bit. We hold the parent's mutex,
9053 * so we won't race with perf_event_{en, dis}able_family.
9055 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
9056 child_event->state = PERF_EVENT_STATE_INACTIVE;
9058 child_event->state = PERF_EVENT_STATE_OFF;
9060 if (parent_event->attr.freq) {
9061 u64 sample_period = parent_event->hw.sample_period;
9062 struct hw_perf_event *hwc = &child_event->hw;
9064 hwc->sample_period = sample_period;
9065 hwc->last_period = sample_period;
9067 local64_set(&hwc->period_left, sample_period);
9070 child_event->ctx = child_ctx;
9071 child_event->overflow_handler = parent_event->overflow_handler;
9072 child_event->overflow_handler_context
9073 = parent_event->overflow_handler_context;
9076 * Precalculate sample_data sizes
9078 perf_event__header_size(child_event);
9079 perf_event__id_header_size(child_event);
9082 * Link it up in the child's context:
9084 raw_spin_lock_irqsave(&child_ctx->lock, flags);
9085 add_event_to_ctx(child_event, child_ctx);
9086 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
9089 * Link this into the parent event's child list
9091 list_add_tail(&child_event->child_list, &parent_event->child_list);
9092 mutex_unlock(&parent_event->child_mutex);
9097 static int inherit_group(struct perf_event *parent_event,
9098 struct task_struct *parent,
9099 struct perf_event_context *parent_ctx,
9100 struct task_struct *child,
9101 struct perf_event_context *child_ctx)
9103 struct perf_event *leader;
9104 struct perf_event *sub;
9105 struct perf_event *child_ctr;
9107 leader = inherit_event(parent_event, parent, parent_ctx,
9108 child, NULL, child_ctx);
9110 return PTR_ERR(leader);
9111 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
9112 child_ctr = inherit_event(sub, parent, parent_ctx,
9113 child, leader, child_ctx);
9114 if (IS_ERR(child_ctr))
9115 return PTR_ERR(child_ctr);
9121 inherit_task_group(struct perf_event *event, struct task_struct *parent,
9122 struct perf_event_context *parent_ctx,
9123 struct task_struct *child, int ctxn,
9127 struct perf_event_context *child_ctx;
9129 if (!event->attr.inherit) {
9134 child_ctx = child->perf_event_ctxp[ctxn];
9137 * This is executed from the parent task context, so
9138 * inherit events that have been marked for cloning.
9139 * First allocate and initialize a context for the
9143 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
9147 child->perf_event_ctxp[ctxn] = child_ctx;
9150 ret = inherit_group(event, parent, parent_ctx,
9160 * Initialize the perf_event context in task_struct
9162 static int perf_event_init_context(struct task_struct *child, int ctxn)
9164 struct perf_event_context *child_ctx, *parent_ctx;
9165 struct perf_event_context *cloned_ctx;
9166 struct perf_event *event;
9167 struct task_struct *parent = current;
9168 int inherited_all = 1;
9169 unsigned long flags;
9172 if (likely(!parent->perf_event_ctxp[ctxn]))
9176 * If the parent's context is a clone, pin it so it won't get
9179 parent_ctx = perf_pin_task_context(parent, ctxn);
9184 * No need to check if parent_ctx != NULL here; since we saw
9185 * it non-NULL earlier, the only reason for it to become NULL
9186 * is if we exit, and since we're currently in the middle of
9187 * a fork we can't be exiting at the same time.
9191 * Lock the parent list. No need to lock the child - not PID
9192 * hashed yet and not running, so nobody can access it.
9194 mutex_lock(&parent_ctx->mutex);
9197 * We dont have to disable NMIs - we are only looking at
9198 * the list, not manipulating it:
9200 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
9201 ret = inherit_task_group(event, parent, parent_ctx,
9202 child, ctxn, &inherited_all);
9208 * We can't hold ctx->lock when iterating the ->flexible_group list due
9209 * to allocations, but we need to prevent rotation because
9210 * rotate_ctx() will change the list from interrupt context.
9212 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9213 parent_ctx->rotate_disable = 1;
9214 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9216 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
9217 ret = inherit_task_group(event, parent, parent_ctx,
9218 child, ctxn, &inherited_all);
9223 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9224 parent_ctx->rotate_disable = 0;
9226 child_ctx = child->perf_event_ctxp[ctxn];
9228 if (child_ctx && inherited_all) {
9230 * Mark the child context as a clone of the parent
9231 * context, or of whatever the parent is a clone of.
9233 * Note that if the parent is a clone, the holding of
9234 * parent_ctx->lock avoids it from being uncloned.
9236 cloned_ctx = parent_ctx->parent_ctx;
9238 child_ctx->parent_ctx = cloned_ctx;
9239 child_ctx->parent_gen = parent_ctx->parent_gen;
9241 child_ctx->parent_ctx = parent_ctx;
9242 child_ctx->parent_gen = parent_ctx->generation;
9244 get_ctx(child_ctx->parent_ctx);
9247 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9248 mutex_unlock(&parent_ctx->mutex);
9250 perf_unpin_context(parent_ctx);
9251 put_ctx(parent_ctx);
9257 * Initialize the perf_event context in task_struct
9259 int perf_event_init_task(struct task_struct *child)
9263 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
9264 mutex_init(&child->perf_event_mutex);
9265 INIT_LIST_HEAD(&child->perf_event_list);
9267 for_each_task_context_nr(ctxn) {
9268 ret = perf_event_init_context(child, ctxn);
9270 perf_event_free_task(child);
9278 static void __init perf_event_init_all_cpus(void)
9280 struct swevent_htable *swhash;
9283 for_each_possible_cpu(cpu) {
9284 swhash = &per_cpu(swevent_htable, cpu);
9285 mutex_init(&swhash->hlist_mutex);
9286 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
9290 static void perf_event_init_cpu(int cpu)
9292 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9294 mutex_lock(&swhash->hlist_mutex);
9295 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
9296 struct swevent_hlist *hlist;
9298 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
9300 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9302 mutex_unlock(&swhash->hlist_mutex);
9305 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
9306 static void __perf_event_exit_context(void *__info)
9308 struct perf_event_context *ctx = __info;
9309 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
9310 struct perf_event *event;
9312 raw_spin_lock(&ctx->lock);
9313 list_for_each_entry(event, &ctx->event_list, event_entry)
9314 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
9315 raw_spin_unlock(&ctx->lock);
9318 static void perf_event_exit_cpu_context(int cpu)
9320 struct perf_event_context *ctx;
9324 idx = srcu_read_lock(&pmus_srcu);
9325 list_for_each_entry_rcu(pmu, &pmus, entry) {
9326 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
9328 mutex_lock(&ctx->mutex);
9329 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
9330 mutex_unlock(&ctx->mutex);
9332 srcu_read_unlock(&pmus_srcu, idx);
9335 static void perf_event_exit_cpu(int cpu)
9337 perf_event_exit_cpu_context(cpu);
9340 static inline void perf_event_exit_cpu(int cpu) { }
9344 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
9348 for_each_online_cpu(cpu)
9349 perf_event_exit_cpu(cpu);
9355 * Run the perf reboot notifier at the very last possible moment so that
9356 * the generic watchdog code runs as long as possible.
9358 static struct notifier_block perf_reboot_notifier = {
9359 .notifier_call = perf_reboot,
9360 .priority = INT_MIN,
9364 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
9366 unsigned int cpu = (long)hcpu;
9368 switch (action & ~CPU_TASKS_FROZEN) {
9370 case CPU_UP_PREPARE:
9371 perf_event_init_cpu(cpu);
9374 case CPU_DOWN_PREPARE:
9375 perf_event_exit_cpu(cpu);
9384 void __init perf_event_init(void)
9390 perf_event_init_all_cpus();
9391 init_srcu_struct(&pmus_srcu);
9392 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
9393 perf_pmu_register(&perf_cpu_clock, NULL, -1);
9394 perf_pmu_register(&perf_task_clock, NULL, -1);
9396 perf_cpu_notifier(perf_cpu_notify);
9397 register_reboot_notifier(&perf_reboot_notifier);
9399 ret = init_hw_breakpoint();
9400 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
9403 * Build time assertion that we keep the data_head at the intended
9404 * location. IOW, validation we got the __reserved[] size right.
9406 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
9410 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
9413 struct perf_pmu_events_attr *pmu_attr =
9414 container_of(attr, struct perf_pmu_events_attr, attr);
9416 if (pmu_attr->event_str)
9417 return sprintf(page, "%s\n", pmu_attr->event_str);
9422 static int __init perf_event_sysfs_init(void)
9427 mutex_lock(&pmus_lock);
9429 ret = bus_register(&pmu_bus);
9433 list_for_each_entry(pmu, &pmus, entry) {
9434 if (!pmu->name || pmu->type < 0)
9437 ret = pmu_dev_alloc(pmu);
9438 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
9440 pmu_bus_running = 1;
9444 mutex_unlock(&pmus_lock);
9448 device_initcall(perf_event_sysfs_init);
9450 #ifdef CONFIG_CGROUP_PERF
9451 static struct cgroup_subsys_state *
9452 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
9454 struct perf_cgroup *jc;
9456 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
9458 return ERR_PTR(-ENOMEM);
9460 jc->info = alloc_percpu(struct perf_cgroup_info);
9463 return ERR_PTR(-ENOMEM);
9469 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
9471 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
9473 free_percpu(jc->info);
9477 static int __perf_cgroup_move(void *info)
9479 struct task_struct *task = info;
9481 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
9486 static void perf_cgroup_attach(struct cgroup_taskset *tset)
9488 struct task_struct *task;
9489 struct cgroup_subsys_state *css;
9491 cgroup_taskset_for_each(task, css, tset)
9492 task_function_call(task, __perf_cgroup_move, task);
9495 struct cgroup_subsys perf_event_cgrp_subsys = {
9496 .css_alloc = perf_cgroup_css_alloc,
9497 .css_free = perf_cgroup_css_free,
9498 .attach = perf_cgroup_attach,
9500 #endif /* CONFIG_CGROUP_PERF */