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())
72 * Now that we're on right CPU with IRQs disabled, we can test
73 * if we hit the right task without races.
76 tfc->ret = -ESRCH; /* No such (running) process */
81 tfc->ret = tfc->func(tfc->info);
85 * task_function_call - call a function on the cpu on which a task runs
86 * @p: the task to evaluate
87 * @func: the function to be called
88 * @info: the function call argument
90 * Calls the function @func when the task is currently running. This might
91 * be on the current CPU, which just calls the function directly
93 * returns: @func return value, or
94 * -ESRCH - when the process isn't running
95 * -EAGAIN - when the process moved away
98 task_function_call(struct task_struct *p, remote_function_f func, void *info)
100 struct remote_function_call data = {
109 ret = smp_call_function_single(task_cpu(p), remote_function, &data, 1);
112 } while (ret == -EAGAIN);
118 * cpu_function_call - call a function on the cpu
119 * @func: the function to be called
120 * @info: the function call argument
122 * Calls the function @func on the remote cpu.
124 * returns: @func return value or -ENXIO when the cpu is offline
126 static int cpu_function_call(int cpu, remote_function_f func, void *info)
128 struct remote_function_call data = {
132 .ret = -ENXIO, /* No such CPU */
135 smp_call_function_single(cpu, remote_function, &data, 1);
140 static inline struct perf_cpu_context *
141 __get_cpu_context(struct perf_event_context *ctx)
143 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
146 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
147 struct perf_event_context *ctx)
149 raw_spin_lock(&cpuctx->ctx.lock);
151 raw_spin_lock(&ctx->lock);
154 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
155 struct perf_event_context *ctx)
158 raw_spin_unlock(&ctx->lock);
159 raw_spin_unlock(&cpuctx->ctx.lock);
162 #define TASK_TOMBSTONE ((void *)-1L)
164 static bool is_kernel_event(struct perf_event *event)
166 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
170 * On task ctx scheduling...
172 * When !ctx->nr_events a task context will not be scheduled. This means
173 * we can disable the scheduler hooks (for performance) without leaving
174 * pending task ctx state.
176 * This however results in two special cases:
178 * - removing the last event from a task ctx; this is relatively straight
179 * forward and is done in __perf_remove_from_context.
181 * - adding the first event to a task ctx; this is tricky because we cannot
182 * rely on ctx->is_active and therefore cannot use event_function_call().
183 * See perf_install_in_context().
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);
279 if (task == TASK_TOMBSTONE)
283 if (!task_function_call(task, event_function, &efs))
286 raw_spin_lock_irq(&ctx->lock);
288 * Reload the task pointer, it might have been changed by
289 * a concurrent perf_event_context_sched_out().
292 if (task == TASK_TOMBSTONE) {
293 raw_spin_unlock_irq(&ctx->lock);
296 if (ctx->is_active) {
297 raw_spin_unlock_irq(&ctx->lock);
300 func(event, NULL, ctx, data);
301 raw_spin_unlock_irq(&ctx->lock);
304 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
305 PERF_FLAG_FD_OUTPUT |\
306 PERF_FLAG_PID_CGROUP |\
307 PERF_FLAG_FD_CLOEXEC)
310 * branch priv levels that need permission checks
312 #define PERF_SAMPLE_BRANCH_PERM_PLM \
313 (PERF_SAMPLE_BRANCH_KERNEL |\
314 PERF_SAMPLE_BRANCH_HV)
317 EVENT_FLEXIBLE = 0x1,
320 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
324 * perf_sched_events : >0 events exist
325 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
328 static void perf_sched_delayed(struct work_struct *work);
329 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
330 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
331 static DEFINE_MUTEX(perf_sched_mutex);
332 static atomic_t perf_sched_count;
334 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
335 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
337 static atomic_t nr_mmap_events __read_mostly;
338 static atomic_t nr_comm_events __read_mostly;
339 static atomic_t nr_task_events __read_mostly;
340 static atomic_t nr_freq_events __read_mostly;
341 static atomic_t nr_switch_events __read_mostly;
343 static LIST_HEAD(pmus);
344 static DEFINE_MUTEX(pmus_lock);
345 static struct srcu_struct pmus_srcu;
348 * perf event paranoia level:
349 * -1 - not paranoid at all
350 * 0 - disallow raw tracepoint access for unpriv
351 * 1 - disallow cpu events for unpriv
352 * 2 - disallow kernel profiling for unpriv
354 int sysctl_perf_event_paranoid __read_mostly = 1;
356 /* Minimum for 512 kiB + 1 user control page */
357 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
360 * max perf event sample rate
362 #define DEFAULT_MAX_SAMPLE_RATE 100000
363 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
364 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
366 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
368 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
369 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
371 static int perf_sample_allowed_ns __read_mostly =
372 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
374 static void update_perf_cpu_limits(void)
376 u64 tmp = perf_sample_period_ns;
378 tmp *= sysctl_perf_cpu_time_max_percent;
379 tmp = div_u64(tmp, 100);
383 WRITE_ONCE(perf_sample_allowed_ns, tmp);
386 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
388 int perf_proc_update_handler(struct ctl_table *table, int write,
389 void __user *buffer, size_t *lenp,
392 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
397 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
398 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
399 update_perf_cpu_limits();
404 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
406 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
407 void __user *buffer, size_t *lenp,
410 int ret = proc_dointvec(table, write, buffer, lenp, ppos);
415 if (sysctl_perf_cpu_time_max_percent == 100) {
417 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
418 WRITE_ONCE(perf_sample_allowed_ns, 0);
420 update_perf_cpu_limits();
427 * perf samples are done in some very critical code paths (NMIs).
428 * If they take too much CPU time, the system can lock up and not
429 * get any real work done. This will drop the sample rate when
430 * we detect that events are taking too long.
432 #define NR_ACCUMULATED_SAMPLES 128
433 static DEFINE_PER_CPU(u64, running_sample_length);
435 static u64 __report_avg;
436 static u64 __report_allowed;
438 static void perf_duration_warn(struct irq_work *w)
440 printk_ratelimited(KERN_WARNING
441 "perf: interrupt took too long (%lld > %lld), lowering "
442 "kernel.perf_event_max_sample_rate to %d\n",
443 __report_avg, __report_allowed,
444 sysctl_perf_event_sample_rate);
447 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
449 void perf_sample_event_took(u64 sample_len_ns)
451 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
459 /* Decay the counter by 1 average sample. */
460 running_len = __this_cpu_read(running_sample_length);
461 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
462 running_len += sample_len_ns;
463 __this_cpu_write(running_sample_length, running_len);
466 * Note: this will be biased artifically low until we have
467 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
468 * from having to maintain a count.
470 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
471 if (avg_len <= max_len)
474 __report_avg = avg_len;
475 __report_allowed = max_len;
478 * Compute a throttle threshold 25% below the current duration.
480 avg_len += avg_len / 4;
481 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
487 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
488 WRITE_ONCE(max_samples_per_tick, max);
490 sysctl_perf_event_sample_rate = max * HZ;
491 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
493 if (!irq_work_queue(&perf_duration_work)) {
494 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
495 "kernel.perf_event_max_sample_rate to %d\n",
496 __report_avg, __report_allowed,
497 sysctl_perf_event_sample_rate);
501 static atomic64_t perf_event_id;
503 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
504 enum event_type_t event_type);
506 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
507 enum event_type_t event_type,
508 struct task_struct *task);
510 static void update_context_time(struct perf_event_context *ctx);
511 static u64 perf_event_time(struct perf_event *event);
513 void __weak perf_event_print_debug(void) { }
515 extern __weak const char *perf_pmu_name(void)
520 static inline u64 perf_clock(void)
522 return local_clock();
525 static inline u64 perf_event_clock(struct perf_event *event)
527 return event->clock();
530 #ifdef CONFIG_CGROUP_PERF
533 perf_cgroup_match(struct perf_event *event)
535 struct perf_event_context *ctx = event->ctx;
536 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
538 /* @event doesn't care about cgroup */
542 /* wants specific cgroup scope but @cpuctx isn't associated with any */
547 * Cgroup scoping is recursive. An event enabled for a cgroup is
548 * also enabled for all its descendant cgroups. If @cpuctx's
549 * cgroup is a descendant of @event's (the test covers identity
550 * case), it's a match.
552 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
553 event->cgrp->css.cgroup);
556 static inline void perf_detach_cgroup(struct perf_event *event)
558 css_put(&event->cgrp->css);
562 static inline int is_cgroup_event(struct perf_event *event)
564 return event->cgrp != NULL;
567 static inline u64 perf_cgroup_event_time(struct perf_event *event)
569 struct perf_cgroup_info *t;
571 t = per_cpu_ptr(event->cgrp->info, event->cpu);
575 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
577 struct perf_cgroup_info *info;
582 info = this_cpu_ptr(cgrp->info);
584 info->time += now - info->timestamp;
585 info->timestamp = now;
588 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
590 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
592 __update_cgrp_time(cgrp_out);
595 static inline void update_cgrp_time_from_event(struct perf_event *event)
597 struct perf_cgroup *cgrp;
600 * ensure we access cgroup data only when needed and
601 * when we know the cgroup is pinned (css_get)
603 if (!is_cgroup_event(event))
606 cgrp = perf_cgroup_from_task(current, event->ctx);
608 * Do not update time when cgroup is not active
610 if (cgrp == event->cgrp)
611 __update_cgrp_time(event->cgrp);
615 perf_cgroup_set_timestamp(struct task_struct *task,
616 struct perf_event_context *ctx)
618 struct perf_cgroup *cgrp;
619 struct perf_cgroup_info *info;
622 * ctx->lock held by caller
623 * ensure we do not access cgroup data
624 * unless we have the cgroup pinned (css_get)
626 if (!task || !ctx->nr_cgroups)
629 cgrp = perf_cgroup_from_task(task, ctx);
630 info = this_cpu_ptr(cgrp->info);
631 info->timestamp = ctx->timestamp;
634 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
635 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
638 * reschedule events based on the cgroup constraint of task.
640 * mode SWOUT : schedule out everything
641 * mode SWIN : schedule in based on cgroup for next
643 static void perf_cgroup_switch(struct task_struct *task, int mode)
645 struct perf_cpu_context *cpuctx;
650 * disable interrupts to avoid geting nr_cgroup
651 * changes via __perf_event_disable(). Also
654 local_irq_save(flags);
657 * we reschedule only in the presence of cgroup
658 * constrained events.
661 list_for_each_entry_rcu(pmu, &pmus, entry) {
662 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
663 if (cpuctx->unique_pmu != pmu)
664 continue; /* ensure we process each cpuctx once */
667 * perf_cgroup_events says at least one
668 * context on this CPU has cgroup events.
670 * ctx->nr_cgroups reports the number of cgroup
671 * events for a context.
673 if (cpuctx->ctx.nr_cgroups > 0) {
674 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
675 perf_pmu_disable(cpuctx->ctx.pmu);
677 if (mode & PERF_CGROUP_SWOUT) {
678 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
680 * must not be done before ctxswout due
681 * to event_filter_match() in event_sched_out()
686 if (mode & PERF_CGROUP_SWIN) {
687 WARN_ON_ONCE(cpuctx->cgrp);
689 * set cgrp before ctxsw in to allow
690 * event_filter_match() to not have to pass
692 * we pass the cpuctx->ctx to perf_cgroup_from_task()
693 * because cgorup events are only per-cpu
695 cpuctx->cgrp = perf_cgroup_from_task(task, &cpuctx->ctx);
696 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
698 perf_pmu_enable(cpuctx->ctx.pmu);
699 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
703 local_irq_restore(flags);
706 static inline void perf_cgroup_sched_out(struct task_struct *task,
707 struct task_struct *next)
709 struct perf_cgroup *cgrp1;
710 struct perf_cgroup *cgrp2 = NULL;
714 * we come here when we know perf_cgroup_events > 0
715 * we do not need to pass the ctx here because we know
716 * we are holding the rcu lock
718 cgrp1 = perf_cgroup_from_task(task, NULL);
719 cgrp2 = perf_cgroup_from_task(next, NULL);
722 * only schedule out current cgroup events if we know
723 * that we are switching to a different cgroup. Otherwise,
724 * do no touch the cgroup events.
727 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
732 static inline void perf_cgroup_sched_in(struct task_struct *prev,
733 struct task_struct *task)
735 struct perf_cgroup *cgrp1;
736 struct perf_cgroup *cgrp2 = NULL;
740 * we come here when we know perf_cgroup_events > 0
741 * we do not need to pass the ctx here because we know
742 * we are holding the rcu lock
744 cgrp1 = perf_cgroup_from_task(task, NULL);
745 cgrp2 = perf_cgroup_from_task(prev, NULL);
748 * only need to schedule in cgroup events if we are changing
749 * cgroup during ctxsw. Cgroup events were not scheduled
750 * out of ctxsw out if that was not the case.
753 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
758 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
759 struct perf_event_attr *attr,
760 struct perf_event *group_leader)
762 struct perf_cgroup *cgrp;
763 struct cgroup_subsys_state *css;
764 struct fd f = fdget(fd);
770 css = css_tryget_online_from_dir(f.file->f_path.dentry,
771 &perf_event_cgrp_subsys);
777 cgrp = container_of(css, struct perf_cgroup, css);
781 * all events in a group must monitor
782 * the same cgroup because a task belongs
783 * to only one perf cgroup at a time
785 if (group_leader && group_leader->cgrp != cgrp) {
786 perf_detach_cgroup(event);
795 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
797 struct perf_cgroup_info *t;
798 t = per_cpu_ptr(event->cgrp->info, event->cpu);
799 event->shadow_ctx_time = now - t->timestamp;
803 perf_cgroup_defer_enabled(struct perf_event *event)
806 * when the current task's perf cgroup does not match
807 * the event's, we need to remember to call the
808 * perf_mark_enable() function the first time a task with
809 * a matching perf cgroup is scheduled in.
811 if (is_cgroup_event(event) && !perf_cgroup_match(event))
812 event->cgrp_defer_enabled = 1;
816 perf_cgroup_mark_enabled(struct perf_event *event,
817 struct perf_event_context *ctx)
819 struct perf_event *sub;
820 u64 tstamp = perf_event_time(event);
822 if (!event->cgrp_defer_enabled)
825 event->cgrp_defer_enabled = 0;
827 event->tstamp_enabled = tstamp - event->total_time_enabled;
828 list_for_each_entry(sub, &event->sibling_list, group_entry) {
829 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
830 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
831 sub->cgrp_defer_enabled = 0;
835 #else /* !CONFIG_CGROUP_PERF */
838 perf_cgroup_match(struct perf_event *event)
843 static inline void perf_detach_cgroup(struct perf_event *event)
846 static inline int is_cgroup_event(struct perf_event *event)
851 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
856 static inline void update_cgrp_time_from_event(struct perf_event *event)
860 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
864 static inline void perf_cgroup_sched_out(struct task_struct *task,
865 struct task_struct *next)
869 static inline void perf_cgroup_sched_in(struct task_struct *prev,
870 struct task_struct *task)
874 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
875 struct perf_event_attr *attr,
876 struct perf_event *group_leader)
882 perf_cgroup_set_timestamp(struct task_struct *task,
883 struct perf_event_context *ctx)
888 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
893 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
897 static inline u64 perf_cgroup_event_time(struct perf_event *event)
903 perf_cgroup_defer_enabled(struct perf_event *event)
908 perf_cgroup_mark_enabled(struct perf_event *event,
909 struct perf_event_context *ctx)
915 * set default to be dependent on timer tick just
918 #define PERF_CPU_HRTIMER (1000 / HZ)
920 * function must be called with interrupts disbled
922 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
924 struct perf_cpu_context *cpuctx;
927 WARN_ON(!irqs_disabled());
929 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
930 rotations = perf_rotate_context(cpuctx);
932 raw_spin_lock(&cpuctx->hrtimer_lock);
934 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
936 cpuctx->hrtimer_active = 0;
937 raw_spin_unlock(&cpuctx->hrtimer_lock);
939 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
942 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
944 struct hrtimer *timer = &cpuctx->hrtimer;
945 struct pmu *pmu = cpuctx->ctx.pmu;
948 /* no multiplexing needed for SW PMU */
949 if (pmu->task_ctx_nr == perf_sw_context)
953 * check default is sane, if not set then force to
954 * default interval (1/tick)
956 interval = pmu->hrtimer_interval_ms;
958 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
960 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
962 raw_spin_lock_init(&cpuctx->hrtimer_lock);
963 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
964 timer->function = perf_mux_hrtimer_handler;
967 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
969 struct hrtimer *timer = &cpuctx->hrtimer;
970 struct pmu *pmu = cpuctx->ctx.pmu;
974 if (pmu->task_ctx_nr == perf_sw_context)
977 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
978 if (!cpuctx->hrtimer_active) {
979 cpuctx->hrtimer_active = 1;
980 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
981 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
983 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
988 void perf_pmu_disable(struct pmu *pmu)
990 int *count = this_cpu_ptr(pmu->pmu_disable_count);
992 pmu->pmu_disable(pmu);
995 void perf_pmu_enable(struct pmu *pmu)
997 int *count = this_cpu_ptr(pmu->pmu_disable_count);
999 pmu->pmu_enable(pmu);
1002 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1005 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1006 * perf_event_task_tick() are fully serialized because they're strictly cpu
1007 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1008 * disabled, while perf_event_task_tick is called from IRQ context.
1010 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1012 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1014 WARN_ON(!irqs_disabled());
1016 WARN_ON(!list_empty(&ctx->active_ctx_list));
1018 list_add(&ctx->active_ctx_list, head);
1021 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1023 WARN_ON(!irqs_disabled());
1025 WARN_ON(list_empty(&ctx->active_ctx_list));
1027 list_del_init(&ctx->active_ctx_list);
1030 static void get_ctx(struct perf_event_context *ctx)
1032 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
1035 static void free_ctx(struct rcu_head *head)
1037 struct perf_event_context *ctx;
1039 ctx = container_of(head, struct perf_event_context, rcu_head);
1040 kfree(ctx->task_ctx_data);
1044 static void put_ctx(struct perf_event_context *ctx)
1046 if (atomic_dec_and_test(&ctx->refcount)) {
1047 if (ctx->parent_ctx)
1048 put_ctx(ctx->parent_ctx);
1049 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1050 put_task_struct(ctx->task);
1051 call_rcu(&ctx->rcu_head, free_ctx);
1056 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1057 * perf_pmu_migrate_context() we need some magic.
1059 * Those places that change perf_event::ctx will hold both
1060 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1062 * Lock ordering is by mutex address. There are two other sites where
1063 * perf_event_context::mutex nests and those are:
1065 * - perf_event_exit_task_context() [ child , 0 ]
1066 * perf_event_exit_event()
1067 * put_event() [ parent, 1 ]
1069 * - perf_event_init_context() [ parent, 0 ]
1070 * inherit_task_group()
1073 * perf_event_alloc()
1075 * perf_try_init_event() [ child , 1 ]
1077 * While it appears there is an obvious deadlock here -- the parent and child
1078 * nesting levels are inverted between the two. This is in fact safe because
1079 * life-time rules separate them. That is an exiting task cannot fork, and a
1080 * spawning task cannot (yet) exit.
1082 * But remember that that these are parent<->child context relations, and
1083 * migration does not affect children, therefore these two orderings should not
1086 * The change in perf_event::ctx does not affect children (as claimed above)
1087 * because the sys_perf_event_open() case will install a new event and break
1088 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1089 * concerned with cpuctx and that doesn't have children.
1091 * The places that change perf_event::ctx will issue:
1093 * perf_remove_from_context();
1094 * synchronize_rcu();
1095 * perf_install_in_context();
1097 * to affect the change. The remove_from_context() + synchronize_rcu() should
1098 * quiesce the event, after which we can install it in the new location. This
1099 * means that only external vectors (perf_fops, prctl) can perturb the event
1100 * while in transit. Therefore all such accessors should also acquire
1101 * perf_event_context::mutex to serialize against this.
1103 * However; because event->ctx can change while we're waiting to acquire
1104 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1108 * task_struct::perf_event_mutex
1109 * perf_event_context::mutex
1110 * perf_event::child_mutex;
1111 * perf_event_context::lock
1112 * perf_event::mmap_mutex
1115 static struct perf_event_context *
1116 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1118 struct perf_event_context *ctx;
1122 ctx = ACCESS_ONCE(event->ctx);
1123 if (!atomic_inc_not_zero(&ctx->refcount)) {
1129 mutex_lock_nested(&ctx->mutex, nesting);
1130 if (event->ctx != ctx) {
1131 mutex_unlock(&ctx->mutex);
1139 static inline struct perf_event_context *
1140 perf_event_ctx_lock(struct perf_event *event)
1142 return perf_event_ctx_lock_nested(event, 0);
1145 static void perf_event_ctx_unlock(struct perf_event *event,
1146 struct perf_event_context *ctx)
1148 mutex_unlock(&ctx->mutex);
1153 * This must be done under the ctx->lock, such as to serialize against
1154 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1155 * calling scheduler related locks and ctx->lock nests inside those.
1157 static __must_check struct perf_event_context *
1158 unclone_ctx(struct perf_event_context *ctx)
1160 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1162 lockdep_assert_held(&ctx->lock);
1165 ctx->parent_ctx = NULL;
1171 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1174 * only top level events have the pid namespace they were created in
1177 event = event->parent;
1179 return task_tgid_nr_ns(p, event->ns);
1182 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1185 * only top level events have the pid namespace they were created in
1188 event = event->parent;
1190 return task_pid_nr_ns(p, event->ns);
1194 * If we inherit events we want to return the parent event id
1197 static u64 primary_event_id(struct perf_event *event)
1202 id = event->parent->id;
1208 * Get the perf_event_context for a task and lock it.
1210 * This has to cope with with the fact that until it is locked,
1211 * the context could get moved to another task.
1213 static struct perf_event_context *
1214 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1216 struct perf_event_context *ctx;
1220 * One of the few rules of preemptible RCU is that one cannot do
1221 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1222 * part of the read side critical section was irqs-enabled -- see
1223 * rcu_read_unlock_special().
1225 * Since ctx->lock nests under rq->lock we must ensure the entire read
1226 * side critical section has interrupts disabled.
1228 local_irq_save(*flags);
1230 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1233 * If this context is a clone of another, it might
1234 * get swapped for another underneath us by
1235 * perf_event_task_sched_out, though the
1236 * rcu_read_lock() protects us from any context
1237 * getting freed. Lock the context and check if it
1238 * got swapped before we could get the lock, and retry
1239 * if so. If we locked the right context, then it
1240 * can't get swapped on us any more.
1242 raw_spin_lock(&ctx->lock);
1243 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1244 raw_spin_unlock(&ctx->lock);
1246 local_irq_restore(*flags);
1250 if (ctx->task == TASK_TOMBSTONE ||
1251 !atomic_inc_not_zero(&ctx->refcount)) {
1252 raw_spin_unlock(&ctx->lock);
1255 WARN_ON_ONCE(ctx->task != task);
1260 local_irq_restore(*flags);
1265 * Get the context for a task and increment its pin_count so it
1266 * can't get swapped to another task. This also increments its
1267 * reference count so that the context can't get freed.
1269 static struct perf_event_context *
1270 perf_pin_task_context(struct task_struct *task, int ctxn)
1272 struct perf_event_context *ctx;
1273 unsigned long flags;
1275 ctx = perf_lock_task_context(task, ctxn, &flags);
1278 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1283 static void perf_unpin_context(struct perf_event_context *ctx)
1285 unsigned long flags;
1287 raw_spin_lock_irqsave(&ctx->lock, flags);
1289 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1293 * Update the record of the current time in a context.
1295 static void update_context_time(struct perf_event_context *ctx)
1297 u64 now = perf_clock();
1299 ctx->time += now - ctx->timestamp;
1300 ctx->timestamp = now;
1303 static u64 perf_event_time(struct perf_event *event)
1305 struct perf_event_context *ctx = event->ctx;
1307 if (is_cgroup_event(event))
1308 return perf_cgroup_event_time(event);
1310 return ctx ? ctx->time : 0;
1314 * Update the total_time_enabled and total_time_running fields for a event.
1316 static void update_event_times(struct perf_event *event)
1318 struct perf_event_context *ctx = event->ctx;
1321 lockdep_assert_held(&ctx->lock);
1323 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1324 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1328 * in cgroup mode, time_enabled represents
1329 * the time the event was enabled AND active
1330 * tasks were in the monitored cgroup. This is
1331 * independent of the activity of the context as
1332 * there may be a mix of cgroup and non-cgroup events.
1334 * That is why we treat cgroup events differently
1337 if (is_cgroup_event(event))
1338 run_end = perf_cgroup_event_time(event);
1339 else if (ctx->is_active)
1340 run_end = ctx->time;
1342 run_end = event->tstamp_stopped;
1344 event->total_time_enabled = run_end - event->tstamp_enabled;
1346 if (event->state == PERF_EVENT_STATE_INACTIVE)
1347 run_end = event->tstamp_stopped;
1349 run_end = perf_event_time(event);
1351 event->total_time_running = run_end - event->tstamp_running;
1356 * Update total_time_enabled and total_time_running for all events in a group.
1358 static void update_group_times(struct perf_event *leader)
1360 struct perf_event *event;
1362 update_event_times(leader);
1363 list_for_each_entry(event, &leader->sibling_list, group_entry)
1364 update_event_times(event);
1367 static struct list_head *
1368 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1370 if (event->attr.pinned)
1371 return &ctx->pinned_groups;
1373 return &ctx->flexible_groups;
1377 * Add a event from the lists for its context.
1378 * Must be called with ctx->mutex and ctx->lock held.
1381 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1383 lockdep_assert_held(&ctx->lock);
1385 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1386 event->attach_state |= PERF_ATTACH_CONTEXT;
1389 * If we're a stand alone event or group leader, we go to the context
1390 * list, group events are kept attached to the group so that
1391 * perf_group_detach can, at all times, locate all siblings.
1393 if (event->group_leader == event) {
1394 struct list_head *list;
1396 if (is_software_event(event))
1397 event->group_flags |= PERF_GROUP_SOFTWARE;
1399 list = ctx_group_list(event, ctx);
1400 list_add_tail(&event->group_entry, list);
1403 if (is_cgroup_event(event))
1406 list_add_rcu(&event->event_entry, &ctx->event_list);
1408 if (event->attr.inherit_stat)
1415 * Initialize event state based on the perf_event_attr::disabled.
1417 static inline void perf_event__state_init(struct perf_event *event)
1419 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1420 PERF_EVENT_STATE_INACTIVE;
1423 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1425 int entry = sizeof(u64); /* value */
1429 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1430 size += sizeof(u64);
1432 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1433 size += sizeof(u64);
1435 if (event->attr.read_format & PERF_FORMAT_ID)
1436 entry += sizeof(u64);
1438 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1440 size += sizeof(u64);
1444 event->read_size = size;
1447 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1449 struct perf_sample_data *data;
1452 if (sample_type & PERF_SAMPLE_IP)
1453 size += sizeof(data->ip);
1455 if (sample_type & PERF_SAMPLE_ADDR)
1456 size += sizeof(data->addr);
1458 if (sample_type & PERF_SAMPLE_PERIOD)
1459 size += sizeof(data->period);
1461 if (sample_type & PERF_SAMPLE_WEIGHT)
1462 size += sizeof(data->weight);
1464 if (sample_type & PERF_SAMPLE_READ)
1465 size += event->read_size;
1467 if (sample_type & PERF_SAMPLE_DATA_SRC)
1468 size += sizeof(data->data_src.val);
1470 if (sample_type & PERF_SAMPLE_TRANSACTION)
1471 size += sizeof(data->txn);
1473 event->header_size = size;
1477 * Called at perf_event creation and when events are attached/detached from a
1480 static void perf_event__header_size(struct perf_event *event)
1482 __perf_event_read_size(event,
1483 event->group_leader->nr_siblings);
1484 __perf_event_header_size(event, event->attr.sample_type);
1487 static void perf_event__id_header_size(struct perf_event *event)
1489 struct perf_sample_data *data;
1490 u64 sample_type = event->attr.sample_type;
1493 if (sample_type & PERF_SAMPLE_TID)
1494 size += sizeof(data->tid_entry);
1496 if (sample_type & PERF_SAMPLE_TIME)
1497 size += sizeof(data->time);
1499 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1500 size += sizeof(data->id);
1502 if (sample_type & PERF_SAMPLE_ID)
1503 size += sizeof(data->id);
1505 if (sample_type & PERF_SAMPLE_STREAM_ID)
1506 size += sizeof(data->stream_id);
1508 if (sample_type & PERF_SAMPLE_CPU)
1509 size += sizeof(data->cpu_entry);
1511 event->id_header_size = size;
1514 static bool perf_event_validate_size(struct perf_event *event)
1517 * The values computed here will be over-written when we actually
1520 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1521 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1522 perf_event__id_header_size(event);
1525 * Sum the lot; should not exceed the 64k limit we have on records.
1526 * Conservative limit to allow for callchains and other variable fields.
1528 if (event->read_size + event->header_size +
1529 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1535 static void perf_group_attach(struct perf_event *event)
1537 struct perf_event *group_leader = event->group_leader, *pos;
1540 * We can have double attach due to group movement in perf_event_open.
1542 if (event->attach_state & PERF_ATTACH_GROUP)
1545 event->attach_state |= PERF_ATTACH_GROUP;
1547 if (group_leader == event)
1550 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1552 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1553 !is_software_event(event))
1554 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1556 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1557 group_leader->nr_siblings++;
1559 perf_event__header_size(group_leader);
1561 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1562 perf_event__header_size(pos);
1566 * Remove a event from the lists for its context.
1567 * Must be called with ctx->mutex and ctx->lock held.
1570 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1572 struct perf_cpu_context *cpuctx;
1574 WARN_ON_ONCE(event->ctx != ctx);
1575 lockdep_assert_held(&ctx->lock);
1578 * We can have double detach due to exit/hot-unplug + close.
1580 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1583 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1585 if (is_cgroup_event(event)) {
1588 * Because cgroup events are always per-cpu events, this will
1589 * always be called from the right CPU.
1591 cpuctx = __get_cpu_context(ctx);
1593 * If there are no more cgroup events then clear cgrp to avoid
1594 * stale pointer in update_cgrp_time_from_cpuctx().
1596 if (!ctx->nr_cgroups)
1597 cpuctx->cgrp = NULL;
1601 if (event->attr.inherit_stat)
1604 list_del_rcu(&event->event_entry);
1606 if (event->group_leader == event)
1607 list_del_init(&event->group_entry);
1609 update_group_times(event);
1612 * If event was in error state, then keep it
1613 * that way, otherwise bogus counts will be
1614 * returned on read(). The only way to get out
1615 * of error state is by explicit re-enabling
1618 if (event->state > PERF_EVENT_STATE_OFF)
1619 event->state = PERF_EVENT_STATE_OFF;
1624 static void perf_group_detach(struct perf_event *event)
1626 struct perf_event *sibling, *tmp;
1627 struct list_head *list = NULL;
1630 * We can have double detach due to exit/hot-unplug + close.
1632 if (!(event->attach_state & PERF_ATTACH_GROUP))
1635 event->attach_state &= ~PERF_ATTACH_GROUP;
1638 * If this is a sibling, remove it from its group.
1640 if (event->group_leader != event) {
1641 list_del_init(&event->group_entry);
1642 event->group_leader->nr_siblings--;
1646 if (!list_empty(&event->group_entry))
1647 list = &event->group_entry;
1650 * If this was a group event with sibling events then
1651 * upgrade the siblings to singleton events by adding them
1652 * to whatever list we are on.
1654 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1656 list_move_tail(&sibling->group_entry, list);
1657 sibling->group_leader = sibling;
1659 /* Inherit group flags from the previous leader */
1660 sibling->group_flags = event->group_flags;
1662 WARN_ON_ONCE(sibling->ctx != event->ctx);
1666 perf_event__header_size(event->group_leader);
1668 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1669 perf_event__header_size(tmp);
1672 static bool is_orphaned_event(struct perf_event *event)
1674 return event->state == PERF_EVENT_STATE_DEAD;
1677 static inline int pmu_filter_match(struct perf_event *event)
1679 struct pmu *pmu = event->pmu;
1680 return pmu->filter_match ? pmu->filter_match(event) : 1;
1684 event_filter_match(struct perf_event *event)
1686 return (event->cpu == -1 || event->cpu == smp_processor_id())
1687 && perf_cgroup_match(event) && pmu_filter_match(event);
1691 event_sched_out(struct perf_event *event,
1692 struct perf_cpu_context *cpuctx,
1693 struct perf_event_context *ctx)
1695 u64 tstamp = perf_event_time(event);
1698 WARN_ON_ONCE(event->ctx != ctx);
1699 lockdep_assert_held(&ctx->lock);
1702 * An event which could not be activated because of
1703 * filter mismatch still needs to have its timings
1704 * maintained, otherwise bogus information is return
1705 * via read() for time_enabled, time_running:
1707 if (event->state == PERF_EVENT_STATE_INACTIVE
1708 && !event_filter_match(event)) {
1709 delta = tstamp - event->tstamp_stopped;
1710 event->tstamp_running += delta;
1711 event->tstamp_stopped = tstamp;
1714 if (event->state != PERF_EVENT_STATE_ACTIVE)
1717 perf_pmu_disable(event->pmu);
1719 event->tstamp_stopped = tstamp;
1720 event->pmu->del(event, 0);
1722 event->state = PERF_EVENT_STATE_INACTIVE;
1723 if (event->pending_disable) {
1724 event->pending_disable = 0;
1725 event->state = PERF_EVENT_STATE_OFF;
1728 if (!is_software_event(event))
1729 cpuctx->active_oncpu--;
1730 if (!--ctx->nr_active)
1731 perf_event_ctx_deactivate(ctx);
1732 if (event->attr.freq && event->attr.sample_freq)
1734 if (event->attr.exclusive || !cpuctx->active_oncpu)
1735 cpuctx->exclusive = 0;
1737 perf_pmu_enable(event->pmu);
1741 group_sched_out(struct perf_event *group_event,
1742 struct perf_cpu_context *cpuctx,
1743 struct perf_event_context *ctx)
1745 struct perf_event *event;
1746 int state = group_event->state;
1748 event_sched_out(group_event, cpuctx, ctx);
1751 * Schedule out siblings (if any):
1753 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1754 event_sched_out(event, cpuctx, ctx);
1756 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1757 cpuctx->exclusive = 0;
1760 #define DETACH_GROUP 0x01UL
1763 * Cross CPU call to remove a performance event
1765 * We disable the event on the hardware level first. After that we
1766 * remove it from the context list.
1769 __perf_remove_from_context(struct perf_event *event,
1770 struct perf_cpu_context *cpuctx,
1771 struct perf_event_context *ctx,
1774 unsigned long flags = (unsigned long)info;
1776 event_sched_out(event, cpuctx, ctx);
1777 if (flags & DETACH_GROUP)
1778 perf_group_detach(event);
1779 list_del_event(event, ctx);
1781 if (!ctx->nr_events && ctx->is_active) {
1784 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
1785 cpuctx->task_ctx = NULL;
1791 * Remove the event from a task's (or a CPU's) list of events.
1793 * If event->ctx is a cloned context, callers must make sure that
1794 * every task struct that event->ctx->task could possibly point to
1795 * remains valid. This is OK when called from perf_release since
1796 * that only calls us on the top-level context, which can't be a clone.
1797 * When called from perf_event_exit_task, it's OK because the
1798 * context has been detached from its task.
1800 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
1802 lockdep_assert_held(&event->ctx->mutex);
1804 event_function_call(event, __perf_remove_from_context, (void *)flags);
1808 * Cross CPU call to disable a performance event
1810 static void __perf_event_disable(struct perf_event *event,
1811 struct perf_cpu_context *cpuctx,
1812 struct perf_event_context *ctx,
1815 if (event->state < PERF_EVENT_STATE_INACTIVE)
1818 update_context_time(ctx);
1819 update_cgrp_time_from_event(event);
1820 update_group_times(event);
1821 if (event == event->group_leader)
1822 group_sched_out(event, cpuctx, ctx);
1824 event_sched_out(event, cpuctx, ctx);
1825 event->state = PERF_EVENT_STATE_OFF;
1831 * If event->ctx is a cloned context, callers must make sure that
1832 * every task struct that event->ctx->task could possibly point to
1833 * remains valid. This condition is satisifed when called through
1834 * perf_event_for_each_child or perf_event_for_each because they
1835 * hold the top-level event's child_mutex, so any descendant that
1836 * goes to exit will block in perf_event_exit_event().
1838 * When called from perf_pending_event it's OK because event->ctx
1839 * is the current context on this CPU and preemption is disabled,
1840 * hence we can't get into perf_event_task_sched_out for this context.
1842 static void _perf_event_disable(struct perf_event *event)
1844 struct perf_event_context *ctx = event->ctx;
1846 raw_spin_lock_irq(&ctx->lock);
1847 if (event->state <= PERF_EVENT_STATE_OFF) {
1848 raw_spin_unlock_irq(&ctx->lock);
1851 raw_spin_unlock_irq(&ctx->lock);
1853 event_function_call(event, __perf_event_disable, NULL);
1856 void perf_event_disable_local(struct perf_event *event)
1858 event_function_local(event, __perf_event_disable, NULL);
1862 * Strictly speaking kernel users cannot create groups and therefore this
1863 * interface does not need the perf_event_ctx_lock() magic.
1865 void perf_event_disable(struct perf_event *event)
1867 struct perf_event_context *ctx;
1869 ctx = perf_event_ctx_lock(event);
1870 _perf_event_disable(event);
1871 perf_event_ctx_unlock(event, ctx);
1873 EXPORT_SYMBOL_GPL(perf_event_disable);
1875 static void perf_set_shadow_time(struct perf_event *event,
1876 struct perf_event_context *ctx,
1880 * use the correct time source for the time snapshot
1882 * We could get by without this by leveraging the
1883 * fact that to get to this function, the caller
1884 * has most likely already called update_context_time()
1885 * and update_cgrp_time_xx() and thus both timestamp
1886 * are identical (or very close). Given that tstamp is,
1887 * already adjusted for cgroup, we could say that:
1888 * tstamp - ctx->timestamp
1890 * tstamp - cgrp->timestamp.
1892 * Then, in perf_output_read(), the calculation would
1893 * work with no changes because:
1894 * - event is guaranteed scheduled in
1895 * - no scheduled out in between
1896 * - thus the timestamp would be the same
1898 * But this is a bit hairy.
1900 * So instead, we have an explicit cgroup call to remain
1901 * within the time time source all along. We believe it
1902 * is cleaner and simpler to understand.
1904 if (is_cgroup_event(event))
1905 perf_cgroup_set_shadow_time(event, tstamp);
1907 event->shadow_ctx_time = tstamp - ctx->timestamp;
1910 #define MAX_INTERRUPTS (~0ULL)
1912 static void perf_log_throttle(struct perf_event *event, int enable);
1913 static void perf_log_itrace_start(struct perf_event *event);
1916 event_sched_in(struct perf_event *event,
1917 struct perf_cpu_context *cpuctx,
1918 struct perf_event_context *ctx)
1920 u64 tstamp = perf_event_time(event);
1923 lockdep_assert_held(&ctx->lock);
1925 if (event->state <= PERF_EVENT_STATE_OFF)
1928 WRITE_ONCE(event->oncpu, smp_processor_id());
1930 * Order event::oncpu write to happen before the ACTIVE state
1934 WRITE_ONCE(event->state, PERF_EVENT_STATE_ACTIVE);
1937 * Unthrottle events, since we scheduled we might have missed several
1938 * ticks already, also for a heavily scheduling task there is little
1939 * guarantee it'll get a tick in a timely manner.
1941 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1942 perf_log_throttle(event, 1);
1943 event->hw.interrupts = 0;
1947 * The new state must be visible before we turn it on in the hardware:
1951 perf_pmu_disable(event->pmu);
1953 perf_set_shadow_time(event, ctx, tstamp);
1955 perf_log_itrace_start(event);
1957 if (event->pmu->add(event, PERF_EF_START)) {
1958 event->state = PERF_EVENT_STATE_INACTIVE;
1964 event->tstamp_running += tstamp - event->tstamp_stopped;
1966 if (!is_software_event(event))
1967 cpuctx->active_oncpu++;
1968 if (!ctx->nr_active++)
1969 perf_event_ctx_activate(ctx);
1970 if (event->attr.freq && event->attr.sample_freq)
1973 if (event->attr.exclusive)
1974 cpuctx->exclusive = 1;
1977 perf_pmu_enable(event->pmu);
1983 group_sched_in(struct perf_event *group_event,
1984 struct perf_cpu_context *cpuctx,
1985 struct perf_event_context *ctx)
1987 struct perf_event *event, *partial_group = NULL;
1988 struct pmu *pmu = ctx->pmu;
1989 u64 now = ctx->time;
1990 bool simulate = false;
1992 if (group_event->state == PERF_EVENT_STATE_OFF)
1995 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
1997 if (event_sched_in(group_event, cpuctx, ctx)) {
1998 pmu->cancel_txn(pmu);
1999 perf_mux_hrtimer_restart(cpuctx);
2004 * Schedule in siblings as one group (if any):
2006 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2007 if (event_sched_in(event, cpuctx, ctx)) {
2008 partial_group = event;
2013 if (!pmu->commit_txn(pmu))
2018 * Groups can be scheduled in as one unit only, so undo any
2019 * partial group before returning:
2020 * The events up to the failed event are scheduled out normally,
2021 * tstamp_stopped will be updated.
2023 * The failed events and the remaining siblings need to have
2024 * their timings updated as if they had gone thru event_sched_in()
2025 * and event_sched_out(). This is required to get consistent timings
2026 * across the group. This also takes care of the case where the group
2027 * could never be scheduled by ensuring tstamp_stopped is set to mark
2028 * the time the event was actually stopped, such that time delta
2029 * calculation in update_event_times() is correct.
2031 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2032 if (event == partial_group)
2036 event->tstamp_running += now - event->tstamp_stopped;
2037 event->tstamp_stopped = now;
2039 event_sched_out(event, cpuctx, ctx);
2042 event_sched_out(group_event, cpuctx, ctx);
2044 pmu->cancel_txn(pmu);
2046 perf_mux_hrtimer_restart(cpuctx);
2052 * Work out whether we can put this event group on the CPU now.
2054 static int group_can_go_on(struct perf_event *event,
2055 struct perf_cpu_context *cpuctx,
2059 * Groups consisting entirely of software events can always go on.
2061 if (event->group_flags & PERF_GROUP_SOFTWARE)
2064 * If an exclusive group is already on, no other hardware
2067 if (cpuctx->exclusive)
2070 * If this group is exclusive and there are already
2071 * events on the CPU, it can't go on.
2073 if (event->attr.exclusive && cpuctx->active_oncpu)
2076 * Otherwise, try to add it if all previous groups were able
2082 static void add_event_to_ctx(struct perf_event *event,
2083 struct perf_event_context *ctx)
2085 u64 tstamp = perf_event_time(event);
2087 list_add_event(event, ctx);
2088 perf_group_attach(event);
2089 event->tstamp_enabled = tstamp;
2090 event->tstamp_running = tstamp;
2091 event->tstamp_stopped = tstamp;
2094 static void ctx_sched_out(struct perf_event_context *ctx,
2095 struct perf_cpu_context *cpuctx,
2096 enum event_type_t event_type);
2098 ctx_sched_in(struct perf_event_context *ctx,
2099 struct perf_cpu_context *cpuctx,
2100 enum event_type_t event_type,
2101 struct task_struct *task);
2103 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2104 struct perf_event_context *ctx)
2106 if (!cpuctx->task_ctx)
2109 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2112 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2115 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2116 struct perf_event_context *ctx,
2117 struct task_struct *task)
2119 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2121 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2122 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2124 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2127 static void ctx_resched(struct perf_cpu_context *cpuctx,
2128 struct perf_event_context *task_ctx)
2130 perf_pmu_disable(cpuctx->ctx.pmu);
2132 task_ctx_sched_out(cpuctx, task_ctx);
2133 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
2134 perf_event_sched_in(cpuctx, task_ctx, current);
2135 perf_pmu_enable(cpuctx->ctx.pmu);
2139 * Cross CPU call to install and enable a performance event
2141 * Very similar to remote_function() + event_function() but cannot assume that
2142 * things like ctx->is_active and cpuctx->task_ctx are set.
2144 static int __perf_install_in_context(void *info)
2146 struct perf_event *event = info;
2147 struct perf_event_context *ctx = event->ctx;
2148 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2149 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2150 bool activate = true;
2153 raw_spin_lock(&cpuctx->ctx.lock);
2155 raw_spin_lock(&ctx->lock);
2158 /* If we're on the wrong CPU, try again */
2159 if (task_cpu(ctx->task) != smp_processor_id()) {
2165 * If we're on the right CPU, see if the task we target is
2166 * current, if not we don't have to activate the ctx, a future
2167 * context switch will do that for us.
2169 if (ctx->task != current)
2172 WARN_ON_ONCE(cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2174 } else if (task_ctx) {
2175 raw_spin_lock(&task_ctx->lock);
2179 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2180 add_event_to_ctx(event, ctx);
2181 ctx_resched(cpuctx, task_ctx);
2183 add_event_to_ctx(event, ctx);
2187 perf_ctx_unlock(cpuctx, task_ctx);
2193 * Attach a performance event to a context.
2195 * Very similar to event_function_call, see comment there.
2198 perf_install_in_context(struct perf_event_context *ctx,
2199 struct perf_event *event,
2202 struct task_struct *task = READ_ONCE(ctx->task);
2204 lockdep_assert_held(&ctx->mutex);
2207 if (event->cpu != -1)
2211 cpu_function_call(cpu, __perf_install_in_context, event);
2216 * Should not happen, we validate the ctx is still alive before calling.
2218 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2222 * Installing events is tricky because we cannot rely on ctx->is_active
2223 * to be set in case this is the nr_events 0 -> 1 transition.
2227 * Cannot use task_function_call() because we need to run on the task's
2228 * CPU regardless of whether its current or not.
2230 if (!cpu_function_call(task_cpu(task), __perf_install_in_context, event))
2233 raw_spin_lock_irq(&ctx->lock);
2235 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2237 * Cannot happen because we already checked above (which also
2238 * cannot happen), and we hold ctx->mutex, which serializes us
2239 * against perf_event_exit_task_context().
2241 raw_spin_unlock_irq(&ctx->lock);
2244 raw_spin_unlock_irq(&ctx->lock);
2246 * Since !ctx->is_active doesn't mean anything, we must IPI
2253 * Put a event into inactive state and update time fields.
2254 * Enabling the leader of a group effectively enables all
2255 * the group members that aren't explicitly disabled, so we
2256 * have to update their ->tstamp_enabled also.
2257 * Note: this works for group members as well as group leaders
2258 * since the non-leader members' sibling_lists will be empty.
2260 static void __perf_event_mark_enabled(struct perf_event *event)
2262 struct perf_event *sub;
2263 u64 tstamp = perf_event_time(event);
2265 event->state = PERF_EVENT_STATE_INACTIVE;
2266 event->tstamp_enabled = tstamp - event->total_time_enabled;
2267 list_for_each_entry(sub, &event->sibling_list, group_entry) {
2268 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2269 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2274 * Cross CPU call to enable a performance event
2276 static void __perf_event_enable(struct perf_event *event,
2277 struct perf_cpu_context *cpuctx,
2278 struct perf_event_context *ctx,
2281 struct perf_event *leader = event->group_leader;
2282 struct perf_event_context *task_ctx;
2284 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2285 event->state <= PERF_EVENT_STATE_ERROR)
2289 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2291 __perf_event_mark_enabled(event);
2293 if (!ctx->is_active)
2296 if (!event_filter_match(event)) {
2297 if (is_cgroup_event(event))
2298 perf_cgroup_defer_enabled(event);
2299 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2304 * If the event is in a group and isn't the group leader,
2305 * then don't put it on unless the group is on.
2307 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2308 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2312 task_ctx = cpuctx->task_ctx;
2314 WARN_ON_ONCE(task_ctx != ctx);
2316 ctx_resched(cpuctx, task_ctx);
2322 * If event->ctx is a cloned context, callers must make sure that
2323 * every task struct that event->ctx->task could possibly point to
2324 * remains valid. This condition is satisfied when called through
2325 * perf_event_for_each_child or perf_event_for_each as described
2326 * for perf_event_disable.
2328 static void _perf_event_enable(struct perf_event *event)
2330 struct perf_event_context *ctx = event->ctx;
2332 raw_spin_lock_irq(&ctx->lock);
2333 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2334 event->state < PERF_EVENT_STATE_ERROR) {
2335 raw_spin_unlock_irq(&ctx->lock);
2340 * If the event is in error state, clear that first.
2342 * That way, if we see the event in error state below, we know that it
2343 * has gone back into error state, as distinct from the task having
2344 * been scheduled away before the cross-call arrived.
2346 if (event->state == PERF_EVENT_STATE_ERROR)
2347 event->state = PERF_EVENT_STATE_OFF;
2348 raw_spin_unlock_irq(&ctx->lock);
2350 event_function_call(event, __perf_event_enable, NULL);
2354 * See perf_event_disable();
2356 void perf_event_enable(struct perf_event *event)
2358 struct perf_event_context *ctx;
2360 ctx = perf_event_ctx_lock(event);
2361 _perf_event_enable(event);
2362 perf_event_ctx_unlock(event, ctx);
2364 EXPORT_SYMBOL_GPL(perf_event_enable);
2366 static int __perf_event_stop(void *info)
2368 struct perf_event *event = info;
2370 /* for AUX events, our job is done if the event is already inactive */
2371 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2374 /* matches smp_wmb() in event_sched_in() */
2378 * There is a window with interrupts enabled before we get here,
2379 * so we need to check again lest we try to stop another CPU's event.
2381 if (READ_ONCE(event->oncpu) != smp_processor_id())
2384 event->pmu->stop(event, PERF_EF_UPDATE);
2389 static int _perf_event_refresh(struct perf_event *event, int refresh)
2392 * not supported on inherited events
2394 if (event->attr.inherit || !is_sampling_event(event))
2397 atomic_add(refresh, &event->event_limit);
2398 _perf_event_enable(event);
2404 * See perf_event_disable()
2406 int perf_event_refresh(struct perf_event *event, int refresh)
2408 struct perf_event_context *ctx;
2411 ctx = perf_event_ctx_lock(event);
2412 ret = _perf_event_refresh(event, refresh);
2413 perf_event_ctx_unlock(event, ctx);
2417 EXPORT_SYMBOL_GPL(perf_event_refresh);
2419 static void ctx_sched_out(struct perf_event_context *ctx,
2420 struct perf_cpu_context *cpuctx,
2421 enum event_type_t event_type)
2423 int is_active = ctx->is_active;
2424 struct perf_event *event;
2426 lockdep_assert_held(&ctx->lock);
2428 if (likely(!ctx->nr_events)) {
2430 * See __perf_remove_from_context().
2432 WARN_ON_ONCE(ctx->is_active);
2434 WARN_ON_ONCE(cpuctx->task_ctx);
2438 ctx->is_active &= ~event_type;
2439 if (!(ctx->is_active & EVENT_ALL))
2443 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2444 if (!ctx->is_active)
2445 cpuctx->task_ctx = NULL;
2449 * Always update time if it was set; not only when it changes.
2450 * Otherwise we can 'forget' to update time for any but the last
2451 * context we sched out. For example:
2453 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
2454 * ctx_sched_out(.event_type = EVENT_PINNED)
2456 * would only update time for the pinned events.
2458 if (is_active & EVENT_TIME) {
2459 /* update (and stop) ctx time */
2460 update_context_time(ctx);
2461 update_cgrp_time_from_cpuctx(cpuctx);
2464 is_active ^= ctx->is_active; /* changed bits */
2466 if (!ctx->nr_active || !(is_active & EVENT_ALL))
2469 perf_pmu_disable(ctx->pmu);
2470 if (is_active & EVENT_PINNED) {
2471 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2472 group_sched_out(event, cpuctx, ctx);
2475 if (is_active & EVENT_FLEXIBLE) {
2476 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2477 group_sched_out(event, cpuctx, ctx);
2479 perf_pmu_enable(ctx->pmu);
2483 * Test whether two contexts are equivalent, i.e. whether they have both been
2484 * cloned from the same version of the same context.
2486 * Equivalence is measured using a generation number in the context that is
2487 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2488 * and list_del_event().
2490 static int context_equiv(struct perf_event_context *ctx1,
2491 struct perf_event_context *ctx2)
2493 lockdep_assert_held(&ctx1->lock);
2494 lockdep_assert_held(&ctx2->lock);
2496 /* Pinning disables the swap optimization */
2497 if (ctx1->pin_count || ctx2->pin_count)
2500 /* If ctx1 is the parent of ctx2 */
2501 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2504 /* If ctx2 is the parent of ctx1 */
2505 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2509 * If ctx1 and ctx2 have the same parent; we flatten the parent
2510 * hierarchy, see perf_event_init_context().
2512 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2513 ctx1->parent_gen == ctx2->parent_gen)
2520 static void __perf_event_sync_stat(struct perf_event *event,
2521 struct perf_event *next_event)
2525 if (!event->attr.inherit_stat)
2529 * Update the event value, we cannot use perf_event_read()
2530 * because we're in the middle of a context switch and have IRQs
2531 * disabled, which upsets smp_call_function_single(), however
2532 * we know the event must be on the current CPU, therefore we
2533 * don't need to use it.
2535 switch (event->state) {
2536 case PERF_EVENT_STATE_ACTIVE:
2537 event->pmu->read(event);
2540 case PERF_EVENT_STATE_INACTIVE:
2541 update_event_times(event);
2549 * In order to keep per-task stats reliable we need to flip the event
2550 * values when we flip the contexts.
2552 value = local64_read(&next_event->count);
2553 value = local64_xchg(&event->count, value);
2554 local64_set(&next_event->count, value);
2556 swap(event->total_time_enabled, next_event->total_time_enabled);
2557 swap(event->total_time_running, next_event->total_time_running);
2560 * Since we swizzled the values, update the user visible data too.
2562 perf_event_update_userpage(event);
2563 perf_event_update_userpage(next_event);
2566 static void perf_event_sync_stat(struct perf_event_context *ctx,
2567 struct perf_event_context *next_ctx)
2569 struct perf_event *event, *next_event;
2574 update_context_time(ctx);
2576 event = list_first_entry(&ctx->event_list,
2577 struct perf_event, event_entry);
2579 next_event = list_first_entry(&next_ctx->event_list,
2580 struct perf_event, event_entry);
2582 while (&event->event_entry != &ctx->event_list &&
2583 &next_event->event_entry != &next_ctx->event_list) {
2585 __perf_event_sync_stat(event, next_event);
2587 event = list_next_entry(event, event_entry);
2588 next_event = list_next_entry(next_event, event_entry);
2592 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2593 struct task_struct *next)
2595 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2596 struct perf_event_context *next_ctx;
2597 struct perf_event_context *parent, *next_parent;
2598 struct perf_cpu_context *cpuctx;
2604 cpuctx = __get_cpu_context(ctx);
2605 if (!cpuctx->task_ctx)
2609 next_ctx = next->perf_event_ctxp[ctxn];
2613 parent = rcu_dereference(ctx->parent_ctx);
2614 next_parent = rcu_dereference(next_ctx->parent_ctx);
2616 /* If neither context have a parent context; they cannot be clones. */
2617 if (!parent && !next_parent)
2620 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2622 * Looks like the two contexts are clones, so we might be
2623 * able to optimize the context switch. We lock both
2624 * contexts and check that they are clones under the
2625 * lock (including re-checking that neither has been
2626 * uncloned in the meantime). It doesn't matter which
2627 * order we take the locks because no other cpu could
2628 * be trying to lock both of these tasks.
2630 raw_spin_lock(&ctx->lock);
2631 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2632 if (context_equiv(ctx, next_ctx)) {
2633 WRITE_ONCE(ctx->task, next);
2634 WRITE_ONCE(next_ctx->task, task);
2636 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
2639 * RCU_INIT_POINTER here is safe because we've not
2640 * modified the ctx and the above modification of
2641 * ctx->task and ctx->task_ctx_data are immaterial
2642 * since those values are always verified under
2643 * ctx->lock which we're now holding.
2645 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
2646 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
2650 perf_event_sync_stat(ctx, next_ctx);
2652 raw_spin_unlock(&next_ctx->lock);
2653 raw_spin_unlock(&ctx->lock);
2659 raw_spin_lock(&ctx->lock);
2660 task_ctx_sched_out(cpuctx, ctx);
2661 raw_spin_unlock(&ctx->lock);
2665 void perf_sched_cb_dec(struct pmu *pmu)
2667 this_cpu_dec(perf_sched_cb_usages);
2670 void perf_sched_cb_inc(struct pmu *pmu)
2672 this_cpu_inc(perf_sched_cb_usages);
2676 * This function provides the context switch callback to the lower code
2677 * layer. It is invoked ONLY when the context switch callback is enabled.
2679 static void perf_pmu_sched_task(struct task_struct *prev,
2680 struct task_struct *next,
2683 struct perf_cpu_context *cpuctx;
2685 unsigned long flags;
2690 local_irq_save(flags);
2694 list_for_each_entry_rcu(pmu, &pmus, entry) {
2695 if (pmu->sched_task) {
2696 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2698 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2700 perf_pmu_disable(pmu);
2702 pmu->sched_task(cpuctx->task_ctx, sched_in);
2704 perf_pmu_enable(pmu);
2706 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2712 local_irq_restore(flags);
2715 static void perf_event_switch(struct task_struct *task,
2716 struct task_struct *next_prev, bool sched_in);
2718 #define for_each_task_context_nr(ctxn) \
2719 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2722 * Called from scheduler to remove the events of the current task,
2723 * with interrupts disabled.
2725 * We stop each event and update the event value in event->count.
2727 * This does not protect us against NMI, but disable()
2728 * sets the disabled bit in the control field of event _before_
2729 * accessing the event control register. If a NMI hits, then it will
2730 * not restart the event.
2732 void __perf_event_task_sched_out(struct task_struct *task,
2733 struct task_struct *next)
2737 if (__this_cpu_read(perf_sched_cb_usages))
2738 perf_pmu_sched_task(task, next, false);
2740 if (atomic_read(&nr_switch_events))
2741 perf_event_switch(task, next, false);
2743 for_each_task_context_nr(ctxn)
2744 perf_event_context_sched_out(task, ctxn, next);
2747 * if cgroup events exist on this CPU, then we need
2748 * to check if we have to switch out PMU state.
2749 * cgroup event are system-wide mode only
2751 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2752 perf_cgroup_sched_out(task, next);
2756 * Called with IRQs disabled
2758 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2759 enum event_type_t event_type)
2761 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2765 ctx_pinned_sched_in(struct perf_event_context *ctx,
2766 struct perf_cpu_context *cpuctx)
2768 struct perf_event *event;
2770 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2771 if (event->state <= PERF_EVENT_STATE_OFF)
2773 if (!event_filter_match(event))
2776 /* may need to reset tstamp_enabled */
2777 if (is_cgroup_event(event))
2778 perf_cgroup_mark_enabled(event, ctx);
2780 if (group_can_go_on(event, cpuctx, 1))
2781 group_sched_in(event, cpuctx, ctx);
2784 * If this pinned group hasn't been scheduled,
2785 * put it in error state.
2787 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2788 update_group_times(event);
2789 event->state = PERF_EVENT_STATE_ERROR;
2795 ctx_flexible_sched_in(struct perf_event_context *ctx,
2796 struct perf_cpu_context *cpuctx)
2798 struct perf_event *event;
2801 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2802 /* Ignore events in OFF or ERROR state */
2803 if (event->state <= PERF_EVENT_STATE_OFF)
2806 * Listen to the 'cpu' scheduling filter constraint
2809 if (!event_filter_match(event))
2812 /* may need to reset tstamp_enabled */
2813 if (is_cgroup_event(event))
2814 perf_cgroup_mark_enabled(event, ctx);
2816 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2817 if (group_sched_in(event, cpuctx, ctx))
2824 ctx_sched_in(struct perf_event_context *ctx,
2825 struct perf_cpu_context *cpuctx,
2826 enum event_type_t event_type,
2827 struct task_struct *task)
2829 int is_active = ctx->is_active;
2832 lockdep_assert_held(&ctx->lock);
2834 if (likely(!ctx->nr_events))
2837 ctx->is_active |= (event_type | EVENT_TIME);
2840 cpuctx->task_ctx = ctx;
2842 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2845 is_active ^= ctx->is_active; /* changed bits */
2847 if (is_active & EVENT_TIME) {
2848 /* start ctx time */
2850 ctx->timestamp = now;
2851 perf_cgroup_set_timestamp(task, ctx);
2855 * First go through the list and put on any pinned groups
2856 * in order to give them the best chance of going on.
2858 if (is_active & EVENT_PINNED)
2859 ctx_pinned_sched_in(ctx, cpuctx);
2861 /* Then walk through the lower prio flexible groups */
2862 if (is_active & EVENT_FLEXIBLE)
2863 ctx_flexible_sched_in(ctx, cpuctx);
2866 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2867 enum event_type_t event_type,
2868 struct task_struct *task)
2870 struct perf_event_context *ctx = &cpuctx->ctx;
2872 ctx_sched_in(ctx, cpuctx, event_type, task);
2875 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2876 struct task_struct *task)
2878 struct perf_cpu_context *cpuctx;
2880 cpuctx = __get_cpu_context(ctx);
2881 if (cpuctx->task_ctx == ctx)
2884 perf_ctx_lock(cpuctx, ctx);
2885 perf_pmu_disable(ctx->pmu);
2887 * We want to keep the following priority order:
2888 * cpu pinned (that don't need to move), task pinned,
2889 * cpu flexible, task flexible.
2891 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2892 perf_event_sched_in(cpuctx, ctx, task);
2893 perf_pmu_enable(ctx->pmu);
2894 perf_ctx_unlock(cpuctx, ctx);
2898 * Called from scheduler to add the events of the current task
2899 * with interrupts disabled.
2901 * We restore the event value and then enable it.
2903 * This does not protect us against NMI, but enable()
2904 * sets the enabled bit in the control field of event _before_
2905 * accessing the event control register. If a NMI hits, then it will
2906 * keep the event running.
2908 void __perf_event_task_sched_in(struct task_struct *prev,
2909 struct task_struct *task)
2911 struct perf_event_context *ctx;
2915 * If cgroup events exist on this CPU, then we need to check if we have
2916 * to switch in PMU state; cgroup event are system-wide mode only.
2918 * Since cgroup events are CPU events, we must schedule these in before
2919 * we schedule in the task events.
2921 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2922 perf_cgroup_sched_in(prev, task);
2924 for_each_task_context_nr(ctxn) {
2925 ctx = task->perf_event_ctxp[ctxn];
2929 perf_event_context_sched_in(ctx, task);
2932 if (atomic_read(&nr_switch_events))
2933 perf_event_switch(task, prev, true);
2935 if (__this_cpu_read(perf_sched_cb_usages))
2936 perf_pmu_sched_task(prev, task, true);
2939 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2941 u64 frequency = event->attr.sample_freq;
2942 u64 sec = NSEC_PER_SEC;
2943 u64 divisor, dividend;
2945 int count_fls, nsec_fls, frequency_fls, sec_fls;
2947 count_fls = fls64(count);
2948 nsec_fls = fls64(nsec);
2949 frequency_fls = fls64(frequency);
2953 * We got @count in @nsec, with a target of sample_freq HZ
2954 * the target period becomes:
2957 * period = -------------------
2958 * @nsec * sample_freq
2963 * Reduce accuracy by one bit such that @a and @b converge
2964 * to a similar magnitude.
2966 #define REDUCE_FLS(a, b) \
2968 if (a##_fls > b##_fls) { \
2978 * Reduce accuracy until either term fits in a u64, then proceed with
2979 * the other, so that finally we can do a u64/u64 division.
2981 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2982 REDUCE_FLS(nsec, frequency);
2983 REDUCE_FLS(sec, count);
2986 if (count_fls + sec_fls > 64) {
2987 divisor = nsec * frequency;
2989 while (count_fls + sec_fls > 64) {
2990 REDUCE_FLS(count, sec);
2994 dividend = count * sec;
2996 dividend = count * sec;
2998 while (nsec_fls + frequency_fls > 64) {
2999 REDUCE_FLS(nsec, frequency);
3003 divisor = nsec * frequency;
3009 return div64_u64(dividend, divisor);
3012 static DEFINE_PER_CPU(int, perf_throttled_count);
3013 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3015 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3017 struct hw_perf_event *hwc = &event->hw;
3018 s64 period, sample_period;
3021 period = perf_calculate_period(event, nsec, count);
3023 delta = (s64)(period - hwc->sample_period);
3024 delta = (delta + 7) / 8; /* low pass filter */
3026 sample_period = hwc->sample_period + delta;
3031 hwc->sample_period = sample_period;
3033 if (local64_read(&hwc->period_left) > 8*sample_period) {
3035 event->pmu->stop(event, PERF_EF_UPDATE);
3037 local64_set(&hwc->period_left, 0);
3040 event->pmu->start(event, PERF_EF_RELOAD);
3045 * combine freq adjustment with unthrottling to avoid two passes over the
3046 * events. At the same time, make sure, having freq events does not change
3047 * the rate of unthrottling as that would introduce bias.
3049 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3052 struct perf_event *event;
3053 struct hw_perf_event *hwc;
3054 u64 now, period = TICK_NSEC;
3058 * only need to iterate over all events iff:
3059 * - context have events in frequency mode (needs freq adjust)
3060 * - there are events to unthrottle on this cpu
3062 if (!(ctx->nr_freq || needs_unthr))
3065 raw_spin_lock(&ctx->lock);
3066 perf_pmu_disable(ctx->pmu);
3068 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3069 if (event->state != PERF_EVENT_STATE_ACTIVE)
3072 if (!event_filter_match(event))
3075 perf_pmu_disable(event->pmu);
3079 if (hwc->interrupts == MAX_INTERRUPTS) {
3080 hwc->interrupts = 0;
3081 perf_log_throttle(event, 1);
3082 event->pmu->start(event, 0);
3085 if (!event->attr.freq || !event->attr.sample_freq)
3089 * stop the event and update event->count
3091 event->pmu->stop(event, PERF_EF_UPDATE);
3093 now = local64_read(&event->count);
3094 delta = now - hwc->freq_count_stamp;
3095 hwc->freq_count_stamp = now;
3099 * reload only if value has changed
3100 * we have stopped the event so tell that
3101 * to perf_adjust_period() to avoid stopping it
3105 perf_adjust_period(event, period, delta, false);
3107 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3109 perf_pmu_enable(event->pmu);
3112 perf_pmu_enable(ctx->pmu);
3113 raw_spin_unlock(&ctx->lock);
3117 * Round-robin a context's events:
3119 static void rotate_ctx(struct perf_event_context *ctx)
3122 * Rotate the first entry last of non-pinned groups. Rotation might be
3123 * disabled by the inheritance code.
3125 if (!ctx->rotate_disable)
3126 list_rotate_left(&ctx->flexible_groups);
3129 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
3131 struct perf_event_context *ctx = NULL;
3134 if (cpuctx->ctx.nr_events) {
3135 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
3139 ctx = cpuctx->task_ctx;
3140 if (ctx && ctx->nr_events) {
3141 if (ctx->nr_events != ctx->nr_active)
3148 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3149 perf_pmu_disable(cpuctx->ctx.pmu);
3151 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3153 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
3155 rotate_ctx(&cpuctx->ctx);
3159 perf_event_sched_in(cpuctx, ctx, current);
3161 perf_pmu_enable(cpuctx->ctx.pmu);
3162 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3168 void perf_event_task_tick(void)
3170 struct list_head *head = this_cpu_ptr(&active_ctx_list);
3171 struct perf_event_context *ctx, *tmp;
3174 WARN_ON(!irqs_disabled());
3176 __this_cpu_inc(perf_throttled_seq);
3177 throttled = __this_cpu_xchg(perf_throttled_count, 0);
3178 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
3180 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
3181 perf_adjust_freq_unthr_context(ctx, throttled);
3184 static int event_enable_on_exec(struct perf_event *event,
3185 struct perf_event_context *ctx)
3187 if (!event->attr.enable_on_exec)
3190 event->attr.enable_on_exec = 0;
3191 if (event->state >= PERF_EVENT_STATE_INACTIVE)
3194 __perf_event_mark_enabled(event);
3200 * Enable all of a task's events that have been marked enable-on-exec.
3201 * This expects task == current.
3203 static void perf_event_enable_on_exec(int ctxn)
3205 struct perf_event_context *ctx, *clone_ctx = NULL;
3206 struct perf_cpu_context *cpuctx;
3207 struct perf_event *event;
3208 unsigned long flags;
3211 local_irq_save(flags);
3212 ctx = current->perf_event_ctxp[ctxn];
3213 if (!ctx || !ctx->nr_events)
3216 cpuctx = __get_cpu_context(ctx);
3217 perf_ctx_lock(cpuctx, ctx);
3218 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
3219 list_for_each_entry(event, &ctx->event_list, event_entry)
3220 enabled |= event_enable_on_exec(event, ctx);
3223 * Unclone and reschedule this context if we enabled any event.
3226 clone_ctx = unclone_ctx(ctx);
3227 ctx_resched(cpuctx, ctx);
3229 perf_ctx_unlock(cpuctx, ctx);
3232 local_irq_restore(flags);
3238 void perf_event_exec(void)
3243 for_each_task_context_nr(ctxn)
3244 perf_event_enable_on_exec(ctxn);
3248 struct perf_read_data {
3249 struct perf_event *event;
3255 * Cross CPU call to read the hardware event
3257 static void __perf_event_read(void *info)
3259 struct perf_read_data *data = info;
3260 struct perf_event *sub, *event = data->event;
3261 struct perf_event_context *ctx = event->ctx;
3262 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3263 struct pmu *pmu = event->pmu;
3266 * If this is a task context, we need to check whether it is
3267 * the current task context of this cpu. If not it has been
3268 * scheduled out before the smp call arrived. In that case
3269 * event->count would have been updated to a recent sample
3270 * when the event was scheduled out.
3272 if (ctx->task && cpuctx->task_ctx != ctx)
3275 raw_spin_lock(&ctx->lock);
3276 if (ctx->is_active) {
3277 update_context_time(ctx);
3278 update_cgrp_time_from_event(event);
3281 update_event_times(event);
3282 if (event->state != PERF_EVENT_STATE_ACTIVE)
3291 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
3295 list_for_each_entry(sub, &event->sibling_list, group_entry) {
3296 update_event_times(sub);
3297 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
3299 * Use sibling's PMU rather than @event's since
3300 * sibling could be on different (eg: software) PMU.
3302 sub->pmu->read(sub);
3306 data->ret = pmu->commit_txn(pmu);
3309 raw_spin_unlock(&ctx->lock);
3312 static inline u64 perf_event_count(struct perf_event *event)
3314 if (event->pmu->count)
3315 return event->pmu->count(event);
3317 return __perf_event_count(event);
3321 * NMI-safe method to read a local event, that is an event that
3323 * - either for the current task, or for this CPU
3324 * - does not have inherit set, for inherited task events
3325 * will not be local and we cannot read them atomically
3326 * - must not have a pmu::count method
3328 u64 perf_event_read_local(struct perf_event *event)
3330 unsigned long flags;
3334 * Disabling interrupts avoids all counter scheduling (context
3335 * switches, timer based rotation and IPIs).
3337 local_irq_save(flags);
3339 /* If this is a per-task event, it must be for current */
3340 WARN_ON_ONCE((event->attach_state & PERF_ATTACH_TASK) &&
3341 event->hw.target != current);
3343 /* If this is a per-CPU event, it must be for this CPU */
3344 WARN_ON_ONCE(!(event->attach_state & PERF_ATTACH_TASK) &&
3345 event->cpu != smp_processor_id());
3348 * It must not be an event with inherit set, we cannot read
3349 * all child counters from atomic context.
3351 WARN_ON_ONCE(event->attr.inherit);
3354 * It must not have a pmu::count method, those are not
3357 WARN_ON_ONCE(event->pmu->count);
3360 * If the event is currently on this CPU, its either a per-task event,
3361 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
3364 if (event->oncpu == smp_processor_id())
3365 event->pmu->read(event);
3367 val = local64_read(&event->count);
3368 local_irq_restore(flags);
3373 static int perf_event_read(struct perf_event *event, bool group)
3378 * If event is enabled and currently active on a CPU, update the
3379 * value in the event structure:
3381 if (event->state == PERF_EVENT_STATE_ACTIVE) {
3382 struct perf_read_data data = {
3387 smp_call_function_single(event->oncpu,
3388 __perf_event_read, &data, 1);
3390 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3391 struct perf_event_context *ctx = event->ctx;
3392 unsigned long flags;
3394 raw_spin_lock_irqsave(&ctx->lock, flags);
3396 * may read while context is not active
3397 * (e.g., thread is blocked), in that case
3398 * we cannot update context time
3400 if (ctx->is_active) {
3401 update_context_time(ctx);
3402 update_cgrp_time_from_event(event);
3405 update_group_times(event);
3407 update_event_times(event);
3408 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3415 * Initialize the perf_event context in a task_struct:
3417 static void __perf_event_init_context(struct perf_event_context *ctx)
3419 raw_spin_lock_init(&ctx->lock);
3420 mutex_init(&ctx->mutex);
3421 INIT_LIST_HEAD(&ctx->active_ctx_list);
3422 INIT_LIST_HEAD(&ctx->pinned_groups);
3423 INIT_LIST_HEAD(&ctx->flexible_groups);
3424 INIT_LIST_HEAD(&ctx->event_list);
3425 atomic_set(&ctx->refcount, 1);
3428 static struct perf_event_context *
3429 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3431 struct perf_event_context *ctx;
3433 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3437 __perf_event_init_context(ctx);
3440 get_task_struct(task);
3447 static struct task_struct *
3448 find_lively_task_by_vpid(pid_t vpid)
3450 struct task_struct *task;
3457 task = find_task_by_vpid(vpid);
3459 get_task_struct(task);
3463 return ERR_PTR(-ESRCH);
3465 /* Reuse ptrace permission checks for now. */
3467 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
3472 put_task_struct(task);
3473 return ERR_PTR(err);
3478 * Returns a matching context with refcount and pincount.
3480 static struct perf_event_context *
3481 find_get_context(struct pmu *pmu, struct task_struct *task,
3482 struct perf_event *event)
3484 struct perf_event_context *ctx, *clone_ctx = NULL;
3485 struct perf_cpu_context *cpuctx;
3486 void *task_ctx_data = NULL;
3487 unsigned long flags;
3489 int cpu = event->cpu;
3492 /* Must be root to operate on a CPU event: */
3493 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3494 return ERR_PTR(-EACCES);
3497 * We could be clever and allow to attach a event to an
3498 * offline CPU and activate it when the CPU comes up, but
3501 if (!cpu_online(cpu))
3502 return ERR_PTR(-ENODEV);
3504 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3513 ctxn = pmu->task_ctx_nr;
3517 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
3518 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
3519 if (!task_ctx_data) {
3526 ctx = perf_lock_task_context(task, ctxn, &flags);
3528 clone_ctx = unclone_ctx(ctx);
3531 if (task_ctx_data && !ctx->task_ctx_data) {
3532 ctx->task_ctx_data = task_ctx_data;
3533 task_ctx_data = NULL;
3535 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3540 ctx = alloc_perf_context(pmu, task);
3545 if (task_ctx_data) {
3546 ctx->task_ctx_data = task_ctx_data;
3547 task_ctx_data = NULL;
3551 mutex_lock(&task->perf_event_mutex);
3553 * If it has already passed perf_event_exit_task().
3554 * we must see PF_EXITING, it takes this mutex too.
3556 if (task->flags & PF_EXITING)
3558 else if (task->perf_event_ctxp[ctxn])
3563 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3565 mutex_unlock(&task->perf_event_mutex);
3567 if (unlikely(err)) {
3576 kfree(task_ctx_data);
3580 kfree(task_ctx_data);
3581 return ERR_PTR(err);
3584 static void perf_event_free_filter(struct perf_event *event);
3585 static void perf_event_free_bpf_prog(struct perf_event *event);
3587 static void free_event_rcu(struct rcu_head *head)
3589 struct perf_event *event;
3591 event = container_of(head, struct perf_event, rcu_head);
3593 put_pid_ns(event->ns);
3594 perf_event_free_filter(event);
3598 static void ring_buffer_attach(struct perf_event *event,
3599 struct ring_buffer *rb);
3601 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3606 if (is_cgroup_event(event))
3607 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3610 #ifdef CONFIG_NO_HZ_FULL
3611 static DEFINE_SPINLOCK(nr_freq_lock);
3614 static void unaccount_freq_event_nohz(void)
3616 #ifdef CONFIG_NO_HZ_FULL
3617 spin_lock(&nr_freq_lock);
3618 if (atomic_dec_and_test(&nr_freq_events))
3619 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
3620 spin_unlock(&nr_freq_lock);
3624 static void unaccount_freq_event(void)
3626 if (tick_nohz_full_enabled())
3627 unaccount_freq_event_nohz();
3629 atomic_dec(&nr_freq_events);
3632 static void unaccount_event(struct perf_event *event)
3639 if (event->attach_state & PERF_ATTACH_TASK)
3641 if (event->attr.mmap || event->attr.mmap_data)
3642 atomic_dec(&nr_mmap_events);
3643 if (event->attr.comm)
3644 atomic_dec(&nr_comm_events);
3645 if (event->attr.task)
3646 atomic_dec(&nr_task_events);
3647 if (event->attr.freq)
3648 unaccount_freq_event();
3649 if (event->attr.context_switch) {
3651 atomic_dec(&nr_switch_events);
3653 if (is_cgroup_event(event))
3655 if (has_branch_stack(event))
3659 if (!atomic_add_unless(&perf_sched_count, -1, 1))
3660 schedule_delayed_work(&perf_sched_work, HZ);
3663 unaccount_event_cpu(event, event->cpu);
3666 static void perf_sched_delayed(struct work_struct *work)
3668 mutex_lock(&perf_sched_mutex);
3669 if (atomic_dec_and_test(&perf_sched_count))
3670 static_branch_disable(&perf_sched_events);
3671 mutex_unlock(&perf_sched_mutex);
3675 * The following implement mutual exclusion of events on "exclusive" pmus
3676 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
3677 * at a time, so we disallow creating events that might conflict, namely:
3679 * 1) cpu-wide events in the presence of per-task events,
3680 * 2) per-task events in the presence of cpu-wide events,
3681 * 3) two matching events on the same context.
3683 * The former two cases are handled in the allocation path (perf_event_alloc(),
3684 * _free_event()), the latter -- before the first perf_install_in_context().
3686 static int exclusive_event_init(struct perf_event *event)
3688 struct pmu *pmu = event->pmu;
3690 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3694 * Prevent co-existence of per-task and cpu-wide events on the
3695 * same exclusive pmu.
3697 * Negative pmu::exclusive_cnt means there are cpu-wide
3698 * events on this "exclusive" pmu, positive means there are
3701 * Since this is called in perf_event_alloc() path, event::ctx
3702 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
3703 * to mean "per-task event", because unlike other attach states it
3704 * never gets cleared.
3706 if (event->attach_state & PERF_ATTACH_TASK) {
3707 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
3710 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
3717 static void exclusive_event_destroy(struct perf_event *event)
3719 struct pmu *pmu = event->pmu;
3721 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3724 /* see comment in exclusive_event_init() */
3725 if (event->attach_state & PERF_ATTACH_TASK)
3726 atomic_dec(&pmu->exclusive_cnt);
3728 atomic_inc(&pmu->exclusive_cnt);
3731 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
3733 if ((e1->pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) &&
3734 (e1->cpu == e2->cpu ||
3741 /* Called under the same ctx::mutex as perf_install_in_context() */
3742 static bool exclusive_event_installable(struct perf_event *event,
3743 struct perf_event_context *ctx)
3745 struct perf_event *iter_event;
3746 struct pmu *pmu = event->pmu;
3748 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3751 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
3752 if (exclusive_event_match(iter_event, event))
3759 static void _free_event(struct perf_event *event)
3761 irq_work_sync(&event->pending);
3763 unaccount_event(event);
3767 * Can happen when we close an event with re-directed output.
3769 * Since we have a 0 refcount, perf_mmap_close() will skip
3770 * over us; possibly making our ring_buffer_put() the last.
3772 mutex_lock(&event->mmap_mutex);
3773 ring_buffer_attach(event, NULL);
3774 mutex_unlock(&event->mmap_mutex);
3777 if (is_cgroup_event(event))
3778 perf_detach_cgroup(event);
3780 if (!event->parent) {
3781 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3782 put_callchain_buffers();
3785 perf_event_free_bpf_prog(event);
3788 event->destroy(event);
3791 put_ctx(event->ctx);
3794 exclusive_event_destroy(event);
3795 module_put(event->pmu->module);
3798 call_rcu(&event->rcu_head, free_event_rcu);
3802 * Used to free events which have a known refcount of 1, such as in error paths
3803 * where the event isn't exposed yet and inherited events.
3805 static void free_event(struct perf_event *event)
3807 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3808 "unexpected event refcount: %ld; ptr=%p\n",
3809 atomic_long_read(&event->refcount), event)) {
3810 /* leak to avoid use-after-free */
3818 * Remove user event from the owner task.
3820 static void perf_remove_from_owner(struct perf_event *event)
3822 struct task_struct *owner;
3826 * Matches the smp_store_release() in perf_event_exit_task(). If we
3827 * observe !owner it means the list deletion is complete and we can
3828 * indeed free this event, otherwise we need to serialize on
3829 * owner->perf_event_mutex.
3831 owner = lockless_dereference(event->owner);
3834 * Since delayed_put_task_struct() also drops the last
3835 * task reference we can safely take a new reference
3836 * while holding the rcu_read_lock().
3838 get_task_struct(owner);
3844 * If we're here through perf_event_exit_task() we're already
3845 * holding ctx->mutex which would be an inversion wrt. the
3846 * normal lock order.
3848 * However we can safely take this lock because its the child
3851 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
3854 * We have to re-check the event->owner field, if it is cleared
3855 * we raced with perf_event_exit_task(), acquiring the mutex
3856 * ensured they're done, and we can proceed with freeing the
3860 list_del_init(&event->owner_entry);
3861 smp_store_release(&event->owner, NULL);
3863 mutex_unlock(&owner->perf_event_mutex);
3864 put_task_struct(owner);
3868 static void put_event(struct perf_event *event)
3870 if (!atomic_long_dec_and_test(&event->refcount))
3877 * Kill an event dead; while event:refcount will preserve the event
3878 * object, it will not preserve its functionality. Once the last 'user'
3879 * gives up the object, we'll destroy the thing.
3881 int perf_event_release_kernel(struct perf_event *event)
3883 struct perf_event_context *ctx = event->ctx;
3884 struct perf_event *child, *tmp;
3887 * If we got here through err_file: fput(event_file); we will not have
3888 * attached to a context yet.
3891 WARN_ON_ONCE(event->attach_state &
3892 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
3896 if (!is_kernel_event(event))
3897 perf_remove_from_owner(event);
3899 ctx = perf_event_ctx_lock(event);
3900 WARN_ON_ONCE(ctx->parent_ctx);
3901 perf_remove_from_context(event, DETACH_GROUP);
3903 raw_spin_lock_irq(&ctx->lock);
3905 * Mark this even as STATE_DEAD, there is no external reference to it
3908 * Anybody acquiring event->child_mutex after the below loop _must_
3909 * also see this, most importantly inherit_event() which will avoid
3910 * placing more children on the list.
3912 * Thus this guarantees that we will in fact observe and kill _ALL_
3915 event->state = PERF_EVENT_STATE_DEAD;
3916 raw_spin_unlock_irq(&ctx->lock);
3918 perf_event_ctx_unlock(event, ctx);
3921 mutex_lock(&event->child_mutex);
3922 list_for_each_entry(child, &event->child_list, child_list) {
3925 * Cannot change, child events are not migrated, see the
3926 * comment with perf_event_ctx_lock_nested().
3928 ctx = lockless_dereference(child->ctx);
3930 * Since child_mutex nests inside ctx::mutex, we must jump
3931 * through hoops. We start by grabbing a reference on the ctx.
3933 * Since the event cannot get freed while we hold the
3934 * child_mutex, the context must also exist and have a !0
3940 * Now that we have a ctx ref, we can drop child_mutex, and
3941 * acquire ctx::mutex without fear of it going away. Then we
3942 * can re-acquire child_mutex.
3944 mutex_unlock(&event->child_mutex);
3945 mutex_lock(&ctx->mutex);
3946 mutex_lock(&event->child_mutex);
3949 * Now that we hold ctx::mutex and child_mutex, revalidate our
3950 * state, if child is still the first entry, it didn't get freed
3951 * and we can continue doing so.
3953 tmp = list_first_entry_or_null(&event->child_list,
3954 struct perf_event, child_list);
3956 perf_remove_from_context(child, DETACH_GROUP);
3957 list_del(&child->child_list);
3960 * This matches the refcount bump in inherit_event();
3961 * this can't be the last reference.
3966 mutex_unlock(&event->child_mutex);
3967 mutex_unlock(&ctx->mutex);
3971 mutex_unlock(&event->child_mutex);
3974 put_event(event); /* Must be the 'last' reference */
3977 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3980 * Called when the last reference to the file is gone.
3982 static int perf_release(struct inode *inode, struct file *file)
3984 perf_event_release_kernel(file->private_data);
3988 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3990 struct perf_event *child;
3996 mutex_lock(&event->child_mutex);
3998 (void)perf_event_read(event, false);
3999 total += perf_event_count(event);
4001 *enabled += event->total_time_enabled +
4002 atomic64_read(&event->child_total_time_enabled);
4003 *running += event->total_time_running +
4004 atomic64_read(&event->child_total_time_running);
4006 list_for_each_entry(child, &event->child_list, child_list) {
4007 (void)perf_event_read(child, false);
4008 total += perf_event_count(child);
4009 *enabled += child->total_time_enabled;
4010 *running += child->total_time_running;
4012 mutex_unlock(&event->child_mutex);
4016 EXPORT_SYMBOL_GPL(perf_event_read_value);
4018 static int __perf_read_group_add(struct perf_event *leader,
4019 u64 read_format, u64 *values)
4021 struct perf_event *sub;
4022 int n = 1; /* skip @nr */
4025 ret = perf_event_read(leader, true);
4030 * Since we co-schedule groups, {enabled,running} times of siblings
4031 * will be identical to those of the leader, so we only publish one
4034 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4035 values[n++] += leader->total_time_enabled +
4036 atomic64_read(&leader->child_total_time_enabled);
4039 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4040 values[n++] += leader->total_time_running +
4041 atomic64_read(&leader->child_total_time_running);
4045 * Write {count,id} tuples for every sibling.
4047 values[n++] += perf_event_count(leader);
4048 if (read_format & PERF_FORMAT_ID)
4049 values[n++] = primary_event_id(leader);
4051 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4052 values[n++] += perf_event_count(sub);
4053 if (read_format & PERF_FORMAT_ID)
4054 values[n++] = primary_event_id(sub);
4060 static int perf_read_group(struct perf_event *event,
4061 u64 read_format, char __user *buf)
4063 struct perf_event *leader = event->group_leader, *child;
4064 struct perf_event_context *ctx = leader->ctx;
4068 lockdep_assert_held(&ctx->mutex);
4070 values = kzalloc(event->read_size, GFP_KERNEL);
4074 values[0] = 1 + leader->nr_siblings;
4077 * By locking the child_mutex of the leader we effectively
4078 * lock the child list of all siblings.. XXX explain how.
4080 mutex_lock(&leader->child_mutex);
4082 ret = __perf_read_group_add(leader, read_format, values);
4086 list_for_each_entry(child, &leader->child_list, child_list) {
4087 ret = __perf_read_group_add(child, read_format, values);
4092 mutex_unlock(&leader->child_mutex);
4094 ret = event->read_size;
4095 if (copy_to_user(buf, values, event->read_size))
4100 mutex_unlock(&leader->child_mutex);
4106 static int perf_read_one(struct perf_event *event,
4107 u64 read_format, char __user *buf)
4109 u64 enabled, running;
4113 values[n++] = perf_event_read_value(event, &enabled, &running);
4114 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4115 values[n++] = enabled;
4116 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4117 values[n++] = running;
4118 if (read_format & PERF_FORMAT_ID)
4119 values[n++] = primary_event_id(event);
4121 if (copy_to_user(buf, values, n * sizeof(u64)))
4124 return n * sizeof(u64);
4127 static bool is_event_hup(struct perf_event *event)
4131 if (event->state > PERF_EVENT_STATE_EXIT)
4134 mutex_lock(&event->child_mutex);
4135 no_children = list_empty(&event->child_list);
4136 mutex_unlock(&event->child_mutex);
4141 * Read the performance event - simple non blocking version for now
4144 __perf_read(struct perf_event *event, char __user *buf, size_t count)
4146 u64 read_format = event->attr.read_format;
4150 * Return end-of-file for a read on a event that is in
4151 * error state (i.e. because it was pinned but it couldn't be
4152 * scheduled on to the CPU at some point).
4154 if (event->state == PERF_EVENT_STATE_ERROR)
4157 if (count < event->read_size)
4160 WARN_ON_ONCE(event->ctx->parent_ctx);
4161 if (read_format & PERF_FORMAT_GROUP)
4162 ret = perf_read_group(event, read_format, buf);
4164 ret = perf_read_one(event, read_format, buf);
4170 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
4172 struct perf_event *event = file->private_data;
4173 struct perf_event_context *ctx;
4176 ctx = perf_event_ctx_lock(event);
4177 ret = __perf_read(event, buf, count);
4178 perf_event_ctx_unlock(event, ctx);
4183 static unsigned int perf_poll(struct file *file, poll_table *wait)
4185 struct perf_event *event = file->private_data;
4186 struct ring_buffer *rb;
4187 unsigned int events = POLLHUP;
4189 poll_wait(file, &event->waitq, wait);
4191 if (is_event_hup(event))
4195 * Pin the event->rb by taking event->mmap_mutex; otherwise
4196 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
4198 mutex_lock(&event->mmap_mutex);
4201 events = atomic_xchg(&rb->poll, 0);
4202 mutex_unlock(&event->mmap_mutex);
4206 static void _perf_event_reset(struct perf_event *event)
4208 (void)perf_event_read(event, false);
4209 local64_set(&event->count, 0);
4210 perf_event_update_userpage(event);
4214 * Holding the top-level event's child_mutex means that any
4215 * descendant process that has inherited this event will block
4216 * in perf_event_exit_event() if it goes to exit, thus satisfying the
4217 * task existence requirements of perf_event_enable/disable.
4219 static void perf_event_for_each_child(struct perf_event *event,
4220 void (*func)(struct perf_event *))
4222 struct perf_event *child;
4224 WARN_ON_ONCE(event->ctx->parent_ctx);
4226 mutex_lock(&event->child_mutex);
4228 list_for_each_entry(child, &event->child_list, child_list)
4230 mutex_unlock(&event->child_mutex);
4233 static void perf_event_for_each(struct perf_event *event,
4234 void (*func)(struct perf_event *))
4236 struct perf_event_context *ctx = event->ctx;
4237 struct perf_event *sibling;
4239 lockdep_assert_held(&ctx->mutex);
4241 event = event->group_leader;
4243 perf_event_for_each_child(event, func);
4244 list_for_each_entry(sibling, &event->sibling_list, group_entry)
4245 perf_event_for_each_child(sibling, func);
4248 static void __perf_event_period(struct perf_event *event,
4249 struct perf_cpu_context *cpuctx,
4250 struct perf_event_context *ctx,
4253 u64 value = *((u64 *)info);
4256 if (event->attr.freq) {
4257 event->attr.sample_freq = value;
4259 event->attr.sample_period = value;
4260 event->hw.sample_period = value;
4263 active = (event->state == PERF_EVENT_STATE_ACTIVE);
4265 perf_pmu_disable(ctx->pmu);
4267 * We could be throttled; unthrottle now to avoid the tick
4268 * trying to unthrottle while we already re-started the event.
4270 if (event->hw.interrupts == MAX_INTERRUPTS) {
4271 event->hw.interrupts = 0;
4272 perf_log_throttle(event, 1);
4274 event->pmu->stop(event, PERF_EF_UPDATE);
4277 local64_set(&event->hw.period_left, 0);
4280 event->pmu->start(event, PERF_EF_RELOAD);
4281 perf_pmu_enable(ctx->pmu);
4285 static int perf_event_period(struct perf_event *event, u64 __user *arg)
4289 if (!is_sampling_event(event))
4292 if (copy_from_user(&value, arg, sizeof(value)))
4298 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
4301 event_function_call(event, __perf_event_period, &value);
4306 static const struct file_operations perf_fops;
4308 static inline int perf_fget_light(int fd, struct fd *p)
4310 struct fd f = fdget(fd);
4314 if (f.file->f_op != &perf_fops) {
4322 static int perf_event_set_output(struct perf_event *event,
4323 struct perf_event *output_event);
4324 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
4325 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
4327 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
4329 void (*func)(struct perf_event *);
4333 case PERF_EVENT_IOC_ENABLE:
4334 func = _perf_event_enable;
4336 case PERF_EVENT_IOC_DISABLE:
4337 func = _perf_event_disable;
4339 case PERF_EVENT_IOC_RESET:
4340 func = _perf_event_reset;
4343 case PERF_EVENT_IOC_REFRESH:
4344 return _perf_event_refresh(event, arg);
4346 case PERF_EVENT_IOC_PERIOD:
4347 return perf_event_period(event, (u64 __user *)arg);
4349 case PERF_EVENT_IOC_ID:
4351 u64 id = primary_event_id(event);
4353 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
4358 case PERF_EVENT_IOC_SET_OUTPUT:
4362 struct perf_event *output_event;
4364 ret = perf_fget_light(arg, &output);
4367 output_event = output.file->private_data;
4368 ret = perf_event_set_output(event, output_event);
4371 ret = perf_event_set_output(event, NULL);
4376 case PERF_EVENT_IOC_SET_FILTER:
4377 return perf_event_set_filter(event, (void __user *)arg);
4379 case PERF_EVENT_IOC_SET_BPF:
4380 return perf_event_set_bpf_prog(event, arg);
4382 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
4383 struct ring_buffer *rb;
4386 rb = rcu_dereference(event->rb);
4387 if (!rb || !rb->nr_pages) {
4391 rb_toggle_paused(rb, !!arg);
4399 if (flags & PERF_IOC_FLAG_GROUP)
4400 perf_event_for_each(event, func);
4402 perf_event_for_each_child(event, func);
4407 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4409 struct perf_event *event = file->private_data;
4410 struct perf_event_context *ctx;
4413 ctx = perf_event_ctx_lock(event);
4414 ret = _perf_ioctl(event, cmd, arg);
4415 perf_event_ctx_unlock(event, ctx);
4420 #ifdef CONFIG_COMPAT
4421 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
4424 switch (_IOC_NR(cmd)) {
4425 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
4426 case _IOC_NR(PERF_EVENT_IOC_ID):
4427 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
4428 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
4429 cmd &= ~IOCSIZE_MASK;
4430 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
4434 return perf_ioctl(file, cmd, arg);
4437 # define perf_compat_ioctl NULL
4440 int perf_event_task_enable(void)
4442 struct perf_event_context *ctx;
4443 struct perf_event *event;
4445 mutex_lock(¤t->perf_event_mutex);
4446 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4447 ctx = perf_event_ctx_lock(event);
4448 perf_event_for_each_child(event, _perf_event_enable);
4449 perf_event_ctx_unlock(event, ctx);
4451 mutex_unlock(¤t->perf_event_mutex);
4456 int perf_event_task_disable(void)
4458 struct perf_event_context *ctx;
4459 struct perf_event *event;
4461 mutex_lock(¤t->perf_event_mutex);
4462 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4463 ctx = perf_event_ctx_lock(event);
4464 perf_event_for_each_child(event, _perf_event_disable);
4465 perf_event_ctx_unlock(event, ctx);
4467 mutex_unlock(¤t->perf_event_mutex);
4472 static int perf_event_index(struct perf_event *event)
4474 if (event->hw.state & PERF_HES_STOPPED)
4477 if (event->state != PERF_EVENT_STATE_ACTIVE)
4480 return event->pmu->event_idx(event);
4483 static void calc_timer_values(struct perf_event *event,
4490 *now = perf_clock();
4491 ctx_time = event->shadow_ctx_time + *now;
4492 *enabled = ctx_time - event->tstamp_enabled;
4493 *running = ctx_time - event->tstamp_running;
4496 static void perf_event_init_userpage(struct perf_event *event)
4498 struct perf_event_mmap_page *userpg;
4499 struct ring_buffer *rb;
4502 rb = rcu_dereference(event->rb);
4506 userpg = rb->user_page;
4508 /* Allow new userspace to detect that bit 0 is deprecated */
4509 userpg->cap_bit0_is_deprecated = 1;
4510 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
4511 userpg->data_offset = PAGE_SIZE;
4512 userpg->data_size = perf_data_size(rb);
4518 void __weak arch_perf_update_userpage(
4519 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
4524 * Callers need to ensure there can be no nesting of this function, otherwise
4525 * the seqlock logic goes bad. We can not serialize this because the arch
4526 * code calls this from NMI context.
4528 void perf_event_update_userpage(struct perf_event *event)
4530 struct perf_event_mmap_page *userpg;
4531 struct ring_buffer *rb;
4532 u64 enabled, running, now;
4535 rb = rcu_dereference(event->rb);
4540 * compute total_time_enabled, total_time_running
4541 * based on snapshot values taken when the event
4542 * was last scheduled in.
4544 * we cannot simply called update_context_time()
4545 * because of locking issue as we can be called in
4548 calc_timer_values(event, &now, &enabled, &running);
4550 userpg = rb->user_page;
4552 * Disable preemption so as to not let the corresponding user-space
4553 * spin too long if we get preempted.
4558 userpg->index = perf_event_index(event);
4559 userpg->offset = perf_event_count(event);
4561 userpg->offset -= local64_read(&event->hw.prev_count);
4563 userpg->time_enabled = enabled +
4564 atomic64_read(&event->child_total_time_enabled);
4566 userpg->time_running = running +
4567 atomic64_read(&event->child_total_time_running);
4569 arch_perf_update_userpage(event, userpg, now);
4578 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
4580 struct perf_event *event = vma->vm_file->private_data;
4581 struct ring_buffer *rb;
4582 int ret = VM_FAULT_SIGBUS;
4584 if (vmf->flags & FAULT_FLAG_MKWRITE) {
4585 if (vmf->pgoff == 0)
4591 rb = rcu_dereference(event->rb);
4595 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
4598 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
4602 get_page(vmf->page);
4603 vmf->page->mapping = vma->vm_file->f_mapping;
4604 vmf->page->index = vmf->pgoff;
4613 static void ring_buffer_attach(struct perf_event *event,
4614 struct ring_buffer *rb)
4616 struct ring_buffer *old_rb = NULL;
4617 unsigned long flags;
4621 * Should be impossible, we set this when removing
4622 * event->rb_entry and wait/clear when adding event->rb_entry.
4624 WARN_ON_ONCE(event->rcu_pending);
4627 spin_lock_irqsave(&old_rb->event_lock, flags);
4628 list_del_rcu(&event->rb_entry);
4629 spin_unlock_irqrestore(&old_rb->event_lock, flags);
4631 event->rcu_batches = get_state_synchronize_rcu();
4632 event->rcu_pending = 1;
4636 if (event->rcu_pending) {
4637 cond_synchronize_rcu(event->rcu_batches);
4638 event->rcu_pending = 0;
4641 spin_lock_irqsave(&rb->event_lock, flags);
4642 list_add_rcu(&event->rb_entry, &rb->event_list);
4643 spin_unlock_irqrestore(&rb->event_lock, flags);
4646 rcu_assign_pointer(event->rb, rb);
4649 ring_buffer_put(old_rb);
4651 * Since we detached before setting the new rb, so that we
4652 * could attach the new rb, we could have missed a wakeup.
4655 wake_up_all(&event->waitq);
4659 static void ring_buffer_wakeup(struct perf_event *event)
4661 struct ring_buffer *rb;
4664 rb = rcu_dereference(event->rb);
4666 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
4667 wake_up_all(&event->waitq);
4672 struct ring_buffer *ring_buffer_get(struct perf_event *event)
4674 struct ring_buffer *rb;
4677 rb = rcu_dereference(event->rb);
4679 if (!atomic_inc_not_zero(&rb->refcount))
4687 void ring_buffer_put(struct ring_buffer *rb)
4689 if (!atomic_dec_and_test(&rb->refcount))
4692 WARN_ON_ONCE(!list_empty(&rb->event_list));
4694 call_rcu(&rb->rcu_head, rb_free_rcu);
4697 static void perf_mmap_open(struct vm_area_struct *vma)
4699 struct perf_event *event = vma->vm_file->private_data;
4701 atomic_inc(&event->mmap_count);
4702 atomic_inc(&event->rb->mmap_count);
4705 atomic_inc(&event->rb->aux_mmap_count);
4707 if (event->pmu->event_mapped)
4708 event->pmu->event_mapped(event);
4711 static void perf_pmu_output_stop(struct perf_event *event);
4714 * A buffer can be mmap()ed multiple times; either directly through the same
4715 * event, or through other events by use of perf_event_set_output().
4717 * In order to undo the VM accounting done by perf_mmap() we need to destroy
4718 * the buffer here, where we still have a VM context. This means we need
4719 * to detach all events redirecting to us.
4721 static void perf_mmap_close(struct vm_area_struct *vma)
4723 struct perf_event *event = vma->vm_file->private_data;
4725 struct ring_buffer *rb = ring_buffer_get(event);
4726 struct user_struct *mmap_user = rb->mmap_user;
4727 int mmap_locked = rb->mmap_locked;
4728 unsigned long size = perf_data_size(rb);
4730 if (event->pmu->event_unmapped)
4731 event->pmu->event_unmapped(event);
4734 * rb->aux_mmap_count will always drop before rb->mmap_count and
4735 * event->mmap_count, so it is ok to use event->mmap_mutex to
4736 * serialize with perf_mmap here.
4738 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
4739 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
4741 * Stop all AUX events that are writing to this buffer,
4742 * so that we can free its AUX pages and corresponding PMU
4743 * data. Note that after rb::aux_mmap_count dropped to zero,
4744 * they won't start any more (see perf_aux_output_begin()).
4746 perf_pmu_output_stop(event);
4748 /* now it's safe to free the pages */
4749 atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
4750 vma->vm_mm->pinned_vm -= rb->aux_mmap_locked;
4752 /* this has to be the last one */
4754 WARN_ON_ONCE(atomic_read(&rb->aux_refcount));
4756 mutex_unlock(&event->mmap_mutex);
4759 atomic_dec(&rb->mmap_count);
4761 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
4764 ring_buffer_attach(event, NULL);
4765 mutex_unlock(&event->mmap_mutex);
4767 /* If there's still other mmap()s of this buffer, we're done. */
4768 if (atomic_read(&rb->mmap_count))
4772 * No other mmap()s, detach from all other events that might redirect
4773 * into the now unreachable buffer. Somewhat complicated by the
4774 * fact that rb::event_lock otherwise nests inside mmap_mutex.
4778 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4779 if (!atomic_long_inc_not_zero(&event->refcount)) {
4781 * This event is en-route to free_event() which will
4782 * detach it and remove it from the list.
4788 mutex_lock(&event->mmap_mutex);
4790 * Check we didn't race with perf_event_set_output() which can
4791 * swizzle the rb from under us while we were waiting to
4792 * acquire mmap_mutex.
4794 * If we find a different rb; ignore this event, a next
4795 * iteration will no longer find it on the list. We have to
4796 * still restart the iteration to make sure we're not now
4797 * iterating the wrong list.
4799 if (event->rb == rb)
4800 ring_buffer_attach(event, NULL);
4802 mutex_unlock(&event->mmap_mutex);
4806 * Restart the iteration; either we're on the wrong list or
4807 * destroyed its integrity by doing a deletion.
4814 * It could be there's still a few 0-ref events on the list; they'll
4815 * get cleaned up by free_event() -- they'll also still have their
4816 * ref on the rb and will free it whenever they are done with it.
4818 * Aside from that, this buffer is 'fully' detached and unmapped,
4819 * undo the VM accounting.
4822 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4823 vma->vm_mm->pinned_vm -= mmap_locked;
4824 free_uid(mmap_user);
4827 ring_buffer_put(rb); /* could be last */
4830 static const struct vm_operations_struct perf_mmap_vmops = {
4831 .open = perf_mmap_open,
4832 .close = perf_mmap_close, /* non mergable */
4833 .fault = perf_mmap_fault,
4834 .page_mkwrite = perf_mmap_fault,
4837 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
4839 struct perf_event *event = file->private_data;
4840 unsigned long user_locked, user_lock_limit;
4841 struct user_struct *user = current_user();
4842 unsigned long locked, lock_limit;
4843 struct ring_buffer *rb = NULL;
4844 unsigned long vma_size;
4845 unsigned long nr_pages;
4846 long user_extra = 0, extra = 0;
4847 int ret = 0, flags = 0;
4850 * Don't allow mmap() of inherited per-task counters. This would
4851 * create a performance issue due to all children writing to the
4854 if (event->cpu == -1 && event->attr.inherit)
4857 if (!(vma->vm_flags & VM_SHARED))
4860 vma_size = vma->vm_end - vma->vm_start;
4862 if (vma->vm_pgoff == 0) {
4863 nr_pages = (vma_size / PAGE_SIZE) - 1;
4866 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
4867 * mapped, all subsequent mappings should have the same size
4868 * and offset. Must be above the normal perf buffer.
4870 u64 aux_offset, aux_size;
4875 nr_pages = vma_size / PAGE_SIZE;
4877 mutex_lock(&event->mmap_mutex);
4884 aux_offset = ACCESS_ONCE(rb->user_page->aux_offset);
4885 aux_size = ACCESS_ONCE(rb->user_page->aux_size);
4887 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
4890 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
4893 /* already mapped with a different offset */
4894 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
4897 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
4900 /* already mapped with a different size */
4901 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
4904 if (!is_power_of_2(nr_pages))
4907 if (!atomic_inc_not_zero(&rb->mmap_count))
4910 if (rb_has_aux(rb)) {
4911 atomic_inc(&rb->aux_mmap_count);
4916 atomic_set(&rb->aux_mmap_count, 1);
4917 user_extra = nr_pages;
4923 * If we have rb pages ensure they're a power-of-two number, so we
4924 * can do bitmasks instead of modulo.
4926 if (nr_pages != 0 && !is_power_of_2(nr_pages))
4929 if (vma_size != PAGE_SIZE * (1 + nr_pages))
4932 WARN_ON_ONCE(event->ctx->parent_ctx);
4934 mutex_lock(&event->mmap_mutex);
4936 if (event->rb->nr_pages != nr_pages) {
4941 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4943 * Raced against perf_mmap_close() through
4944 * perf_event_set_output(). Try again, hope for better
4947 mutex_unlock(&event->mmap_mutex);
4954 user_extra = nr_pages + 1;
4957 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
4960 * Increase the limit linearly with more CPUs:
4962 user_lock_limit *= num_online_cpus();
4964 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
4966 if (user_locked > user_lock_limit)
4967 extra = user_locked - user_lock_limit;
4969 lock_limit = rlimit(RLIMIT_MEMLOCK);
4970 lock_limit >>= PAGE_SHIFT;
4971 locked = vma->vm_mm->pinned_vm + extra;
4973 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
4974 !capable(CAP_IPC_LOCK)) {
4979 WARN_ON(!rb && event->rb);
4981 if (vma->vm_flags & VM_WRITE)
4982 flags |= RING_BUFFER_WRITABLE;
4985 rb = rb_alloc(nr_pages,
4986 event->attr.watermark ? event->attr.wakeup_watermark : 0,
4994 atomic_set(&rb->mmap_count, 1);
4995 rb->mmap_user = get_current_user();
4996 rb->mmap_locked = extra;
4998 ring_buffer_attach(event, rb);
5000 perf_event_init_userpage(event);
5001 perf_event_update_userpage(event);
5003 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
5004 event->attr.aux_watermark, flags);
5006 rb->aux_mmap_locked = extra;
5011 atomic_long_add(user_extra, &user->locked_vm);
5012 vma->vm_mm->pinned_vm += extra;
5014 atomic_inc(&event->mmap_count);
5016 atomic_dec(&rb->mmap_count);
5019 mutex_unlock(&event->mmap_mutex);
5022 * Since pinned accounting is per vm we cannot allow fork() to copy our
5025 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
5026 vma->vm_ops = &perf_mmap_vmops;
5028 if (event->pmu->event_mapped)
5029 event->pmu->event_mapped(event);
5034 static int perf_fasync(int fd, struct file *filp, int on)
5036 struct inode *inode = file_inode(filp);
5037 struct perf_event *event = filp->private_data;
5041 retval = fasync_helper(fd, filp, on, &event->fasync);
5042 inode_unlock(inode);
5050 static const struct file_operations perf_fops = {
5051 .llseek = no_llseek,
5052 .release = perf_release,
5055 .unlocked_ioctl = perf_ioctl,
5056 .compat_ioctl = perf_compat_ioctl,
5058 .fasync = perf_fasync,
5064 * If there's data, ensure we set the poll() state and publish everything
5065 * to user-space before waking everybody up.
5068 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
5070 /* only the parent has fasync state */
5072 event = event->parent;
5073 return &event->fasync;
5076 void perf_event_wakeup(struct perf_event *event)
5078 ring_buffer_wakeup(event);
5080 if (event->pending_kill) {
5081 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
5082 event->pending_kill = 0;
5086 static void perf_pending_event(struct irq_work *entry)
5088 struct perf_event *event = container_of(entry,
5089 struct perf_event, pending);
5092 rctx = perf_swevent_get_recursion_context();
5094 * If we 'fail' here, that's OK, it means recursion is already disabled
5095 * and we won't recurse 'further'.
5098 if (event->pending_disable) {
5099 event->pending_disable = 0;
5100 perf_event_disable_local(event);
5103 if (event->pending_wakeup) {
5104 event->pending_wakeup = 0;
5105 perf_event_wakeup(event);
5109 perf_swevent_put_recursion_context(rctx);
5113 * We assume there is only KVM supporting the callbacks.
5114 * Later on, we might change it to a list if there is
5115 * another virtualization implementation supporting the callbacks.
5117 struct perf_guest_info_callbacks *perf_guest_cbs;
5119 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5121 perf_guest_cbs = cbs;
5124 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
5126 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5128 perf_guest_cbs = NULL;
5131 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
5134 perf_output_sample_regs(struct perf_output_handle *handle,
5135 struct pt_regs *regs, u64 mask)
5139 for_each_set_bit(bit, (const unsigned long *) &mask,
5140 sizeof(mask) * BITS_PER_BYTE) {
5143 val = perf_reg_value(regs, bit);
5144 perf_output_put(handle, val);
5148 static void perf_sample_regs_user(struct perf_regs *regs_user,
5149 struct pt_regs *regs,
5150 struct pt_regs *regs_user_copy)
5152 if (user_mode(regs)) {
5153 regs_user->abi = perf_reg_abi(current);
5154 regs_user->regs = regs;
5155 } else if (current->mm) {
5156 perf_get_regs_user(regs_user, regs, regs_user_copy);
5158 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
5159 regs_user->regs = NULL;
5163 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
5164 struct pt_regs *regs)
5166 regs_intr->regs = regs;
5167 regs_intr->abi = perf_reg_abi(current);
5172 * Get remaining task size from user stack pointer.
5174 * It'd be better to take stack vma map and limit this more
5175 * precisly, but there's no way to get it safely under interrupt,
5176 * so using TASK_SIZE as limit.
5178 static u64 perf_ustack_task_size(struct pt_regs *regs)
5180 unsigned long addr = perf_user_stack_pointer(regs);
5182 if (!addr || addr >= TASK_SIZE)
5185 return TASK_SIZE - addr;
5189 perf_sample_ustack_size(u16 stack_size, u16 header_size,
5190 struct pt_regs *regs)
5194 /* No regs, no stack pointer, no dump. */
5199 * Check if we fit in with the requested stack size into the:
5201 * If we don't, we limit the size to the TASK_SIZE.
5203 * - remaining sample size
5204 * If we don't, we customize the stack size to
5205 * fit in to the remaining sample size.
5208 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
5209 stack_size = min(stack_size, (u16) task_size);
5211 /* Current header size plus static size and dynamic size. */
5212 header_size += 2 * sizeof(u64);
5214 /* Do we fit in with the current stack dump size? */
5215 if ((u16) (header_size + stack_size) < header_size) {
5217 * If we overflow the maximum size for the sample,
5218 * we customize the stack dump size to fit in.
5220 stack_size = USHRT_MAX - header_size - sizeof(u64);
5221 stack_size = round_up(stack_size, sizeof(u64));
5228 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
5229 struct pt_regs *regs)
5231 /* Case of a kernel thread, nothing to dump */
5234 perf_output_put(handle, size);
5243 * - the size requested by user or the best one we can fit
5244 * in to the sample max size
5246 * - user stack dump data
5248 * - the actual dumped size
5252 perf_output_put(handle, dump_size);
5255 sp = perf_user_stack_pointer(regs);
5256 rem = __output_copy_user(handle, (void *) sp, dump_size);
5257 dyn_size = dump_size - rem;
5259 perf_output_skip(handle, rem);
5262 perf_output_put(handle, dyn_size);
5266 static void __perf_event_header__init_id(struct perf_event_header *header,
5267 struct perf_sample_data *data,
5268 struct perf_event *event)
5270 u64 sample_type = event->attr.sample_type;
5272 data->type = sample_type;
5273 header->size += event->id_header_size;
5275 if (sample_type & PERF_SAMPLE_TID) {
5276 /* namespace issues */
5277 data->tid_entry.pid = perf_event_pid(event, current);
5278 data->tid_entry.tid = perf_event_tid(event, current);
5281 if (sample_type & PERF_SAMPLE_TIME)
5282 data->time = perf_event_clock(event);
5284 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
5285 data->id = primary_event_id(event);
5287 if (sample_type & PERF_SAMPLE_STREAM_ID)
5288 data->stream_id = event->id;
5290 if (sample_type & PERF_SAMPLE_CPU) {
5291 data->cpu_entry.cpu = raw_smp_processor_id();
5292 data->cpu_entry.reserved = 0;
5296 void perf_event_header__init_id(struct perf_event_header *header,
5297 struct perf_sample_data *data,
5298 struct perf_event *event)
5300 if (event->attr.sample_id_all)
5301 __perf_event_header__init_id(header, data, event);
5304 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
5305 struct perf_sample_data *data)
5307 u64 sample_type = data->type;
5309 if (sample_type & PERF_SAMPLE_TID)
5310 perf_output_put(handle, data->tid_entry);
5312 if (sample_type & PERF_SAMPLE_TIME)
5313 perf_output_put(handle, data->time);
5315 if (sample_type & PERF_SAMPLE_ID)
5316 perf_output_put(handle, data->id);
5318 if (sample_type & PERF_SAMPLE_STREAM_ID)
5319 perf_output_put(handle, data->stream_id);
5321 if (sample_type & PERF_SAMPLE_CPU)
5322 perf_output_put(handle, data->cpu_entry);
5324 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5325 perf_output_put(handle, data->id);
5328 void perf_event__output_id_sample(struct perf_event *event,
5329 struct perf_output_handle *handle,
5330 struct perf_sample_data *sample)
5332 if (event->attr.sample_id_all)
5333 __perf_event__output_id_sample(handle, sample);
5336 static void perf_output_read_one(struct perf_output_handle *handle,
5337 struct perf_event *event,
5338 u64 enabled, u64 running)
5340 u64 read_format = event->attr.read_format;
5344 values[n++] = perf_event_count(event);
5345 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5346 values[n++] = enabled +
5347 atomic64_read(&event->child_total_time_enabled);
5349 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5350 values[n++] = running +
5351 atomic64_read(&event->child_total_time_running);
5353 if (read_format & PERF_FORMAT_ID)
5354 values[n++] = primary_event_id(event);
5356 __output_copy(handle, values, n * sizeof(u64));
5360 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
5362 static void perf_output_read_group(struct perf_output_handle *handle,
5363 struct perf_event *event,
5364 u64 enabled, u64 running)
5366 struct perf_event *leader = event->group_leader, *sub;
5367 u64 read_format = event->attr.read_format;
5371 values[n++] = 1 + leader->nr_siblings;
5373 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5374 values[n++] = enabled;
5376 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5377 values[n++] = running;
5379 if (leader != event)
5380 leader->pmu->read(leader);
5382 values[n++] = perf_event_count(leader);
5383 if (read_format & PERF_FORMAT_ID)
5384 values[n++] = primary_event_id(leader);
5386 __output_copy(handle, values, n * sizeof(u64));
5388 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
5391 if ((sub != event) &&
5392 (sub->state == PERF_EVENT_STATE_ACTIVE))
5393 sub->pmu->read(sub);
5395 values[n++] = perf_event_count(sub);
5396 if (read_format & PERF_FORMAT_ID)
5397 values[n++] = primary_event_id(sub);
5399 __output_copy(handle, values, n * sizeof(u64));
5403 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
5404 PERF_FORMAT_TOTAL_TIME_RUNNING)
5406 static void perf_output_read(struct perf_output_handle *handle,
5407 struct perf_event *event)
5409 u64 enabled = 0, running = 0, now;
5410 u64 read_format = event->attr.read_format;
5413 * compute total_time_enabled, total_time_running
5414 * based on snapshot values taken when the event
5415 * was last scheduled in.
5417 * we cannot simply called update_context_time()
5418 * because of locking issue as we are called in
5421 if (read_format & PERF_FORMAT_TOTAL_TIMES)
5422 calc_timer_values(event, &now, &enabled, &running);
5424 if (event->attr.read_format & PERF_FORMAT_GROUP)
5425 perf_output_read_group(handle, event, enabled, running);
5427 perf_output_read_one(handle, event, enabled, running);
5430 void perf_output_sample(struct perf_output_handle *handle,
5431 struct perf_event_header *header,
5432 struct perf_sample_data *data,
5433 struct perf_event *event)
5435 u64 sample_type = data->type;
5437 perf_output_put(handle, *header);
5439 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5440 perf_output_put(handle, data->id);
5442 if (sample_type & PERF_SAMPLE_IP)
5443 perf_output_put(handle, data->ip);
5445 if (sample_type & PERF_SAMPLE_TID)
5446 perf_output_put(handle, data->tid_entry);
5448 if (sample_type & PERF_SAMPLE_TIME)
5449 perf_output_put(handle, data->time);
5451 if (sample_type & PERF_SAMPLE_ADDR)
5452 perf_output_put(handle, data->addr);
5454 if (sample_type & PERF_SAMPLE_ID)
5455 perf_output_put(handle, data->id);
5457 if (sample_type & PERF_SAMPLE_STREAM_ID)
5458 perf_output_put(handle, data->stream_id);
5460 if (sample_type & PERF_SAMPLE_CPU)
5461 perf_output_put(handle, data->cpu_entry);
5463 if (sample_type & PERF_SAMPLE_PERIOD)
5464 perf_output_put(handle, data->period);
5466 if (sample_type & PERF_SAMPLE_READ)
5467 perf_output_read(handle, event);
5469 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5470 if (data->callchain) {
5473 if (data->callchain)
5474 size += data->callchain->nr;
5476 size *= sizeof(u64);
5478 __output_copy(handle, data->callchain, size);
5481 perf_output_put(handle, nr);
5485 if (sample_type & PERF_SAMPLE_RAW) {
5487 u32 raw_size = data->raw->size;
5488 u32 real_size = round_up(raw_size + sizeof(u32),
5489 sizeof(u64)) - sizeof(u32);
5492 perf_output_put(handle, real_size);
5493 __output_copy(handle, data->raw->data, raw_size);
5494 if (real_size - raw_size)
5495 __output_copy(handle, &zero, real_size - raw_size);
5501 .size = sizeof(u32),
5504 perf_output_put(handle, raw);
5508 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5509 if (data->br_stack) {
5512 size = data->br_stack->nr
5513 * sizeof(struct perf_branch_entry);
5515 perf_output_put(handle, data->br_stack->nr);
5516 perf_output_copy(handle, data->br_stack->entries, size);
5519 * we always store at least the value of nr
5522 perf_output_put(handle, nr);
5526 if (sample_type & PERF_SAMPLE_REGS_USER) {
5527 u64 abi = data->regs_user.abi;
5530 * If there are no regs to dump, notice it through
5531 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5533 perf_output_put(handle, abi);
5536 u64 mask = event->attr.sample_regs_user;
5537 perf_output_sample_regs(handle,
5538 data->regs_user.regs,
5543 if (sample_type & PERF_SAMPLE_STACK_USER) {
5544 perf_output_sample_ustack(handle,
5545 data->stack_user_size,
5546 data->regs_user.regs);
5549 if (sample_type & PERF_SAMPLE_WEIGHT)
5550 perf_output_put(handle, data->weight);
5552 if (sample_type & PERF_SAMPLE_DATA_SRC)
5553 perf_output_put(handle, data->data_src.val);
5555 if (sample_type & PERF_SAMPLE_TRANSACTION)
5556 perf_output_put(handle, data->txn);
5558 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5559 u64 abi = data->regs_intr.abi;
5561 * If there are no regs to dump, notice it through
5562 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5564 perf_output_put(handle, abi);
5567 u64 mask = event->attr.sample_regs_intr;
5569 perf_output_sample_regs(handle,
5570 data->regs_intr.regs,
5575 if (!event->attr.watermark) {
5576 int wakeup_events = event->attr.wakeup_events;
5578 if (wakeup_events) {
5579 struct ring_buffer *rb = handle->rb;
5580 int events = local_inc_return(&rb->events);
5582 if (events >= wakeup_events) {
5583 local_sub(wakeup_events, &rb->events);
5584 local_inc(&rb->wakeup);
5590 void perf_prepare_sample(struct perf_event_header *header,
5591 struct perf_sample_data *data,
5592 struct perf_event *event,
5593 struct pt_regs *regs)
5595 u64 sample_type = event->attr.sample_type;
5597 header->type = PERF_RECORD_SAMPLE;
5598 header->size = sizeof(*header) + event->header_size;
5601 header->misc |= perf_misc_flags(regs);
5603 __perf_event_header__init_id(header, data, event);
5605 if (sample_type & PERF_SAMPLE_IP)
5606 data->ip = perf_instruction_pointer(regs);
5608 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5611 data->callchain = perf_callchain(event, regs);
5613 if (data->callchain)
5614 size += data->callchain->nr;
5616 header->size += size * sizeof(u64);
5619 if (sample_type & PERF_SAMPLE_RAW) {
5620 int size = sizeof(u32);
5623 size += data->raw->size;
5625 size += sizeof(u32);
5627 header->size += round_up(size, sizeof(u64));
5630 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5631 int size = sizeof(u64); /* nr */
5632 if (data->br_stack) {
5633 size += data->br_stack->nr
5634 * sizeof(struct perf_branch_entry);
5636 header->size += size;
5639 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
5640 perf_sample_regs_user(&data->regs_user, regs,
5641 &data->regs_user_copy);
5643 if (sample_type & PERF_SAMPLE_REGS_USER) {
5644 /* regs dump ABI info */
5645 int size = sizeof(u64);
5647 if (data->regs_user.regs) {
5648 u64 mask = event->attr.sample_regs_user;
5649 size += hweight64(mask) * sizeof(u64);
5652 header->size += size;
5655 if (sample_type & PERF_SAMPLE_STACK_USER) {
5657 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
5658 * processed as the last one or have additional check added
5659 * in case new sample type is added, because we could eat
5660 * up the rest of the sample size.
5662 u16 stack_size = event->attr.sample_stack_user;
5663 u16 size = sizeof(u64);
5665 stack_size = perf_sample_ustack_size(stack_size, header->size,
5666 data->regs_user.regs);
5669 * If there is something to dump, add space for the dump
5670 * itself and for the field that tells the dynamic size,
5671 * which is how many have been actually dumped.
5674 size += sizeof(u64) + stack_size;
5676 data->stack_user_size = stack_size;
5677 header->size += size;
5680 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5681 /* regs dump ABI info */
5682 int size = sizeof(u64);
5684 perf_sample_regs_intr(&data->regs_intr, regs);
5686 if (data->regs_intr.regs) {
5687 u64 mask = event->attr.sample_regs_intr;
5689 size += hweight64(mask) * sizeof(u64);
5692 header->size += size;
5696 void perf_event_output(struct perf_event *event,
5697 struct perf_sample_data *data,
5698 struct pt_regs *regs)
5700 struct perf_output_handle handle;
5701 struct perf_event_header header;
5703 /* protect the callchain buffers */
5706 perf_prepare_sample(&header, data, event, regs);
5708 if (perf_output_begin(&handle, event, header.size))
5711 perf_output_sample(&handle, &header, data, event);
5713 perf_output_end(&handle);
5723 struct perf_read_event {
5724 struct perf_event_header header;
5731 perf_event_read_event(struct perf_event *event,
5732 struct task_struct *task)
5734 struct perf_output_handle handle;
5735 struct perf_sample_data sample;
5736 struct perf_read_event read_event = {
5738 .type = PERF_RECORD_READ,
5740 .size = sizeof(read_event) + event->read_size,
5742 .pid = perf_event_pid(event, task),
5743 .tid = perf_event_tid(event, task),
5747 perf_event_header__init_id(&read_event.header, &sample, event);
5748 ret = perf_output_begin(&handle, event, read_event.header.size);
5752 perf_output_put(&handle, read_event);
5753 perf_output_read(&handle, event);
5754 perf_event__output_id_sample(event, &handle, &sample);
5756 perf_output_end(&handle);
5759 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
5762 perf_event_aux_ctx(struct perf_event_context *ctx,
5763 perf_event_aux_output_cb output,
5766 struct perf_event *event;
5768 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5769 if (event->state < PERF_EVENT_STATE_INACTIVE)
5771 if (!event_filter_match(event))
5773 output(event, data);
5778 perf_event_aux_task_ctx(perf_event_aux_output_cb output, void *data,
5779 struct perf_event_context *task_ctx)
5783 perf_event_aux_ctx(task_ctx, output, data);
5789 perf_event_aux(perf_event_aux_output_cb output, void *data,
5790 struct perf_event_context *task_ctx)
5792 struct perf_cpu_context *cpuctx;
5793 struct perf_event_context *ctx;
5798 * If we have task_ctx != NULL we only notify
5799 * the task context itself. The task_ctx is set
5800 * only for EXIT events before releasing task
5804 perf_event_aux_task_ctx(output, data, task_ctx);
5809 list_for_each_entry_rcu(pmu, &pmus, entry) {
5810 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
5811 if (cpuctx->unique_pmu != pmu)
5813 perf_event_aux_ctx(&cpuctx->ctx, output, data);
5814 ctxn = pmu->task_ctx_nr;
5817 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
5819 perf_event_aux_ctx(ctx, output, data);
5821 put_cpu_ptr(pmu->pmu_cpu_context);
5826 struct remote_output {
5827 struct ring_buffer *rb;
5831 static void __perf_event_output_stop(struct perf_event *event, void *data)
5833 struct perf_event *parent = event->parent;
5834 struct remote_output *ro = data;
5835 struct ring_buffer *rb = ro->rb;
5837 if (!has_aux(event))
5844 * In case of inheritance, it will be the parent that links to the
5845 * ring-buffer, but it will be the child that's actually using it:
5847 if (rcu_dereference(parent->rb) == rb)
5848 ro->err = __perf_event_stop(event);
5851 static int __perf_pmu_output_stop(void *info)
5853 struct perf_event *event = info;
5854 struct pmu *pmu = event->pmu;
5855 struct perf_cpu_context *cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
5856 struct remote_output ro = {
5861 perf_event_aux_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro);
5862 if (cpuctx->task_ctx)
5863 perf_event_aux_ctx(cpuctx->task_ctx, __perf_event_output_stop,
5870 static void perf_pmu_output_stop(struct perf_event *event)
5872 struct perf_event *iter;
5877 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
5879 * For per-CPU events, we need to make sure that neither they
5880 * nor their children are running; for cpu==-1 events it's
5881 * sufficient to stop the event itself if it's active, since
5882 * it can't have children.
5886 cpu = READ_ONCE(iter->oncpu);
5891 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
5892 if (err == -EAGAIN) {
5901 * task tracking -- fork/exit
5903 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
5906 struct perf_task_event {
5907 struct task_struct *task;
5908 struct perf_event_context *task_ctx;
5911 struct perf_event_header header;
5921 static int perf_event_task_match(struct perf_event *event)
5923 return event->attr.comm || event->attr.mmap ||
5924 event->attr.mmap2 || event->attr.mmap_data ||
5928 static void perf_event_task_output(struct perf_event *event,
5931 struct perf_task_event *task_event = data;
5932 struct perf_output_handle handle;
5933 struct perf_sample_data sample;
5934 struct task_struct *task = task_event->task;
5935 int ret, size = task_event->event_id.header.size;
5937 if (!perf_event_task_match(event))
5940 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
5942 ret = perf_output_begin(&handle, event,
5943 task_event->event_id.header.size);
5947 task_event->event_id.pid = perf_event_pid(event, task);
5948 task_event->event_id.ppid = perf_event_pid(event, current);
5950 task_event->event_id.tid = perf_event_tid(event, task);
5951 task_event->event_id.ptid = perf_event_tid(event, current);
5953 task_event->event_id.time = perf_event_clock(event);
5955 perf_output_put(&handle, task_event->event_id);
5957 perf_event__output_id_sample(event, &handle, &sample);
5959 perf_output_end(&handle);
5961 task_event->event_id.header.size = size;
5964 static void perf_event_task(struct task_struct *task,
5965 struct perf_event_context *task_ctx,
5968 struct perf_task_event task_event;
5970 if (!atomic_read(&nr_comm_events) &&
5971 !atomic_read(&nr_mmap_events) &&
5972 !atomic_read(&nr_task_events))
5975 task_event = (struct perf_task_event){
5977 .task_ctx = task_ctx,
5980 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
5982 .size = sizeof(task_event.event_id),
5992 perf_event_aux(perf_event_task_output,
5997 void perf_event_fork(struct task_struct *task)
5999 perf_event_task(task, NULL, 1);
6006 struct perf_comm_event {
6007 struct task_struct *task;
6012 struct perf_event_header header;
6019 static int perf_event_comm_match(struct perf_event *event)
6021 return event->attr.comm;
6024 static void perf_event_comm_output(struct perf_event *event,
6027 struct perf_comm_event *comm_event = data;
6028 struct perf_output_handle handle;
6029 struct perf_sample_data sample;
6030 int size = comm_event->event_id.header.size;
6033 if (!perf_event_comm_match(event))
6036 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
6037 ret = perf_output_begin(&handle, event,
6038 comm_event->event_id.header.size);
6043 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
6044 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
6046 perf_output_put(&handle, comm_event->event_id);
6047 __output_copy(&handle, comm_event->comm,
6048 comm_event->comm_size);
6050 perf_event__output_id_sample(event, &handle, &sample);
6052 perf_output_end(&handle);
6054 comm_event->event_id.header.size = size;
6057 static void perf_event_comm_event(struct perf_comm_event *comm_event)
6059 char comm[TASK_COMM_LEN];
6062 memset(comm, 0, sizeof(comm));
6063 strlcpy(comm, comm_event->task->comm, sizeof(comm));
6064 size = ALIGN(strlen(comm)+1, sizeof(u64));
6066 comm_event->comm = comm;
6067 comm_event->comm_size = size;
6069 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
6071 perf_event_aux(perf_event_comm_output,
6076 void perf_event_comm(struct task_struct *task, bool exec)
6078 struct perf_comm_event comm_event;
6080 if (!atomic_read(&nr_comm_events))
6083 comm_event = (struct perf_comm_event){
6089 .type = PERF_RECORD_COMM,
6090 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
6098 perf_event_comm_event(&comm_event);
6105 struct perf_mmap_event {
6106 struct vm_area_struct *vma;
6108 const char *file_name;
6116 struct perf_event_header header;
6126 static int perf_event_mmap_match(struct perf_event *event,
6129 struct perf_mmap_event *mmap_event = data;
6130 struct vm_area_struct *vma = mmap_event->vma;
6131 int executable = vma->vm_flags & VM_EXEC;
6133 return (!executable && event->attr.mmap_data) ||
6134 (executable && (event->attr.mmap || event->attr.mmap2));
6137 static void perf_event_mmap_output(struct perf_event *event,
6140 struct perf_mmap_event *mmap_event = data;
6141 struct perf_output_handle handle;
6142 struct perf_sample_data sample;
6143 int size = mmap_event->event_id.header.size;
6146 if (!perf_event_mmap_match(event, data))
6149 if (event->attr.mmap2) {
6150 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
6151 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
6152 mmap_event->event_id.header.size += sizeof(mmap_event->min);
6153 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
6154 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
6155 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
6156 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
6159 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
6160 ret = perf_output_begin(&handle, event,
6161 mmap_event->event_id.header.size);
6165 mmap_event->event_id.pid = perf_event_pid(event, current);
6166 mmap_event->event_id.tid = perf_event_tid(event, current);
6168 perf_output_put(&handle, mmap_event->event_id);
6170 if (event->attr.mmap2) {
6171 perf_output_put(&handle, mmap_event->maj);
6172 perf_output_put(&handle, mmap_event->min);
6173 perf_output_put(&handle, mmap_event->ino);
6174 perf_output_put(&handle, mmap_event->ino_generation);
6175 perf_output_put(&handle, mmap_event->prot);
6176 perf_output_put(&handle, mmap_event->flags);
6179 __output_copy(&handle, mmap_event->file_name,
6180 mmap_event->file_size);
6182 perf_event__output_id_sample(event, &handle, &sample);
6184 perf_output_end(&handle);
6186 mmap_event->event_id.header.size = size;
6189 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
6191 struct vm_area_struct *vma = mmap_event->vma;
6192 struct file *file = vma->vm_file;
6193 int maj = 0, min = 0;
6194 u64 ino = 0, gen = 0;
6195 u32 prot = 0, flags = 0;
6202 struct inode *inode;
6205 buf = kmalloc(PATH_MAX, GFP_KERNEL);
6211 * d_path() works from the end of the rb backwards, so we
6212 * need to add enough zero bytes after the string to handle
6213 * the 64bit alignment we do later.
6215 name = file_path(file, buf, PATH_MAX - sizeof(u64));
6220 inode = file_inode(vma->vm_file);
6221 dev = inode->i_sb->s_dev;
6223 gen = inode->i_generation;
6227 if (vma->vm_flags & VM_READ)
6229 if (vma->vm_flags & VM_WRITE)
6231 if (vma->vm_flags & VM_EXEC)
6234 if (vma->vm_flags & VM_MAYSHARE)
6237 flags = MAP_PRIVATE;
6239 if (vma->vm_flags & VM_DENYWRITE)
6240 flags |= MAP_DENYWRITE;
6241 if (vma->vm_flags & VM_MAYEXEC)
6242 flags |= MAP_EXECUTABLE;
6243 if (vma->vm_flags & VM_LOCKED)
6244 flags |= MAP_LOCKED;
6245 if (vma->vm_flags & VM_HUGETLB)
6246 flags |= MAP_HUGETLB;
6250 if (vma->vm_ops && vma->vm_ops->name) {
6251 name = (char *) vma->vm_ops->name(vma);
6256 name = (char *)arch_vma_name(vma);
6260 if (vma->vm_start <= vma->vm_mm->start_brk &&
6261 vma->vm_end >= vma->vm_mm->brk) {
6265 if (vma->vm_start <= vma->vm_mm->start_stack &&
6266 vma->vm_end >= vma->vm_mm->start_stack) {
6276 strlcpy(tmp, name, sizeof(tmp));
6280 * Since our buffer works in 8 byte units we need to align our string
6281 * size to a multiple of 8. However, we must guarantee the tail end is
6282 * zero'd out to avoid leaking random bits to userspace.
6284 size = strlen(name)+1;
6285 while (!IS_ALIGNED(size, sizeof(u64)))
6286 name[size++] = '\0';
6288 mmap_event->file_name = name;
6289 mmap_event->file_size = size;
6290 mmap_event->maj = maj;
6291 mmap_event->min = min;
6292 mmap_event->ino = ino;
6293 mmap_event->ino_generation = gen;
6294 mmap_event->prot = prot;
6295 mmap_event->flags = flags;
6297 if (!(vma->vm_flags & VM_EXEC))
6298 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
6300 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
6302 perf_event_aux(perf_event_mmap_output,
6309 void perf_event_mmap(struct vm_area_struct *vma)
6311 struct perf_mmap_event mmap_event;
6313 if (!atomic_read(&nr_mmap_events))
6316 mmap_event = (struct perf_mmap_event){
6322 .type = PERF_RECORD_MMAP,
6323 .misc = PERF_RECORD_MISC_USER,
6328 .start = vma->vm_start,
6329 .len = vma->vm_end - vma->vm_start,
6330 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
6332 /* .maj (attr_mmap2 only) */
6333 /* .min (attr_mmap2 only) */
6334 /* .ino (attr_mmap2 only) */
6335 /* .ino_generation (attr_mmap2 only) */
6336 /* .prot (attr_mmap2 only) */
6337 /* .flags (attr_mmap2 only) */
6340 perf_event_mmap_event(&mmap_event);
6343 void perf_event_aux_event(struct perf_event *event, unsigned long head,
6344 unsigned long size, u64 flags)
6346 struct perf_output_handle handle;
6347 struct perf_sample_data sample;
6348 struct perf_aux_event {
6349 struct perf_event_header header;
6355 .type = PERF_RECORD_AUX,
6357 .size = sizeof(rec),
6365 perf_event_header__init_id(&rec.header, &sample, event);
6366 ret = perf_output_begin(&handle, event, rec.header.size);
6371 perf_output_put(&handle, rec);
6372 perf_event__output_id_sample(event, &handle, &sample);
6374 perf_output_end(&handle);
6378 * Lost/dropped samples logging
6380 void perf_log_lost_samples(struct perf_event *event, u64 lost)
6382 struct perf_output_handle handle;
6383 struct perf_sample_data sample;
6387 struct perf_event_header header;
6389 } lost_samples_event = {
6391 .type = PERF_RECORD_LOST_SAMPLES,
6393 .size = sizeof(lost_samples_event),
6398 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
6400 ret = perf_output_begin(&handle, event,
6401 lost_samples_event.header.size);
6405 perf_output_put(&handle, lost_samples_event);
6406 perf_event__output_id_sample(event, &handle, &sample);
6407 perf_output_end(&handle);
6411 * context_switch tracking
6414 struct perf_switch_event {
6415 struct task_struct *task;
6416 struct task_struct *next_prev;
6419 struct perf_event_header header;
6425 static int perf_event_switch_match(struct perf_event *event)
6427 return event->attr.context_switch;
6430 static void perf_event_switch_output(struct perf_event *event, void *data)
6432 struct perf_switch_event *se = data;
6433 struct perf_output_handle handle;
6434 struct perf_sample_data sample;
6437 if (!perf_event_switch_match(event))
6440 /* Only CPU-wide events are allowed to see next/prev pid/tid */
6441 if (event->ctx->task) {
6442 se->event_id.header.type = PERF_RECORD_SWITCH;
6443 se->event_id.header.size = sizeof(se->event_id.header);
6445 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
6446 se->event_id.header.size = sizeof(se->event_id);
6447 se->event_id.next_prev_pid =
6448 perf_event_pid(event, se->next_prev);
6449 se->event_id.next_prev_tid =
6450 perf_event_tid(event, se->next_prev);
6453 perf_event_header__init_id(&se->event_id.header, &sample, event);
6455 ret = perf_output_begin(&handle, event, se->event_id.header.size);
6459 if (event->ctx->task)
6460 perf_output_put(&handle, se->event_id.header);
6462 perf_output_put(&handle, se->event_id);
6464 perf_event__output_id_sample(event, &handle, &sample);
6466 perf_output_end(&handle);
6469 static void perf_event_switch(struct task_struct *task,
6470 struct task_struct *next_prev, bool sched_in)
6472 struct perf_switch_event switch_event;
6474 /* N.B. caller checks nr_switch_events != 0 */
6476 switch_event = (struct perf_switch_event){
6478 .next_prev = next_prev,
6482 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
6485 /* .next_prev_pid */
6486 /* .next_prev_tid */
6490 perf_event_aux(perf_event_switch_output,
6496 * IRQ throttle logging
6499 static void perf_log_throttle(struct perf_event *event, int enable)
6501 struct perf_output_handle handle;
6502 struct perf_sample_data sample;
6506 struct perf_event_header header;
6510 } throttle_event = {
6512 .type = PERF_RECORD_THROTTLE,
6514 .size = sizeof(throttle_event),
6516 .time = perf_event_clock(event),
6517 .id = primary_event_id(event),
6518 .stream_id = event->id,
6522 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
6524 perf_event_header__init_id(&throttle_event.header, &sample, event);
6526 ret = perf_output_begin(&handle, event,
6527 throttle_event.header.size);
6531 perf_output_put(&handle, throttle_event);
6532 perf_event__output_id_sample(event, &handle, &sample);
6533 perf_output_end(&handle);
6536 static void perf_log_itrace_start(struct perf_event *event)
6538 struct perf_output_handle handle;
6539 struct perf_sample_data sample;
6540 struct perf_aux_event {
6541 struct perf_event_header header;
6548 event = event->parent;
6550 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
6551 event->hw.itrace_started)
6554 rec.header.type = PERF_RECORD_ITRACE_START;
6555 rec.header.misc = 0;
6556 rec.header.size = sizeof(rec);
6557 rec.pid = perf_event_pid(event, current);
6558 rec.tid = perf_event_tid(event, current);
6560 perf_event_header__init_id(&rec.header, &sample, event);
6561 ret = perf_output_begin(&handle, event, rec.header.size);
6566 perf_output_put(&handle, rec);
6567 perf_event__output_id_sample(event, &handle, &sample);
6569 perf_output_end(&handle);
6573 * Generic event overflow handling, sampling.
6576 static int __perf_event_overflow(struct perf_event *event,
6577 int throttle, struct perf_sample_data *data,
6578 struct pt_regs *regs)
6580 int events = atomic_read(&event->event_limit);
6581 struct hw_perf_event *hwc = &event->hw;
6586 * Non-sampling counters might still use the PMI to fold short
6587 * hardware counters, ignore those.
6589 if (unlikely(!is_sampling_event(event)))
6592 seq = __this_cpu_read(perf_throttled_seq);
6593 if (seq != hwc->interrupts_seq) {
6594 hwc->interrupts_seq = seq;
6595 hwc->interrupts = 1;
6598 if (unlikely(throttle
6599 && hwc->interrupts >= max_samples_per_tick)) {
6600 __this_cpu_inc(perf_throttled_count);
6601 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
6602 hwc->interrupts = MAX_INTERRUPTS;
6603 perf_log_throttle(event, 0);
6608 if (event->attr.freq) {
6609 u64 now = perf_clock();
6610 s64 delta = now - hwc->freq_time_stamp;
6612 hwc->freq_time_stamp = now;
6614 if (delta > 0 && delta < 2*TICK_NSEC)
6615 perf_adjust_period(event, delta, hwc->last_period, true);
6619 * XXX event_limit might not quite work as expected on inherited
6623 event->pending_kill = POLL_IN;
6624 if (events && atomic_dec_and_test(&event->event_limit)) {
6626 event->pending_kill = POLL_HUP;
6627 event->pending_disable = 1;
6628 irq_work_queue(&event->pending);
6631 event->overflow_handler(event, data, regs);
6633 if (*perf_event_fasync(event) && event->pending_kill) {
6634 event->pending_wakeup = 1;
6635 irq_work_queue(&event->pending);
6641 int perf_event_overflow(struct perf_event *event,
6642 struct perf_sample_data *data,
6643 struct pt_regs *regs)
6645 return __perf_event_overflow(event, 1, data, regs);
6649 * Generic software event infrastructure
6652 struct swevent_htable {
6653 struct swevent_hlist *swevent_hlist;
6654 struct mutex hlist_mutex;
6657 /* Recursion avoidance in each contexts */
6658 int recursion[PERF_NR_CONTEXTS];
6661 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
6664 * We directly increment event->count and keep a second value in
6665 * event->hw.period_left to count intervals. This period event
6666 * is kept in the range [-sample_period, 0] so that we can use the
6670 u64 perf_swevent_set_period(struct perf_event *event)
6672 struct hw_perf_event *hwc = &event->hw;
6673 u64 period = hwc->last_period;
6677 hwc->last_period = hwc->sample_period;
6680 old = val = local64_read(&hwc->period_left);
6684 nr = div64_u64(period + val, period);
6685 offset = nr * period;
6687 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
6693 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
6694 struct perf_sample_data *data,
6695 struct pt_regs *regs)
6697 struct hw_perf_event *hwc = &event->hw;
6701 overflow = perf_swevent_set_period(event);
6703 if (hwc->interrupts == MAX_INTERRUPTS)
6706 for (; overflow; overflow--) {
6707 if (__perf_event_overflow(event, throttle,
6710 * We inhibit the overflow from happening when
6711 * hwc->interrupts == MAX_INTERRUPTS.
6719 static void perf_swevent_event(struct perf_event *event, u64 nr,
6720 struct perf_sample_data *data,
6721 struct pt_regs *regs)
6723 struct hw_perf_event *hwc = &event->hw;
6725 local64_add(nr, &event->count);
6730 if (!is_sampling_event(event))
6733 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
6735 return perf_swevent_overflow(event, 1, data, regs);
6737 data->period = event->hw.last_period;
6739 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
6740 return perf_swevent_overflow(event, 1, data, regs);
6742 if (local64_add_negative(nr, &hwc->period_left))
6745 perf_swevent_overflow(event, 0, data, regs);
6748 static int perf_exclude_event(struct perf_event *event,
6749 struct pt_regs *regs)
6751 if (event->hw.state & PERF_HES_STOPPED)
6755 if (event->attr.exclude_user && user_mode(regs))
6758 if (event->attr.exclude_kernel && !user_mode(regs))
6765 static int perf_swevent_match(struct perf_event *event,
6766 enum perf_type_id type,
6768 struct perf_sample_data *data,
6769 struct pt_regs *regs)
6771 if (event->attr.type != type)
6774 if (event->attr.config != event_id)
6777 if (perf_exclude_event(event, regs))
6783 static inline u64 swevent_hash(u64 type, u32 event_id)
6785 u64 val = event_id | (type << 32);
6787 return hash_64(val, SWEVENT_HLIST_BITS);
6790 static inline struct hlist_head *
6791 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
6793 u64 hash = swevent_hash(type, event_id);
6795 return &hlist->heads[hash];
6798 /* For the read side: events when they trigger */
6799 static inline struct hlist_head *
6800 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
6802 struct swevent_hlist *hlist;
6804 hlist = rcu_dereference(swhash->swevent_hlist);
6808 return __find_swevent_head(hlist, type, event_id);
6811 /* For the event head insertion and removal in the hlist */
6812 static inline struct hlist_head *
6813 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
6815 struct swevent_hlist *hlist;
6816 u32 event_id = event->attr.config;
6817 u64 type = event->attr.type;
6820 * Event scheduling is always serialized against hlist allocation
6821 * and release. Which makes the protected version suitable here.
6822 * The context lock guarantees that.
6824 hlist = rcu_dereference_protected(swhash->swevent_hlist,
6825 lockdep_is_held(&event->ctx->lock));
6829 return __find_swevent_head(hlist, type, event_id);
6832 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
6834 struct perf_sample_data *data,
6835 struct pt_regs *regs)
6837 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6838 struct perf_event *event;
6839 struct hlist_head *head;
6842 head = find_swevent_head_rcu(swhash, type, event_id);
6846 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6847 if (perf_swevent_match(event, type, event_id, data, regs))
6848 perf_swevent_event(event, nr, data, regs);
6854 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
6856 int perf_swevent_get_recursion_context(void)
6858 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6860 return get_recursion_context(swhash->recursion);
6862 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
6864 inline void perf_swevent_put_recursion_context(int rctx)
6866 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6868 put_recursion_context(swhash->recursion, rctx);
6871 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6873 struct perf_sample_data data;
6875 if (WARN_ON_ONCE(!regs))
6878 perf_sample_data_init(&data, addr, 0);
6879 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
6882 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6886 preempt_disable_notrace();
6887 rctx = perf_swevent_get_recursion_context();
6888 if (unlikely(rctx < 0))
6891 ___perf_sw_event(event_id, nr, regs, addr);
6893 perf_swevent_put_recursion_context(rctx);
6895 preempt_enable_notrace();
6898 static void perf_swevent_read(struct perf_event *event)
6902 static int perf_swevent_add(struct perf_event *event, int flags)
6904 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6905 struct hw_perf_event *hwc = &event->hw;
6906 struct hlist_head *head;
6908 if (is_sampling_event(event)) {
6909 hwc->last_period = hwc->sample_period;
6910 perf_swevent_set_period(event);
6913 hwc->state = !(flags & PERF_EF_START);
6915 head = find_swevent_head(swhash, event);
6916 if (WARN_ON_ONCE(!head))
6919 hlist_add_head_rcu(&event->hlist_entry, head);
6920 perf_event_update_userpage(event);
6925 static void perf_swevent_del(struct perf_event *event, int flags)
6927 hlist_del_rcu(&event->hlist_entry);
6930 static void perf_swevent_start(struct perf_event *event, int flags)
6932 event->hw.state = 0;
6935 static void perf_swevent_stop(struct perf_event *event, int flags)
6937 event->hw.state = PERF_HES_STOPPED;
6940 /* Deref the hlist from the update side */
6941 static inline struct swevent_hlist *
6942 swevent_hlist_deref(struct swevent_htable *swhash)
6944 return rcu_dereference_protected(swhash->swevent_hlist,
6945 lockdep_is_held(&swhash->hlist_mutex));
6948 static void swevent_hlist_release(struct swevent_htable *swhash)
6950 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
6955 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
6956 kfree_rcu(hlist, rcu_head);
6959 static void swevent_hlist_put_cpu(int cpu)
6961 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6963 mutex_lock(&swhash->hlist_mutex);
6965 if (!--swhash->hlist_refcount)
6966 swevent_hlist_release(swhash);
6968 mutex_unlock(&swhash->hlist_mutex);
6971 static void swevent_hlist_put(void)
6975 for_each_possible_cpu(cpu)
6976 swevent_hlist_put_cpu(cpu);
6979 static int swevent_hlist_get_cpu(int cpu)
6981 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6984 mutex_lock(&swhash->hlist_mutex);
6985 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
6986 struct swevent_hlist *hlist;
6988 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
6993 rcu_assign_pointer(swhash->swevent_hlist, hlist);
6995 swhash->hlist_refcount++;
6997 mutex_unlock(&swhash->hlist_mutex);
7002 static int swevent_hlist_get(void)
7004 int err, cpu, failed_cpu;
7007 for_each_possible_cpu(cpu) {
7008 err = swevent_hlist_get_cpu(cpu);
7018 for_each_possible_cpu(cpu) {
7019 if (cpu == failed_cpu)
7021 swevent_hlist_put_cpu(cpu);
7028 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
7030 static void sw_perf_event_destroy(struct perf_event *event)
7032 u64 event_id = event->attr.config;
7034 WARN_ON(event->parent);
7036 static_key_slow_dec(&perf_swevent_enabled[event_id]);
7037 swevent_hlist_put();
7040 static int perf_swevent_init(struct perf_event *event)
7042 u64 event_id = event->attr.config;
7044 if (event->attr.type != PERF_TYPE_SOFTWARE)
7048 * no branch sampling for software events
7050 if (has_branch_stack(event))
7054 case PERF_COUNT_SW_CPU_CLOCK:
7055 case PERF_COUNT_SW_TASK_CLOCK:
7062 if (event_id >= PERF_COUNT_SW_MAX)
7065 if (!event->parent) {
7068 err = swevent_hlist_get();
7072 static_key_slow_inc(&perf_swevent_enabled[event_id]);
7073 event->destroy = sw_perf_event_destroy;
7079 static struct pmu perf_swevent = {
7080 .task_ctx_nr = perf_sw_context,
7082 .capabilities = PERF_PMU_CAP_NO_NMI,
7084 .event_init = perf_swevent_init,
7085 .add = perf_swevent_add,
7086 .del = perf_swevent_del,
7087 .start = perf_swevent_start,
7088 .stop = perf_swevent_stop,
7089 .read = perf_swevent_read,
7092 #ifdef CONFIG_EVENT_TRACING
7094 static int perf_tp_filter_match(struct perf_event *event,
7095 struct perf_sample_data *data)
7097 void *record = data->raw->data;
7099 /* only top level events have filters set */
7101 event = event->parent;
7103 if (likely(!event->filter) || filter_match_preds(event->filter, record))
7108 static int perf_tp_event_match(struct perf_event *event,
7109 struct perf_sample_data *data,
7110 struct pt_regs *regs)
7112 if (event->hw.state & PERF_HES_STOPPED)
7115 * All tracepoints are from kernel-space.
7117 if (event->attr.exclude_kernel)
7120 if (!perf_tp_filter_match(event, data))
7126 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
7127 struct pt_regs *regs, struct hlist_head *head, int rctx,
7128 struct task_struct *task)
7130 struct perf_sample_data data;
7131 struct perf_event *event;
7133 struct perf_raw_record raw = {
7138 perf_sample_data_init(&data, addr, 0);
7141 hlist_for_each_entry_rcu(event, head, hlist_entry) {
7142 if (perf_tp_event_match(event, &data, regs))
7143 perf_swevent_event(event, count, &data, regs);
7147 * If we got specified a target task, also iterate its context and
7148 * deliver this event there too.
7150 if (task && task != current) {
7151 struct perf_event_context *ctx;
7152 struct trace_entry *entry = record;
7155 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
7159 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7160 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7162 if (event->attr.config != entry->type)
7164 if (perf_tp_event_match(event, &data, regs))
7165 perf_swevent_event(event, count, &data, regs);
7171 perf_swevent_put_recursion_context(rctx);
7173 EXPORT_SYMBOL_GPL(perf_tp_event);
7175 static void tp_perf_event_destroy(struct perf_event *event)
7177 perf_trace_destroy(event);
7180 static int perf_tp_event_init(struct perf_event *event)
7184 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7188 * no branch sampling for tracepoint events
7190 if (has_branch_stack(event))
7193 err = perf_trace_init(event);
7197 event->destroy = tp_perf_event_destroy;
7202 static struct pmu perf_tracepoint = {
7203 .task_ctx_nr = perf_sw_context,
7205 .event_init = perf_tp_event_init,
7206 .add = perf_trace_add,
7207 .del = perf_trace_del,
7208 .start = perf_swevent_start,
7209 .stop = perf_swevent_stop,
7210 .read = perf_swevent_read,
7213 static inline void perf_tp_register(void)
7215 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
7218 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7223 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7226 filter_str = strndup_user(arg, PAGE_SIZE);
7227 if (IS_ERR(filter_str))
7228 return PTR_ERR(filter_str);
7230 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
7236 static void perf_event_free_filter(struct perf_event *event)
7238 ftrace_profile_free_filter(event);
7241 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7243 struct bpf_prog *prog;
7245 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7248 if (event->tp_event->prog)
7251 if (!(event->tp_event->flags & TRACE_EVENT_FL_UKPROBE))
7252 /* bpf programs can only be attached to u/kprobes */
7255 prog = bpf_prog_get(prog_fd);
7257 return PTR_ERR(prog);
7259 if (prog->type != BPF_PROG_TYPE_KPROBE) {
7260 /* valid fd, but invalid bpf program type */
7265 event->tp_event->prog = prog;
7270 static void perf_event_free_bpf_prog(struct perf_event *event)
7272 struct bpf_prog *prog;
7274 if (!event->tp_event)
7277 prog = event->tp_event->prog;
7279 event->tp_event->prog = NULL;
7286 static inline void perf_tp_register(void)
7290 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7295 static void perf_event_free_filter(struct perf_event *event)
7299 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7304 static void perf_event_free_bpf_prog(struct perf_event *event)
7307 #endif /* CONFIG_EVENT_TRACING */
7309 #ifdef CONFIG_HAVE_HW_BREAKPOINT
7310 void perf_bp_event(struct perf_event *bp, void *data)
7312 struct perf_sample_data sample;
7313 struct pt_regs *regs = data;
7315 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
7317 if (!bp->hw.state && !perf_exclude_event(bp, regs))
7318 perf_swevent_event(bp, 1, &sample, regs);
7323 * hrtimer based swevent callback
7326 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
7328 enum hrtimer_restart ret = HRTIMER_RESTART;
7329 struct perf_sample_data data;
7330 struct pt_regs *regs;
7331 struct perf_event *event;
7334 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
7336 if (event->state != PERF_EVENT_STATE_ACTIVE)
7337 return HRTIMER_NORESTART;
7339 event->pmu->read(event);
7341 perf_sample_data_init(&data, 0, event->hw.last_period);
7342 regs = get_irq_regs();
7344 if (regs && !perf_exclude_event(event, regs)) {
7345 if (!(event->attr.exclude_idle && is_idle_task(current)))
7346 if (__perf_event_overflow(event, 1, &data, regs))
7347 ret = HRTIMER_NORESTART;
7350 period = max_t(u64, 10000, event->hw.sample_period);
7351 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
7356 static void perf_swevent_start_hrtimer(struct perf_event *event)
7358 struct hw_perf_event *hwc = &event->hw;
7361 if (!is_sampling_event(event))
7364 period = local64_read(&hwc->period_left);
7369 local64_set(&hwc->period_left, 0);
7371 period = max_t(u64, 10000, hwc->sample_period);
7373 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
7374 HRTIMER_MODE_REL_PINNED);
7377 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
7379 struct hw_perf_event *hwc = &event->hw;
7381 if (is_sampling_event(event)) {
7382 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
7383 local64_set(&hwc->period_left, ktime_to_ns(remaining));
7385 hrtimer_cancel(&hwc->hrtimer);
7389 static void perf_swevent_init_hrtimer(struct perf_event *event)
7391 struct hw_perf_event *hwc = &event->hw;
7393 if (!is_sampling_event(event))
7396 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7397 hwc->hrtimer.function = perf_swevent_hrtimer;
7400 * Since hrtimers have a fixed rate, we can do a static freq->period
7401 * mapping and avoid the whole period adjust feedback stuff.
7403 if (event->attr.freq) {
7404 long freq = event->attr.sample_freq;
7406 event->attr.sample_period = NSEC_PER_SEC / freq;
7407 hwc->sample_period = event->attr.sample_period;
7408 local64_set(&hwc->period_left, hwc->sample_period);
7409 hwc->last_period = hwc->sample_period;
7410 event->attr.freq = 0;
7415 * Software event: cpu wall time clock
7418 static void cpu_clock_event_update(struct perf_event *event)
7423 now = local_clock();
7424 prev = local64_xchg(&event->hw.prev_count, now);
7425 local64_add(now - prev, &event->count);
7428 static void cpu_clock_event_start(struct perf_event *event, int flags)
7430 local64_set(&event->hw.prev_count, local_clock());
7431 perf_swevent_start_hrtimer(event);
7434 static void cpu_clock_event_stop(struct perf_event *event, int flags)
7436 perf_swevent_cancel_hrtimer(event);
7437 cpu_clock_event_update(event);
7440 static int cpu_clock_event_add(struct perf_event *event, int flags)
7442 if (flags & PERF_EF_START)
7443 cpu_clock_event_start(event, flags);
7444 perf_event_update_userpage(event);
7449 static void cpu_clock_event_del(struct perf_event *event, int flags)
7451 cpu_clock_event_stop(event, flags);
7454 static void cpu_clock_event_read(struct perf_event *event)
7456 cpu_clock_event_update(event);
7459 static int cpu_clock_event_init(struct perf_event *event)
7461 if (event->attr.type != PERF_TYPE_SOFTWARE)
7464 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
7468 * no branch sampling for software events
7470 if (has_branch_stack(event))
7473 perf_swevent_init_hrtimer(event);
7478 static struct pmu perf_cpu_clock = {
7479 .task_ctx_nr = perf_sw_context,
7481 .capabilities = PERF_PMU_CAP_NO_NMI,
7483 .event_init = cpu_clock_event_init,
7484 .add = cpu_clock_event_add,
7485 .del = cpu_clock_event_del,
7486 .start = cpu_clock_event_start,
7487 .stop = cpu_clock_event_stop,
7488 .read = cpu_clock_event_read,
7492 * Software event: task time clock
7495 static void task_clock_event_update(struct perf_event *event, u64 now)
7500 prev = local64_xchg(&event->hw.prev_count, now);
7502 local64_add(delta, &event->count);
7505 static void task_clock_event_start(struct perf_event *event, int flags)
7507 local64_set(&event->hw.prev_count, event->ctx->time);
7508 perf_swevent_start_hrtimer(event);
7511 static void task_clock_event_stop(struct perf_event *event, int flags)
7513 perf_swevent_cancel_hrtimer(event);
7514 task_clock_event_update(event, event->ctx->time);
7517 static int task_clock_event_add(struct perf_event *event, int flags)
7519 if (flags & PERF_EF_START)
7520 task_clock_event_start(event, flags);
7521 perf_event_update_userpage(event);
7526 static void task_clock_event_del(struct perf_event *event, int flags)
7528 task_clock_event_stop(event, PERF_EF_UPDATE);
7531 static void task_clock_event_read(struct perf_event *event)
7533 u64 now = perf_clock();
7534 u64 delta = now - event->ctx->timestamp;
7535 u64 time = event->ctx->time + delta;
7537 task_clock_event_update(event, time);
7540 static int task_clock_event_init(struct perf_event *event)
7542 if (event->attr.type != PERF_TYPE_SOFTWARE)
7545 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
7549 * no branch sampling for software events
7551 if (has_branch_stack(event))
7554 perf_swevent_init_hrtimer(event);
7559 static struct pmu perf_task_clock = {
7560 .task_ctx_nr = perf_sw_context,
7562 .capabilities = PERF_PMU_CAP_NO_NMI,
7564 .event_init = task_clock_event_init,
7565 .add = task_clock_event_add,
7566 .del = task_clock_event_del,
7567 .start = task_clock_event_start,
7568 .stop = task_clock_event_stop,
7569 .read = task_clock_event_read,
7572 static void perf_pmu_nop_void(struct pmu *pmu)
7576 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
7580 static int perf_pmu_nop_int(struct pmu *pmu)
7585 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
7587 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
7589 __this_cpu_write(nop_txn_flags, flags);
7591 if (flags & ~PERF_PMU_TXN_ADD)
7594 perf_pmu_disable(pmu);
7597 static int perf_pmu_commit_txn(struct pmu *pmu)
7599 unsigned int flags = __this_cpu_read(nop_txn_flags);
7601 __this_cpu_write(nop_txn_flags, 0);
7603 if (flags & ~PERF_PMU_TXN_ADD)
7606 perf_pmu_enable(pmu);
7610 static void perf_pmu_cancel_txn(struct pmu *pmu)
7612 unsigned int flags = __this_cpu_read(nop_txn_flags);
7614 __this_cpu_write(nop_txn_flags, 0);
7616 if (flags & ~PERF_PMU_TXN_ADD)
7619 perf_pmu_enable(pmu);
7622 static int perf_event_idx_default(struct perf_event *event)
7628 * Ensures all contexts with the same task_ctx_nr have the same
7629 * pmu_cpu_context too.
7631 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
7638 list_for_each_entry(pmu, &pmus, entry) {
7639 if (pmu->task_ctx_nr == ctxn)
7640 return pmu->pmu_cpu_context;
7646 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
7650 for_each_possible_cpu(cpu) {
7651 struct perf_cpu_context *cpuctx;
7653 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7655 if (cpuctx->unique_pmu == old_pmu)
7656 cpuctx->unique_pmu = pmu;
7660 static void free_pmu_context(struct pmu *pmu)
7664 mutex_lock(&pmus_lock);
7666 * Like a real lame refcount.
7668 list_for_each_entry(i, &pmus, entry) {
7669 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
7670 update_pmu_context(i, pmu);
7675 free_percpu(pmu->pmu_cpu_context);
7677 mutex_unlock(&pmus_lock);
7679 static struct idr pmu_idr;
7682 type_show(struct device *dev, struct device_attribute *attr, char *page)
7684 struct pmu *pmu = dev_get_drvdata(dev);
7686 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
7688 static DEVICE_ATTR_RO(type);
7691 perf_event_mux_interval_ms_show(struct device *dev,
7692 struct device_attribute *attr,
7695 struct pmu *pmu = dev_get_drvdata(dev);
7697 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
7700 static DEFINE_MUTEX(mux_interval_mutex);
7703 perf_event_mux_interval_ms_store(struct device *dev,
7704 struct device_attribute *attr,
7705 const char *buf, size_t count)
7707 struct pmu *pmu = dev_get_drvdata(dev);
7708 int timer, cpu, ret;
7710 ret = kstrtoint(buf, 0, &timer);
7717 /* same value, noting to do */
7718 if (timer == pmu->hrtimer_interval_ms)
7721 mutex_lock(&mux_interval_mutex);
7722 pmu->hrtimer_interval_ms = timer;
7724 /* update all cpuctx for this PMU */
7726 for_each_online_cpu(cpu) {
7727 struct perf_cpu_context *cpuctx;
7728 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7729 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
7731 cpu_function_call(cpu,
7732 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
7735 mutex_unlock(&mux_interval_mutex);
7739 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
7741 static struct attribute *pmu_dev_attrs[] = {
7742 &dev_attr_type.attr,
7743 &dev_attr_perf_event_mux_interval_ms.attr,
7746 ATTRIBUTE_GROUPS(pmu_dev);
7748 static int pmu_bus_running;
7749 static struct bus_type pmu_bus = {
7750 .name = "event_source",
7751 .dev_groups = pmu_dev_groups,
7754 static void pmu_dev_release(struct device *dev)
7759 static int pmu_dev_alloc(struct pmu *pmu)
7763 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
7767 pmu->dev->groups = pmu->attr_groups;
7768 device_initialize(pmu->dev);
7769 ret = dev_set_name(pmu->dev, "%s", pmu->name);
7773 dev_set_drvdata(pmu->dev, pmu);
7774 pmu->dev->bus = &pmu_bus;
7775 pmu->dev->release = pmu_dev_release;
7776 ret = device_add(pmu->dev);
7784 put_device(pmu->dev);
7788 static struct lock_class_key cpuctx_mutex;
7789 static struct lock_class_key cpuctx_lock;
7791 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
7795 mutex_lock(&pmus_lock);
7797 pmu->pmu_disable_count = alloc_percpu(int);
7798 if (!pmu->pmu_disable_count)
7807 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
7815 if (pmu_bus_running) {
7816 ret = pmu_dev_alloc(pmu);
7822 if (pmu->task_ctx_nr == perf_hw_context) {
7823 static int hw_context_taken = 0;
7825 if (WARN_ON_ONCE(hw_context_taken))
7826 pmu->task_ctx_nr = perf_invalid_context;
7828 hw_context_taken = 1;
7831 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
7832 if (pmu->pmu_cpu_context)
7833 goto got_cpu_context;
7836 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
7837 if (!pmu->pmu_cpu_context)
7840 for_each_possible_cpu(cpu) {
7841 struct perf_cpu_context *cpuctx;
7843 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7844 __perf_event_init_context(&cpuctx->ctx);
7845 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
7846 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
7847 cpuctx->ctx.pmu = pmu;
7849 __perf_mux_hrtimer_init(cpuctx, cpu);
7851 cpuctx->unique_pmu = pmu;
7855 if (!pmu->start_txn) {
7856 if (pmu->pmu_enable) {
7858 * If we have pmu_enable/pmu_disable calls, install
7859 * transaction stubs that use that to try and batch
7860 * hardware accesses.
7862 pmu->start_txn = perf_pmu_start_txn;
7863 pmu->commit_txn = perf_pmu_commit_txn;
7864 pmu->cancel_txn = perf_pmu_cancel_txn;
7866 pmu->start_txn = perf_pmu_nop_txn;
7867 pmu->commit_txn = perf_pmu_nop_int;
7868 pmu->cancel_txn = perf_pmu_nop_void;
7872 if (!pmu->pmu_enable) {
7873 pmu->pmu_enable = perf_pmu_nop_void;
7874 pmu->pmu_disable = perf_pmu_nop_void;
7877 if (!pmu->event_idx)
7878 pmu->event_idx = perf_event_idx_default;
7880 list_add_rcu(&pmu->entry, &pmus);
7881 atomic_set(&pmu->exclusive_cnt, 0);
7884 mutex_unlock(&pmus_lock);
7889 device_del(pmu->dev);
7890 put_device(pmu->dev);
7893 if (pmu->type >= PERF_TYPE_MAX)
7894 idr_remove(&pmu_idr, pmu->type);
7897 free_percpu(pmu->pmu_disable_count);
7900 EXPORT_SYMBOL_GPL(perf_pmu_register);
7902 void perf_pmu_unregister(struct pmu *pmu)
7904 mutex_lock(&pmus_lock);
7905 list_del_rcu(&pmu->entry);
7906 mutex_unlock(&pmus_lock);
7909 * We dereference the pmu list under both SRCU and regular RCU, so
7910 * synchronize against both of those.
7912 synchronize_srcu(&pmus_srcu);
7915 free_percpu(pmu->pmu_disable_count);
7916 if (pmu->type >= PERF_TYPE_MAX)
7917 idr_remove(&pmu_idr, pmu->type);
7918 device_del(pmu->dev);
7919 put_device(pmu->dev);
7920 free_pmu_context(pmu);
7922 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
7924 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
7926 struct perf_event_context *ctx = NULL;
7929 if (!try_module_get(pmu->module))
7932 if (event->group_leader != event) {
7934 * This ctx->mutex can nest when we're called through
7935 * inheritance. See the perf_event_ctx_lock_nested() comment.
7937 ctx = perf_event_ctx_lock_nested(event->group_leader,
7938 SINGLE_DEPTH_NESTING);
7943 ret = pmu->event_init(event);
7946 perf_event_ctx_unlock(event->group_leader, ctx);
7949 module_put(pmu->module);
7954 static struct pmu *perf_init_event(struct perf_event *event)
7956 struct pmu *pmu = NULL;
7960 idx = srcu_read_lock(&pmus_srcu);
7963 pmu = idr_find(&pmu_idr, event->attr.type);
7966 ret = perf_try_init_event(pmu, event);
7972 list_for_each_entry_rcu(pmu, &pmus, entry) {
7973 ret = perf_try_init_event(pmu, event);
7977 if (ret != -ENOENT) {
7982 pmu = ERR_PTR(-ENOENT);
7984 srcu_read_unlock(&pmus_srcu, idx);
7989 static void account_event_cpu(struct perf_event *event, int cpu)
7994 if (is_cgroup_event(event))
7995 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
7998 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
7999 static void account_freq_event_nohz(void)
8001 #ifdef CONFIG_NO_HZ_FULL
8002 /* Lock so we don't race with concurrent unaccount */
8003 spin_lock(&nr_freq_lock);
8004 if (atomic_inc_return(&nr_freq_events) == 1)
8005 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
8006 spin_unlock(&nr_freq_lock);
8010 static void account_freq_event(void)
8012 if (tick_nohz_full_enabled())
8013 account_freq_event_nohz();
8015 atomic_inc(&nr_freq_events);
8019 static void account_event(struct perf_event *event)
8026 if (event->attach_state & PERF_ATTACH_TASK)
8028 if (event->attr.mmap || event->attr.mmap_data)
8029 atomic_inc(&nr_mmap_events);
8030 if (event->attr.comm)
8031 atomic_inc(&nr_comm_events);
8032 if (event->attr.task)
8033 atomic_inc(&nr_task_events);
8034 if (event->attr.freq)
8035 account_freq_event();
8036 if (event->attr.context_switch) {
8037 atomic_inc(&nr_switch_events);
8040 if (has_branch_stack(event))
8042 if (is_cgroup_event(event))
8046 if (atomic_inc_not_zero(&perf_sched_count))
8049 mutex_lock(&perf_sched_mutex);
8050 if (!atomic_read(&perf_sched_count)) {
8051 static_branch_enable(&perf_sched_events);
8053 * Guarantee that all CPUs observe they key change and
8054 * call the perf scheduling hooks before proceeding to
8055 * install events that need them.
8057 synchronize_sched();
8060 * Now that we have waited for the sync_sched(), allow further
8061 * increments to by-pass the mutex.
8063 atomic_inc(&perf_sched_count);
8064 mutex_unlock(&perf_sched_mutex);
8068 account_event_cpu(event, event->cpu);
8072 * Allocate and initialize a event structure
8074 static struct perf_event *
8075 perf_event_alloc(struct perf_event_attr *attr, int cpu,
8076 struct task_struct *task,
8077 struct perf_event *group_leader,
8078 struct perf_event *parent_event,
8079 perf_overflow_handler_t overflow_handler,
8080 void *context, int cgroup_fd)
8083 struct perf_event *event;
8084 struct hw_perf_event *hwc;
8087 if ((unsigned)cpu >= nr_cpu_ids) {
8088 if (!task || cpu != -1)
8089 return ERR_PTR(-EINVAL);
8092 event = kzalloc(sizeof(*event), GFP_KERNEL);
8094 return ERR_PTR(-ENOMEM);
8097 * Single events are their own group leaders, with an
8098 * empty sibling list:
8101 group_leader = event;
8103 mutex_init(&event->child_mutex);
8104 INIT_LIST_HEAD(&event->child_list);
8106 INIT_LIST_HEAD(&event->group_entry);
8107 INIT_LIST_HEAD(&event->event_entry);
8108 INIT_LIST_HEAD(&event->sibling_list);
8109 INIT_LIST_HEAD(&event->rb_entry);
8110 INIT_LIST_HEAD(&event->active_entry);
8111 INIT_HLIST_NODE(&event->hlist_entry);
8114 init_waitqueue_head(&event->waitq);
8115 init_irq_work(&event->pending, perf_pending_event);
8117 mutex_init(&event->mmap_mutex);
8119 atomic_long_set(&event->refcount, 1);
8121 event->attr = *attr;
8122 event->group_leader = group_leader;
8126 event->parent = parent_event;
8128 event->ns = get_pid_ns(task_active_pid_ns(current));
8129 event->id = atomic64_inc_return(&perf_event_id);
8131 event->state = PERF_EVENT_STATE_INACTIVE;
8134 event->attach_state = PERF_ATTACH_TASK;
8136 * XXX pmu::event_init needs to know what task to account to
8137 * and we cannot use the ctx information because we need the
8138 * pmu before we get a ctx.
8140 event->hw.target = task;
8143 event->clock = &local_clock;
8145 event->clock = parent_event->clock;
8147 if (!overflow_handler && parent_event) {
8148 overflow_handler = parent_event->overflow_handler;
8149 context = parent_event->overflow_handler_context;
8152 if (overflow_handler) {
8153 event->overflow_handler = overflow_handler;
8154 event->overflow_handler_context = context;
8156 event->overflow_handler = perf_event_output;
8157 event->overflow_handler_context = NULL;
8160 perf_event__state_init(event);
8165 hwc->sample_period = attr->sample_period;
8166 if (attr->freq && attr->sample_freq)
8167 hwc->sample_period = 1;
8168 hwc->last_period = hwc->sample_period;
8170 local64_set(&hwc->period_left, hwc->sample_period);
8173 * we currently do not support PERF_FORMAT_GROUP on inherited events
8175 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
8178 if (!has_branch_stack(event))
8179 event->attr.branch_sample_type = 0;
8181 if (cgroup_fd != -1) {
8182 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
8187 pmu = perf_init_event(event);
8190 else if (IS_ERR(pmu)) {
8195 err = exclusive_event_init(event);
8199 if (!event->parent) {
8200 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
8201 err = get_callchain_buffers();
8207 /* symmetric to unaccount_event() in _free_event() */
8208 account_event(event);
8213 exclusive_event_destroy(event);
8217 event->destroy(event);
8218 module_put(pmu->module);
8220 if (is_cgroup_event(event))
8221 perf_detach_cgroup(event);
8223 put_pid_ns(event->ns);
8226 return ERR_PTR(err);
8229 static int perf_copy_attr(struct perf_event_attr __user *uattr,
8230 struct perf_event_attr *attr)
8235 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
8239 * zero the full structure, so that a short copy will be nice.
8241 memset(attr, 0, sizeof(*attr));
8243 ret = get_user(size, &uattr->size);
8247 if (size > PAGE_SIZE) /* silly large */
8250 if (!size) /* abi compat */
8251 size = PERF_ATTR_SIZE_VER0;
8253 if (size < PERF_ATTR_SIZE_VER0)
8257 * If we're handed a bigger struct than we know of,
8258 * ensure all the unknown bits are 0 - i.e. new
8259 * user-space does not rely on any kernel feature
8260 * extensions we dont know about yet.
8262 if (size > sizeof(*attr)) {
8263 unsigned char __user *addr;
8264 unsigned char __user *end;
8267 addr = (void __user *)uattr + sizeof(*attr);
8268 end = (void __user *)uattr + size;
8270 for (; addr < end; addr++) {
8271 ret = get_user(val, addr);
8277 size = sizeof(*attr);
8280 ret = copy_from_user(attr, uattr, size);
8284 if (attr->__reserved_1)
8287 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
8290 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
8293 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
8294 u64 mask = attr->branch_sample_type;
8296 /* only using defined bits */
8297 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
8300 /* at least one branch bit must be set */
8301 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
8304 /* propagate priv level, when not set for branch */
8305 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
8307 /* exclude_kernel checked on syscall entry */
8308 if (!attr->exclude_kernel)
8309 mask |= PERF_SAMPLE_BRANCH_KERNEL;
8311 if (!attr->exclude_user)
8312 mask |= PERF_SAMPLE_BRANCH_USER;
8314 if (!attr->exclude_hv)
8315 mask |= PERF_SAMPLE_BRANCH_HV;
8317 * adjust user setting (for HW filter setup)
8319 attr->branch_sample_type = mask;
8321 /* privileged levels capture (kernel, hv): check permissions */
8322 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
8323 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8327 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
8328 ret = perf_reg_validate(attr->sample_regs_user);
8333 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
8334 if (!arch_perf_have_user_stack_dump())
8338 * We have __u32 type for the size, but so far
8339 * we can only use __u16 as maximum due to the
8340 * __u16 sample size limit.
8342 if (attr->sample_stack_user >= USHRT_MAX)
8344 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
8348 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
8349 ret = perf_reg_validate(attr->sample_regs_intr);
8354 put_user(sizeof(*attr), &uattr->size);
8360 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
8362 struct ring_buffer *rb = NULL;
8368 /* don't allow circular references */
8369 if (event == output_event)
8373 * Don't allow cross-cpu buffers
8375 if (output_event->cpu != event->cpu)
8379 * If its not a per-cpu rb, it must be the same task.
8381 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
8385 * Mixing clocks in the same buffer is trouble you don't need.
8387 if (output_event->clock != event->clock)
8391 * If both events generate aux data, they must be on the same PMU
8393 if (has_aux(event) && has_aux(output_event) &&
8394 event->pmu != output_event->pmu)
8398 mutex_lock(&event->mmap_mutex);
8399 /* Can't redirect output if we've got an active mmap() */
8400 if (atomic_read(&event->mmap_count))
8404 /* get the rb we want to redirect to */
8405 rb = ring_buffer_get(output_event);
8410 ring_buffer_attach(event, rb);
8414 mutex_unlock(&event->mmap_mutex);
8420 static void mutex_lock_double(struct mutex *a, struct mutex *b)
8426 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
8429 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
8431 bool nmi_safe = false;
8434 case CLOCK_MONOTONIC:
8435 event->clock = &ktime_get_mono_fast_ns;
8439 case CLOCK_MONOTONIC_RAW:
8440 event->clock = &ktime_get_raw_fast_ns;
8444 case CLOCK_REALTIME:
8445 event->clock = &ktime_get_real_ns;
8448 case CLOCK_BOOTTIME:
8449 event->clock = &ktime_get_boot_ns;
8453 event->clock = &ktime_get_tai_ns;
8460 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
8467 * sys_perf_event_open - open a performance event, associate it to a task/cpu
8469 * @attr_uptr: event_id type attributes for monitoring/sampling
8472 * @group_fd: group leader event fd
8474 SYSCALL_DEFINE5(perf_event_open,
8475 struct perf_event_attr __user *, attr_uptr,
8476 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
8478 struct perf_event *group_leader = NULL, *output_event = NULL;
8479 struct perf_event *event, *sibling;
8480 struct perf_event_attr attr;
8481 struct perf_event_context *ctx, *uninitialized_var(gctx);
8482 struct file *event_file = NULL;
8483 struct fd group = {NULL, 0};
8484 struct task_struct *task = NULL;
8489 int f_flags = O_RDWR;
8492 /* for future expandability... */
8493 if (flags & ~PERF_FLAG_ALL)
8496 err = perf_copy_attr(attr_uptr, &attr);
8500 if (!attr.exclude_kernel) {
8501 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8506 if (attr.sample_freq > sysctl_perf_event_sample_rate)
8509 if (attr.sample_period & (1ULL << 63))
8514 * In cgroup mode, the pid argument is used to pass the fd
8515 * opened to the cgroup directory in cgroupfs. The cpu argument
8516 * designates the cpu on which to monitor threads from that
8519 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
8522 if (flags & PERF_FLAG_FD_CLOEXEC)
8523 f_flags |= O_CLOEXEC;
8525 event_fd = get_unused_fd_flags(f_flags);
8529 if (group_fd != -1) {
8530 err = perf_fget_light(group_fd, &group);
8533 group_leader = group.file->private_data;
8534 if (flags & PERF_FLAG_FD_OUTPUT)
8535 output_event = group_leader;
8536 if (flags & PERF_FLAG_FD_NO_GROUP)
8537 group_leader = NULL;
8540 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
8541 task = find_lively_task_by_vpid(pid);
8543 err = PTR_ERR(task);
8548 if (task && group_leader &&
8549 group_leader->attr.inherit != attr.inherit) {
8556 if (flags & PERF_FLAG_PID_CGROUP)
8559 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
8560 NULL, NULL, cgroup_fd);
8561 if (IS_ERR(event)) {
8562 err = PTR_ERR(event);
8566 if (is_sampling_event(event)) {
8567 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
8574 * Special case software events and allow them to be part of
8575 * any hardware group.
8579 if (attr.use_clockid) {
8580 err = perf_event_set_clock(event, attr.clockid);
8586 (is_software_event(event) != is_software_event(group_leader))) {
8587 if (is_software_event(event)) {
8589 * If event and group_leader are not both a software
8590 * event, and event is, then group leader is not.
8592 * Allow the addition of software events to !software
8593 * groups, this is safe because software events never
8596 pmu = group_leader->pmu;
8597 } else if (is_software_event(group_leader) &&
8598 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
8600 * In case the group is a pure software group, and we
8601 * try to add a hardware event, move the whole group to
8602 * the hardware context.
8609 * Get the target context (task or percpu):
8611 ctx = find_get_context(pmu, task, event);
8617 if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
8623 put_task_struct(task);
8628 * Look up the group leader (we will attach this event to it):
8634 * Do not allow a recursive hierarchy (this new sibling
8635 * becoming part of another group-sibling):
8637 if (group_leader->group_leader != group_leader)
8640 /* All events in a group should have the same clock */
8641 if (group_leader->clock != event->clock)
8645 * Do not allow to attach to a group in a different
8646 * task or CPU context:
8650 * Make sure we're both on the same task, or both
8653 if (group_leader->ctx->task != ctx->task)
8657 * Make sure we're both events for the same CPU;
8658 * grouping events for different CPUs is broken; since
8659 * you can never concurrently schedule them anyhow.
8661 if (group_leader->cpu != event->cpu)
8664 if (group_leader->ctx != ctx)
8669 * Only a group leader can be exclusive or pinned
8671 if (attr.exclusive || attr.pinned)
8676 err = perf_event_set_output(event, output_event);
8681 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
8683 if (IS_ERR(event_file)) {
8684 err = PTR_ERR(event_file);
8690 gctx = group_leader->ctx;
8691 mutex_lock_double(&gctx->mutex, &ctx->mutex);
8692 if (gctx->task == TASK_TOMBSTONE) {
8697 mutex_lock(&ctx->mutex);
8700 if (ctx->task == TASK_TOMBSTONE) {
8705 if (!perf_event_validate_size(event)) {
8711 * Must be under the same ctx::mutex as perf_install_in_context(),
8712 * because we need to serialize with concurrent event creation.
8714 if (!exclusive_event_installable(event, ctx)) {
8715 /* exclusive and group stuff are assumed mutually exclusive */
8716 WARN_ON_ONCE(move_group);
8722 WARN_ON_ONCE(ctx->parent_ctx);
8726 * See perf_event_ctx_lock() for comments on the details
8727 * of swizzling perf_event::ctx.
8729 perf_remove_from_context(group_leader, 0);
8731 list_for_each_entry(sibling, &group_leader->sibling_list,
8733 perf_remove_from_context(sibling, 0);
8738 * Wait for everybody to stop referencing the events through
8739 * the old lists, before installing it on new lists.
8744 * Install the group siblings before the group leader.
8746 * Because a group leader will try and install the entire group
8747 * (through the sibling list, which is still in-tact), we can
8748 * end up with siblings installed in the wrong context.
8750 * By installing siblings first we NO-OP because they're not
8751 * reachable through the group lists.
8753 list_for_each_entry(sibling, &group_leader->sibling_list,
8755 perf_event__state_init(sibling);
8756 perf_install_in_context(ctx, sibling, sibling->cpu);
8761 * Removing from the context ends up with disabled
8762 * event. What we want here is event in the initial
8763 * startup state, ready to be add into new context.
8765 perf_event__state_init(group_leader);
8766 perf_install_in_context(ctx, group_leader, group_leader->cpu);
8770 * Now that all events are installed in @ctx, nothing
8771 * references @gctx anymore, so drop the last reference we have
8778 * Precalculate sample_data sizes; do while holding ctx::mutex such
8779 * that we're serialized against further additions and before
8780 * perf_install_in_context() which is the point the event is active and
8781 * can use these values.
8783 perf_event__header_size(event);
8784 perf_event__id_header_size(event);
8786 event->owner = current;
8788 perf_install_in_context(ctx, event, event->cpu);
8789 perf_unpin_context(ctx);
8792 mutex_unlock(&gctx->mutex);
8793 mutex_unlock(&ctx->mutex);
8797 mutex_lock(¤t->perf_event_mutex);
8798 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
8799 mutex_unlock(¤t->perf_event_mutex);
8802 * Drop the reference on the group_event after placing the
8803 * new event on the sibling_list. This ensures destruction
8804 * of the group leader will find the pointer to itself in
8805 * perf_group_detach().
8808 fd_install(event_fd, event_file);
8813 mutex_unlock(&gctx->mutex);
8814 mutex_unlock(&ctx->mutex);
8818 perf_unpin_context(ctx);
8822 * If event_file is set, the fput() above will have called ->release()
8823 * and that will take care of freeing the event.
8831 put_task_struct(task);
8835 put_unused_fd(event_fd);
8840 * perf_event_create_kernel_counter
8842 * @attr: attributes of the counter to create
8843 * @cpu: cpu in which the counter is bound
8844 * @task: task to profile (NULL for percpu)
8847 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
8848 struct task_struct *task,
8849 perf_overflow_handler_t overflow_handler,
8852 struct perf_event_context *ctx;
8853 struct perf_event *event;
8857 * Get the target context (task or percpu):
8860 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
8861 overflow_handler, context, -1);
8862 if (IS_ERR(event)) {
8863 err = PTR_ERR(event);
8867 /* Mark owner so we could distinguish it from user events. */
8868 event->owner = TASK_TOMBSTONE;
8870 ctx = find_get_context(event->pmu, task, event);
8876 WARN_ON_ONCE(ctx->parent_ctx);
8877 mutex_lock(&ctx->mutex);
8878 if (ctx->task == TASK_TOMBSTONE) {
8883 if (!exclusive_event_installable(event, ctx)) {
8888 perf_install_in_context(ctx, event, cpu);
8889 perf_unpin_context(ctx);
8890 mutex_unlock(&ctx->mutex);
8895 mutex_unlock(&ctx->mutex);
8896 perf_unpin_context(ctx);
8901 return ERR_PTR(err);
8903 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
8905 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
8907 struct perf_event_context *src_ctx;
8908 struct perf_event_context *dst_ctx;
8909 struct perf_event *event, *tmp;
8912 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
8913 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
8916 * See perf_event_ctx_lock() for comments on the details
8917 * of swizzling perf_event::ctx.
8919 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
8920 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
8922 perf_remove_from_context(event, 0);
8923 unaccount_event_cpu(event, src_cpu);
8925 list_add(&event->migrate_entry, &events);
8929 * Wait for the events to quiesce before re-instating them.
8934 * Re-instate events in 2 passes.
8936 * Skip over group leaders and only install siblings on this first
8937 * pass, siblings will not get enabled without a leader, however a
8938 * leader will enable its siblings, even if those are still on the old
8941 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
8942 if (event->group_leader == event)
8945 list_del(&event->migrate_entry);
8946 if (event->state >= PERF_EVENT_STATE_OFF)
8947 event->state = PERF_EVENT_STATE_INACTIVE;
8948 account_event_cpu(event, dst_cpu);
8949 perf_install_in_context(dst_ctx, event, dst_cpu);
8954 * Once all the siblings are setup properly, install the group leaders
8957 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
8958 list_del(&event->migrate_entry);
8959 if (event->state >= PERF_EVENT_STATE_OFF)
8960 event->state = PERF_EVENT_STATE_INACTIVE;
8961 account_event_cpu(event, dst_cpu);
8962 perf_install_in_context(dst_ctx, event, dst_cpu);
8965 mutex_unlock(&dst_ctx->mutex);
8966 mutex_unlock(&src_ctx->mutex);
8968 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
8970 static void sync_child_event(struct perf_event *child_event,
8971 struct task_struct *child)
8973 struct perf_event *parent_event = child_event->parent;
8976 if (child_event->attr.inherit_stat)
8977 perf_event_read_event(child_event, child);
8979 child_val = perf_event_count(child_event);
8982 * Add back the child's count to the parent's count:
8984 atomic64_add(child_val, &parent_event->child_count);
8985 atomic64_add(child_event->total_time_enabled,
8986 &parent_event->child_total_time_enabled);
8987 atomic64_add(child_event->total_time_running,
8988 &parent_event->child_total_time_running);
8992 perf_event_exit_event(struct perf_event *child_event,
8993 struct perf_event_context *child_ctx,
8994 struct task_struct *child)
8996 struct perf_event *parent_event = child_event->parent;
8999 * Do not destroy the 'original' grouping; because of the context
9000 * switch optimization the original events could've ended up in a
9001 * random child task.
9003 * If we were to destroy the original group, all group related
9004 * operations would cease to function properly after this random
9007 * Do destroy all inherited groups, we don't care about those
9008 * and being thorough is better.
9010 raw_spin_lock_irq(&child_ctx->lock);
9011 WARN_ON_ONCE(child_ctx->is_active);
9014 perf_group_detach(child_event);
9015 list_del_event(child_event, child_ctx);
9016 child_event->state = PERF_EVENT_STATE_EXIT; /* is_event_hup() */
9017 raw_spin_unlock_irq(&child_ctx->lock);
9020 * Parent events are governed by their filedesc, retain them.
9022 if (!parent_event) {
9023 perf_event_wakeup(child_event);
9027 * Child events can be cleaned up.
9030 sync_child_event(child_event, child);
9033 * Remove this event from the parent's list
9035 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
9036 mutex_lock(&parent_event->child_mutex);
9037 list_del_init(&child_event->child_list);
9038 mutex_unlock(&parent_event->child_mutex);
9041 * Kick perf_poll() for is_event_hup().
9043 perf_event_wakeup(parent_event);
9044 free_event(child_event);
9045 put_event(parent_event);
9048 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
9050 struct perf_event_context *child_ctx, *clone_ctx = NULL;
9051 struct perf_event *child_event, *next;
9053 WARN_ON_ONCE(child != current);
9055 child_ctx = perf_pin_task_context(child, ctxn);
9060 * In order to reduce the amount of tricky in ctx tear-down, we hold
9061 * ctx::mutex over the entire thing. This serializes against almost
9062 * everything that wants to access the ctx.
9064 * The exception is sys_perf_event_open() /
9065 * perf_event_create_kernel_count() which does find_get_context()
9066 * without ctx::mutex (it cannot because of the move_group double mutex
9067 * lock thing). See the comments in perf_install_in_context().
9069 mutex_lock(&child_ctx->mutex);
9072 * In a single ctx::lock section, de-schedule the events and detach the
9073 * context from the task such that we cannot ever get it scheduled back
9076 raw_spin_lock_irq(&child_ctx->lock);
9077 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx);
9080 * Now that the context is inactive, destroy the task <-> ctx relation
9081 * and mark the context dead.
9083 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
9084 put_ctx(child_ctx); /* cannot be last */
9085 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
9086 put_task_struct(current); /* cannot be last */
9088 clone_ctx = unclone_ctx(child_ctx);
9089 raw_spin_unlock_irq(&child_ctx->lock);
9095 * Report the task dead after unscheduling the events so that we
9096 * won't get any samples after PERF_RECORD_EXIT. We can however still
9097 * get a few PERF_RECORD_READ events.
9099 perf_event_task(child, child_ctx, 0);
9101 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
9102 perf_event_exit_event(child_event, child_ctx, child);
9104 mutex_unlock(&child_ctx->mutex);
9110 * When a child task exits, feed back event values to parent events.
9112 void perf_event_exit_task(struct task_struct *child)
9114 struct perf_event *event, *tmp;
9117 mutex_lock(&child->perf_event_mutex);
9118 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
9120 list_del_init(&event->owner_entry);
9123 * Ensure the list deletion is visible before we clear
9124 * the owner, closes a race against perf_release() where
9125 * we need to serialize on the owner->perf_event_mutex.
9127 smp_store_release(&event->owner, NULL);
9129 mutex_unlock(&child->perf_event_mutex);
9131 for_each_task_context_nr(ctxn)
9132 perf_event_exit_task_context(child, ctxn);
9135 * The perf_event_exit_task_context calls perf_event_task
9136 * with child's task_ctx, which generates EXIT events for
9137 * child contexts and sets child->perf_event_ctxp[] to NULL.
9138 * At this point we need to send EXIT events to cpu contexts.
9140 perf_event_task(child, NULL, 0);
9143 static void perf_free_event(struct perf_event *event,
9144 struct perf_event_context *ctx)
9146 struct perf_event *parent = event->parent;
9148 if (WARN_ON_ONCE(!parent))
9151 mutex_lock(&parent->child_mutex);
9152 list_del_init(&event->child_list);
9153 mutex_unlock(&parent->child_mutex);
9157 raw_spin_lock_irq(&ctx->lock);
9158 perf_group_detach(event);
9159 list_del_event(event, ctx);
9160 raw_spin_unlock_irq(&ctx->lock);
9165 * Free an unexposed, unused context as created by inheritance by
9166 * perf_event_init_task below, used by fork() in case of fail.
9168 * Not all locks are strictly required, but take them anyway to be nice and
9169 * help out with the lockdep assertions.
9171 void perf_event_free_task(struct task_struct *task)
9173 struct perf_event_context *ctx;
9174 struct perf_event *event, *tmp;
9177 for_each_task_context_nr(ctxn) {
9178 ctx = task->perf_event_ctxp[ctxn];
9182 mutex_lock(&ctx->mutex);
9184 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
9186 perf_free_event(event, ctx);
9188 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
9190 perf_free_event(event, ctx);
9192 if (!list_empty(&ctx->pinned_groups) ||
9193 !list_empty(&ctx->flexible_groups))
9196 mutex_unlock(&ctx->mutex);
9202 void perf_event_delayed_put(struct task_struct *task)
9206 for_each_task_context_nr(ctxn)
9207 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
9210 struct file *perf_event_get(unsigned int fd)
9214 file = fget_raw(fd);
9216 return ERR_PTR(-EBADF);
9218 if (file->f_op != &perf_fops) {
9220 return ERR_PTR(-EBADF);
9226 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
9229 return ERR_PTR(-EINVAL);
9231 return &event->attr;
9235 * inherit a event from parent task to child task:
9237 static struct perf_event *
9238 inherit_event(struct perf_event *parent_event,
9239 struct task_struct *parent,
9240 struct perf_event_context *parent_ctx,
9241 struct task_struct *child,
9242 struct perf_event *group_leader,
9243 struct perf_event_context *child_ctx)
9245 enum perf_event_active_state parent_state = parent_event->state;
9246 struct perf_event *child_event;
9247 unsigned long flags;
9250 * Instead of creating recursive hierarchies of events,
9251 * we link inherited events back to the original parent,
9252 * which has a filp for sure, which we use as the reference
9255 if (parent_event->parent)
9256 parent_event = parent_event->parent;
9258 child_event = perf_event_alloc(&parent_event->attr,
9261 group_leader, parent_event,
9263 if (IS_ERR(child_event))
9267 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
9268 * must be under the same lock in order to serialize against
9269 * perf_event_release_kernel(), such that either we must observe
9270 * is_orphaned_event() or they will observe us on the child_list.
9272 mutex_lock(&parent_event->child_mutex);
9273 if (is_orphaned_event(parent_event) ||
9274 !atomic_long_inc_not_zero(&parent_event->refcount)) {
9275 mutex_unlock(&parent_event->child_mutex);
9276 free_event(child_event);
9283 * Make the child state follow the state of the parent event,
9284 * not its attr.disabled bit. We hold the parent's mutex,
9285 * so we won't race with perf_event_{en, dis}able_family.
9287 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
9288 child_event->state = PERF_EVENT_STATE_INACTIVE;
9290 child_event->state = PERF_EVENT_STATE_OFF;
9292 if (parent_event->attr.freq) {
9293 u64 sample_period = parent_event->hw.sample_period;
9294 struct hw_perf_event *hwc = &child_event->hw;
9296 hwc->sample_period = sample_period;
9297 hwc->last_period = sample_period;
9299 local64_set(&hwc->period_left, sample_period);
9302 child_event->ctx = child_ctx;
9303 child_event->overflow_handler = parent_event->overflow_handler;
9304 child_event->overflow_handler_context
9305 = parent_event->overflow_handler_context;
9308 * Precalculate sample_data sizes
9310 perf_event__header_size(child_event);
9311 perf_event__id_header_size(child_event);
9314 * Link it up in the child's context:
9316 raw_spin_lock_irqsave(&child_ctx->lock, flags);
9317 add_event_to_ctx(child_event, child_ctx);
9318 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
9321 * Link this into the parent event's child list
9323 list_add_tail(&child_event->child_list, &parent_event->child_list);
9324 mutex_unlock(&parent_event->child_mutex);
9329 static int inherit_group(struct perf_event *parent_event,
9330 struct task_struct *parent,
9331 struct perf_event_context *parent_ctx,
9332 struct task_struct *child,
9333 struct perf_event_context *child_ctx)
9335 struct perf_event *leader;
9336 struct perf_event *sub;
9337 struct perf_event *child_ctr;
9339 leader = inherit_event(parent_event, parent, parent_ctx,
9340 child, NULL, child_ctx);
9342 return PTR_ERR(leader);
9343 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
9344 child_ctr = inherit_event(sub, parent, parent_ctx,
9345 child, leader, child_ctx);
9346 if (IS_ERR(child_ctr))
9347 return PTR_ERR(child_ctr);
9353 inherit_task_group(struct perf_event *event, struct task_struct *parent,
9354 struct perf_event_context *parent_ctx,
9355 struct task_struct *child, int ctxn,
9359 struct perf_event_context *child_ctx;
9361 if (!event->attr.inherit) {
9366 child_ctx = child->perf_event_ctxp[ctxn];
9369 * This is executed from the parent task context, so
9370 * inherit events that have been marked for cloning.
9371 * First allocate and initialize a context for the
9375 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
9379 child->perf_event_ctxp[ctxn] = child_ctx;
9382 ret = inherit_group(event, parent, parent_ctx,
9392 * Initialize the perf_event context in task_struct
9394 static int perf_event_init_context(struct task_struct *child, int ctxn)
9396 struct perf_event_context *child_ctx, *parent_ctx;
9397 struct perf_event_context *cloned_ctx;
9398 struct perf_event *event;
9399 struct task_struct *parent = current;
9400 int inherited_all = 1;
9401 unsigned long flags;
9404 if (likely(!parent->perf_event_ctxp[ctxn]))
9408 * If the parent's context is a clone, pin it so it won't get
9411 parent_ctx = perf_pin_task_context(parent, ctxn);
9416 * No need to check if parent_ctx != NULL here; since we saw
9417 * it non-NULL earlier, the only reason for it to become NULL
9418 * is if we exit, and since we're currently in the middle of
9419 * a fork we can't be exiting at the same time.
9423 * Lock the parent list. No need to lock the child - not PID
9424 * hashed yet and not running, so nobody can access it.
9426 mutex_lock(&parent_ctx->mutex);
9429 * We dont have to disable NMIs - we are only looking at
9430 * the list, not manipulating it:
9432 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
9433 ret = inherit_task_group(event, parent, parent_ctx,
9434 child, ctxn, &inherited_all);
9440 * We can't hold ctx->lock when iterating the ->flexible_group list due
9441 * to allocations, but we need to prevent rotation because
9442 * rotate_ctx() will change the list from interrupt context.
9444 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9445 parent_ctx->rotate_disable = 1;
9446 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9448 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
9449 ret = inherit_task_group(event, parent, parent_ctx,
9450 child, ctxn, &inherited_all);
9455 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9456 parent_ctx->rotate_disable = 0;
9458 child_ctx = child->perf_event_ctxp[ctxn];
9460 if (child_ctx && inherited_all) {
9462 * Mark the child context as a clone of the parent
9463 * context, or of whatever the parent is a clone of.
9465 * Note that if the parent is a clone, the holding of
9466 * parent_ctx->lock avoids it from being uncloned.
9468 cloned_ctx = parent_ctx->parent_ctx;
9470 child_ctx->parent_ctx = cloned_ctx;
9471 child_ctx->parent_gen = parent_ctx->parent_gen;
9473 child_ctx->parent_ctx = parent_ctx;
9474 child_ctx->parent_gen = parent_ctx->generation;
9476 get_ctx(child_ctx->parent_ctx);
9479 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9480 mutex_unlock(&parent_ctx->mutex);
9482 perf_unpin_context(parent_ctx);
9483 put_ctx(parent_ctx);
9489 * Initialize the perf_event context in task_struct
9491 int perf_event_init_task(struct task_struct *child)
9495 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
9496 mutex_init(&child->perf_event_mutex);
9497 INIT_LIST_HEAD(&child->perf_event_list);
9499 for_each_task_context_nr(ctxn) {
9500 ret = perf_event_init_context(child, ctxn);
9502 perf_event_free_task(child);
9510 static void __init perf_event_init_all_cpus(void)
9512 struct swevent_htable *swhash;
9515 for_each_possible_cpu(cpu) {
9516 swhash = &per_cpu(swevent_htable, cpu);
9517 mutex_init(&swhash->hlist_mutex);
9518 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
9522 static void perf_event_init_cpu(int cpu)
9524 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9526 mutex_lock(&swhash->hlist_mutex);
9527 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
9528 struct swevent_hlist *hlist;
9530 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
9532 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9534 mutex_unlock(&swhash->hlist_mutex);
9537 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
9538 static void __perf_event_exit_context(void *__info)
9540 struct perf_event_context *ctx = __info;
9541 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
9542 struct perf_event *event;
9544 raw_spin_lock(&ctx->lock);
9545 list_for_each_entry(event, &ctx->event_list, event_entry)
9546 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
9547 raw_spin_unlock(&ctx->lock);
9550 static void perf_event_exit_cpu_context(int cpu)
9552 struct perf_event_context *ctx;
9556 idx = srcu_read_lock(&pmus_srcu);
9557 list_for_each_entry_rcu(pmu, &pmus, entry) {
9558 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
9560 mutex_lock(&ctx->mutex);
9561 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
9562 mutex_unlock(&ctx->mutex);
9564 srcu_read_unlock(&pmus_srcu, idx);
9567 static void perf_event_exit_cpu(int cpu)
9569 perf_event_exit_cpu_context(cpu);
9572 static inline void perf_event_exit_cpu(int cpu) { }
9576 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
9580 for_each_online_cpu(cpu)
9581 perf_event_exit_cpu(cpu);
9587 * Run the perf reboot notifier at the very last possible moment so that
9588 * the generic watchdog code runs as long as possible.
9590 static struct notifier_block perf_reboot_notifier = {
9591 .notifier_call = perf_reboot,
9592 .priority = INT_MIN,
9596 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
9598 unsigned int cpu = (long)hcpu;
9600 switch (action & ~CPU_TASKS_FROZEN) {
9602 case CPU_UP_PREPARE:
9604 * This must be done before the CPU comes alive, because the
9605 * moment we can run tasks we can encounter (software) events.
9607 * Specifically, someone can have inherited events on kthreadd
9608 * or a pre-existing worker thread that gets re-bound.
9610 perf_event_init_cpu(cpu);
9613 case CPU_DOWN_PREPARE:
9615 * This must be done before the CPU dies because after that an
9616 * active event might want to IPI the CPU and that'll not work
9617 * so great for dead CPUs.
9619 * XXX smp_call_function_single() return -ENXIO without a warn
9620 * so we could possibly deal with this.
9622 * This is safe against new events arriving because
9623 * sys_perf_event_open() serializes against hotplug using
9624 * get_online_cpus().
9626 perf_event_exit_cpu(cpu);
9635 void __init perf_event_init(void)
9641 perf_event_init_all_cpus();
9642 init_srcu_struct(&pmus_srcu);
9643 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
9644 perf_pmu_register(&perf_cpu_clock, NULL, -1);
9645 perf_pmu_register(&perf_task_clock, NULL, -1);
9647 perf_cpu_notifier(perf_cpu_notify);
9648 register_reboot_notifier(&perf_reboot_notifier);
9650 ret = init_hw_breakpoint();
9651 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
9654 * Build time assertion that we keep the data_head at the intended
9655 * location. IOW, validation we got the __reserved[] size right.
9657 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
9661 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
9664 struct perf_pmu_events_attr *pmu_attr =
9665 container_of(attr, struct perf_pmu_events_attr, attr);
9667 if (pmu_attr->event_str)
9668 return sprintf(page, "%s\n", pmu_attr->event_str);
9672 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
9674 static int __init perf_event_sysfs_init(void)
9679 mutex_lock(&pmus_lock);
9681 ret = bus_register(&pmu_bus);
9685 list_for_each_entry(pmu, &pmus, entry) {
9686 if (!pmu->name || pmu->type < 0)
9689 ret = pmu_dev_alloc(pmu);
9690 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
9692 pmu_bus_running = 1;
9696 mutex_unlock(&pmus_lock);
9700 device_initcall(perf_event_sysfs_init);
9702 #ifdef CONFIG_CGROUP_PERF
9703 static struct cgroup_subsys_state *
9704 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
9706 struct perf_cgroup *jc;
9708 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
9710 return ERR_PTR(-ENOMEM);
9712 jc->info = alloc_percpu(struct perf_cgroup_info);
9715 return ERR_PTR(-ENOMEM);
9721 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
9723 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
9725 free_percpu(jc->info);
9729 static int __perf_cgroup_move(void *info)
9731 struct task_struct *task = info;
9733 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
9738 static void perf_cgroup_attach(struct cgroup_taskset *tset)
9740 struct task_struct *task;
9741 struct cgroup_subsys_state *css;
9743 cgroup_taskset_for_each(task, css, tset)
9744 task_function_call(task, __perf_cgroup_move, task);
9747 struct cgroup_subsys perf_event_cgrp_subsys = {
9748 .css_alloc = perf_cgroup_css_alloc,
9749 .css_free = perf_cgroup_css_free,
9750 .attach = perf_cgroup_attach,
9752 #endif /* CONFIG_CGROUP_PERF */