perf: Fix unclone_ctx() vs. locking
[linux-2.6/btrfs-unstable.git] / kernel / events / core.c
blobafdd9e1d714441a42364a1ad1b308e07fea4cd49
1 /*
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 <pzijlstr@redhat.com>
7 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
9 * For licensing details see kernel-base/COPYING
12 #include <linux/fs.h>
13 #include <linux/mm.h>
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/perf_event.h>
38 #include <linux/ftrace_event.h>
39 #include <linux/hw_breakpoint.h>
40 #include <linux/mm_types.h>
41 #include <linux/cgroup.h>
42 #include <linux/module.h>
43 #include <linux/mman.h>
44 #include <linux/compat.h>
46 #include "internal.h"
48 #include <asm/irq_regs.h>
50 struct remote_function_call {
51 struct task_struct *p;
52 int (*func)(void *info);
53 void *info;
54 int ret;
57 static void remote_function(void *data)
59 struct remote_function_call *tfc = data;
60 struct task_struct *p = tfc->p;
62 if (p) {
63 tfc->ret = -EAGAIN;
64 if (task_cpu(p) != smp_processor_id() || !task_curr(p))
65 return;
68 tfc->ret = tfc->func(tfc->info);
71 /**
72 * task_function_call - call a function on the cpu on which a task runs
73 * @p: the task to evaluate
74 * @func: the function to be called
75 * @info: the function call argument
77 * Calls the function @func when the task is currently running. This might
78 * be on the current CPU, which just calls the function directly
80 * returns: @func return value, or
81 * -ESRCH - when the process isn't running
82 * -EAGAIN - when the process moved away
84 static int
85 task_function_call(struct task_struct *p, int (*func) (void *info), void *info)
87 struct remote_function_call data = {
88 .p = p,
89 .func = func,
90 .info = info,
91 .ret = -ESRCH, /* No such (running) process */
94 if (task_curr(p))
95 smp_call_function_single(task_cpu(p), remote_function, &data, 1);
97 return data.ret;
101 * cpu_function_call - call a function on the cpu
102 * @func: the function to be called
103 * @info: the function call argument
105 * Calls the function @func on the remote cpu.
107 * returns: @func return value or -ENXIO when the cpu is offline
109 static int cpu_function_call(int cpu, int (*func) (void *info), void *info)
111 struct remote_function_call data = {
112 .p = NULL,
113 .func = func,
114 .info = info,
115 .ret = -ENXIO, /* No such CPU */
118 smp_call_function_single(cpu, remote_function, &data, 1);
120 return data.ret;
123 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
124 PERF_FLAG_FD_OUTPUT |\
125 PERF_FLAG_PID_CGROUP |\
126 PERF_FLAG_FD_CLOEXEC)
129 * branch priv levels that need permission checks
131 #define PERF_SAMPLE_BRANCH_PERM_PLM \
132 (PERF_SAMPLE_BRANCH_KERNEL |\
133 PERF_SAMPLE_BRANCH_HV)
135 enum event_type_t {
136 EVENT_FLEXIBLE = 0x1,
137 EVENT_PINNED = 0x2,
138 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
142 * perf_sched_events : >0 events exist
143 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
145 struct static_key_deferred perf_sched_events __read_mostly;
146 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
147 static DEFINE_PER_CPU(atomic_t, perf_branch_stack_events);
149 static atomic_t nr_mmap_events __read_mostly;
150 static atomic_t nr_comm_events __read_mostly;
151 static atomic_t nr_task_events __read_mostly;
152 static atomic_t nr_freq_events __read_mostly;
154 static LIST_HEAD(pmus);
155 static DEFINE_MUTEX(pmus_lock);
156 static struct srcu_struct pmus_srcu;
159 * perf event paranoia level:
160 * -1 - not paranoid at all
161 * 0 - disallow raw tracepoint access for unpriv
162 * 1 - disallow cpu events for unpriv
163 * 2 - disallow kernel profiling for unpriv
165 int sysctl_perf_event_paranoid __read_mostly = 1;
167 /* Minimum for 512 kiB + 1 user control page */
168 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
171 * max perf event sample rate
173 #define DEFAULT_MAX_SAMPLE_RATE 100000
174 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
175 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
177 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
179 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
180 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
182 static int perf_sample_allowed_ns __read_mostly =
183 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
185 void update_perf_cpu_limits(void)
187 u64 tmp = perf_sample_period_ns;
189 tmp *= sysctl_perf_cpu_time_max_percent;
190 do_div(tmp, 100);
191 ACCESS_ONCE(perf_sample_allowed_ns) = tmp;
194 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
196 int perf_proc_update_handler(struct ctl_table *table, int write,
197 void __user *buffer, size_t *lenp,
198 loff_t *ppos)
200 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
202 if (ret || !write)
203 return ret;
205 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
206 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
207 update_perf_cpu_limits();
209 return 0;
212 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
214 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
215 void __user *buffer, size_t *lenp,
216 loff_t *ppos)
218 int ret = proc_dointvec(table, write, buffer, lenp, ppos);
220 if (ret || !write)
221 return ret;
223 update_perf_cpu_limits();
225 return 0;
229 * perf samples are done in some very critical code paths (NMIs).
230 * If they take too much CPU time, the system can lock up and not
231 * get any real work done. This will drop the sample rate when
232 * we detect that events are taking too long.
234 #define NR_ACCUMULATED_SAMPLES 128
235 static DEFINE_PER_CPU(u64, running_sample_length);
237 static void perf_duration_warn(struct irq_work *w)
239 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
240 u64 avg_local_sample_len;
241 u64 local_samples_len;
243 local_samples_len = __get_cpu_var(running_sample_length);
244 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
246 printk_ratelimited(KERN_WARNING
247 "perf interrupt took too long (%lld > %lld), lowering "
248 "kernel.perf_event_max_sample_rate to %d\n",
249 avg_local_sample_len, allowed_ns >> 1,
250 sysctl_perf_event_sample_rate);
253 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
255 void perf_sample_event_took(u64 sample_len_ns)
257 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
258 u64 avg_local_sample_len;
259 u64 local_samples_len;
261 if (allowed_ns == 0)
262 return;
264 /* decay the counter by 1 average sample */
265 local_samples_len = __get_cpu_var(running_sample_length);
266 local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES;
267 local_samples_len += sample_len_ns;
268 __get_cpu_var(running_sample_length) = local_samples_len;
271 * note: this will be biased artifically low until we have
272 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
273 * from having to maintain a count.
275 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
277 if (avg_local_sample_len <= allowed_ns)
278 return;
280 if (max_samples_per_tick <= 1)
281 return;
283 max_samples_per_tick = DIV_ROUND_UP(max_samples_per_tick, 2);
284 sysctl_perf_event_sample_rate = max_samples_per_tick * HZ;
285 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
287 update_perf_cpu_limits();
289 if (!irq_work_queue(&perf_duration_work)) {
290 early_printk("perf interrupt took too long (%lld > %lld), lowering "
291 "kernel.perf_event_max_sample_rate to %d\n",
292 avg_local_sample_len, allowed_ns >> 1,
293 sysctl_perf_event_sample_rate);
297 static atomic64_t perf_event_id;
299 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
300 enum event_type_t event_type);
302 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
303 enum event_type_t event_type,
304 struct task_struct *task);
306 static void update_context_time(struct perf_event_context *ctx);
307 static u64 perf_event_time(struct perf_event *event);
309 void __weak perf_event_print_debug(void) { }
311 extern __weak const char *perf_pmu_name(void)
313 return "pmu";
316 static inline u64 perf_clock(void)
318 return local_clock();
321 static inline struct perf_cpu_context *
322 __get_cpu_context(struct perf_event_context *ctx)
324 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
327 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
328 struct perf_event_context *ctx)
330 raw_spin_lock(&cpuctx->ctx.lock);
331 if (ctx)
332 raw_spin_lock(&ctx->lock);
335 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
336 struct perf_event_context *ctx)
338 if (ctx)
339 raw_spin_unlock(&ctx->lock);
340 raw_spin_unlock(&cpuctx->ctx.lock);
343 #ifdef CONFIG_CGROUP_PERF
346 * perf_cgroup_info keeps track of time_enabled for a cgroup.
347 * This is a per-cpu dynamically allocated data structure.
349 struct perf_cgroup_info {
350 u64 time;
351 u64 timestamp;
354 struct perf_cgroup {
355 struct cgroup_subsys_state css;
356 struct perf_cgroup_info __percpu *info;
360 * Must ensure cgroup is pinned (css_get) before calling
361 * this function. In other words, we cannot call this function
362 * if there is no cgroup event for the current CPU context.
364 static inline struct perf_cgroup *
365 perf_cgroup_from_task(struct task_struct *task)
367 return container_of(task_css(task, perf_event_cgrp_id),
368 struct perf_cgroup, css);
371 static inline bool
372 perf_cgroup_match(struct perf_event *event)
374 struct perf_event_context *ctx = event->ctx;
375 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
377 /* @event doesn't care about cgroup */
378 if (!event->cgrp)
379 return true;
381 /* wants specific cgroup scope but @cpuctx isn't associated with any */
382 if (!cpuctx->cgrp)
383 return false;
386 * Cgroup scoping is recursive. An event enabled for a cgroup is
387 * also enabled for all its descendant cgroups. If @cpuctx's
388 * cgroup is a descendant of @event's (the test covers identity
389 * case), it's a match.
391 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
392 event->cgrp->css.cgroup);
395 static inline void perf_put_cgroup(struct perf_event *event)
397 css_put(&event->cgrp->css);
400 static inline void perf_detach_cgroup(struct perf_event *event)
402 perf_put_cgroup(event);
403 event->cgrp = NULL;
406 static inline int is_cgroup_event(struct perf_event *event)
408 return event->cgrp != NULL;
411 static inline u64 perf_cgroup_event_time(struct perf_event *event)
413 struct perf_cgroup_info *t;
415 t = per_cpu_ptr(event->cgrp->info, event->cpu);
416 return t->time;
419 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
421 struct perf_cgroup_info *info;
422 u64 now;
424 now = perf_clock();
426 info = this_cpu_ptr(cgrp->info);
428 info->time += now - info->timestamp;
429 info->timestamp = now;
432 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
434 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
435 if (cgrp_out)
436 __update_cgrp_time(cgrp_out);
439 static inline void update_cgrp_time_from_event(struct perf_event *event)
441 struct perf_cgroup *cgrp;
444 * ensure we access cgroup data only when needed and
445 * when we know the cgroup is pinned (css_get)
447 if (!is_cgroup_event(event))
448 return;
450 cgrp = perf_cgroup_from_task(current);
452 * Do not update time when cgroup is not active
454 if (cgrp == event->cgrp)
455 __update_cgrp_time(event->cgrp);
458 static inline void
459 perf_cgroup_set_timestamp(struct task_struct *task,
460 struct perf_event_context *ctx)
462 struct perf_cgroup *cgrp;
463 struct perf_cgroup_info *info;
466 * ctx->lock held by caller
467 * ensure we do not access cgroup data
468 * unless we have the cgroup pinned (css_get)
470 if (!task || !ctx->nr_cgroups)
471 return;
473 cgrp = perf_cgroup_from_task(task);
474 info = this_cpu_ptr(cgrp->info);
475 info->timestamp = ctx->timestamp;
478 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
479 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
482 * reschedule events based on the cgroup constraint of task.
484 * mode SWOUT : schedule out everything
485 * mode SWIN : schedule in based on cgroup for next
487 void perf_cgroup_switch(struct task_struct *task, int mode)
489 struct perf_cpu_context *cpuctx;
490 struct pmu *pmu;
491 unsigned long flags;
494 * disable interrupts to avoid geting nr_cgroup
495 * changes via __perf_event_disable(). Also
496 * avoids preemption.
498 local_irq_save(flags);
501 * we reschedule only in the presence of cgroup
502 * constrained events.
504 rcu_read_lock();
506 list_for_each_entry_rcu(pmu, &pmus, entry) {
507 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
508 if (cpuctx->unique_pmu != pmu)
509 continue; /* ensure we process each cpuctx once */
512 * perf_cgroup_events says at least one
513 * context on this CPU has cgroup events.
515 * ctx->nr_cgroups reports the number of cgroup
516 * events for a context.
518 if (cpuctx->ctx.nr_cgroups > 0) {
519 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
520 perf_pmu_disable(cpuctx->ctx.pmu);
522 if (mode & PERF_CGROUP_SWOUT) {
523 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
525 * must not be done before ctxswout due
526 * to event_filter_match() in event_sched_out()
528 cpuctx->cgrp = NULL;
531 if (mode & PERF_CGROUP_SWIN) {
532 WARN_ON_ONCE(cpuctx->cgrp);
534 * set cgrp before ctxsw in to allow
535 * event_filter_match() to not have to pass
536 * task around
538 cpuctx->cgrp = perf_cgroup_from_task(task);
539 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
541 perf_pmu_enable(cpuctx->ctx.pmu);
542 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
546 rcu_read_unlock();
548 local_irq_restore(flags);
551 static inline void perf_cgroup_sched_out(struct task_struct *task,
552 struct task_struct *next)
554 struct perf_cgroup *cgrp1;
555 struct perf_cgroup *cgrp2 = NULL;
558 * we come here when we know perf_cgroup_events > 0
560 cgrp1 = perf_cgroup_from_task(task);
563 * next is NULL when called from perf_event_enable_on_exec()
564 * that will systematically cause a cgroup_switch()
566 if (next)
567 cgrp2 = perf_cgroup_from_task(next);
570 * only schedule out current cgroup events if we know
571 * that we are switching to a different cgroup. Otherwise,
572 * do no touch the cgroup events.
574 if (cgrp1 != cgrp2)
575 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
578 static inline void perf_cgroup_sched_in(struct task_struct *prev,
579 struct task_struct *task)
581 struct perf_cgroup *cgrp1;
582 struct perf_cgroup *cgrp2 = NULL;
585 * we come here when we know perf_cgroup_events > 0
587 cgrp1 = perf_cgroup_from_task(task);
589 /* prev can never be NULL */
590 cgrp2 = perf_cgroup_from_task(prev);
593 * only need to schedule in cgroup events if we are changing
594 * cgroup during ctxsw. Cgroup events were not scheduled
595 * out of ctxsw out if that was not the case.
597 if (cgrp1 != cgrp2)
598 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
601 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
602 struct perf_event_attr *attr,
603 struct perf_event *group_leader)
605 struct perf_cgroup *cgrp;
606 struct cgroup_subsys_state *css;
607 struct fd f = fdget(fd);
608 int ret = 0;
610 if (!f.file)
611 return -EBADF;
613 css = css_tryget_online_from_dir(f.file->f_dentry,
614 &perf_event_cgrp_subsys);
615 if (IS_ERR(css)) {
616 ret = PTR_ERR(css);
617 goto out;
620 cgrp = container_of(css, struct perf_cgroup, css);
621 event->cgrp = cgrp;
624 * all events in a group must monitor
625 * the same cgroup because a task belongs
626 * to only one perf cgroup at a time
628 if (group_leader && group_leader->cgrp != cgrp) {
629 perf_detach_cgroup(event);
630 ret = -EINVAL;
632 out:
633 fdput(f);
634 return ret;
637 static inline void
638 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
640 struct perf_cgroup_info *t;
641 t = per_cpu_ptr(event->cgrp->info, event->cpu);
642 event->shadow_ctx_time = now - t->timestamp;
645 static inline void
646 perf_cgroup_defer_enabled(struct perf_event *event)
649 * when the current task's perf cgroup does not match
650 * the event's, we need to remember to call the
651 * perf_mark_enable() function the first time a task with
652 * a matching perf cgroup is scheduled in.
654 if (is_cgroup_event(event) && !perf_cgroup_match(event))
655 event->cgrp_defer_enabled = 1;
658 static inline void
659 perf_cgroup_mark_enabled(struct perf_event *event,
660 struct perf_event_context *ctx)
662 struct perf_event *sub;
663 u64 tstamp = perf_event_time(event);
665 if (!event->cgrp_defer_enabled)
666 return;
668 event->cgrp_defer_enabled = 0;
670 event->tstamp_enabled = tstamp - event->total_time_enabled;
671 list_for_each_entry(sub, &event->sibling_list, group_entry) {
672 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
673 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
674 sub->cgrp_defer_enabled = 0;
678 #else /* !CONFIG_CGROUP_PERF */
680 static inline bool
681 perf_cgroup_match(struct perf_event *event)
683 return true;
686 static inline void perf_detach_cgroup(struct perf_event *event)
689 static inline int is_cgroup_event(struct perf_event *event)
691 return 0;
694 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
696 return 0;
699 static inline void update_cgrp_time_from_event(struct perf_event *event)
703 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
707 static inline void perf_cgroup_sched_out(struct task_struct *task,
708 struct task_struct *next)
712 static inline void perf_cgroup_sched_in(struct task_struct *prev,
713 struct task_struct *task)
717 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
718 struct perf_event_attr *attr,
719 struct perf_event *group_leader)
721 return -EINVAL;
724 static inline void
725 perf_cgroup_set_timestamp(struct task_struct *task,
726 struct perf_event_context *ctx)
730 void
731 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
735 static inline void
736 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
740 static inline u64 perf_cgroup_event_time(struct perf_event *event)
742 return 0;
745 static inline void
746 perf_cgroup_defer_enabled(struct perf_event *event)
750 static inline void
751 perf_cgroup_mark_enabled(struct perf_event *event,
752 struct perf_event_context *ctx)
755 #endif
758 * set default to be dependent on timer tick just
759 * like original code
761 #define PERF_CPU_HRTIMER (1000 / HZ)
763 * function must be called with interrupts disbled
765 static enum hrtimer_restart perf_cpu_hrtimer_handler(struct hrtimer *hr)
767 struct perf_cpu_context *cpuctx;
768 enum hrtimer_restart ret = HRTIMER_NORESTART;
769 int rotations = 0;
771 WARN_ON(!irqs_disabled());
773 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
775 rotations = perf_rotate_context(cpuctx);
778 * arm timer if needed
780 if (rotations) {
781 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
782 ret = HRTIMER_RESTART;
785 return ret;
788 /* CPU is going down */
789 void perf_cpu_hrtimer_cancel(int cpu)
791 struct perf_cpu_context *cpuctx;
792 struct pmu *pmu;
793 unsigned long flags;
795 if (WARN_ON(cpu != smp_processor_id()))
796 return;
798 local_irq_save(flags);
800 rcu_read_lock();
802 list_for_each_entry_rcu(pmu, &pmus, entry) {
803 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
805 if (pmu->task_ctx_nr == perf_sw_context)
806 continue;
808 hrtimer_cancel(&cpuctx->hrtimer);
811 rcu_read_unlock();
813 local_irq_restore(flags);
816 static void __perf_cpu_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
818 struct hrtimer *hr = &cpuctx->hrtimer;
819 struct pmu *pmu = cpuctx->ctx.pmu;
820 int timer;
822 /* no multiplexing needed for SW PMU */
823 if (pmu->task_ctx_nr == perf_sw_context)
824 return;
827 * check default is sane, if not set then force to
828 * default interval (1/tick)
830 timer = pmu->hrtimer_interval_ms;
831 if (timer < 1)
832 timer = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
834 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
836 hrtimer_init(hr, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
837 hr->function = perf_cpu_hrtimer_handler;
840 static void perf_cpu_hrtimer_restart(struct perf_cpu_context *cpuctx)
842 struct hrtimer *hr = &cpuctx->hrtimer;
843 struct pmu *pmu = cpuctx->ctx.pmu;
845 /* not for SW PMU */
846 if (pmu->task_ctx_nr == perf_sw_context)
847 return;
849 if (hrtimer_active(hr))
850 return;
852 if (!hrtimer_callback_running(hr))
853 __hrtimer_start_range_ns(hr, cpuctx->hrtimer_interval,
854 0, HRTIMER_MODE_REL_PINNED, 0);
857 void perf_pmu_disable(struct pmu *pmu)
859 int *count = this_cpu_ptr(pmu->pmu_disable_count);
860 if (!(*count)++)
861 pmu->pmu_disable(pmu);
864 void perf_pmu_enable(struct pmu *pmu)
866 int *count = this_cpu_ptr(pmu->pmu_disable_count);
867 if (!--(*count))
868 pmu->pmu_enable(pmu);
871 static DEFINE_PER_CPU(struct list_head, rotation_list);
874 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
875 * because they're strictly cpu affine and rotate_start is called with IRQs
876 * disabled, while rotate_context is called from IRQ context.
878 static void perf_pmu_rotate_start(struct pmu *pmu)
880 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
881 struct list_head *head = &__get_cpu_var(rotation_list);
883 WARN_ON(!irqs_disabled());
885 if (list_empty(&cpuctx->rotation_list))
886 list_add(&cpuctx->rotation_list, head);
889 static void get_ctx(struct perf_event_context *ctx)
891 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
894 static void put_ctx(struct perf_event_context *ctx)
896 if (atomic_dec_and_test(&ctx->refcount)) {
897 if (ctx->parent_ctx)
898 put_ctx(ctx->parent_ctx);
899 if (ctx->task)
900 put_task_struct(ctx->task);
901 kfree_rcu(ctx, rcu_head);
906 * This must be done under the ctx->lock, such as to serialize against
907 * context_equiv(), therefore we cannot call put_ctx() since that might end up
908 * calling scheduler related locks and ctx->lock nests inside those.
910 static __must_check struct perf_event_context *
911 unclone_ctx(struct perf_event_context *ctx)
913 struct perf_event_context *parent_ctx = ctx->parent_ctx;
915 lockdep_assert_held(&ctx->lock);
917 if (parent_ctx)
918 ctx->parent_ctx = NULL;
919 ctx->generation++;
921 return parent_ctx;
924 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
927 * only top level events have the pid namespace they were created in
929 if (event->parent)
930 event = event->parent;
932 return task_tgid_nr_ns(p, event->ns);
935 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
938 * only top level events have the pid namespace they were created in
940 if (event->parent)
941 event = event->parent;
943 return task_pid_nr_ns(p, event->ns);
947 * If we inherit events we want to return the parent event id
948 * to userspace.
950 static u64 primary_event_id(struct perf_event *event)
952 u64 id = event->id;
954 if (event->parent)
955 id = event->parent->id;
957 return id;
961 * Get the perf_event_context for a task and lock it.
962 * This has to cope with with the fact that until it is locked,
963 * the context could get moved to another task.
965 static struct perf_event_context *
966 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
968 struct perf_event_context *ctx;
970 retry:
972 * One of the few rules of preemptible RCU is that one cannot do
973 * rcu_read_unlock() while holding a scheduler (or nested) lock when
974 * part of the read side critical section was preemptible -- see
975 * rcu_read_unlock_special().
977 * Since ctx->lock nests under rq->lock we must ensure the entire read
978 * side critical section is non-preemptible.
980 preempt_disable();
981 rcu_read_lock();
982 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
983 if (ctx) {
985 * If this context is a clone of another, it might
986 * get swapped for another underneath us by
987 * perf_event_task_sched_out, though the
988 * rcu_read_lock() protects us from any context
989 * getting freed. Lock the context and check if it
990 * got swapped before we could get the lock, and retry
991 * if so. If we locked the right context, then it
992 * can't get swapped on us any more.
994 raw_spin_lock_irqsave(&ctx->lock, *flags);
995 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
996 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
997 rcu_read_unlock();
998 preempt_enable();
999 goto retry;
1002 if (!atomic_inc_not_zero(&ctx->refcount)) {
1003 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
1004 ctx = NULL;
1007 rcu_read_unlock();
1008 preempt_enable();
1009 return ctx;
1013 * Get the context for a task and increment its pin_count so it
1014 * can't get swapped to another task. This also increments its
1015 * reference count so that the context can't get freed.
1017 static struct perf_event_context *
1018 perf_pin_task_context(struct task_struct *task, int ctxn)
1020 struct perf_event_context *ctx;
1021 unsigned long flags;
1023 ctx = perf_lock_task_context(task, ctxn, &flags);
1024 if (ctx) {
1025 ++ctx->pin_count;
1026 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1028 return ctx;
1031 static void perf_unpin_context(struct perf_event_context *ctx)
1033 unsigned long flags;
1035 raw_spin_lock_irqsave(&ctx->lock, flags);
1036 --ctx->pin_count;
1037 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1041 * Update the record of the current time in a context.
1043 static void update_context_time(struct perf_event_context *ctx)
1045 u64 now = perf_clock();
1047 ctx->time += now - ctx->timestamp;
1048 ctx->timestamp = now;
1051 static u64 perf_event_time(struct perf_event *event)
1053 struct perf_event_context *ctx = event->ctx;
1055 if (is_cgroup_event(event))
1056 return perf_cgroup_event_time(event);
1058 return ctx ? ctx->time : 0;
1062 * Update the total_time_enabled and total_time_running fields for a event.
1063 * The caller of this function needs to hold the ctx->lock.
1065 static void update_event_times(struct perf_event *event)
1067 struct perf_event_context *ctx = event->ctx;
1068 u64 run_end;
1070 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1071 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1072 return;
1074 * in cgroup mode, time_enabled represents
1075 * the time the event was enabled AND active
1076 * tasks were in the monitored cgroup. This is
1077 * independent of the activity of the context as
1078 * there may be a mix of cgroup and non-cgroup events.
1080 * That is why we treat cgroup events differently
1081 * here.
1083 if (is_cgroup_event(event))
1084 run_end = perf_cgroup_event_time(event);
1085 else if (ctx->is_active)
1086 run_end = ctx->time;
1087 else
1088 run_end = event->tstamp_stopped;
1090 event->total_time_enabled = run_end - event->tstamp_enabled;
1092 if (event->state == PERF_EVENT_STATE_INACTIVE)
1093 run_end = event->tstamp_stopped;
1094 else
1095 run_end = perf_event_time(event);
1097 event->total_time_running = run_end - event->tstamp_running;
1102 * Update total_time_enabled and total_time_running for all events in a group.
1104 static void update_group_times(struct perf_event *leader)
1106 struct perf_event *event;
1108 update_event_times(leader);
1109 list_for_each_entry(event, &leader->sibling_list, group_entry)
1110 update_event_times(event);
1113 static struct list_head *
1114 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1116 if (event->attr.pinned)
1117 return &ctx->pinned_groups;
1118 else
1119 return &ctx->flexible_groups;
1123 * Add a event from the lists for its context.
1124 * Must be called with ctx->mutex and ctx->lock held.
1126 static void
1127 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1129 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1130 event->attach_state |= PERF_ATTACH_CONTEXT;
1133 * If we're a stand alone event or group leader, we go to the context
1134 * list, group events are kept attached to the group so that
1135 * perf_group_detach can, at all times, locate all siblings.
1137 if (event->group_leader == event) {
1138 struct list_head *list;
1140 if (is_software_event(event))
1141 event->group_flags |= PERF_GROUP_SOFTWARE;
1143 list = ctx_group_list(event, ctx);
1144 list_add_tail(&event->group_entry, list);
1147 if (is_cgroup_event(event))
1148 ctx->nr_cgroups++;
1150 if (has_branch_stack(event))
1151 ctx->nr_branch_stack++;
1153 list_add_rcu(&event->event_entry, &ctx->event_list);
1154 if (!ctx->nr_events)
1155 perf_pmu_rotate_start(ctx->pmu);
1156 ctx->nr_events++;
1157 if (event->attr.inherit_stat)
1158 ctx->nr_stat++;
1160 ctx->generation++;
1164 * Initialize event state based on the perf_event_attr::disabled.
1166 static inline void perf_event__state_init(struct perf_event *event)
1168 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1169 PERF_EVENT_STATE_INACTIVE;
1173 * Called at perf_event creation and when events are attached/detached from a
1174 * group.
1176 static void perf_event__read_size(struct perf_event *event)
1178 int entry = sizeof(u64); /* value */
1179 int size = 0;
1180 int nr = 1;
1182 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1183 size += sizeof(u64);
1185 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1186 size += sizeof(u64);
1188 if (event->attr.read_format & PERF_FORMAT_ID)
1189 entry += sizeof(u64);
1191 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1192 nr += event->group_leader->nr_siblings;
1193 size += sizeof(u64);
1196 size += entry * nr;
1197 event->read_size = size;
1200 static void perf_event__header_size(struct perf_event *event)
1202 struct perf_sample_data *data;
1203 u64 sample_type = event->attr.sample_type;
1204 u16 size = 0;
1206 perf_event__read_size(event);
1208 if (sample_type & PERF_SAMPLE_IP)
1209 size += sizeof(data->ip);
1211 if (sample_type & PERF_SAMPLE_ADDR)
1212 size += sizeof(data->addr);
1214 if (sample_type & PERF_SAMPLE_PERIOD)
1215 size += sizeof(data->period);
1217 if (sample_type & PERF_SAMPLE_WEIGHT)
1218 size += sizeof(data->weight);
1220 if (sample_type & PERF_SAMPLE_READ)
1221 size += event->read_size;
1223 if (sample_type & PERF_SAMPLE_DATA_SRC)
1224 size += sizeof(data->data_src.val);
1226 if (sample_type & PERF_SAMPLE_TRANSACTION)
1227 size += sizeof(data->txn);
1229 event->header_size = size;
1232 static void perf_event__id_header_size(struct perf_event *event)
1234 struct perf_sample_data *data;
1235 u64 sample_type = event->attr.sample_type;
1236 u16 size = 0;
1238 if (sample_type & PERF_SAMPLE_TID)
1239 size += sizeof(data->tid_entry);
1241 if (sample_type & PERF_SAMPLE_TIME)
1242 size += sizeof(data->time);
1244 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1245 size += sizeof(data->id);
1247 if (sample_type & PERF_SAMPLE_ID)
1248 size += sizeof(data->id);
1250 if (sample_type & PERF_SAMPLE_STREAM_ID)
1251 size += sizeof(data->stream_id);
1253 if (sample_type & PERF_SAMPLE_CPU)
1254 size += sizeof(data->cpu_entry);
1256 event->id_header_size = size;
1259 static void perf_group_attach(struct perf_event *event)
1261 struct perf_event *group_leader = event->group_leader, *pos;
1264 * We can have double attach due to group movement in perf_event_open.
1266 if (event->attach_state & PERF_ATTACH_GROUP)
1267 return;
1269 event->attach_state |= PERF_ATTACH_GROUP;
1271 if (group_leader == event)
1272 return;
1274 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1275 !is_software_event(event))
1276 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1278 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1279 group_leader->nr_siblings++;
1281 perf_event__header_size(group_leader);
1283 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1284 perf_event__header_size(pos);
1288 * Remove a event from the lists for its context.
1289 * Must be called with ctx->mutex and ctx->lock held.
1291 static void
1292 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1294 struct perf_cpu_context *cpuctx;
1296 * We can have double detach due to exit/hot-unplug + close.
1298 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1299 return;
1301 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1303 if (is_cgroup_event(event)) {
1304 ctx->nr_cgroups--;
1305 cpuctx = __get_cpu_context(ctx);
1307 * if there are no more cgroup events
1308 * then cler cgrp to avoid stale pointer
1309 * in update_cgrp_time_from_cpuctx()
1311 if (!ctx->nr_cgroups)
1312 cpuctx->cgrp = NULL;
1315 if (has_branch_stack(event))
1316 ctx->nr_branch_stack--;
1318 ctx->nr_events--;
1319 if (event->attr.inherit_stat)
1320 ctx->nr_stat--;
1322 list_del_rcu(&event->event_entry);
1324 if (event->group_leader == event)
1325 list_del_init(&event->group_entry);
1327 update_group_times(event);
1330 * If event was in error state, then keep it
1331 * that way, otherwise bogus counts will be
1332 * returned on read(). The only way to get out
1333 * of error state is by explicit re-enabling
1334 * of the event
1336 if (event->state > PERF_EVENT_STATE_OFF)
1337 event->state = PERF_EVENT_STATE_OFF;
1339 ctx->generation++;
1342 static void perf_group_detach(struct perf_event *event)
1344 struct perf_event *sibling, *tmp;
1345 struct list_head *list = NULL;
1348 * We can have double detach due to exit/hot-unplug + close.
1350 if (!(event->attach_state & PERF_ATTACH_GROUP))
1351 return;
1353 event->attach_state &= ~PERF_ATTACH_GROUP;
1356 * If this is a sibling, remove it from its group.
1358 if (event->group_leader != event) {
1359 list_del_init(&event->group_entry);
1360 event->group_leader->nr_siblings--;
1361 goto out;
1364 if (!list_empty(&event->group_entry))
1365 list = &event->group_entry;
1368 * If this was a group event with sibling events then
1369 * upgrade the siblings to singleton events by adding them
1370 * to whatever list we are on.
1372 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1373 if (list)
1374 list_move_tail(&sibling->group_entry, list);
1375 sibling->group_leader = sibling;
1377 /* Inherit group flags from the previous leader */
1378 sibling->group_flags = event->group_flags;
1381 out:
1382 perf_event__header_size(event->group_leader);
1384 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1385 perf_event__header_size(tmp);
1388 static inline int
1389 event_filter_match(struct perf_event *event)
1391 return (event->cpu == -1 || event->cpu == smp_processor_id())
1392 && perf_cgroup_match(event);
1395 static void
1396 event_sched_out(struct perf_event *event,
1397 struct perf_cpu_context *cpuctx,
1398 struct perf_event_context *ctx)
1400 u64 tstamp = perf_event_time(event);
1401 u64 delta;
1403 * An event which could not be activated because of
1404 * filter mismatch still needs to have its timings
1405 * maintained, otherwise bogus information is return
1406 * via read() for time_enabled, time_running:
1408 if (event->state == PERF_EVENT_STATE_INACTIVE
1409 && !event_filter_match(event)) {
1410 delta = tstamp - event->tstamp_stopped;
1411 event->tstamp_running += delta;
1412 event->tstamp_stopped = tstamp;
1415 if (event->state != PERF_EVENT_STATE_ACTIVE)
1416 return;
1418 perf_pmu_disable(event->pmu);
1420 event->state = PERF_EVENT_STATE_INACTIVE;
1421 if (event->pending_disable) {
1422 event->pending_disable = 0;
1423 event->state = PERF_EVENT_STATE_OFF;
1425 event->tstamp_stopped = tstamp;
1426 event->pmu->del(event, 0);
1427 event->oncpu = -1;
1429 if (!is_software_event(event))
1430 cpuctx->active_oncpu--;
1431 ctx->nr_active--;
1432 if (event->attr.freq && event->attr.sample_freq)
1433 ctx->nr_freq--;
1434 if (event->attr.exclusive || !cpuctx->active_oncpu)
1435 cpuctx->exclusive = 0;
1437 perf_pmu_enable(event->pmu);
1440 static void
1441 group_sched_out(struct perf_event *group_event,
1442 struct perf_cpu_context *cpuctx,
1443 struct perf_event_context *ctx)
1445 struct perf_event *event;
1446 int state = group_event->state;
1448 event_sched_out(group_event, cpuctx, ctx);
1451 * Schedule out siblings (if any):
1453 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1454 event_sched_out(event, cpuctx, ctx);
1456 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1457 cpuctx->exclusive = 0;
1460 struct remove_event {
1461 struct perf_event *event;
1462 bool detach_group;
1466 * Cross CPU call to remove a performance event
1468 * We disable the event on the hardware level first. After that we
1469 * remove it from the context list.
1471 static int __perf_remove_from_context(void *info)
1473 struct remove_event *re = info;
1474 struct perf_event *event = re->event;
1475 struct perf_event_context *ctx = event->ctx;
1476 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1478 raw_spin_lock(&ctx->lock);
1479 event_sched_out(event, cpuctx, ctx);
1480 if (re->detach_group)
1481 perf_group_detach(event);
1482 list_del_event(event, ctx);
1483 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1484 ctx->is_active = 0;
1485 cpuctx->task_ctx = NULL;
1487 raw_spin_unlock(&ctx->lock);
1489 return 0;
1494 * Remove the event from a task's (or a CPU's) list of events.
1496 * CPU events are removed with a smp call. For task events we only
1497 * call when the task is on a CPU.
1499 * If event->ctx is a cloned context, callers must make sure that
1500 * every task struct that event->ctx->task could possibly point to
1501 * remains valid. This is OK when called from perf_release since
1502 * that only calls us on the top-level context, which can't be a clone.
1503 * When called from perf_event_exit_task, it's OK because the
1504 * context has been detached from its task.
1506 static void perf_remove_from_context(struct perf_event *event, bool detach_group)
1508 struct perf_event_context *ctx = event->ctx;
1509 struct task_struct *task = ctx->task;
1510 struct remove_event re = {
1511 .event = event,
1512 .detach_group = detach_group,
1515 lockdep_assert_held(&ctx->mutex);
1517 if (!task) {
1519 * Per cpu events are removed via an smp call and
1520 * the removal is always successful.
1522 cpu_function_call(event->cpu, __perf_remove_from_context, &re);
1523 return;
1526 retry:
1527 if (!task_function_call(task, __perf_remove_from_context, &re))
1528 return;
1530 raw_spin_lock_irq(&ctx->lock);
1532 * If we failed to find a running task, but find the context active now
1533 * that we've acquired the ctx->lock, retry.
1535 if (ctx->is_active) {
1536 raw_spin_unlock_irq(&ctx->lock);
1538 * Reload the task pointer, it might have been changed by
1539 * a concurrent perf_event_context_sched_out().
1541 task = ctx->task;
1542 goto retry;
1546 * Since the task isn't running, its safe to remove the event, us
1547 * holding the ctx->lock ensures the task won't get scheduled in.
1549 if (detach_group)
1550 perf_group_detach(event);
1551 list_del_event(event, ctx);
1552 raw_spin_unlock_irq(&ctx->lock);
1556 * Cross CPU call to disable a performance event
1558 int __perf_event_disable(void *info)
1560 struct perf_event *event = info;
1561 struct perf_event_context *ctx = event->ctx;
1562 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1565 * If this is a per-task event, need to check whether this
1566 * event's task is the current task on this cpu.
1568 * Can trigger due to concurrent perf_event_context_sched_out()
1569 * flipping contexts around.
1571 if (ctx->task && cpuctx->task_ctx != ctx)
1572 return -EINVAL;
1574 raw_spin_lock(&ctx->lock);
1577 * If the event is on, turn it off.
1578 * If it is in error state, leave it in error state.
1580 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1581 update_context_time(ctx);
1582 update_cgrp_time_from_event(event);
1583 update_group_times(event);
1584 if (event == event->group_leader)
1585 group_sched_out(event, cpuctx, ctx);
1586 else
1587 event_sched_out(event, cpuctx, ctx);
1588 event->state = PERF_EVENT_STATE_OFF;
1591 raw_spin_unlock(&ctx->lock);
1593 return 0;
1597 * Disable a event.
1599 * If event->ctx is a cloned context, callers must make sure that
1600 * every task struct that event->ctx->task could possibly point to
1601 * remains valid. This condition is satisifed when called through
1602 * perf_event_for_each_child or perf_event_for_each because they
1603 * hold the top-level event's child_mutex, so any descendant that
1604 * goes to exit will block in sync_child_event.
1605 * When called from perf_pending_event it's OK because event->ctx
1606 * is the current context on this CPU and preemption is disabled,
1607 * hence we can't get into perf_event_task_sched_out for this context.
1609 void perf_event_disable(struct perf_event *event)
1611 struct perf_event_context *ctx = event->ctx;
1612 struct task_struct *task = ctx->task;
1614 if (!task) {
1616 * Disable the event on the cpu that it's on
1618 cpu_function_call(event->cpu, __perf_event_disable, event);
1619 return;
1622 retry:
1623 if (!task_function_call(task, __perf_event_disable, event))
1624 return;
1626 raw_spin_lock_irq(&ctx->lock);
1628 * If the event is still active, we need to retry the cross-call.
1630 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1631 raw_spin_unlock_irq(&ctx->lock);
1633 * Reload the task pointer, it might have been changed by
1634 * a concurrent perf_event_context_sched_out().
1636 task = ctx->task;
1637 goto retry;
1641 * Since we have the lock this context can't be scheduled
1642 * in, so we can change the state safely.
1644 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1645 update_group_times(event);
1646 event->state = PERF_EVENT_STATE_OFF;
1648 raw_spin_unlock_irq(&ctx->lock);
1650 EXPORT_SYMBOL_GPL(perf_event_disable);
1652 static void perf_set_shadow_time(struct perf_event *event,
1653 struct perf_event_context *ctx,
1654 u64 tstamp)
1657 * use the correct time source for the time snapshot
1659 * We could get by without this by leveraging the
1660 * fact that to get to this function, the caller
1661 * has most likely already called update_context_time()
1662 * and update_cgrp_time_xx() and thus both timestamp
1663 * are identical (or very close). Given that tstamp is,
1664 * already adjusted for cgroup, we could say that:
1665 * tstamp - ctx->timestamp
1666 * is equivalent to
1667 * tstamp - cgrp->timestamp.
1669 * Then, in perf_output_read(), the calculation would
1670 * work with no changes because:
1671 * - event is guaranteed scheduled in
1672 * - no scheduled out in between
1673 * - thus the timestamp would be the same
1675 * But this is a bit hairy.
1677 * So instead, we have an explicit cgroup call to remain
1678 * within the time time source all along. We believe it
1679 * is cleaner and simpler to understand.
1681 if (is_cgroup_event(event))
1682 perf_cgroup_set_shadow_time(event, tstamp);
1683 else
1684 event->shadow_ctx_time = tstamp - ctx->timestamp;
1687 #define MAX_INTERRUPTS (~0ULL)
1689 static void perf_log_throttle(struct perf_event *event, int enable);
1691 static int
1692 event_sched_in(struct perf_event *event,
1693 struct perf_cpu_context *cpuctx,
1694 struct perf_event_context *ctx)
1696 u64 tstamp = perf_event_time(event);
1697 int ret = 0;
1699 lockdep_assert_held(&ctx->lock);
1701 if (event->state <= PERF_EVENT_STATE_OFF)
1702 return 0;
1704 event->state = PERF_EVENT_STATE_ACTIVE;
1705 event->oncpu = smp_processor_id();
1708 * Unthrottle events, since we scheduled we might have missed several
1709 * ticks already, also for a heavily scheduling task there is little
1710 * guarantee it'll get a tick in a timely manner.
1712 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1713 perf_log_throttle(event, 1);
1714 event->hw.interrupts = 0;
1718 * The new state must be visible before we turn it on in the hardware:
1720 smp_wmb();
1722 perf_pmu_disable(event->pmu);
1724 if (event->pmu->add(event, PERF_EF_START)) {
1725 event->state = PERF_EVENT_STATE_INACTIVE;
1726 event->oncpu = -1;
1727 ret = -EAGAIN;
1728 goto out;
1731 event->tstamp_running += tstamp - event->tstamp_stopped;
1733 perf_set_shadow_time(event, ctx, tstamp);
1735 if (!is_software_event(event))
1736 cpuctx->active_oncpu++;
1737 ctx->nr_active++;
1738 if (event->attr.freq && event->attr.sample_freq)
1739 ctx->nr_freq++;
1741 if (event->attr.exclusive)
1742 cpuctx->exclusive = 1;
1744 out:
1745 perf_pmu_enable(event->pmu);
1747 return ret;
1750 static int
1751 group_sched_in(struct perf_event *group_event,
1752 struct perf_cpu_context *cpuctx,
1753 struct perf_event_context *ctx)
1755 struct perf_event *event, *partial_group = NULL;
1756 struct pmu *pmu = ctx->pmu;
1757 u64 now = ctx->time;
1758 bool simulate = false;
1760 if (group_event->state == PERF_EVENT_STATE_OFF)
1761 return 0;
1763 pmu->start_txn(pmu);
1765 if (event_sched_in(group_event, cpuctx, ctx)) {
1766 pmu->cancel_txn(pmu);
1767 perf_cpu_hrtimer_restart(cpuctx);
1768 return -EAGAIN;
1772 * Schedule in siblings as one group (if any):
1774 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1775 if (event_sched_in(event, cpuctx, ctx)) {
1776 partial_group = event;
1777 goto group_error;
1781 if (!pmu->commit_txn(pmu))
1782 return 0;
1784 group_error:
1786 * Groups can be scheduled in as one unit only, so undo any
1787 * partial group before returning:
1788 * The events up to the failed event are scheduled out normally,
1789 * tstamp_stopped will be updated.
1791 * The failed events and the remaining siblings need to have
1792 * their timings updated as if they had gone thru event_sched_in()
1793 * and event_sched_out(). This is required to get consistent timings
1794 * across the group. This also takes care of the case where the group
1795 * could never be scheduled by ensuring tstamp_stopped is set to mark
1796 * the time the event was actually stopped, such that time delta
1797 * calculation in update_event_times() is correct.
1799 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1800 if (event == partial_group)
1801 simulate = true;
1803 if (simulate) {
1804 event->tstamp_running += now - event->tstamp_stopped;
1805 event->tstamp_stopped = now;
1806 } else {
1807 event_sched_out(event, cpuctx, ctx);
1810 event_sched_out(group_event, cpuctx, ctx);
1812 pmu->cancel_txn(pmu);
1814 perf_cpu_hrtimer_restart(cpuctx);
1816 return -EAGAIN;
1820 * Work out whether we can put this event group on the CPU now.
1822 static int group_can_go_on(struct perf_event *event,
1823 struct perf_cpu_context *cpuctx,
1824 int can_add_hw)
1827 * Groups consisting entirely of software events can always go on.
1829 if (event->group_flags & PERF_GROUP_SOFTWARE)
1830 return 1;
1832 * If an exclusive group is already on, no other hardware
1833 * events can go on.
1835 if (cpuctx->exclusive)
1836 return 0;
1838 * If this group is exclusive and there are already
1839 * events on the CPU, it can't go on.
1841 if (event->attr.exclusive && cpuctx->active_oncpu)
1842 return 0;
1844 * Otherwise, try to add it if all previous groups were able
1845 * to go on.
1847 return can_add_hw;
1850 static void add_event_to_ctx(struct perf_event *event,
1851 struct perf_event_context *ctx)
1853 u64 tstamp = perf_event_time(event);
1855 list_add_event(event, ctx);
1856 perf_group_attach(event);
1857 event->tstamp_enabled = tstamp;
1858 event->tstamp_running = tstamp;
1859 event->tstamp_stopped = tstamp;
1862 static void task_ctx_sched_out(struct perf_event_context *ctx);
1863 static void
1864 ctx_sched_in(struct perf_event_context *ctx,
1865 struct perf_cpu_context *cpuctx,
1866 enum event_type_t event_type,
1867 struct task_struct *task);
1869 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
1870 struct perf_event_context *ctx,
1871 struct task_struct *task)
1873 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
1874 if (ctx)
1875 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
1876 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
1877 if (ctx)
1878 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
1882 * Cross CPU call to install and enable a performance event
1884 * Must be called with ctx->mutex held
1886 static int __perf_install_in_context(void *info)
1888 struct perf_event *event = info;
1889 struct perf_event_context *ctx = event->ctx;
1890 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1891 struct perf_event_context *task_ctx = cpuctx->task_ctx;
1892 struct task_struct *task = current;
1894 perf_ctx_lock(cpuctx, task_ctx);
1895 perf_pmu_disable(cpuctx->ctx.pmu);
1898 * If there was an active task_ctx schedule it out.
1900 if (task_ctx)
1901 task_ctx_sched_out(task_ctx);
1904 * If the context we're installing events in is not the
1905 * active task_ctx, flip them.
1907 if (ctx->task && task_ctx != ctx) {
1908 if (task_ctx)
1909 raw_spin_unlock(&task_ctx->lock);
1910 raw_spin_lock(&ctx->lock);
1911 task_ctx = ctx;
1914 if (task_ctx) {
1915 cpuctx->task_ctx = task_ctx;
1916 task = task_ctx->task;
1919 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
1921 update_context_time(ctx);
1923 * update cgrp time only if current cgrp
1924 * matches event->cgrp. Must be done before
1925 * calling add_event_to_ctx()
1927 update_cgrp_time_from_event(event);
1929 add_event_to_ctx(event, ctx);
1932 * Schedule everything back in
1934 perf_event_sched_in(cpuctx, task_ctx, task);
1936 perf_pmu_enable(cpuctx->ctx.pmu);
1937 perf_ctx_unlock(cpuctx, task_ctx);
1939 return 0;
1943 * Attach a performance event to a context
1945 * First we add the event to the list with the hardware enable bit
1946 * in event->hw_config cleared.
1948 * If the event is attached to a task which is on a CPU we use a smp
1949 * call to enable it in the task context. The task might have been
1950 * scheduled away, but we check this in the smp call again.
1952 static void
1953 perf_install_in_context(struct perf_event_context *ctx,
1954 struct perf_event *event,
1955 int cpu)
1957 struct task_struct *task = ctx->task;
1959 lockdep_assert_held(&ctx->mutex);
1961 event->ctx = ctx;
1962 if (event->cpu != -1)
1963 event->cpu = cpu;
1965 if (!task) {
1967 * Per cpu events are installed via an smp call and
1968 * the install is always successful.
1970 cpu_function_call(cpu, __perf_install_in_context, event);
1971 return;
1974 retry:
1975 if (!task_function_call(task, __perf_install_in_context, event))
1976 return;
1978 raw_spin_lock_irq(&ctx->lock);
1980 * If we failed to find a running task, but find the context active now
1981 * that we've acquired the ctx->lock, retry.
1983 if (ctx->is_active) {
1984 raw_spin_unlock_irq(&ctx->lock);
1986 * Reload the task pointer, it might have been changed by
1987 * a concurrent perf_event_context_sched_out().
1989 task = ctx->task;
1990 goto retry;
1994 * Since the task isn't running, its safe to add the event, us holding
1995 * the ctx->lock ensures the task won't get scheduled in.
1997 add_event_to_ctx(event, ctx);
1998 raw_spin_unlock_irq(&ctx->lock);
2002 * Put a event into inactive state and update time fields.
2003 * Enabling the leader of a group effectively enables all
2004 * the group members that aren't explicitly disabled, so we
2005 * have to update their ->tstamp_enabled also.
2006 * Note: this works for group members as well as group leaders
2007 * since the non-leader members' sibling_lists will be empty.
2009 static void __perf_event_mark_enabled(struct perf_event *event)
2011 struct perf_event *sub;
2012 u64 tstamp = perf_event_time(event);
2014 event->state = PERF_EVENT_STATE_INACTIVE;
2015 event->tstamp_enabled = tstamp - event->total_time_enabled;
2016 list_for_each_entry(sub, &event->sibling_list, group_entry) {
2017 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2018 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2023 * Cross CPU call to enable a performance event
2025 static int __perf_event_enable(void *info)
2027 struct perf_event *event = info;
2028 struct perf_event_context *ctx = event->ctx;
2029 struct perf_event *leader = event->group_leader;
2030 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2031 int err;
2034 * There's a time window between 'ctx->is_active' check
2035 * in perf_event_enable function and this place having:
2036 * - IRQs on
2037 * - ctx->lock unlocked
2039 * where the task could be killed and 'ctx' deactivated
2040 * by perf_event_exit_task.
2042 if (!ctx->is_active)
2043 return -EINVAL;
2045 raw_spin_lock(&ctx->lock);
2046 update_context_time(ctx);
2048 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2049 goto unlock;
2052 * set current task's cgroup time reference point
2054 perf_cgroup_set_timestamp(current, ctx);
2056 __perf_event_mark_enabled(event);
2058 if (!event_filter_match(event)) {
2059 if (is_cgroup_event(event))
2060 perf_cgroup_defer_enabled(event);
2061 goto unlock;
2065 * If the event is in a group and isn't the group leader,
2066 * then don't put it on unless the group is on.
2068 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
2069 goto unlock;
2071 if (!group_can_go_on(event, cpuctx, 1)) {
2072 err = -EEXIST;
2073 } else {
2074 if (event == leader)
2075 err = group_sched_in(event, cpuctx, ctx);
2076 else
2077 err = event_sched_in(event, cpuctx, ctx);
2080 if (err) {
2082 * If this event can't go on and it's part of a
2083 * group, then the whole group has to come off.
2085 if (leader != event) {
2086 group_sched_out(leader, cpuctx, ctx);
2087 perf_cpu_hrtimer_restart(cpuctx);
2089 if (leader->attr.pinned) {
2090 update_group_times(leader);
2091 leader->state = PERF_EVENT_STATE_ERROR;
2095 unlock:
2096 raw_spin_unlock(&ctx->lock);
2098 return 0;
2102 * Enable a event.
2104 * If event->ctx is a cloned context, callers must make sure that
2105 * every task struct that event->ctx->task could possibly point to
2106 * remains valid. This condition is satisfied when called through
2107 * perf_event_for_each_child or perf_event_for_each as described
2108 * for perf_event_disable.
2110 void perf_event_enable(struct perf_event *event)
2112 struct perf_event_context *ctx = event->ctx;
2113 struct task_struct *task = ctx->task;
2115 if (!task) {
2117 * Enable the event on the cpu that it's on
2119 cpu_function_call(event->cpu, __perf_event_enable, event);
2120 return;
2123 raw_spin_lock_irq(&ctx->lock);
2124 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2125 goto out;
2128 * If the event is in error state, clear that first.
2129 * That way, if we see the event in error state below, we
2130 * know that it has gone back into error state, as distinct
2131 * from the task having been scheduled away before the
2132 * cross-call arrived.
2134 if (event->state == PERF_EVENT_STATE_ERROR)
2135 event->state = PERF_EVENT_STATE_OFF;
2137 retry:
2138 if (!ctx->is_active) {
2139 __perf_event_mark_enabled(event);
2140 goto out;
2143 raw_spin_unlock_irq(&ctx->lock);
2145 if (!task_function_call(task, __perf_event_enable, event))
2146 return;
2148 raw_spin_lock_irq(&ctx->lock);
2151 * If the context is active and the event is still off,
2152 * we need to retry the cross-call.
2154 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
2156 * task could have been flipped by a concurrent
2157 * perf_event_context_sched_out()
2159 task = ctx->task;
2160 goto retry;
2163 out:
2164 raw_spin_unlock_irq(&ctx->lock);
2166 EXPORT_SYMBOL_GPL(perf_event_enable);
2168 int perf_event_refresh(struct perf_event *event, int refresh)
2171 * not supported on inherited events
2173 if (event->attr.inherit || !is_sampling_event(event))
2174 return -EINVAL;
2176 atomic_add(refresh, &event->event_limit);
2177 perf_event_enable(event);
2179 return 0;
2181 EXPORT_SYMBOL_GPL(perf_event_refresh);
2183 static void ctx_sched_out(struct perf_event_context *ctx,
2184 struct perf_cpu_context *cpuctx,
2185 enum event_type_t event_type)
2187 struct perf_event *event;
2188 int is_active = ctx->is_active;
2190 ctx->is_active &= ~event_type;
2191 if (likely(!ctx->nr_events))
2192 return;
2194 update_context_time(ctx);
2195 update_cgrp_time_from_cpuctx(cpuctx);
2196 if (!ctx->nr_active)
2197 return;
2199 perf_pmu_disable(ctx->pmu);
2200 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2201 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2202 group_sched_out(event, cpuctx, ctx);
2205 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2206 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2207 group_sched_out(event, cpuctx, ctx);
2209 perf_pmu_enable(ctx->pmu);
2213 * Test whether two contexts are equivalent, i.e. whether they have both been
2214 * cloned from the same version of the same context.
2216 * Equivalence is measured using a generation number in the context that is
2217 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2218 * and list_del_event().
2220 static int context_equiv(struct perf_event_context *ctx1,
2221 struct perf_event_context *ctx2)
2223 lockdep_assert_held(&ctx1->lock);
2224 lockdep_assert_held(&ctx2->lock);
2226 /* Pinning disables the swap optimization */
2227 if (ctx1->pin_count || ctx2->pin_count)
2228 return 0;
2230 /* If ctx1 is the parent of ctx2 */
2231 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2232 return 1;
2234 /* If ctx2 is the parent of ctx1 */
2235 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2236 return 1;
2239 * If ctx1 and ctx2 have the same parent; we flatten the parent
2240 * hierarchy, see perf_event_init_context().
2242 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2243 ctx1->parent_gen == ctx2->parent_gen)
2244 return 1;
2246 /* Unmatched */
2247 return 0;
2250 static void __perf_event_sync_stat(struct perf_event *event,
2251 struct perf_event *next_event)
2253 u64 value;
2255 if (!event->attr.inherit_stat)
2256 return;
2259 * Update the event value, we cannot use perf_event_read()
2260 * because we're in the middle of a context switch and have IRQs
2261 * disabled, which upsets smp_call_function_single(), however
2262 * we know the event must be on the current CPU, therefore we
2263 * don't need to use it.
2265 switch (event->state) {
2266 case PERF_EVENT_STATE_ACTIVE:
2267 event->pmu->read(event);
2268 /* fall-through */
2270 case PERF_EVENT_STATE_INACTIVE:
2271 update_event_times(event);
2272 break;
2274 default:
2275 break;
2279 * In order to keep per-task stats reliable we need to flip the event
2280 * values when we flip the contexts.
2282 value = local64_read(&next_event->count);
2283 value = local64_xchg(&event->count, value);
2284 local64_set(&next_event->count, value);
2286 swap(event->total_time_enabled, next_event->total_time_enabled);
2287 swap(event->total_time_running, next_event->total_time_running);
2290 * Since we swizzled the values, update the user visible data too.
2292 perf_event_update_userpage(event);
2293 perf_event_update_userpage(next_event);
2296 static void perf_event_sync_stat(struct perf_event_context *ctx,
2297 struct perf_event_context *next_ctx)
2299 struct perf_event *event, *next_event;
2301 if (!ctx->nr_stat)
2302 return;
2304 update_context_time(ctx);
2306 event = list_first_entry(&ctx->event_list,
2307 struct perf_event, event_entry);
2309 next_event = list_first_entry(&next_ctx->event_list,
2310 struct perf_event, event_entry);
2312 while (&event->event_entry != &ctx->event_list &&
2313 &next_event->event_entry != &next_ctx->event_list) {
2315 __perf_event_sync_stat(event, next_event);
2317 event = list_next_entry(event, event_entry);
2318 next_event = list_next_entry(next_event, event_entry);
2322 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2323 struct task_struct *next)
2325 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2326 struct perf_event_context *next_ctx;
2327 struct perf_event_context *parent, *next_parent;
2328 struct perf_cpu_context *cpuctx;
2329 int do_switch = 1;
2331 if (likely(!ctx))
2332 return;
2334 cpuctx = __get_cpu_context(ctx);
2335 if (!cpuctx->task_ctx)
2336 return;
2338 rcu_read_lock();
2339 next_ctx = next->perf_event_ctxp[ctxn];
2340 if (!next_ctx)
2341 goto unlock;
2343 parent = rcu_dereference(ctx->parent_ctx);
2344 next_parent = rcu_dereference(next_ctx->parent_ctx);
2346 /* If neither context have a parent context; they cannot be clones. */
2347 if (!parent || !next_parent)
2348 goto unlock;
2350 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2352 * Looks like the two contexts are clones, so we might be
2353 * able to optimize the context switch. We lock both
2354 * contexts and check that they are clones under the
2355 * lock (including re-checking that neither has been
2356 * uncloned in the meantime). It doesn't matter which
2357 * order we take the locks because no other cpu could
2358 * be trying to lock both of these tasks.
2360 raw_spin_lock(&ctx->lock);
2361 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2362 if (context_equiv(ctx, next_ctx)) {
2364 * XXX do we need a memory barrier of sorts
2365 * wrt to rcu_dereference() of perf_event_ctxp
2367 task->perf_event_ctxp[ctxn] = next_ctx;
2368 next->perf_event_ctxp[ctxn] = ctx;
2369 ctx->task = next;
2370 next_ctx->task = task;
2371 do_switch = 0;
2373 perf_event_sync_stat(ctx, next_ctx);
2375 raw_spin_unlock(&next_ctx->lock);
2376 raw_spin_unlock(&ctx->lock);
2378 unlock:
2379 rcu_read_unlock();
2381 if (do_switch) {
2382 raw_spin_lock(&ctx->lock);
2383 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2384 cpuctx->task_ctx = NULL;
2385 raw_spin_unlock(&ctx->lock);
2389 #define for_each_task_context_nr(ctxn) \
2390 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2393 * Called from scheduler to remove the events of the current task,
2394 * with interrupts disabled.
2396 * We stop each event and update the event value in event->count.
2398 * This does not protect us against NMI, but disable()
2399 * sets the disabled bit in the control field of event _before_
2400 * accessing the event control register. If a NMI hits, then it will
2401 * not restart the event.
2403 void __perf_event_task_sched_out(struct task_struct *task,
2404 struct task_struct *next)
2406 int ctxn;
2408 for_each_task_context_nr(ctxn)
2409 perf_event_context_sched_out(task, ctxn, next);
2412 * if cgroup events exist on this CPU, then we need
2413 * to check if we have to switch out PMU state.
2414 * cgroup event are system-wide mode only
2416 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2417 perf_cgroup_sched_out(task, next);
2420 static void task_ctx_sched_out(struct perf_event_context *ctx)
2422 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2424 if (!cpuctx->task_ctx)
2425 return;
2427 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2428 return;
2430 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2431 cpuctx->task_ctx = NULL;
2435 * Called with IRQs disabled
2437 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2438 enum event_type_t event_type)
2440 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2443 static void
2444 ctx_pinned_sched_in(struct perf_event_context *ctx,
2445 struct perf_cpu_context *cpuctx)
2447 struct perf_event *event;
2449 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2450 if (event->state <= PERF_EVENT_STATE_OFF)
2451 continue;
2452 if (!event_filter_match(event))
2453 continue;
2455 /* may need to reset tstamp_enabled */
2456 if (is_cgroup_event(event))
2457 perf_cgroup_mark_enabled(event, ctx);
2459 if (group_can_go_on(event, cpuctx, 1))
2460 group_sched_in(event, cpuctx, ctx);
2463 * If this pinned group hasn't been scheduled,
2464 * put it in error state.
2466 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2467 update_group_times(event);
2468 event->state = PERF_EVENT_STATE_ERROR;
2473 static void
2474 ctx_flexible_sched_in(struct perf_event_context *ctx,
2475 struct perf_cpu_context *cpuctx)
2477 struct perf_event *event;
2478 int can_add_hw = 1;
2480 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2481 /* Ignore events in OFF or ERROR state */
2482 if (event->state <= PERF_EVENT_STATE_OFF)
2483 continue;
2485 * Listen to the 'cpu' scheduling filter constraint
2486 * of events:
2488 if (!event_filter_match(event))
2489 continue;
2491 /* may need to reset tstamp_enabled */
2492 if (is_cgroup_event(event))
2493 perf_cgroup_mark_enabled(event, ctx);
2495 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2496 if (group_sched_in(event, cpuctx, ctx))
2497 can_add_hw = 0;
2502 static void
2503 ctx_sched_in(struct perf_event_context *ctx,
2504 struct perf_cpu_context *cpuctx,
2505 enum event_type_t event_type,
2506 struct task_struct *task)
2508 u64 now;
2509 int is_active = ctx->is_active;
2511 ctx->is_active |= event_type;
2512 if (likely(!ctx->nr_events))
2513 return;
2515 now = perf_clock();
2516 ctx->timestamp = now;
2517 perf_cgroup_set_timestamp(task, ctx);
2519 * First go through the list and put on any pinned groups
2520 * in order to give them the best chance of going on.
2522 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2523 ctx_pinned_sched_in(ctx, cpuctx);
2525 /* Then walk through the lower prio flexible groups */
2526 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2527 ctx_flexible_sched_in(ctx, cpuctx);
2530 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2531 enum event_type_t event_type,
2532 struct task_struct *task)
2534 struct perf_event_context *ctx = &cpuctx->ctx;
2536 ctx_sched_in(ctx, cpuctx, event_type, task);
2539 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2540 struct task_struct *task)
2542 struct perf_cpu_context *cpuctx;
2544 cpuctx = __get_cpu_context(ctx);
2545 if (cpuctx->task_ctx == ctx)
2546 return;
2548 perf_ctx_lock(cpuctx, ctx);
2549 perf_pmu_disable(ctx->pmu);
2551 * We want to keep the following priority order:
2552 * cpu pinned (that don't need to move), task pinned,
2553 * cpu flexible, task flexible.
2555 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2557 if (ctx->nr_events)
2558 cpuctx->task_ctx = ctx;
2560 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2562 perf_pmu_enable(ctx->pmu);
2563 perf_ctx_unlock(cpuctx, ctx);
2566 * Since these rotations are per-cpu, we need to ensure the
2567 * cpu-context we got scheduled on is actually rotating.
2569 perf_pmu_rotate_start(ctx->pmu);
2573 * When sampling the branck stack in system-wide, it may be necessary
2574 * to flush the stack on context switch. This happens when the branch
2575 * stack does not tag its entries with the pid of the current task.
2576 * Otherwise it becomes impossible to associate a branch entry with a
2577 * task. This ambiguity is more likely to appear when the branch stack
2578 * supports priv level filtering and the user sets it to monitor only
2579 * at the user level (which could be a useful measurement in system-wide
2580 * mode). In that case, the risk is high of having a branch stack with
2581 * branch from multiple tasks. Flushing may mean dropping the existing
2582 * entries or stashing them somewhere in the PMU specific code layer.
2584 * This function provides the context switch callback to the lower code
2585 * layer. It is invoked ONLY when there is at least one system-wide context
2586 * with at least one active event using taken branch sampling.
2588 static void perf_branch_stack_sched_in(struct task_struct *prev,
2589 struct task_struct *task)
2591 struct perf_cpu_context *cpuctx;
2592 struct pmu *pmu;
2593 unsigned long flags;
2595 /* no need to flush branch stack if not changing task */
2596 if (prev == task)
2597 return;
2599 local_irq_save(flags);
2601 rcu_read_lock();
2603 list_for_each_entry_rcu(pmu, &pmus, entry) {
2604 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2607 * check if the context has at least one
2608 * event using PERF_SAMPLE_BRANCH_STACK
2610 if (cpuctx->ctx.nr_branch_stack > 0
2611 && pmu->flush_branch_stack) {
2613 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2615 perf_pmu_disable(pmu);
2617 pmu->flush_branch_stack();
2619 perf_pmu_enable(pmu);
2621 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2625 rcu_read_unlock();
2627 local_irq_restore(flags);
2631 * Called from scheduler to add the events of the current task
2632 * with interrupts disabled.
2634 * We restore the event value and then enable it.
2636 * This does not protect us against NMI, but enable()
2637 * sets the enabled bit in the control field of event _before_
2638 * accessing the event control register. If a NMI hits, then it will
2639 * keep the event running.
2641 void __perf_event_task_sched_in(struct task_struct *prev,
2642 struct task_struct *task)
2644 struct perf_event_context *ctx;
2645 int ctxn;
2647 for_each_task_context_nr(ctxn) {
2648 ctx = task->perf_event_ctxp[ctxn];
2649 if (likely(!ctx))
2650 continue;
2652 perf_event_context_sched_in(ctx, task);
2655 * if cgroup events exist on this CPU, then we need
2656 * to check if we have to switch in PMU state.
2657 * cgroup event are system-wide mode only
2659 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2660 perf_cgroup_sched_in(prev, task);
2662 /* check for system-wide branch_stack events */
2663 if (atomic_read(&__get_cpu_var(perf_branch_stack_events)))
2664 perf_branch_stack_sched_in(prev, task);
2667 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2669 u64 frequency = event->attr.sample_freq;
2670 u64 sec = NSEC_PER_SEC;
2671 u64 divisor, dividend;
2673 int count_fls, nsec_fls, frequency_fls, sec_fls;
2675 count_fls = fls64(count);
2676 nsec_fls = fls64(nsec);
2677 frequency_fls = fls64(frequency);
2678 sec_fls = 30;
2681 * We got @count in @nsec, with a target of sample_freq HZ
2682 * the target period becomes:
2684 * @count * 10^9
2685 * period = -------------------
2686 * @nsec * sample_freq
2691 * Reduce accuracy by one bit such that @a and @b converge
2692 * to a similar magnitude.
2694 #define REDUCE_FLS(a, b) \
2695 do { \
2696 if (a##_fls > b##_fls) { \
2697 a >>= 1; \
2698 a##_fls--; \
2699 } else { \
2700 b >>= 1; \
2701 b##_fls--; \
2703 } while (0)
2706 * Reduce accuracy until either term fits in a u64, then proceed with
2707 * the other, so that finally we can do a u64/u64 division.
2709 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2710 REDUCE_FLS(nsec, frequency);
2711 REDUCE_FLS(sec, count);
2714 if (count_fls + sec_fls > 64) {
2715 divisor = nsec * frequency;
2717 while (count_fls + sec_fls > 64) {
2718 REDUCE_FLS(count, sec);
2719 divisor >>= 1;
2722 dividend = count * sec;
2723 } else {
2724 dividend = count * sec;
2726 while (nsec_fls + frequency_fls > 64) {
2727 REDUCE_FLS(nsec, frequency);
2728 dividend >>= 1;
2731 divisor = nsec * frequency;
2734 if (!divisor)
2735 return dividend;
2737 return div64_u64(dividend, divisor);
2740 static DEFINE_PER_CPU(int, perf_throttled_count);
2741 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2743 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2745 struct hw_perf_event *hwc = &event->hw;
2746 s64 period, sample_period;
2747 s64 delta;
2749 period = perf_calculate_period(event, nsec, count);
2751 delta = (s64)(period - hwc->sample_period);
2752 delta = (delta + 7) / 8; /* low pass filter */
2754 sample_period = hwc->sample_period + delta;
2756 if (!sample_period)
2757 sample_period = 1;
2759 hwc->sample_period = sample_period;
2761 if (local64_read(&hwc->period_left) > 8*sample_period) {
2762 if (disable)
2763 event->pmu->stop(event, PERF_EF_UPDATE);
2765 local64_set(&hwc->period_left, 0);
2767 if (disable)
2768 event->pmu->start(event, PERF_EF_RELOAD);
2773 * combine freq adjustment with unthrottling to avoid two passes over the
2774 * events. At the same time, make sure, having freq events does not change
2775 * the rate of unthrottling as that would introduce bias.
2777 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
2778 int needs_unthr)
2780 struct perf_event *event;
2781 struct hw_perf_event *hwc;
2782 u64 now, period = TICK_NSEC;
2783 s64 delta;
2786 * only need to iterate over all events iff:
2787 * - context have events in frequency mode (needs freq adjust)
2788 * - there are events to unthrottle on this cpu
2790 if (!(ctx->nr_freq || needs_unthr))
2791 return;
2793 raw_spin_lock(&ctx->lock);
2794 perf_pmu_disable(ctx->pmu);
2796 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
2797 if (event->state != PERF_EVENT_STATE_ACTIVE)
2798 continue;
2800 if (!event_filter_match(event))
2801 continue;
2803 perf_pmu_disable(event->pmu);
2805 hwc = &event->hw;
2807 if (hwc->interrupts == MAX_INTERRUPTS) {
2808 hwc->interrupts = 0;
2809 perf_log_throttle(event, 1);
2810 event->pmu->start(event, 0);
2813 if (!event->attr.freq || !event->attr.sample_freq)
2814 goto next;
2817 * stop the event and update event->count
2819 event->pmu->stop(event, PERF_EF_UPDATE);
2821 now = local64_read(&event->count);
2822 delta = now - hwc->freq_count_stamp;
2823 hwc->freq_count_stamp = now;
2826 * restart the event
2827 * reload only if value has changed
2828 * we have stopped the event so tell that
2829 * to perf_adjust_period() to avoid stopping it
2830 * twice.
2832 if (delta > 0)
2833 perf_adjust_period(event, period, delta, false);
2835 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
2836 next:
2837 perf_pmu_enable(event->pmu);
2840 perf_pmu_enable(ctx->pmu);
2841 raw_spin_unlock(&ctx->lock);
2845 * Round-robin a context's events:
2847 static void rotate_ctx(struct perf_event_context *ctx)
2850 * Rotate the first entry last of non-pinned groups. Rotation might be
2851 * disabled by the inheritance code.
2853 if (!ctx->rotate_disable)
2854 list_rotate_left(&ctx->flexible_groups);
2858 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
2859 * because they're strictly cpu affine and rotate_start is called with IRQs
2860 * disabled, while rotate_context is called from IRQ context.
2862 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
2864 struct perf_event_context *ctx = NULL;
2865 int rotate = 0, remove = 1;
2867 if (cpuctx->ctx.nr_events) {
2868 remove = 0;
2869 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
2870 rotate = 1;
2873 ctx = cpuctx->task_ctx;
2874 if (ctx && ctx->nr_events) {
2875 remove = 0;
2876 if (ctx->nr_events != ctx->nr_active)
2877 rotate = 1;
2880 if (!rotate)
2881 goto done;
2883 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2884 perf_pmu_disable(cpuctx->ctx.pmu);
2886 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2887 if (ctx)
2888 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
2890 rotate_ctx(&cpuctx->ctx);
2891 if (ctx)
2892 rotate_ctx(ctx);
2894 perf_event_sched_in(cpuctx, ctx, current);
2896 perf_pmu_enable(cpuctx->ctx.pmu);
2897 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2898 done:
2899 if (remove)
2900 list_del_init(&cpuctx->rotation_list);
2902 return rotate;
2905 #ifdef CONFIG_NO_HZ_FULL
2906 bool perf_event_can_stop_tick(void)
2908 if (atomic_read(&nr_freq_events) ||
2909 __this_cpu_read(perf_throttled_count))
2910 return false;
2911 else
2912 return true;
2914 #endif
2916 void perf_event_task_tick(void)
2918 struct list_head *head = &__get_cpu_var(rotation_list);
2919 struct perf_cpu_context *cpuctx, *tmp;
2920 struct perf_event_context *ctx;
2921 int throttled;
2923 WARN_ON(!irqs_disabled());
2925 __this_cpu_inc(perf_throttled_seq);
2926 throttled = __this_cpu_xchg(perf_throttled_count, 0);
2928 list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) {
2929 ctx = &cpuctx->ctx;
2930 perf_adjust_freq_unthr_context(ctx, throttled);
2932 ctx = cpuctx->task_ctx;
2933 if (ctx)
2934 perf_adjust_freq_unthr_context(ctx, throttled);
2938 static int event_enable_on_exec(struct perf_event *event,
2939 struct perf_event_context *ctx)
2941 if (!event->attr.enable_on_exec)
2942 return 0;
2944 event->attr.enable_on_exec = 0;
2945 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2946 return 0;
2948 __perf_event_mark_enabled(event);
2950 return 1;
2954 * Enable all of a task's events that have been marked enable-on-exec.
2955 * This expects task == current.
2957 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
2959 struct perf_event_context *clone_ctx = NULL;
2960 struct perf_event *event;
2961 unsigned long flags;
2962 int enabled = 0;
2963 int ret;
2965 local_irq_save(flags);
2966 if (!ctx || !ctx->nr_events)
2967 goto out;
2970 * We must ctxsw out cgroup events to avoid conflict
2971 * when invoking perf_task_event_sched_in() later on
2972 * in this function. Otherwise we end up trying to
2973 * ctxswin cgroup events which are already scheduled
2974 * in.
2976 perf_cgroup_sched_out(current, NULL);
2978 raw_spin_lock(&ctx->lock);
2979 task_ctx_sched_out(ctx);
2981 list_for_each_entry(event, &ctx->event_list, event_entry) {
2982 ret = event_enable_on_exec(event, ctx);
2983 if (ret)
2984 enabled = 1;
2988 * Unclone this context if we enabled any event.
2990 if (enabled)
2991 clone_ctx = unclone_ctx(ctx);
2993 raw_spin_unlock(&ctx->lock);
2996 * Also calls ctxswin for cgroup events, if any:
2998 perf_event_context_sched_in(ctx, ctx->task);
2999 out:
3000 local_irq_restore(flags);
3002 if (clone_ctx)
3003 put_ctx(clone_ctx);
3006 void perf_event_exec(void)
3008 struct perf_event_context *ctx;
3009 int ctxn;
3011 rcu_read_lock();
3012 for_each_task_context_nr(ctxn) {
3013 ctx = current->perf_event_ctxp[ctxn];
3014 if (!ctx)
3015 continue;
3017 perf_event_enable_on_exec(ctx);
3019 rcu_read_unlock();
3023 * Cross CPU call to read the hardware event
3025 static void __perf_event_read(void *info)
3027 struct perf_event *event = info;
3028 struct perf_event_context *ctx = event->ctx;
3029 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3032 * If this is a task context, we need to check whether it is
3033 * the current task context of this cpu. If not it has been
3034 * scheduled out before the smp call arrived. In that case
3035 * event->count would have been updated to a recent sample
3036 * when the event was scheduled out.
3038 if (ctx->task && cpuctx->task_ctx != ctx)
3039 return;
3041 raw_spin_lock(&ctx->lock);
3042 if (ctx->is_active) {
3043 update_context_time(ctx);
3044 update_cgrp_time_from_event(event);
3046 update_event_times(event);
3047 if (event->state == PERF_EVENT_STATE_ACTIVE)
3048 event->pmu->read(event);
3049 raw_spin_unlock(&ctx->lock);
3052 static inline u64 perf_event_count(struct perf_event *event)
3054 return local64_read(&event->count) + atomic64_read(&event->child_count);
3057 static u64 perf_event_read(struct perf_event *event)
3060 * If event is enabled and currently active on a CPU, update the
3061 * value in the event structure:
3063 if (event->state == PERF_EVENT_STATE_ACTIVE) {
3064 smp_call_function_single(event->oncpu,
3065 __perf_event_read, event, 1);
3066 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3067 struct perf_event_context *ctx = event->ctx;
3068 unsigned long flags;
3070 raw_spin_lock_irqsave(&ctx->lock, flags);
3072 * may read while context is not active
3073 * (e.g., thread is blocked), in that case
3074 * we cannot update context time
3076 if (ctx->is_active) {
3077 update_context_time(ctx);
3078 update_cgrp_time_from_event(event);
3080 update_event_times(event);
3081 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3084 return perf_event_count(event);
3088 * Initialize the perf_event context in a task_struct:
3090 static void __perf_event_init_context(struct perf_event_context *ctx)
3092 raw_spin_lock_init(&ctx->lock);
3093 mutex_init(&ctx->mutex);
3094 INIT_LIST_HEAD(&ctx->pinned_groups);
3095 INIT_LIST_HEAD(&ctx->flexible_groups);
3096 INIT_LIST_HEAD(&ctx->event_list);
3097 atomic_set(&ctx->refcount, 1);
3100 static struct perf_event_context *
3101 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3103 struct perf_event_context *ctx;
3105 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3106 if (!ctx)
3107 return NULL;
3109 __perf_event_init_context(ctx);
3110 if (task) {
3111 ctx->task = task;
3112 get_task_struct(task);
3114 ctx->pmu = pmu;
3116 return ctx;
3119 static struct task_struct *
3120 find_lively_task_by_vpid(pid_t vpid)
3122 struct task_struct *task;
3123 int err;
3125 rcu_read_lock();
3126 if (!vpid)
3127 task = current;
3128 else
3129 task = find_task_by_vpid(vpid);
3130 if (task)
3131 get_task_struct(task);
3132 rcu_read_unlock();
3134 if (!task)
3135 return ERR_PTR(-ESRCH);
3137 /* Reuse ptrace permission checks for now. */
3138 err = -EACCES;
3139 if (!ptrace_may_access(task, PTRACE_MODE_READ))
3140 goto errout;
3142 return task;
3143 errout:
3144 put_task_struct(task);
3145 return ERR_PTR(err);
3150 * Returns a matching context with refcount and pincount.
3152 static struct perf_event_context *
3153 find_get_context(struct pmu *pmu, struct task_struct *task, int cpu)
3155 struct perf_event_context *ctx, *clone_ctx = NULL;
3156 struct perf_cpu_context *cpuctx;
3157 unsigned long flags;
3158 int ctxn, err;
3160 if (!task) {
3161 /* Must be root to operate on a CPU event: */
3162 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3163 return ERR_PTR(-EACCES);
3166 * We could be clever and allow to attach a event to an
3167 * offline CPU and activate it when the CPU comes up, but
3168 * that's for later.
3170 if (!cpu_online(cpu))
3171 return ERR_PTR(-ENODEV);
3173 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3174 ctx = &cpuctx->ctx;
3175 get_ctx(ctx);
3176 ++ctx->pin_count;
3178 return ctx;
3181 err = -EINVAL;
3182 ctxn = pmu->task_ctx_nr;
3183 if (ctxn < 0)
3184 goto errout;
3186 retry:
3187 ctx = perf_lock_task_context(task, ctxn, &flags);
3188 if (ctx) {
3189 clone_ctx = unclone_ctx(ctx);
3190 ++ctx->pin_count;
3191 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3193 if (clone_ctx)
3194 put_ctx(clone_ctx);
3195 } else {
3196 ctx = alloc_perf_context(pmu, task);
3197 err = -ENOMEM;
3198 if (!ctx)
3199 goto errout;
3201 err = 0;
3202 mutex_lock(&task->perf_event_mutex);
3204 * If it has already passed perf_event_exit_task().
3205 * we must see PF_EXITING, it takes this mutex too.
3207 if (task->flags & PF_EXITING)
3208 err = -ESRCH;
3209 else if (task->perf_event_ctxp[ctxn])
3210 err = -EAGAIN;
3211 else {
3212 get_ctx(ctx);
3213 ++ctx->pin_count;
3214 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3216 mutex_unlock(&task->perf_event_mutex);
3218 if (unlikely(err)) {
3219 put_ctx(ctx);
3221 if (err == -EAGAIN)
3222 goto retry;
3223 goto errout;
3227 return ctx;
3229 errout:
3230 return ERR_PTR(err);
3233 static void perf_event_free_filter(struct perf_event *event);
3235 static void free_event_rcu(struct rcu_head *head)
3237 struct perf_event *event;
3239 event = container_of(head, struct perf_event, rcu_head);
3240 if (event->ns)
3241 put_pid_ns(event->ns);
3242 perf_event_free_filter(event);
3243 kfree(event);
3246 static void ring_buffer_put(struct ring_buffer *rb);
3247 static void ring_buffer_attach(struct perf_event *event,
3248 struct ring_buffer *rb);
3250 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3252 if (event->parent)
3253 return;
3255 if (has_branch_stack(event)) {
3256 if (!(event->attach_state & PERF_ATTACH_TASK))
3257 atomic_dec(&per_cpu(perf_branch_stack_events, cpu));
3259 if (is_cgroup_event(event))
3260 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3263 static void unaccount_event(struct perf_event *event)
3265 if (event->parent)
3266 return;
3268 if (event->attach_state & PERF_ATTACH_TASK)
3269 static_key_slow_dec_deferred(&perf_sched_events);
3270 if (event->attr.mmap || event->attr.mmap_data)
3271 atomic_dec(&nr_mmap_events);
3272 if (event->attr.comm)
3273 atomic_dec(&nr_comm_events);
3274 if (event->attr.task)
3275 atomic_dec(&nr_task_events);
3276 if (event->attr.freq)
3277 atomic_dec(&nr_freq_events);
3278 if (is_cgroup_event(event))
3279 static_key_slow_dec_deferred(&perf_sched_events);
3280 if (has_branch_stack(event))
3281 static_key_slow_dec_deferred(&perf_sched_events);
3283 unaccount_event_cpu(event, event->cpu);
3286 static void __free_event(struct perf_event *event)
3288 if (!event->parent) {
3289 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3290 put_callchain_buffers();
3293 if (event->destroy)
3294 event->destroy(event);
3296 if (event->ctx)
3297 put_ctx(event->ctx);
3299 if (event->pmu)
3300 module_put(event->pmu->module);
3302 call_rcu(&event->rcu_head, free_event_rcu);
3305 static void _free_event(struct perf_event *event)
3307 irq_work_sync(&event->pending);
3309 unaccount_event(event);
3311 if (event->rb) {
3313 * Can happen when we close an event with re-directed output.
3315 * Since we have a 0 refcount, perf_mmap_close() will skip
3316 * over us; possibly making our ring_buffer_put() the last.
3318 mutex_lock(&event->mmap_mutex);
3319 ring_buffer_attach(event, NULL);
3320 mutex_unlock(&event->mmap_mutex);
3323 if (is_cgroup_event(event))
3324 perf_detach_cgroup(event);
3326 __free_event(event);
3330 * Used to free events which have a known refcount of 1, such as in error paths
3331 * where the event isn't exposed yet and inherited events.
3333 static void free_event(struct perf_event *event)
3335 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3336 "unexpected event refcount: %ld; ptr=%p\n",
3337 atomic_long_read(&event->refcount), event)) {
3338 /* leak to avoid use-after-free */
3339 return;
3342 _free_event(event);
3346 * Called when the last reference to the file is gone.
3348 static void put_event(struct perf_event *event)
3350 struct perf_event_context *ctx = event->ctx;
3351 struct task_struct *owner;
3353 if (!atomic_long_dec_and_test(&event->refcount))
3354 return;
3356 rcu_read_lock();
3357 owner = ACCESS_ONCE(event->owner);
3359 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3360 * !owner it means the list deletion is complete and we can indeed
3361 * free this event, otherwise we need to serialize on
3362 * owner->perf_event_mutex.
3364 smp_read_barrier_depends();
3365 if (owner) {
3367 * Since delayed_put_task_struct() also drops the last
3368 * task reference we can safely take a new reference
3369 * while holding the rcu_read_lock().
3371 get_task_struct(owner);
3373 rcu_read_unlock();
3375 if (owner) {
3376 mutex_lock(&owner->perf_event_mutex);
3378 * We have to re-check the event->owner field, if it is cleared
3379 * we raced with perf_event_exit_task(), acquiring the mutex
3380 * ensured they're done, and we can proceed with freeing the
3381 * event.
3383 if (event->owner)
3384 list_del_init(&event->owner_entry);
3385 mutex_unlock(&owner->perf_event_mutex);
3386 put_task_struct(owner);
3389 WARN_ON_ONCE(ctx->parent_ctx);
3391 * There are two ways this annotation is useful:
3393 * 1) there is a lock recursion from perf_event_exit_task
3394 * see the comment there.
3396 * 2) there is a lock-inversion with mmap_sem through
3397 * perf_event_read_group(), which takes faults while
3398 * holding ctx->mutex, however this is called after
3399 * the last filedesc died, so there is no possibility
3400 * to trigger the AB-BA case.
3402 mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
3403 perf_remove_from_context(event, true);
3404 mutex_unlock(&ctx->mutex);
3406 _free_event(event);
3409 int perf_event_release_kernel(struct perf_event *event)
3411 put_event(event);
3412 return 0;
3414 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3416 static int perf_release(struct inode *inode, struct file *file)
3418 put_event(file->private_data);
3419 return 0;
3422 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3424 struct perf_event *child;
3425 u64 total = 0;
3427 *enabled = 0;
3428 *running = 0;
3430 mutex_lock(&event->child_mutex);
3431 total += perf_event_read(event);
3432 *enabled += event->total_time_enabled +
3433 atomic64_read(&event->child_total_time_enabled);
3434 *running += event->total_time_running +
3435 atomic64_read(&event->child_total_time_running);
3437 list_for_each_entry(child, &event->child_list, child_list) {
3438 total += perf_event_read(child);
3439 *enabled += child->total_time_enabled;
3440 *running += child->total_time_running;
3442 mutex_unlock(&event->child_mutex);
3444 return total;
3446 EXPORT_SYMBOL_GPL(perf_event_read_value);
3448 static int perf_event_read_group(struct perf_event *event,
3449 u64 read_format, char __user *buf)
3451 struct perf_event *leader = event->group_leader, *sub;
3452 int n = 0, size = 0, ret = -EFAULT;
3453 struct perf_event_context *ctx = leader->ctx;
3454 u64 values[5];
3455 u64 count, enabled, running;
3457 mutex_lock(&ctx->mutex);
3458 count = perf_event_read_value(leader, &enabled, &running);
3460 values[n++] = 1 + leader->nr_siblings;
3461 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3462 values[n++] = enabled;
3463 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3464 values[n++] = running;
3465 values[n++] = count;
3466 if (read_format & PERF_FORMAT_ID)
3467 values[n++] = primary_event_id(leader);
3469 size = n * sizeof(u64);
3471 if (copy_to_user(buf, values, size))
3472 goto unlock;
3474 ret = size;
3476 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3477 n = 0;
3479 values[n++] = perf_event_read_value(sub, &enabled, &running);
3480 if (read_format & PERF_FORMAT_ID)
3481 values[n++] = primary_event_id(sub);
3483 size = n * sizeof(u64);
3485 if (copy_to_user(buf + ret, values, size)) {
3486 ret = -EFAULT;
3487 goto unlock;
3490 ret += size;
3492 unlock:
3493 mutex_unlock(&ctx->mutex);
3495 return ret;
3498 static int perf_event_read_one(struct perf_event *event,
3499 u64 read_format, char __user *buf)
3501 u64 enabled, running;
3502 u64 values[4];
3503 int n = 0;
3505 values[n++] = perf_event_read_value(event, &enabled, &running);
3506 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3507 values[n++] = enabled;
3508 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3509 values[n++] = running;
3510 if (read_format & PERF_FORMAT_ID)
3511 values[n++] = primary_event_id(event);
3513 if (copy_to_user(buf, values, n * sizeof(u64)))
3514 return -EFAULT;
3516 return n * sizeof(u64);
3520 * Read the performance event - simple non blocking version for now
3522 static ssize_t
3523 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
3525 u64 read_format = event->attr.read_format;
3526 int ret;
3529 * Return end-of-file for a read on a event that is in
3530 * error state (i.e. because it was pinned but it couldn't be
3531 * scheduled on to the CPU at some point).
3533 if (event->state == PERF_EVENT_STATE_ERROR)
3534 return 0;
3536 if (count < event->read_size)
3537 return -ENOSPC;
3539 WARN_ON_ONCE(event->ctx->parent_ctx);
3540 if (read_format & PERF_FORMAT_GROUP)
3541 ret = perf_event_read_group(event, read_format, buf);
3542 else
3543 ret = perf_event_read_one(event, read_format, buf);
3545 return ret;
3548 static ssize_t
3549 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
3551 struct perf_event *event = file->private_data;
3553 return perf_read_hw(event, buf, count);
3556 static unsigned int perf_poll(struct file *file, poll_table *wait)
3558 struct perf_event *event = file->private_data;
3559 struct ring_buffer *rb;
3560 unsigned int events = POLL_HUP;
3563 * Pin the event->rb by taking event->mmap_mutex; otherwise
3564 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
3566 mutex_lock(&event->mmap_mutex);
3567 rb = event->rb;
3568 if (rb)
3569 events = atomic_xchg(&rb->poll, 0);
3570 mutex_unlock(&event->mmap_mutex);
3572 poll_wait(file, &event->waitq, wait);
3574 return events;
3577 static void perf_event_reset(struct perf_event *event)
3579 (void)perf_event_read(event);
3580 local64_set(&event->count, 0);
3581 perf_event_update_userpage(event);
3585 * Holding the top-level event's child_mutex means that any
3586 * descendant process that has inherited this event will block
3587 * in sync_child_event if it goes to exit, thus satisfying the
3588 * task existence requirements of perf_event_enable/disable.
3590 static void perf_event_for_each_child(struct perf_event *event,
3591 void (*func)(struct perf_event *))
3593 struct perf_event *child;
3595 WARN_ON_ONCE(event->ctx->parent_ctx);
3596 mutex_lock(&event->child_mutex);
3597 func(event);
3598 list_for_each_entry(child, &event->child_list, child_list)
3599 func(child);
3600 mutex_unlock(&event->child_mutex);
3603 static void perf_event_for_each(struct perf_event *event,
3604 void (*func)(struct perf_event *))
3606 struct perf_event_context *ctx = event->ctx;
3607 struct perf_event *sibling;
3609 WARN_ON_ONCE(ctx->parent_ctx);
3610 mutex_lock(&ctx->mutex);
3611 event = event->group_leader;
3613 perf_event_for_each_child(event, func);
3614 list_for_each_entry(sibling, &event->sibling_list, group_entry)
3615 perf_event_for_each_child(sibling, func);
3616 mutex_unlock(&ctx->mutex);
3619 static int perf_event_period(struct perf_event *event, u64 __user *arg)
3621 struct perf_event_context *ctx = event->ctx;
3622 int ret = 0, active;
3623 u64 value;
3625 if (!is_sampling_event(event))
3626 return -EINVAL;
3628 if (copy_from_user(&value, arg, sizeof(value)))
3629 return -EFAULT;
3631 if (!value)
3632 return -EINVAL;
3634 raw_spin_lock_irq(&ctx->lock);
3635 if (event->attr.freq) {
3636 if (value > sysctl_perf_event_sample_rate) {
3637 ret = -EINVAL;
3638 goto unlock;
3641 event->attr.sample_freq = value;
3642 } else {
3643 event->attr.sample_period = value;
3644 event->hw.sample_period = value;
3647 active = (event->state == PERF_EVENT_STATE_ACTIVE);
3648 if (active) {
3649 perf_pmu_disable(ctx->pmu);
3650 event->pmu->stop(event, PERF_EF_UPDATE);
3653 local64_set(&event->hw.period_left, 0);
3655 if (active) {
3656 event->pmu->start(event, PERF_EF_RELOAD);
3657 perf_pmu_enable(ctx->pmu);
3660 unlock:
3661 raw_spin_unlock_irq(&ctx->lock);
3663 return ret;
3666 static const struct file_operations perf_fops;
3668 static inline int perf_fget_light(int fd, struct fd *p)
3670 struct fd f = fdget(fd);
3671 if (!f.file)
3672 return -EBADF;
3674 if (f.file->f_op != &perf_fops) {
3675 fdput(f);
3676 return -EBADF;
3678 *p = f;
3679 return 0;
3682 static int perf_event_set_output(struct perf_event *event,
3683 struct perf_event *output_event);
3684 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
3686 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
3688 struct perf_event *event = file->private_data;
3689 void (*func)(struct perf_event *);
3690 u32 flags = arg;
3692 switch (cmd) {
3693 case PERF_EVENT_IOC_ENABLE:
3694 func = perf_event_enable;
3695 break;
3696 case PERF_EVENT_IOC_DISABLE:
3697 func = perf_event_disable;
3698 break;
3699 case PERF_EVENT_IOC_RESET:
3700 func = perf_event_reset;
3701 break;
3703 case PERF_EVENT_IOC_REFRESH:
3704 return perf_event_refresh(event, arg);
3706 case PERF_EVENT_IOC_PERIOD:
3707 return perf_event_period(event, (u64 __user *)arg);
3709 case PERF_EVENT_IOC_ID:
3711 u64 id = primary_event_id(event);
3713 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
3714 return -EFAULT;
3715 return 0;
3718 case PERF_EVENT_IOC_SET_OUTPUT:
3720 int ret;
3721 if (arg != -1) {
3722 struct perf_event *output_event;
3723 struct fd output;
3724 ret = perf_fget_light(arg, &output);
3725 if (ret)
3726 return ret;
3727 output_event = output.file->private_data;
3728 ret = perf_event_set_output(event, output_event);
3729 fdput(output);
3730 } else {
3731 ret = perf_event_set_output(event, NULL);
3733 return ret;
3736 case PERF_EVENT_IOC_SET_FILTER:
3737 return perf_event_set_filter(event, (void __user *)arg);
3739 default:
3740 return -ENOTTY;
3743 if (flags & PERF_IOC_FLAG_GROUP)
3744 perf_event_for_each(event, func);
3745 else
3746 perf_event_for_each_child(event, func);
3748 return 0;
3751 #ifdef CONFIG_COMPAT
3752 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
3753 unsigned long arg)
3755 switch (_IOC_NR(cmd)) {
3756 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
3757 case _IOC_NR(PERF_EVENT_IOC_ID):
3758 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
3759 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
3760 cmd &= ~IOCSIZE_MASK;
3761 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
3763 break;
3765 return perf_ioctl(file, cmd, arg);
3767 #else
3768 # define perf_compat_ioctl NULL
3769 #endif
3771 int perf_event_task_enable(void)
3773 struct perf_event *event;
3775 mutex_lock(&current->perf_event_mutex);
3776 list_for_each_entry(event, &current->perf_event_list, owner_entry)
3777 perf_event_for_each_child(event, perf_event_enable);
3778 mutex_unlock(&current->perf_event_mutex);
3780 return 0;
3783 int perf_event_task_disable(void)
3785 struct perf_event *event;
3787 mutex_lock(&current->perf_event_mutex);
3788 list_for_each_entry(event, &current->perf_event_list, owner_entry)
3789 perf_event_for_each_child(event, perf_event_disable);
3790 mutex_unlock(&current->perf_event_mutex);
3792 return 0;
3795 static int perf_event_index(struct perf_event *event)
3797 if (event->hw.state & PERF_HES_STOPPED)
3798 return 0;
3800 if (event->state != PERF_EVENT_STATE_ACTIVE)
3801 return 0;
3803 return event->pmu->event_idx(event);
3806 static void calc_timer_values(struct perf_event *event,
3807 u64 *now,
3808 u64 *enabled,
3809 u64 *running)
3811 u64 ctx_time;
3813 *now = perf_clock();
3814 ctx_time = event->shadow_ctx_time + *now;
3815 *enabled = ctx_time - event->tstamp_enabled;
3816 *running = ctx_time - event->tstamp_running;
3819 static void perf_event_init_userpage(struct perf_event *event)
3821 struct perf_event_mmap_page *userpg;
3822 struct ring_buffer *rb;
3824 rcu_read_lock();
3825 rb = rcu_dereference(event->rb);
3826 if (!rb)
3827 goto unlock;
3829 userpg = rb->user_page;
3831 /* Allow new userspace to detect that bit 0 is deprecated */
3832 userpg->cap_bit0_is_deprecated = 1;
3833 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
3835 unlock:
3836 rcu_read_unlock();
3839 void __weak arch_perf_update_userpage(struct perf_event_mmap_page *userpg, u64 now)
3844 * Callers need to ensure there can be no nesting of this function, otherwise
3845 * the seqlock logic goes bad. We can not serialize this because the arch
3846 * code calls this from NMI context.
3848 void perf_event_update_userpage(struct perf_event *event)
3850 struct perf_event_mmap_page *userpg;
3851 struct ring_buffer *rb;
3852 u64 enabled, running, now;
3854 rcu_read_lock();
3855 rb = rcu_dereference(event->rb);
3856 if (!rb)
3857 goto unlock;
3860 * compute total_time_enabled, total_time_running
3861 * based on snapshot values taken when the event
3862 * was last scheduled in.
3864 * we cannot simply called update_context_time()
3865 * because of locking issue as we can be called in
3866 * NMI context
3868 calc_timer_values(event, &now, &enabled, &running);
3870 userpg = rb->user_page;
3872 * Disable preemption so as to not let the corresponding user-space
3873 * spin too long if we get preempted.
3875 preempt_disable();
3876 ++userpg->lock;
3877 barrier();
3878 userpg->index = perf_event_index(event);
3879 userpg->offset = perf_event_count(event);
3880 if (userpg->index)
3881 userpg->offset -= local64_read(&event->hw.prev_count);
3883 userpg->time_enabled = enabled +
3884 atomic64_read(&event->child_total_time_enabled);
3886 userpg->time_running = running +
3887 atomic64_read(&event->child_total_time_running);
3889 arch_perf_update_userpage(userpg, now);
3891 barrier();
3892 ++userpg->lock;
3893 preempt_enable();
3894 unlock:
3895 rcu_read_unlock();
3898 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
3900 struct perf_event *event = vma->vm_file->private_data;
3901 struct ring_buffer *rb;
3902 int ret = VM_FAULT_SIGBUS;
3904 if (vmf->flags & FAULT_FLAG_MKWRITE) {
3905 if (vmf->pgoff == 0)
3906 ret = 0;
3907 return ret;
3910 rcu_read_lock();
3911 rb = rcu_dereference(event->rb);
3912 if (!rb)
3913 goto unlock;
3915 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
3916 goto unlock;
3918 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
3919 if (!vmf->page)
3920 goto unlock;
3922 get_page(vmf->page);
3923 vmf->page->mapping = vma->vm_file->f_mapping;
3924 vmf->page->index = vmf->pgoff;
3926 ret = 0;
3927 unlock:
3928 rcu_read_unlock();
3930 return ret;
3933 static void ring_buffer_attach(struct perf_event *event,
3934 struct ring_buffer *rb)
3936 struct ring_buffer *old_rb = NULL;
3937 unsigned long flags;
3939 if (event->rb) {
3941 * Should be impossible, we set this when removing
3942 * event->rb_entry and wait/clear when adding event->rb_entry.
3944 WARN_ON_ONCE(event->rcu_pending);
3946 old_rb = event->rb;
3947 event->rcu_batches = get_state_synchronize_rcu();
3948 event->rcu_pending = 1;
3950 spin_lock_irqsave(&old_rb->event_lock, flags);
3951 list_del_rcu(&event->rb_entry);
3952 spin_unlock_irqrestore(&old_rb->event_lock, flags);
3955 if (event->rcu_pending && rb) {
3956 cond_synchronize_rcu(event->rcu_batches);
3957 event->rcu_pending = 0;
3960 if (rb) {
3961 spin_lock_irqsave(&rb->event_lock, flags);
3962 list_add_rcu(&event->rb_entry, &rb->event_list);
3963 spin_unlock_irqrestore(&rb->event_lock, flags);
3966 rcu_assign_pointer(event->rb, rb);
3968 if (old_rb) {
3969 ring_buffer_put(old_rb);
3971 * Since we detached before setting the new rb, so that we
3972 * could attach the new rb, we could have missed a wakeup.
3973 * Provide it now.
3975 wake_up_all(&event->waitq);
3979 static void ring_buffer_wakeup(struct perf_event *event)
3981 struct ring_buffer *rb;
3983 rcu_read_lock();
3984 rb = rcu_dereference(event->rb);
3985 if (rb) {
3986 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
3987 wake_up_all(&event->waitq);
3989 rcu_read_unlock();
3992 static void rb_free_rcu(struct rcu_head *rcu_head)
3994 struct ring_buffer *rb;
3996 rb = container_of(rcu_head, struct ring_buffer, rcu_head);
3997 rb_free(rb);
4000 static struct ring_buffer *ring_buffer_get(struct perf_event *event)
4002 struct ring_buffer *rb;
4004 rcu_read_lock();
4005 rb = rcu_dereference(event->rb);
4006 if (rb) {
4007 if (!atomic_inc_not_zero(&rb->refcount))
4008 rb = NULL;
4010 rcu_read_unlock();
4012 return rb;
4015 static void ring_buffer_put(struct ring_buffer *rb)
4017 if (!atomic_dec_and_test(&rb->refcount))
4018 return;
4020 WARN_ON_ONCE(!list_empty(&rb->event_list));
4022 call_rcu(&rb->rcu_head, rb_free_rcu);
4025 static void perf_mmap_open(struct vm_area_struct *vma)
4027 struct perf_event *event = vma->vm_file->private_data;
4029 atomic_inc(&event->mmap_count);
4030 atomic_inc(&event->rb->mmap_count);
4034 * A buffer can be mmap()ed multiple times; either directly through the same
4035 * event, or through other events by use of perf_event_set_output().
4037 * In order to undo the VM accounting done by perf_mmap() we need to destroy
4038 * the buffer here, where we still have a VM context. This means we need
4039 * to detach all events redirecting to us.
4041 static void perf_mmap_close(struct vm_area_struct *vma)
4043 struct perf_event *event = vma->vm_file->private_data;
4045 struct ring_buffer *rb = ring_buffer_get(event);
4046 struct user_struct *mmap_user = rb->mmap_user;
4047 int mmap_locked = rb->mmap_locked;
4048 unsigned long size = perf_data_size(rb);
4050 atomic_dec(&rb->mmap_count);
4052 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
4053 goto out_put;
4055 ring_buffer_attach(event, NULL);
4056 mutex_unlock(&event->mmap_mutex);
4058 /* If there's still other mmap()s of this buffer, we're done. */
4059 if (atomic_read(&rb->mmap_count))
4060 goto out_put;
4063 * No other mmap()s, detach from all other events that might redirect
4064 * into the now unreachable buffer. Somewhat complicated by the
4065 * fact that rb::event_lock otherwise nests inside mmap_mutex.
4067 again:
4068 rcu_read_lock();
4069 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4070 if (!atomic_long_inc_not_zero(&event->refcount)) {
4072 * This event is en-route to free_event() which will
4073 * detach it and remove it from the list.
4075 continue;
4077 rcu_read_unlock();
4079 mutex_lock(&event->mmap_mutex);
4081 * Check we didn't race with perf_event_set_output() which can
4082 * swizzle the rb from under us while we were waiting to
4083 * acquire mmap_mutex.
4085 * If we find a different rb; ignore this event, a next
4086 * iteration will no longer find it on the list. We have to
4087 * still restart the iteration to make sure we're not now
4088 * iterating the wrong list.
4090 if (event->rb == rb)
4091 ring_buffer_attach(event, NULL);
4093 mutex_unlock(&event->mmap_mutex);
4094 put_event(event);
4097 * Restart the iteration; either we're on the wrong list or
4098 * destroyed its integrity by doing a deletion.
4100 goto again;
4102 rcu_read_unlock();
4105 * It could be there's still a few 0-ref events on the list; they'll
4106 * get cleaned up by free_event() -- they'll also still have their
4107 * ref on the rb and will free it whenever they are done with it.
4109 * Aside from that, this buffer is 'fully' detached and unmapped,
4110 * undo the VM accounting.
4113 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4114 vma->vm_mm->pinned_vm -= mmap_locked;
4115 free_uid(mmap_user);
4117 out_put:
4118 ring_buffer_put(rb); /* could be last */
4121 static const struct vm_operations_struct perf_mmap_vmops = {
4122 .open = perf_mmap_open,
4123 .close = perf_mmap_close,
4124 .fault = perf_mmap_fault,
4125 .page_mkwrite = perf_mmap_fault,
4128 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
4130 struct perf_event *event = file->private_data;
4131 unsigned long user_locked, user_lock_limit;
4132 struct user_struct *user = current_user();
4133 unsigned long locked, lock_limit;
4134 struct ring_buffer *rb;
4135 unsigned long vma_size;
4136 unsigned long nr_pages;
4137 long user_extra, extra;
4138 int ret = 0, flags = 0;
4141 * Don't allow mmap() of inherited per-task counters. This would
4142 * create a performance issue due to all children writing to the
4143 * same rb.
4145 if (event->cpu == -1 && event->attr.inherit)
4146 return -EINVAL;
4148 if (!(vma->vm_flags & VM_SHARED))
4149 return -EINVAL;
4151 vma_size = vma->vm_end - vma->vm_start;
4152 nr_pages = (vma_size / PAGE_SIZE) - 1;
4155 * If we have rb pages ensure they're a power-of-two number, so we
4156 * can do bitmasks instead of modulo.
4158 if (nr_pages != 0 && !is_power_of_2(nr_pages))
4159 return -EINVAL;
4161 if (vma_size != PAGE_SIZE * (1 + nr_pages))
4162 return -EINVAL;
4164 if (vma->vm_pgoff != 0)
4165 return -EINVAL;
4167 WARN_ON_ONCE(event->ctx->parent_ctx);
4168 again:
4169 mutex_lock(&event->mmap_mutex);
4170 if (event->rb) {
4171 if (event->rb->nr_pages != nr_pages) {
4172 ret = -EINVAL;
4173 goto unlock;
4176 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4178 * Raced against perf_mmap_close() through
4179 * perf_event_set_output(). Try again, hope for better
4180 * luck.
4182 mutex_unlock(&event->mmap_mutex);
4183 goto again;
4186 goto unlock;
4189 user_extra = nr_pages + 1;
4190 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
4193 * Increase the limit linearly with more CPUs:
4195 user_lock_limit *= num_online_cpus();
4197 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
4199 extra = 0;
4200 if (user_locked > user_lock_limit)
4201 extra = user_locked - user_lock_limit;
4203 lock_limit = rlimit(RLIMIT_MEMLOCK);
4204 lock_limit >>= PAGE_SHIFT;
4205 locked = vma->vm_mm->pinned_vm + extra;
4207 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
4208 !capable(CAP_IPC_LOCK)) {
4209 ret = -EPERM;
4210 goto unlock;
4213 WARN_ON(event->rb);
4215 if (vma->vm_flags & VM_WRITE)
4216 flags |= RING_BUFFER_WRITABLE;
4218 rb = rb_alloc(nr_pages,
4219 event->attr.watermark ? event->attr.wakeup_watermark : 0,
4220 event->cpu, flags);
4222 if (!rb) {
4223 ret = -ENOMEM;
4224 goto unlock;
4227 atomic_set(&rb->mmap_count, 1);
4228 rb->mmap_locked = extra;
4229 rb->mmap_user = get_current_user();
4231 atomic_long_add(user_extra, &user->locked_vm);
4232 vma->vm_mm->pinned_vm += extra;
4234 ring_buffer_attach(event, rb);
4236 perf_event_init_userpage(event);
4237 perf_event_update_userpage(event);
4239 unlock:
4240 if (!ret)
4241 atomic_inc(&event->mmap_count);
4242 mutex_unlock(&event->mmap_mutex);
4245 * Since pinned accounting is per vm we cannot allow fork() to copy our
4246 * vma.
4248 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
4249 vma->vm_ops = &perf_mmap_vmops;
4251 return ret;
4254 static int perf_fasync(int fd, struct file *filp, int on)
4256 struct inode *inode = file_inode(filp);
4257 struct perf_event *event = filp->private_data;
4258 int retval;
4260 mutex_lock(&inode->i_mutex);
4261 retval = fasync_helper(fd, filp, on, &event->fasync);
4262 mutex_unlock(&inode->i_mutex);
4264 if (retval < 0)
4265 return retval;
4267 return 0;
4270 static const struct file_operations perf_fops = {
4271 .llseek = no_llseek,
4272 .release = perf_release,
4273 .read = perf_read,
4274 .poll = perf_poll,
4275 .unlocked_ioctl = perf_ioctl,
4276 .compat_ioctl = perf_compat_ioctl,
4277 .mmap = perf_mmap,
4278 .fasync = perf_fasync,
4282 * Perf event wakeup
4284 * If there's data, ensure we set the poll() state and publish everything
4285 * to user-space before waking everybody up.
4288 void perf_event_wakeup(struct perf_event *event)
4290 ring_buffer_wakeup(event);
4292 if (event->pending_kill) {
4293 kill_fasync(&event->fasync, SIGIO, event->pending_kill);
4294 event->pending_kill = 0;
4298 static void perf_pending_event(struct irq_work *entry)
4300 struct perf_event *event = container_of(entry,
4301 struct perf_event, pending);
4303 if (event->pending_disable) {
4304 event->pending_disable = 0;
4305 __perf_event_disable(event);
4308 if (event->pending_wakeup) {
4309 event->pending_wakeup = 0;
4310 perf_event_wakeup(event);
4315 * We assume there is only KVM supporting the callbacks.
4316 * Later on, we might change it to a list if there is
4317 * another virtualization implementation supporting the callbacks.
4319 struct perf_guest_info_callbacks *perf_guest_cbs;
4321 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4323 perf_guest_cbs = cbs;
4324 return 0;
4326 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
4328 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4330 perf_guest_cbs = NULL;
4331 return 0;
4333 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
4335 static void
4336 perf_output_sample_regs(struct perf_output_handle *handle,
4337 struct pt_regs *regs, u64 mask)
4339 int bit;
4341 for_each_set_bit(bit, (const unsigned long *) &mask,
4342 sizeof(mask) * BITS_PER_BYTE) {
4343 u64 val;
4345 val = perf_reg_value(regs, bit);
4346 perf_output_put(handle, val);
4350 static void perf_sample_regs_user(struct perf_regs_user *regs_user,
4351 struct pt_regs *regs)
4353 if (!user_mode(regs)) {
4354 if (current->mm)
4355 regs = task_pt_regs(current);
4356 else
4357 regs = NULL;
4360 if (regs) {
4361 regs_user->regs = regs;
4362 regs_user->abi = perf_reg_abi(current);
4367 * Get remaining task size from user stack pointer.
4369 * It'd be better to take stack vma map and limit this more
4370 * precisly, but there's no way to get it safely under interrupt,
4371 * so using TASK_SIZE as limit.
4373 static u64 perf_ustack_task_size(struct pt_regs *regs)
4375 unsigned long addr = perf_user_stack_pointer(regs);
4377 if (!addr || addr >= TASK_SIZE)
4378 return 0;
4380 return TASK_SIZE - addr;
4383 static u16
4384 perf_sample_ustack_size(u16 stack_size, u16 header_size,
4385 struct pt_regs *regs)
4387 u64 task_size;
4389 /* No regs, no stack pointer, no dump. */
4390 if (!regs)
4391 return 0;
4394 * Check if we fit in with the requested stack size into the:
4395 * - TASK_SIZE
4396 * If we don't, we limit the size to the TASK_SIZE.
4398 * - remaining sample size
4399 * If we don't, we customize the stack size to
4400 * fit in to the remaining sample size.
4403 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
4404 stack_size = min(stack_size, (u16) task_size);
4406 /* Current header size plus static size and dynamic size. */
4407 header_size += 2 * sizeof(u64);
4409 /* Do we fit in with the current stack dump size? */
4410 if ((u16) (header_size + stack_size) < header_size) {
4412 * If we overflow the maximum size for the sample,
4413 * we customize the stack dump size to fit in.
4415 stack_size = USHRT_MAX - header_size - sizeof(u64);
4416 stack_size = round_up(stack_size, sizeof(u64));
4419 return stack_size;
4422 static void
4423 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
4424 struct pt_regs *regs)
4426 /* Case of a kernel thread, nothing to dump */
4427 if (!regs) {
4428 u64 size = 0;
4429 perf_output_put(handle, size);
4430 } else {
4431 unsigned long sp;
4432 unsigned int rem;
4433 u64 dyn_size;
4436 * We dump:
4437 * static size
4438 * - the size requested by user or the best one we can fit
4439 * in to the sample max size
4440 * data
4441 * - user stack dump data
4442 * dynamic size
4443 * - the actual dumped size
4446 /* Static size. */
4447 perf_output_put(handle, dump_size);
4449 /* Data. */
4450 sp = perf_user_stack_pointer(regs);
4451 rem = __output_copy_user(handle, (void *) sp, dump_size);
4452 dyn_size = dump_size - rem;
4454 perf_output_skip(handle, rem);
4456 /* Dynamic size. */
4457 perf_output_put(handle, dyn_size);
4461 static void __perf_event_header__init_id(struct perf_event_header *header,
4462 struct perf_sample_data *data,
4463 struct perf_event *event)
4465 u64 sample_type = event->attr.sample_type;
4467 data->type = sample_type;
4468 header->size += event->id_header_size;
4470 if (sample_type & PERF_SAMPLE_TID) {
4471 /* namespace issues */
4472 data->tid_entry.pid = perf_event_pid(event, current);
4473 data->tid_entry.tid = perf_event_tid(event, current);
4476 if (sample_type & PERF_SAMPLE_TIME)
4477 data->time = perf_clock();
4479 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
4480 data->id = primary_event_id(event);
4482 if (sample_type & PERF_SAMPLE_STREAM_ID)
4483 data->stream_id = event->id;
4485 if (sample_type & PERF_SAMPLE_CPU) {
4486 data->cpu_entry.cpu = raw_smp_processor_id();
4487 data->cpu_entry.reserved = 0;
4491 void perf_event_header__init_id(struct perf_event_header *header,
4492 struct perf_sample_data *data,
4493 struct perf_event *event)
4495 if (event->attr.sample_id_all)
4496 __perf_event_header__init_id(header, data, event);
4499 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
4500 struct perf_sample_data *data)
4502 u64 sample_type = data->type;
4504 if (sample_type & PERF_SAMPLE_TID)
4505 perf_output_put(handle, data->tid_entry);
4507 if (sample_type & PERF_SAMPLE_TIME)
4508 perf_output_put(handle, data->time);
4510 if (sample_type & PERF_SAMPLE_ID)
4511 perf_output_put(handle, data->id);
4513 if (sample_type & PERF_SAMPLE_STREAM_ID)
4514 perf_output_put(handle, data->stream_id);
4516 if (sample_type & PERF_SAMPLE_CPU)
4517 perf_output_put(handle, data->cpu_entry);
4519 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4520 perf_output_put(handle, data->id);
4523 void perf_event__output_id_sample(struct perf_event *event,
4524 struct perf_output_handle *handle,
4525 struct perf_sample_data *sample)
4527 if (event->attr.sample_id_all)
4528 __perf_event__output_id_sample(handle, sample);
4531 static void perf_output_read_one(struct perf_output_handle *handle,
4532 struct perf_event *event,
4533 u64 enabled, u64 running)
4535 u64 read_format = event->attr.read_format;
4536 u64 values[4];
4537 int n = 0;
4539 values[n++] = perf_event_count(event);
4540 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4541 values[n++] = enabled +
4542 atomic64_read(&event->child_total_time_enabled);
4544 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4545 values[n++] = running +
4546 atomic64_read(&event->child_total_time_running);
4548 if (read_format & PERF_FORMAT_ID)
4549 values[n++] = primary_event_id(event);
4551 __output_copy(handle, values, n * sizeof(u64));
4555 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
4557 static void perf_output_read_group(struct perf_output_handle *handle,
4558 struct perf_event *event,
4559 u64 enabled, u64 running)
4561 struct perf_event *leader = event->group_leader, *sub;
4562 u64 read_format = event->attr.read_format;
4563 u64 values[5];
4564 int n = 0;
4566 values[n++] = 1 + leader->nr_siblings;
4568 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4569 values[n++] = enabled;
4571 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4572 values[n++] = running;
4574 if (leader != event)
4575 leader->pmu->read(leader);
4577 values[n++] = perf_event_count(leader);
4578 if (read_format & PERF_FORMAT_ID)
4579 values[n++] = primary_event_id(leader);
4581 __output_copy(handle, values, n * sizeof(u64));
4583 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4584 n = 0;
4586 if ((sub != event) &&
4587 (sub->state == PERF_EVENT_STATE_ACTIVE))
4588 sub->pmu->read(sub);
4590 values[n++] = perf_event_count(sub);
4591 if (read_format & PERF_FORMAT_ID)
4592 values[n++] = primary_event_id(sub);
4594 __output_copy(handle, values, n * sizeof(u64));
4598 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
4599 PERF_FORMAT_TOTAL_TIME_RUNNING)
4601 static void perf_output_read(struct perf_output_handle *handle,
4602 struct perf_event *event)
4604 u64 enabled = 0, running = 0, now;
4605 u64 read_format = event->attr.read_format;
4608 * compute total_time_enabled, total_time_running
4609 * based on snapshot values taken when the event
4610 * was last scheduled in.
4612 * we cannot simply called update_context_time()
4613 * because of locking issue as we are called in
4614 * NMI context
4616 if (read_format & PERF_FORMAT_TOTAL_TIMES)
4617 calc_timer_values(event, &now, &enabled, &running);
4619 if (event->attr.read_format & PERF_FORMAT_GROUP)
4620 perf_output_read_group(handle, event, enabled, running);
4621 else
4622 perf_output_read_one(handle, event, enabled, running);
4625 void perf_output_sample(struct perf_output_handle *handle,
4626 struct perf_event_header *header,
4627 struct perf_sample_data *data,
4628 struct perf_event *event)
4630 u64 sample_type = data->type;
4632 perf_output_put(handle, *header);
4634 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4635 perf_output_put(handle, data->id);
4637 if (sample_type & PERF_SAMPLE_IP)
4638 perf_output_put(handle, data->ip);
4640 if (sample_type & PERF_SAMPLE_TID)
4641 perf_output_put(handle, data->tid_entry);
4643 if (sample_type & PERF_SAMPLE_TIME)
4644 perf_output_put(handle, data->time);
4646 if (sample_type & PERF_SAMPLE_ADDR)
4647 perf_output_put(handle, data->addr);
4649 if (sample_type & PERF_SAMPLE_ID)
4650 perf_output_put(handle, data->id);
4652 if (sample_type & PERF_SAMPLE_STREAM_ID)
4653 perf_output_put(handle, data->stream_id);
4655 if (sample_type & PERF_SAMPLE_CPU)
4656 perf_output_put(handle, data->cpu_entry);
4658 if (sample_type & PERF_SAMPLE_PERIOD)
4659 perf_output_put(handle, data->period);
4661 if (sample_type & PERF_SAMPLE_READ)
4662 perf_output_read(handle, event);
4664 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4665 if (data->callchain) {
4666 int size = 1;
4668 if (data->callchain)
4669 size += data->callchain->nr;
4671 size *= sizeof(u64);
4673 __output_copy(handle, data->callchain, size);
4674 } else {
4675 u64 nr = 0;
4676 perf_output_put(handle, nr);
4680 if (sample_type & PERF_SAMPLE_RAW) {
4681 if (data->raw) {
4682 perf_output_put(handle, data->raw->size);
4683 __output_copy(handle, data->raw->data,
4684 data->raw->size);
4685 } else {
4686 struct {
4687 u32 size;
4688 u32 data;
4689 } raw = {
4690 .size = sizeof(u32),
4691 .data = 0,
4693 perf_output_put(handle, raw);
4697 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4698 if (data->br_stack) {
4699 size_t size;
4701 size = data->br_stack->nr
4702 * sizeof(struct perf_branch_entry);
4704 perf_output_put(handle, data->br_stack->nr);
4705 perf_output_copy(handle, data->br_stack->entries, size);
4706 } else {
4708 * we always store at least the value of nr
4710 u64 nr = 0;
4711 perf_output_put(handle, nr);
4715 if (sample_type & PERF_SAMPLE_REGS_USER) {
4716 u64 abi = data->regs_user.abi;
4719 * If there are no regs to dump, notice it through
4720 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
4722 perf_output_put(handle, abi);
4724 if (abi) {
4725 u64 mask = event->attr.sample_regs_user;
4726 perf_output_sample_regs(handle,
4727 data->regs_user.regs,
4728 mask);
4732 if (sample_type & PERF_SAMPLE_STACK_USER) {
4733 perf_output_sample_ustack(handle,
4734 data->stack_user_size,
4735 data->regs_user.regs);
4738 if (sample_type & PERF_SAMPLE_WEIGHT)
4739 perf_output_put(handle, data->weight);
4741 if (sample_type & PERF_SAMPLE_DATA_SRC)
4742 perf_output_put(handle, data->data_src.val);
4744 if (sample_type & PERF_SAMPLE_TRANSACTION)
4745 perf_output_put(handle, data->txn);
4747 if (!event->attr.watermark) {
4748 int wakeup_events = event->attr.wakeup_events;
4750 if (wakeup_events) {
4751 struct ring_buffer *rb = handle->rb;
4752 int events = local_inc_return(&rb->events);
4754 if (events >= wakeup_events) {
4755 local_sub(wakeup_events, &rb->events);
4756 local_inc(&rb->wakeup);
4762 void perf_prepare_sample(struct perf_event_header *header,
4763 struct perf_sample_data *data,
4764 struct perf_event *event,
4765 struct pt_regs *regs)
4767 u64 sample_type = event->attr.sample_type;
4769 header->type = PERF_RECORD_SAMPLE;
4770 header->size = sizeof(*header) + event->header_size;
4772 header->misc = 0;
4773 header->misc |= perf_misc_flags(regs);
4775 __perf_event_header__init_id(header, data, event);
4777 if (sample_type & PERF_SAMPLE_IP)
4778 data->ip = perf_instruction_pointer(regs);
4780 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4781 int size = 1;
4783 data->callchain = perf_callchain(event, regs);
4785 if (data->callchain)
4786 size += data->callchain->nr;
4788 header->size += size * sizeof(u64);
4791 if (sample_type & PERF_SAMPLE_RAW) {
4792 int size = sizeof(u32);
4794 if (data->raw)
4795 size += data->raw->size;
4796 else
4797 size += sizeof(u32);
4799 WARN_ON_ONCE(size & (sizeof(u64)-1));
4800 header->size += size;
4803 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4804 int size = sizeof(u64); /* nr */
4805 if (data->br_stack) {
4806 size += data->br_stack->nr
4807 * sizeof(struct perf_branch_entry);
4809 header->size += size;
4812 if (sample_type & PERF_SAMPLE_REGS_USER) {
4813 /* regs dump ABI info */
4814 int size = sizeof(u64);
4816 perf_sample_regs_user(&data->regs_user, regs);
4818 if (data->regs_user.regs) {
4819 u64 mask = event->attr.sample_regs_user;
4820 size += hweight64(mask) * sizeof(u64);
4823 header->size += size;
4826 if (sample_type & PERF_SAMPLE_STACK_USER) {
4828 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
4829 * processed as the last one or have additional check added
4830 * in case new sample type is added, because we could eat
4831 * up the rest of the sample size.
4833 struct perf_regs_user *uregs = &data->regs_user;
4834 u16 stack_size = event->attr.sample_stack_user;
4835 u16 size = sizeof(u64);
4837 if (!uregs->abi)
4838 perf_sample_regs_user(uregs, regs);
4840 stack_size = perf_sample_ustack_size(stack_size, header->size,
4841 uregs->regs);
4844 * If there is something to dump, add space for the dump
4845 * itself and for the field that tells the dynamic size,
4846 * which is how many have been actually dumped.
4848 if (stack_size)
4849 size += sizeof(u64) + stack_size;
4851 data->stack_user_size = stack_size;
4852 header->size += size;
4856 static void perf_event_output(struct perf_event *event,
4857 struct perf_sample_data *data,
4858 struct pt_regs *regs)
4860 struct perf_output_handle handle;
4861 struct perf_event_header header;
4863 /* protect the callchain buffers */
4864 rcu_read_lock();
4866 perf_prepare_sample(&header, data, event, regs);
4868 if (perf_output_begin(&handle, event, header.size))
4869 goto exit;
4871 perf_output_sample(&handle, &header, data, event);
4873 perf_output_end(&handle);
4875 exit:
4876 rcu_read_unlock();
4880 * read event_id
4883 struct perf_read_event {
4884 struct perf_event_header header;
4886 u32 pid;
4887 u32 tid;
4890 static void
4891 perf_event_read_event(struct perf_event *event,
4892 struct task_struct *task)
4894 struct perf_output_handle handle;
4895 struct perf_sample_data sample;
4896 struct perf_read_event read_event = {
4897 .header = {
4898 .type = PERF_RECORD_READ,
4899 .misc = 0,
4900 .size = sizeof(read_event) + event->read_size,
4902 .pid = perf_event_pid(event, task),
4903 .tid = perf_event_tid(event, task),
4905 int ret;
4907 perf_event_header__init_id(&read_event.header, &sample, event);
4908 ret = perf_output_begin(&handle, event, read_event.header.size);
4909 if (ret)
4910 return;
4912 perf_output_put(&handle, read_event);
4913 perf_output_read(&handle, event);
4914 perf_event__output_id_sample(event, &handle, &sample);
4916 perf_output_end(&handle);
4919 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
4921 static void
4922 perf_event_aux_ctx(struct perf_event_context *ctx,
4923 perf_event_aux_output_cb output,
4924 void *data)
4926 struct perf_event *event;
4928 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4929 if (event->state < PERF_EVENT_STATE_INACTIVE)
4930 continue;
4931 if (!event_filter_match(event))
4932 continue;
4933 output(event, data);
4937 static void
4938 perf_event_aux(perf_event_aux_output_cb output, void *data,
4939 struct perf_event_context *task_ctx)
4941 struct perf_cpu_context *cpuctx;
4942 struct perf_event_context *ctx;
4943 struct pmu *pmu;
4944 int ctxn;
4946 rcu_read_lock();
4947 list_for_each_entry_rcu(pmu, &pmus, entry) {
4948 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4949 if (cpuctx->unique_pmu != pmu)
4950 goto next;
4951 perf_event_aux_ctx(&cpuctx->ctx, output, data);
4952 if (task_ctx)
4953 goto next;
4954 ctxn = pmu->task_ctx_nr;
4955 if (ctxn < 0)
4956 goto next;
4957 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4958 if (ctx)
4959 perf_event_aux_ctx(ctx, output, data);
4960 next:
4961 put_cpu_ptr(pmu->pmu_cpu_context);
4964 if (task_ctx) {
4965 preempt_disable();
4966 perf_event_aux_ctx(task_ctx, output, data);
4967 preempt_enable();
4969 rcu_read_unlock();
4973 * task tracking -- fork/exit
4975 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
4978 struct perf_task_event {
4979 struct task_struct *task;
4980 struct perf_event_context *task_ctx;
4982 struct {
4983 struct perf_event_header header;
4985 u32 pid;
4986 u32 ppid;
4987 u32 tid;
4988 u32 ptid;
4989 u64 time;
4990 } event_id;
4993 static int perf_event_task_match(struct perf_event *event)
4995 return event->attr.comm || event->attr.mmap ||
4996 event->attr.mmap2 || event->attr.mmap_data ||
4997 event->attr.task;
5000 static void perf_event_task_output(struct perf_event *event,
5001 void *data)
5003 struct perf_task_event *task_event = data;
5004 struct perf_output_handle handle;
5005 struct perf_sample_data sample;
5006 struct task_struct *task = task_event->task;
5007 int ret, size = task_event->event_id.header.size;
5009 if (!perf_event_task_match(event))
5010 return;
5012 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
5014 ret = perf_output_begin(&handle, event,
5015 task_event->event_id.header.size);
5016 if (ret)
5017 goto out;
5019 task_event->event_id.pid = perf_event_pid(event, task);
5020 task_event->event_id.ppid = perf_event_pid(event, current);
5022 task_event->event_id.tid = perf_event_tid(event, task);
5023 task_event->event_id.ptid = perf_event_tid(event, current);
5025 perf_output_put(&handle, task_event->event_id);
5027 perf_event__output_id_sample(event, &handle, &sample);
5029 perf_output_end(&handle);
5030 out:
5031 task_event->event_id.header.size = size;
5034 static void perf_event_task(struct task_struct *task,
5035 struct perf_event_context *task_ctx,
5036 int new)
5038 struct perf_task_event task_event;
5040 if (!atomic_read(&nr_comm_events) &&
5041 !atomic_read(&nr_mmap_events) &&
5042 !atomic_read(&nr_task_events))
5043 return;
5045 task_event = (struct perf_task_event){
5046 .task = task,
5047 .task_ctx = task_ctx,
5048 .event_id = {
5049 .header = {
5050 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
5051 .misc = 0,
5052 .size = sizeof(task_event.event_id),
5054 /* .pid */
5055 /* .ppid */
5056 /* .tid */
5057 /* .ptid */
5058 .time = perf_clock(),
5062 perf_event_aux(perf_event_task_output,
5063 &task_event,
5064 task_ctx);
5067 void perf_event_fork(struct task_struct *task)
5069 perf_event_task(task, NULL, 1);
5073 * comm tracking
5076 struct perf_comm_event {
5077 struct task_struct *task;
5078 char *comm;
5079 int comm_size;
5081 struct {
5082 struct perf_event_header header;
5084 u32 pid;
5085 u32 tid;
5086 } event_id;
5089 static int perf_event_comm_match(struct perf_event *event)
5091 return event->attr.comm;
5094 static void perf_event_comm_output(struct perf_event *event,
5095 void *data)
5097 struct perf_comm_event *comm_event = data;
5098 struct perf_output_handle handle;
5099 struct perf_sample_data sample;
5100 int size = comm_event->event_id.header.size;
5101 int ret;
5103 if (!perf_event_comm_match(event))
5104 return;
5106 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
5107 ret = perf_output_begin(&handle, event,
5108 comm_event->event_id.header.size);
5110 if (ret)
5111 goto out;
5113 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
5114 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
5116 perf_output_put(&handle, comm_event->event_id);
5117 __output_copy(&handle, comm_event->comm,
5118 comm_event->comm_size);
5120 perf_event__output_id_sample(event, &handle, &sample);
5122 perf_output_end(&handle);
5123 out:
5124 comm_event->event_id.header.size = size;
5127 static void perf_event_comm_event(struct perf_comm_event *comm_event)
5129 char comm[TASK_COMM_LEN];
5130 unsigned int size;
5132 memset(comm, 0, sizeof(comm));
5133 strlcpy(comm, comm_event->task->comm, sizeof(comm));
5134 size = ALIGN(strlen(comm)+1, sizeof(u64));
5136 comm_event->comm = comm;
5137 comm_event->comm_size = size;
5139 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
5141 perf_event_aux(perf_event_comm_output,
5142 comm_event,
5143 NULL);
5146 void perf_event_comm(struct task_struct *task, bool exec)
5148 struct perf_comm_event comm_event;
5150 if (!atomic_read(&nr_comm_events))
5151 return;
5153 comm_event = (struct perf_comm_event){
5154 .task = task,
5155 /* .comm */
5156 /* .comm_size */
5157 .event_id = {
5158 .header = {
5159 .type = PERF_RECORD_COMM,
5160 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
5161 /* .size */
5163 /* .pid */
5164 /* .tid */
5168 perf_event_comm_event(&comm_event);
5172 * mmap tracking
5175 struct perf_mmap_event {
5176 struct vm_area_struct *vma;
5178 const char *file_name;
5179 int file_size;
5180 int maj, min;
5181 u64 ino;
5182 u64 ino_generation;
5183 u32 prot, flags;
5185 struct {
5186 struct perf_event_header header;
5188 u32 pid;
5189 u32 tid;
5190 u64 start;
5191 u64 len;
5192 u64 pgoff;
5193 } event_id;
5196 static int perf_event_mmap_match(struct perf_event *event,
5197 void *data)
5199 struct perf_mmap_event *mmap_event = data;
5200 struct vm_area_struct *vma = mmap_event->vma;
5201 int executable = vma->vm_flags & VM_EXEC;
5203 return (!executable && event->attr.mmap_data) ||
5204 (executable && (event->attr.mmap || event->attr.mmap2));
5207 static void perf_event_mmap_output(struct perf_event *event,
5208 void *data)
5210 struct perf_mmap_event *mmap_event = data;
5211 struct perf_output_handle handle;
5212 struct perf_sample_data sample;
5213 int size = mmap_event->event_id.header.size;
5214 int ret;
5216 if (!perf_event_mmap_match(event, data))
5217 return;
5219 if (event->attr.mmap2) {
5220 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
5221 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
5222 mmap_event->event_id.header.size += sizeof(mmap_event->min);
5223 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
5224 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
5225 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
5226 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
5229 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
5230 ret = perf_output_begin(&handle, event,
5231 mmap_event->event_id.header.size);
5232 if (ret)
5233 goto out;
5235 mmap_event->event_id.pid = perf_event_pid(event, current);
5236 mmap_event->event_id.tid = perf_event_tid(event, current);
5238 perf_output_put(&handle, mmap_event->event_id);
5240 if (event->attr.mmap2) {
5241 perf_output_put(&handle, mmap_event->maj);
5242 perf_output_put(&handle, mmap_event->min);
5243 perf_output_put(&handle, mmap_event->ino);
5244 perf_output_put(&handle, mmap_event->ino_generation);
5245 perf_output_put(&handle, mmap_event->prot);
5246 perf_output_put(&handle, mmap_event->flags);
5249 __output_copy(&handle, mmap_event->file_name,
5250 mmap_event->file_size);
5252 perf_event__output_id_sample(event, &handle, &sample);
5254 perf_output_end(&handle);
5255 out:
5256 mmap_event->event_id.header.size = size;
5259 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
5261 struct vm_area_struct *vma = mmap_event->vma;
5262 struct file *file = vma->vm_file;
5263 int maj = 0, min = 0;
5264 u64 ino = 0, gen = 0;
5265 u32 prot = 0, flags = 0;
5266 unsigned int size;
5267 char tmp[16];
5268 char *buf = NULL;
5269 char *name;
5271 if (file) {
5272 struct inode *inode;
5273 dev_t dev;
5275 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5276 if (!buf) {
5277 name = "//enomem";
5278 goto cpy_name;
5281 * d_path() works from the end of the rb backwards, so we
5282 * need to add enough zero bytes after the string to handle
5283 * the 64bit alignment we do later.
5285 name = d_path(&file->f_path, buf, PATH_MAX - sizeof(u64));
5286 if (IS_ERR(name)) {
5287 name = "//toolong";
5288 goto cpy_name;
5290 inode = file_inode(vma->vm_file);
5291 dev = inode->i_sb->s_dev;
5292 ino = inode->i_ino;
5293 gen = inode->i_generation;
5294 maj = MAJOR(dev);
5295 min = MINOR(dev);
5297 if (vma->vm_flags & VM_READ)
5298 prot |= PROT_READ;
5299 if (vma->vm_flags & VM_WRITE)
5300 prot |= PROT_WRITE;
5301 if (vma->vm_flags & VM_EXEC)
5302 prot |= PROT_EXEC;
5304 if (vma->vm_flags & VM_MAYSHARE)
5305 flags = MAP_SHARED;
5306 else
5307 flags = MAP_PRIVATE;
5309 if (vma->vm_flags & VM_DENYWRITE)
5310 flags |= MAP_DENYWRITE;
5311 if (vma->vm_flags & VM_MAYEXEC)
5312 flags |= MAP_EXECUTABLE;
5313 if (vma->vm_flags & VM_LOCKED)
5314 flags |= MAP_LOCKED;
5315 if (vma->vm_flags & VM_HUGETLB)
5316 flags |= MAP_HUGETLB;
5318 goto got_name;
5319 } else {
5320 if (vma->vm_ops && vma->vm_ops->name) {
5321 name = (char *) vma->vm_ops->name(vma);
5322 if (name)
5323 goto cpy_name;
5326 name = (char *)arch_vma_name(vma);
5327 if (name)
5328 goto cpy_name;
5330 if (vma->vm_start <= vma->vm_mm->start_brk &&
5331 vma->vm_end >= vma->vm_mm->brk) {
5332 name = "[heap]";
5333 goto cpy_name;
5335 if (vma->vm_start <= vma->vm_mm->start_stack &&
5336 vma->vm_end >= vma->vm_mm->start_stack) {
5337 name = "[stack]";
5338 goto cpy_name;
5341 name = "//anon";
5342 goto cpy_name;
5345 cpy_name:
5346 strlcpy(tmp, name, sizeof(tmp));
5347 name = tmp;
5348 got_name:
5350 * Since our buffer works in 8 byte units we need to align our string
5351 * size to a multiple of 8. However, we must guarantee the tail end is
5352 * zero'd out to avoid leaking random bits to userspace.
5354 size = strlen(name)+1;
5355 while (!IS_ALIGNED(size, sizeof(u64)))
5356 name[size++] = '\0';
5358 mmap_event->file_name = name;
5359 mmap_event->file_size = size;
5360 mmap_event->maj = maj;
5361 mmap_event->min = min;
5362 mmap_event->ino = ino;
5363 mmap_event->ino_generation = gen;
5364 mmap_event->prot = prot;
5365 mmap_event->flags = flags;
5367 if (!(vma->vm_flags & VM_EXEC))
5368 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
5370 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
5372 perf_event_aux(perf_event_mmap_output,
5373 mmap_event,
5374 NULL);
5376 kfree(buf);
5379 void perf_event_mmap(struct vm_area_struct *vma)
5381 struct perf_mmap_event mmap_event;
5383 if (!atomic_read(&nr_mmap_events))
5384 return;
5386 mmap_event = (struct perf_mmap_event){
5387 .vma = vma,
5388 /* .file_name */
5389 /* .file_size */
5390 .event_id = {
5391 .header = {
5392 .type = PERF_RECORD_MMAP,
5393 .misc = PERF_RECORD_MISC_USER,
5394 /* .size */
5396 /* .pid */
5397 /* .tid */
5398 .start = vma->vm_start,
5399 .len = vma->vm_end - vma->vm_start,
5400 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
5402 /* .maj (attr_mmap2 only) */
5403 /* .min (attr_mmap2 only) */
5404 /* .ino (attr_mmap2 only) */
5405 /* .ino_generation (attr_mmap2 only) */
5406 /* .prot (attr_mmap2 only) */
5407 /* .flags (attr_mmap2 only) */
5410 perf_event_mmap_event(&mmap_event);
5414 * IRQ throttle logging
5417 static void perf_log_throttle(struct perf_event *event, int enable)
5419 struct perf_output_handle handle;
5420 struct perf_sample_data sample;
5421 int ret;
5423 struct {
5424 struct perf_event_header header;
5425 u64 time;
5426 u64 id;
5427 u64 stream_id;
5428 } throttle_event = {
5429 .header = {
5430 .type = PERF_RECORD_THROTTLE,
5431 .misc = 0,
5432 .size = sizeof(throttle_event),
5434 .time = perf_clock(),
5435 .id = primary_event_id(event),
5436 .stream_id = event->id,
5439 if (enable)
5440 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
5442 perf_event_header__init_id(&throttle_event.header, &sample, event);
5444 ret = perf_output_begin(&handle, event,
5445 throttle_event.header.size);
5446 if (ret)
5447 return;
5449 perf_output_put(&handle, throttle_event);
5450 perf_event__output_id_sample(event, &handle, &sample);
5451 perf_output_end(&handle);
5455 * Generic event overflow handling, sampling.
5458 static int __perf_event_overflow(struct perf_event *event,
5459 int throttle, struct perf_sample_data *data,
5460 struct pt_regs *regs)
5462 int events = atomic_read(&event->event_limit);
5463 struct hw_perf_event *hwc = &event->hw;
5464 u64 seq;
5465 int ret = 0;
5468 * Non-sampling counters might still use the PMI to fold short
5469 * hardware counters, ignore those.
5471 if (unlikely(!is_sampling_event(event)))
5472 return 0;
5474 seq = __this_cpu_read(perf_throttled_seq);
5475 if (seq != hwc->interrupts_seq) {
5476 hwc->interrupts_seq = seq;
5477 hwc->interrupts = 1;
5478 } else {
5479 hwc->interrupts++;
5480 if (unlikely(throttle
5481 && hwc->interrupts >= max_samples_per_tick)) {
5482 __this_cpu_inc(perf_throttled_count);
5483 hwc->interrupts = MAX_INTERRUPTS;
5484 perf_log_throttle(event, 0);
5485 tick_nohz_full_kick();
5486 ret = 1;
5490 if (event->attr.freq) {
5491 u64 now = perf_clock();
5492 s64 delta = now - hwc->freq_time_stamp;
5494 hwc->freq_time_stamp = now;
5496 if (delta > 0 && delta < 2*TICK_NSEC)
5497 perf_adjust_period(event, delta, hwc->last_period, true);
5501 * XXX event_limit might not quite work as expected on inherited
5502 * events
5505 event->pending_kill = POLL_IN;
5506 if (events && atomic_dec_and_test(&event->event_limit)) {
5507 ret = 1;
5508 event->pending_kill = POLL_HUP;
5509 event->pending_disable = 1;
5510 irq_work_queue(&event->pending);
5513 if (event->overflow_handler)
5514 event->overflow_handler(event, data, regs);
5515 else
5516 perf_event_output(event, data, regs);
5518 if (event->fasync && event->pending_kill) {
5519 event->pending_wakeup = 1;
5520 irq_work_queue(&event->pending);
5523 return ret;
5526 int perf_event_overflow(struct perf_event *event,
5527 struct perf_sample_data *data,
5528 struct pt_regs *regs)
5530 return __perf_event_overflow(event, 1, data, regs);
5534 * Generic software event infrastructure
5537 struct swevent_htable {
5538 struct swevent_hlist *swevent_hlist;
5539 struct mutex hlist_mutex;
5540 int hlist_refcount;
5542 /* Recursion avoidance in each contexts */
5543 int recursion[PERF_NR_CONTEXTS];
5545 /* Keeps track of cpu being initialized/exited */
5546 bool online;
5549 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
5552 * We directly increment event->count and keep a second value in
5553 * event->hw.period_left to count intervals. This period event
5554 * is kept in the range [-sample_period, 0] so that we can use the
5555 * sign as trigger.
5558 u64 perf_swevent_set_period(struct perf_event *event)
5560 struct hw_perf_event *hwc = &event->hw;
5561 u64 period = hwc->last_period;
5562 u64 nr, offset;
5563 s64 old, val;
5565 hwc->last_period = hwc->sample_period;
5567 again:
5568 old = val = local64_read(&hwc->period_left);
5569 if (val < 0)
5570 return 0;
5572 nr = div64_u64(period + val, period);
5573 offset = nr * period;
5574 val -= offset;
5575 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
5576 goto again;
5578 return nr;
5581 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
5582 struct perf_sample_data *data,
5583 struct pt_regs *regs)
5585 struct hw_perf_event *hwc = &event->hw;
5586 int throttle = 0;
5588 if (!overflow)
5589 overflow = perf_swevent_set_period(event);
5591 if (hwc->interrupts == MAX_INTERRUPTS)
5592 return;
5594 for (; overflow; overflow--) {
5595 if (__perf_event_overflow(event, throttle,
5596 data, regs)) {
5598 * We inhibit the overflow from happening when
5599 * hwc->interrupts == MAX_INTERRUPTS.
5601 break;
5603 throttle = 1;
5607 static void perf_swevent_event(struct perf_event *event, u64 nr,
5608 struct perf_sample_data *data,
5609 struct pt_regs *regs)
5611 struct hw_perf_event *hwc = &event->hw;
5613 local64_add(nr, &event->count);
5615 if (!regs)
5616 return;
5618 if (!is_sampling_event(event))
5619 return;
5621 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
5622 data->period = nr;
5623 return perf_swevent_overflow(event, 1, data, regs);
5624 } else
5625 data->period = event->hw.last_period;
5627 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
5628 return perf_swevent_overflow(event, 1, data, regs);
5630 if (local64_add_negative(nr, &hwc->period_left))
5631 return;
5633 perf_swevent_overflow(event, 0, data, regs);
5636 static int perf_exclude_event(struct perf_event *event,
5637 struct pt_regs *regs)
5639 if (event->hw.state & PERF_HES_STOPPED)
5640 return 1;
5642 if (regs) {
5643 if (event->attr.exclude_user && user_mode(regs))
5644 return 1;
5646 if (event->attr.exclude_kernel && !user_mode(regs))
5647 return 1;
5650 return 0;
5653 static int perf_swevent_match(struct perf_event *event,
5654 enum perf_type_id type,
5655 u32 event_id,
5656 struct perf_sample_data *data,
5657 struct pt_regs *regs)
5659 if (event->attr.type != type)
5660 return 0;
5662 if (event->attr.config != event_id)
5663 return 0;
5665 if (perf_exclude_event(event, regs))
5666 return 0;
5668 return 1;
5671 static inline u64 swevent_hash(u64 type, u32 event_id)
5673 u64 val = event_id | (type << 32);
5675 return hash_64(val, SWEVENT_HLIST_BITS);
5678 static inline struct hlist_head *
5679 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
5681 u64 hash = swevent_hash(type, event_id);
5683 return &hlist->heads[hash];
5686 /* For the read side: events when they trigger */
5687 static inline struct hlist_head *
5688 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
5690 struct swevent_hlist *hlist;
5692 hlist = rcu_dereference(swhash->swevent_hlist);
5693 if (!hlist)
5694 return NULL;
5696 return __find_swevent_head(hlist, type, event_id);
5699 /* For the event head insertion and removal in the hlist */
5700 static inline struct hlist_head *
5701 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
5703 struct swevent_hlist *hlist;
5704 u32 event_id = event->attr.config;
5705 u64 type = event->attr.type;
5708 * Event scheduling is always serialized against hlist allocation
5709 * and release. Which makes the protected version suitable here.
5710 * The context lock guarantees that.
5712 hlist = rcu_dereference_protected(swhash->swevent_hlist,
5713 lockdep_is_held(&event->ctx->lock));
5714 if (!hlist)
5715 return NULL;
5717 return __find_swevent_head(hlist, type, event_id);
5720 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
5721 u64 nr,
5722 struct perf_sample_data *data,
5723 struct pt_regs *regs)
5725 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5726 struct perf_event *event;
5727 struct hlist_head *head;
5729 rcu_read_lock();
5730 head = find_swevent_head_rcu(swhash, type, event_id);
5731 if (!head)
5732 goto end;
5734 hlist_for_each_entry_rcu(event, head, hlist_entry) {
5735 if (perf_swevent_match(event, type, event_id, data, regs))
5736 perf_swevent_event(event, nr, data, regs);
5738 end:
5739 rcu_read_unlock();
5742 int perf_swevent_get_recursion_context(void)
5744 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5746 return get_recursion_context(swhash->recursion);
5748 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
5750 inline void perf_swevent_put_recursion_context(int rctx)
5752 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5754 put_recursion_context(swhash->recursion, rctx);
5757 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
5759 struct perf_sample_data data;
5760 int rctx;
5762 preempt_disable_notrace();
5763 rctx = perf_swevent_get_recursion_context();
5764 if (rctx < 0)
5765 return;
5767 perf_sample_data_init(&data, addr, 0);
5769 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
5771 perf_swevent_put_recursion_context(rctx);
5772 preempt_enable_notrace();
5775 static void perf_swevent_read(struct perf_event *event)
5779 static int perf_swevent_add(struct perf_event *event, int flags)
5781 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5782 struct hw_perf_event *hwc = &event->hw;
5783 struct hlist_head *head;
5785 if (is_sampling_event(event)) {
5786 hwc->last_period = hwc->sample_period;
5787 perf_swevent_set_period(event);
5790 hwc->state = !(flags & PERF_EF_START);
5792 head = find_swevent_head(swhash, event);
5793 if (!head) {
5795 * We can race with cpu hotplug code. Do not
5796 * WARN if the cpu just got unplugged.
5798 WARN_ON_ONCE(swhash->online);
5799 return -EINVAL;
5802 hlist_add_head_rcu(&event->hlist_entry, head);
5804 return 0;
5807 static void perf_swevent_del(struct perf_event *event, int flags)
5809 hlist_del_rcu(&event->hlist_entry);
5812 static void perf_swevent_start(struct perf_event *event, int flags)
5814 event->hw.state = 0;
5817 static void perf_swevent_stop(struct perf_event *event, int flags)
5819 event->hw.state = PERF_HES_STOPPED;
5822 /* Deref the hlist from the update side */
5823 static inline struct swevent_hlist *
5824 swevent_hlist_deref(struct swevent_htable *swhash)
5826 return rcu_dereference_protected(swhash->swevent_hlist,
5827 lockdep_is_held(&swhash->hlist_mutex));
5830 static void swevent_hlist_release(struct swevent_htable *swhash)
5832 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
5834 if (!hlist)
5835 return;
5837 rcu_assign_pointer(swhash->swevent_hlist, NULL);
5838 kfree_rcu(hlist, rcu_head);
5841 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
5843 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5845 mutex_lock(&swhash->hlist_mutex);
5847 if (!--swhash->hlist_refcount)
5848 swevent_hlist_release(swhash);
5850 mutex_unlock(&swhash->hlist_mutex);
5853 static void swevent_hlist_put(struct perf_event *event)
5855 int cpu;
5857 for_each_possible_cpu(cpu)
5858 swevent_hlist_put_cpu(event, cpu);
5861 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
5863 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5864 int err = 0;
5866 mutex_lock(&swhash->hlist_mutex);
5868 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
5869 struct swevent_hlist *hlist;
5871 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
5872 if (!hlist) {
5873 err = -ENOMEM;
5874 goto exit;
5876 rcu_assign_pointer(swhash->swevent_hlist, hlist);
5878 swhash->hlist_refcount++;
5879 exit:
5880 mutex_unlock(&swhash->hlist_mutex);
5882 return err;
5885 static int swevent_hlist_get(struct perf_event *event)
5887 int err;
5888 int cpu, failed_cpu;
5890 get_online_cpus();
5891 for_each_possible_cpu(cpu) {
5892 err = swevent_hlist_get_cpu(event, cpu);
5893 if (err) {
5894 failed_cpu = cpu;
5895 goto fail;
5898 put_online_cpus();
5900 return 0;
5901 fail:
5902 for_each_possible_cpu(cpu) {
5903 if (cpu == failed_cpu)
5904 break;
5905 swevent_hlist_put_cpu(event, cpu);
5908 put_online_cpus();
5909 return err;
5912 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
5914 static void sw_perf_event_destroy(struct perf_event *event)
5916 u64 event_id = event->attr.config;
5918 WARN_ON(event->parent);
5920 static_key_slow_dec(&perf_swevent_enabled[event_id]);
5921 swevent_hlist_put(event);
5924 static int perf_swevent_init(struct perf_event *event)
5926 u64 event_id = event->attr.config;
5928 if (event->attr.type != PERF_TYPE_SOFTWARE)
5929 return -ENOENT;
5932 * no branch sampling for software events
5934 if (has_branch_stack(event))
5935 return -EOPNOTSUPP;
5937 switch (event_id) {
5938 case PERF_COUNT_SW_CPU_CLOCK:
5939 case PERF_COUNT_SW_TASK_CLOCK:
5940 return -ENOENT;
5942 default:
5943 break;
5946 if (event_id >= PERF_COUNT_SW_MAX)
5947 return -ENOENT;
5949 if (!event->parent) {
5950 int err;
5952 err = swevent_hlist_get(event);
5953 if (err)
5954 return err;
5956 static_key_slow_inc(&perf_swevent_enabled[event_id]);
5957 event->destroy = sw_perf_event_destroy;
5960 return 0;
5963 static int perf_swevent_event_idx(struct perf_event *event)
5965 return 0;
5968 static struct pmu perf_swevent = {
5969 .task_ctx_nr = perf_sw_context,
5971 .event_init = perf_swevent_init,
5972 .add = perf_swevent_add,
5973 .del = perf_swevent_del,
5974 .start = perf_swevent_start,
5975 .stop = perf_swevent_stop,
5976 .read = perf_swevent_read,
5978 .event_idx = perf_swevent_event_idx,
5981 #ifdef CONFIG_EVENT_TRACING
5983 static int perf_tp_filter_match(struct perf_event *event,
5984 struct perf_sample_data *data)
5986 void *record = data->raw->data;
5988 if (likely(!event->filter) || filter_match_preds(event->filter, record))
5989 return 1;
5990 return 0;
5993 static int perf_tp_event_match(struct perf_event *event,
5994 struct perf_sample_data *data,
5995 struct pt_regs *regs)
5997 if (event->hw.state & PERF_HES_STOPPED)
5998 return 0;
6000 * All tracepoints are from kernel-space.
6002 if (event->attr.exclude_kernel)
6003 return 0;
6005 if (!perf_tp_filter_match(event, data))
6006 return 0;
6008 return 1;
6011 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
6012 struct pt_regs *regs, struct hlist_head *head, int rctx,
6013 struct task_struct *task)
6015 struct perf_sample_data data;
6016 struct perf_event *event;
6018 struct perf_raw_record raw = {
6019 .size = entry_size,
6020 .data = record,
6023 perf_sample_data_init(&data, addr, 0);
6024 data.raw = &raw;
6026 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6027 if (perf_tp_event_match(event, &data, regs))
6028 perf_swevent_event(event, count, &data, regs);
6032 * If we got specified a target task, also iterate its context and
6033 * deliver this event there too.
6035 if (task && task != current) {
6036 struct perf_event_context *ctx;
6037 struct trace_entry *entry = record;
6039 rcu_read_lock();
6040 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
6041 if (!ctx)
6042 goto unlock;
6044 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
6045 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6046 continue;
6047 if (event->attr.config != entry->type)
6048 continue;
6049 if (perf_tp_event_match(event, &data, regs))
6050 perf_swevent_event(event, count, &data, regs);
6052 unlock:
6053 rcu_read_unlock();
6056 perf_swevent_put_recursion_context(rctx);
6058 EXPORT_SYMBOL_GPL(perf_tp_event);
6060 static void tp_perf_event_destroy(struct perf_event *event)
6062 perf_trace_destroy(event);
6065 static int perf_tp_event_init(struct perf_event *event)
6067 int err;
6069 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6070 return -ENOENT;
6073 * no branch sampling for tracepoint events
6075 if (has_branch_stack(event))
6076 return -EOPNOTSUPP;
6078 err = perf_trace_init(event);
6079 if (err)
6080 return err;
6082 event->destroy = tp_perf_event_destroy;
6084 return 0;
6087 static struct pmu perf_tracepoint = {
6088 .task_ctx_nr = perf_sw_context,
6090 .event_init = perf_tp_event_init,
6091 .add = perf_trace_add,
6092 .del = perf_trace_del,
6093 .start = perf_swevent_start,
6094 .stop = perf_swevent_stop,
6095 .read = perf_swevent_read,
6097 .event_idx = perf_swevent_event_idx,
6100 static inline void perf_tp_register(void)
6102 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
6105 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
6107 char *filter_str;
6108 int ret;
6110 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6111 return -EINVAL;
6113 filter_str = strndup_user(arg, PAGE_SIZE);
6114 if (IS_ERR(filter_str))
6115 return PTR_ERR(filter_str);
6117 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
6119 kfree(filter_str);
6120 return ret;
6123 static void perf_event_free_filter(struct perf_event *event)
6125 ftrace_profile_free_filter(event);
6128 #else
6130 static inline void perf_tp_register(void)
6134 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
6136 return -ENOENT;
6139 static void perf_event_free_filter(struct perf_event *event)
6143 #endif /* CONFIG_EVENT_TRACING */
6145 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6146 void perf_bp_event(struct perf_event *bp, void *data)
6148 struct perf_sample_data sample;
6149 struct pt_regs *regs = data;
6151 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
6153 if (!bp->hw.state && !perf_exclude_event(bp, regs))
6154 perf_swevent_event(bp, 1, &sample, regs);
6156 #endif
6159 * hrtimer based swevent callback
6162 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
6164 enum hrtimer_restart ret = HRTIMER_RESTART;
6165 struct perf_sample_data data;
6166 struct pt_regs *regs;
6167 struct perf_event *event;
6168 u64 period;
6170 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
6172 if (event->state != PERF_EVENT_STATE_ACTIVE)
6173 return HRTIMER_NORESTART;
6175 event->pmu->read(event);
6177 perf_sample_data_init(&data, 0, event->hw.last_period);
6178 regs = get_irq_regs();
6180 if (regs && !perf_exclude_event(event, regs)) {
6181 if (!(event->attr.exclude_idle && is_idle_task(current)))
6182 if (__perf_event_overflow(event, 1, &data, regs))
6183 ret = HRTIMER_NORESTART;
6186 period = max_t(u64, 10000, event->hw.sample_period);
6187 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
6189 return ret;
6192 static void perf_swevent_start_hrtimer(struct perf_event *event)
6194 struct hw_perf_event *hwc = &event->hw;
6195 s64 period;
6197 if (!is_sampling_event(event))
6198 return;
6200 period = local64_read(&hwc->period_left);
6201 if (period) {
6202 if (period < 0)
6203 period = 10000;
6205 local64_set(&hwc->period_left, 0);
6206 } else {
6207 period = max_t(u64, 10000, hwc->sample_period);
6209 __hrtimer_start_range_ns(&hwc->hrtimer,
6210 ns_to_ktime(period), 0,
6211 HRTIMER_MODE_REL_PINNED, 0);
6214 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
6216 struct hw_perf_event *hwc = &event->hw;
6218 if (is_sampling_event(event)) {
6219 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
6220 local64_set(&hwc->period_left, ktime_to_ns(remaining));
6222 hrtimer_cancel(&hwc->hrtimer);
6226 static void perf_swevent_init_hrtimer(struct perf_event *event)
6228 struct hw_perf_event *hwc = &event->hw;
6230 if (!is_sampling_event(event))
6231 return;
6233 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6234 hwc->hrtimer.function = perf_swevent_hrtimer;
6237 * Since hrtimers have a fixed rate, we can do a static freq->period
6238 * mapping and avoid the whole period adjust feedback stuff.
6240 if (event->attr.freq) {
6241 long freq = event->attr.sample_freq;
6243 event->attr.sample_period = NSEC_PER_SEC / freq;
6244 hwc->sample_period = event->attr.sample_period;
6245 local64_set(&hwc->period_left, hwc->sample_period);
6246 hwc->last_period = hwc->sample_period;
6247 event->attr.freq = 0;
6252 * Software event: cpu wall time clock
6255 static void cpu_clock_event_update(struct perf_event *event)
6257 s64 prev;
6258 u64 now;
6260 now = local_clock();
6261 prev = local64_xchg(&event->hw.prev_count, now);
6262 local64_add(now - prev, &event->count);
6265 static void cpu_clock_event_start(struct perf_event *event, int flags)
6267 local64_set(&event->hw.prev_count, local_clock());
6268 perf_swevent_start_hrtimer(event);
6271 static void cpu_clock_event_stop(struct perf_event *event, int flags)
6273 perf_swevent_cancel_hrtimer(event);
6274 cpu_clock_event_update(event);
6277 static int cpu_clock_event_add(struct perf_event *event, int flags)
6279 if (flags & PERF_EF_START)
6280 cpu_clock_event_start(event, flags);
6282 return 0;
6285 static void cpu_clock_event_del(struct perf_event *event, int flags)
6287 cpu_clock_event_stop(event, flags);
6290 static void cpu_clock_event_read(struct perf_event *event)
6292 cpu_clock_event_update(event);
6295 static int cpu_clock_event_init(struct perf_event *event)
6297 if (event->attr.type != PERF_TYPE_SOFTWARE)
6298 return -ENOENT;
6300 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
6301 return -ENOENT;
6304 * no branch sampling for software events
6306 if (has_branch_stack(event))
6307 return -EOPNOTSUPP;
6309 perf_swevent_init_hrtimer(event);
6311 return 0;
6314 static struct pmu perf_cpu_clock = {
6315 .task_ctx_nr = perf_sw_context,
6317 .event_init = cpu_clock_event_init,
6318 .add = cpu_clock_event_add,
6319 .del = cpu_clock_event_del,
6320 .start = cpu_clock_event_start,
6321 .stop = cpu_clock_event_stop,
6322 .read = cpu_clock_event_read,
6324 .event_idx = perf_swevent_event_idx,
6328 * Software event: task time clock
6331 static void task_clock_event_update(struct perf_event *event, u64 now)
6333 u64 prev;
6334 s64 delta;
6336 prev = local64_xchg(&event->hw.prev_count, now);
6337 delta = now - prev;
6338 local64_add(delta, &event->count);
6341 static void task_clock_event_start(struct perf_event *event, int flags)
6343 local64_set(&event->hw.prev_count, event->ctx->time);
6344 perf_swevent_start_hrtimer(event);
6347 static void task_clock_event_stop(struct perf_event *event, int flags)
6349 perf_swevent_cancel_hrtimer(event);
6350 task_clock_event_update(event, event->ctx->time);
6353 static int task_clock_event_add(struct perf_event *event, int flags)
6355 if (flags & PERF_EF_START)
6356 task_clock_event_start(event, flags);
6358 return 0;
6361 static void task_clock_event_del(struct perf_event *event, int flags)
6363 task_clock_event_stop(event, PERF_EF_UPDATE);
6366 static void task_clock_event_read(struct perf_event *event)
6368 u64 now = perf_clock();
6369 u64 delta = now - event->ctx->timestamp;
6370 u64 time = event->ctx->time + delta;
6372 task_clock_event_update(event, time);
6375 static int task_clock_event_init(struct perf_event *event)
6377 if (event->attr.type != PERF_TYPE_SOFTWARE)
6378 return -ENOENT;
6380 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
6381 return -ENOENT;
6384 * no branch sampling for software events
6386 if (has_branch_stack(event))
6387 return -EOPNOTSUPP;
6389 perf_swevent_init_hrtimer(event);
6391 return 0;
6394 static struct pmu perf_task_clock = {
6395 .task_ctx_nr = perf_sw_context,
6397 .event_init = task_clock_event_init,
6398 .add = task_clock_event_add,
6399 .del = task_clock_event_del,
6400 .start = task_clock_event_start,
6401 .stop = task_clock_event_stop,
6402 .read = task_clock_event_read,
6404 .event_idx = perf_swevent_event_idx,
6407 static void perf_pmu_nop_void(struct pmu *pmu)
6411 static int perf_pmu_nop_int(struct pmu *pmu)
6413 return 0;
6416 static void perf_pmu_start_txn(struct pmu *pmu)
6418 perf_pmu_disable(pmu);
6421 static int perf_pmu_commit_txn(struct pmu *pmu)
6423 perf_pmu_enable(pmu);
6424 return 0;
6427 static void perf_pmu_cancel_txn(struct pmu *pmu)
6429 perf_pmu_enable(pmu);
6432 static int perf_event_idx_default(struct perf_event *event)
6434 return event->hw.idx + 1;
6438 * Ensures all contexts with the same task_ctx_nr have the same
6439 * pmu_cpu_context too.
6441 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
6443 struct pmu *pmu;
6445 if (ctxn < 0)
6446 return NULL;
6448 list_for_each_entry(pmu, &pmus, entry) {
6449 if (pmu->task_ctx_nr == ctxn)
6450 return pmu->pmu_cpu_context;
6453 return NULL;
6456 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
6458 int cpu;
6460 for_each_possible_cpu(cpu) {
6461 struct perf_cpu_context *cpuctx;
6463 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6465 if (cpuctx->unique_pmu == old_pmu)
6466 cpuctx->unique_pmu = pmu;
6470 static void free_pmu_context(struct pmu *pmu)
6472 struct pmu *i;
6474 mutex_lock(&pmus_lock);
6476 * Like a real lame refcount.
6478 list_for_each_entry(i, &pmus, entry) {
6479 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
6480 update_pmu_context(i, pmu);
6481 goto out;
6485 free_percpu(pmu->pmu_cpu_context);
6486 out:
6487 mutex_unlock(&pmus_lock);
6489 static struct idr pmu_idr;
6491 static ssize_t
6492 type_show(struct device *dev, struct device_attribute *attr, char *page)
6494 struct pmu *pmu = dev_get_drvdata(dev);
6496 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
6498 static DEVICE_ATTR_RO(type);
6500 static ssize_t
6501 perf_event_mux_interval_ms_show(struct device *dev,
6502 struct device_attribute *attr,
6503 char *page)
6505 struct pmu *pmu = dev_get_drvdata(dev);
6507 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
6510 static ssize_t
6511 perf_event_mux_interval_ms_store(struct device *dev,
6512 struct device_attribute *attr,
6513 const char *buf, size_t count)
6515 struct pmu *pmu = dev_get_drvdata(dev);
6516 int timer, cpu, ret;
6518 ret = kstrtoint(buf, 0, &timer);
6519 if (ret)
6520 return ret;
6522 if (timer < 1)
6523 return -EINVAL;
6525 /* same value, noting to do */
6526 if (timer == pmu->hrtimer_interval_ms)
6527 return count;
6529 pmu->hrtimer_interval_ms = timer;
6531 /* update all cpuctx for this PMU */
6532 for_each_possible_cpu(cpu) {
6533 struct perf_cpu_context *cpuctx;
6534 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6535 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
6537 if (hrtimer_active(&cpuctx->hrtimer))
6538 hrtimer_forward_now(&cpuctx->hrtimer, cpuctx->hrtimer_interval);
6541 return count;
6543 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
6545 static struct attribute *pmu_dev_attrs[] = {
6546 &dev_attr_type.attr,
6547 &dev_attr_perf_event_mux_interval_ms.attr,
6548 NULL,
6550 ATTRIBUTE_GROUPS(pmu_dev);
6552 static int pmu_bus_running;
6553 static struct bus_type pmu_bus = {
6554 .name = "event_source",
6555 .dev_groups = pmu_dev_groups,
6558 static void pmu_dev_release(struct device *dev)
6560 kfree(dev);
6563 static int pmu_dev_alloc(struct pmu *pmu)
6565 int ret = -ENOMEM;
6567 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
6568 if (!pmu->dev)
6569 goto out;
6571 pmu->dev->groups = pmu->attr_groups;
6572 device_initialize(pmu->dev);
6573 ret = dev_set_name(pmu->dev, "%s", pmu->name);
6574 if (ret)
6575 goto free_dev;
6577 dev_set_drvdata(pmu->dev, pmu);
6578 pmu->dev->bus = &pmu_bus;
6579 pmu->dev->release = pmu_dev_release;
6580 ret = device_add(pmu->dev);
6581 if (ret)
6582 goto free_dev;
6584 out:
6585 return ret;
6587 free_dev:
6588 put_device(pmu->dev);
6589 goto out;
6592 static struct lock_class_key cpuctx_mutex;
6593 static struct lock_class_key cpuctx_lock;
6595 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
6597 int cpu, ret;
6599 mutex_lock(&pmus_lock);
6600 ret = -ENOMEM;
6601 pmu->pmu_disable_count = alloc_percpu(int);
6602 if (!pmu->pmu_disable_count)
6603 goto unlock;
6605 pmu->type = -1;
6606 if (!name)
6607 goto skip_type;
6608 pmu->name = name;
6610 if (type < 0) {
6611 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
6612 if (type < 0) {
6613 ret = type;
6614 goto free_pdc;
6617 pmu->type = type;
6619 if (pmu_bus_running) {
6620 ret = pmu_dev_alloc(pmu);
6621 if (ret)
6622 goto free_idr;
6625 skip_type:
6626 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
6627 if (pmu->pmu_cpu_context)
6628 goto got_cpu_context;
6630 ret = -ENOMEM;
6631 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
6632 if (!pmu->pmu_cpu_context)
6633 goto free_dev;
6635 for_each_possible_cpu(cpu) {
6636 struct perf_cpu_context *cpuctx;
6638 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6639 __perf_event_init_context(&cpuctx->ctx);
6640 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
6641 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
6642 cpuctx->ctx.type = cpu_context;
6643 cpuctx->ctx.pmu = pmu;
6645 __perf_cpu_hrtimer_init(cpuctx, cpu);
6647 INIT_LIST_HEAD(&cpuctx->rotation_list);
6648 cpuctx->unique_pmu = pmu;
6651 got_cpu_context:
6652 if (!pmu->start_txn) {
6653 if (pmu->pmu_enable) {
6655 * If we have pmu_enable/pmu_disable calls, install
6656 * transaction stubs that use that to try and batch
6657 * hardware accesses.
6659 pmu->start_txn = perf_pmu_start_txn;
6660 pmu->commit_txn = perf_pmu_commit_txn;
6661 pmu->cancel_txn = perf_pmu_cancel_txn;
6662 } else {
6663 pmu->start_txn = perf_pmu_nop_void;
6664 pmu->commit_txn = perf_pmu_nop_int;
6665 pmu->cancel_txn = perf_pmu_nop_void;
6669 if (!pmu->pmu_enable) {
6670 pmu->pmu_enable = perf_pmu_nop_void;
6671 pmu->pmu_disable = perf_pmu_nop_void;
6674 if (!pmu->event_idx)
6675 pmu->event_idx = perf_event_idx_default;
6677 list_add_rcu(&pmu->entry, &pmus);
6678 ret = 0;
6679 unlock:
6680 mutex_unlock(&pmus_lock);
6682 return ret;
6684 free_dev:
6685 device_del(pmu->dev);
6686 put_device(pmu->dev);
6688 free_idr:
6689 if (pmu->type >= PERF_TYPE_MAX)
6690 idr_remove(&pmu_idr, pmu->type);
6692 free_pdc:
6693 free_percpu(pmu->pmu_disable_count);
6694 goto unlock;
6696 EXPORT_SYMBOL_GPL(perf_pmu_register);
6698 void perf_pmu_unregister(struct pmu *pmu)
6700 mutex_lock(&pmus_lock);
6701 list_del_rcu(&pmu->entry);
6702 mutex_unlock(&pmus_lock);
6705 * We dereference the pmu list under both SRCU and regular RCU, so
6706 * synchronize against both of those.
6708 synchronize_srcu(&pmus_srcu);
6709 synchronize_rcu();
6711 free_percpu(pmu->pmu_disable_count);
6712 if (pmu->type >= PERF_TYPE_MAX)
6713 idr_remove(&pmu_idr, pmu->type);
6714 device_del(pmu->dev);
6715 put_device(pmu->dev);
6716 free_pmu_context(pmu);
6718 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
6720 struct pmu *perf_init_event(struct perf_event *event)
6722 struct pmu *pmu = NULL;
6723 int idx;
6724 int ret;
6726 idx = srcu_read_lock(&pmus_srcu);
6728 rcu_read_lock();
6729 pmu = idr_find(&pmu_idr, event->attr.type);
6730 rcu_read_unlock();
6731 if (pmu) {
6732 if (!try_module_get(pmu->module)) {
6733 pmu = ERR_PTR(-ENODEV);
6734 goto unlock;
6736 event->pmu = pmu;
6737 ret = pmu->event_init(event);
6738 if (ret)
6739 pmu = ERR_PTR(ret);
6740 goto unlock;
6743 list_for_each_entry_rcu(pmu, &pmus, entry) {
6744 if (!try_module_get(pmu->module)) {
6745 pmu = ERR_PTR(-ENODEV);
6746 goto unlock;
6748 event->pmu = pmu;
6749 ret = pmu->event_init(event);
6750 if (!ret)
6751 goto unlock;
6753 if (ret != -ENOENT) {
6754 pmu = ERR_PTR(ret);
6755 goto unlock;
6758 pmu = ERR_PTR(-ENOENT);
6759 unlock:
6760 srcu_read_unlock(&pmus_srcu, idx);
6762 return pmu;
6765 static void account_event_cpu(struct perf_event *event, int cpu)
6767 if (event->parent)
6768 return;
6770 if (has_branch_stack(event)) {
6771 if (!(event->attach_state & PERF_ATTACH_TASK))
6772 atomic_inc(&per_cpu(perf_branch_stack_events, cpu));
6774 if (is_cgroup_event(event))
6775 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
6778 static void account_event(struct perf_event *event)
6780 if (event->parent)
6781 return;
6783 if (event->attach_state & PERF_ATTACH_TASK)
6784 static_key_slow_inc(&perf_sched_events.key);
6785 if (event->attr.mmap || event->attr.mmap_data)
6786 atomic_inc(&nr_mmap_events);
6787 if (event->attr.comm)
6788 atomic_inc(&nr_comm_events);
6789 if (event->attr.task)
6790 atomic_inc(&nr_task_events);
6791 if (event->attr.freq) {
6792 if (atomic_inc_return(&nr_freq_events) == 1)
6793 tick_nohz_full_kick_all();
6795 if (has_branch_stack(event))
6796 static_key_slow_inc(&perf_sched_events.key);
6797 if (is_cgroup_event(event))
6798 static_key_slow_inc(&perf_sched_events.key);
6800 account_event_cpu(event, event->cpu);
6804 * Allocate and initialize a event structure
6806 static struct perf_event *
6807 perf_event_alloc(struct perf_event_attr *attr, int cpu,
6808 struct task_struct *task,
6809 struct perf_event *group_leader,
6810 struct perf_event *parent_event,
6811 perf_overflow_handler_t overflow_handler,
6812 void *context)
6814 struct pmu *pmu;
6815 struct perf_event *event;
6816 struct hw_perf_event *hwc;
6817 long err = -EINVAL;
6819 if ((unsigned)cpu >= nr_cpu_ids) {
6820 if (!task || cpu != -1)
6821 return ERR_PTR(-EINVAL);
6824 event = kzalloc(sizeof(*event), GFP_KERNEL);
6825 if (!event)
6826 return ERR_PTR(-ENOMEM);
6829 * Single events are their own group leaders, with an
6830 * empty sibling list:
6832 if (!group_leader)
6833 group_leader = event;
6835 mutex_init(&event->child_mutex);
6836 INIT_LIST_HEAD(&event->child_list);
6838 INIT_LIST_HEAD(&event->group_entry);
6839 INIT_LIST_HEAD(&event->event_entry);
6840 INIT_LIST_HEAD(&event->sibling_list);
6841 INIT_LIST_HEAD(&event->rb_entry);
6842 INIT_LIST_HEAD(&event->active_entry);
6843 INIT_HLIST_NODE(&event->hlist_entry);
6846 init_waitqueue_head(&event->waitq);
6847 init_irq_work(&event->pending, perf_pending_event);
6849 mutex_init(&event->mmap_mutex);
6851 atomic_long_set(&event->refcount, 1);
6852 event->cpu = cpu;
6853 event->attr = *attr;
6854 event->group_leader = group_leader;
6855 event->pmu = NULL;
6856 event->oncpu = -1;
6858 event->parent = parent_event;
6860 event->ns = get_pid_ns(task_active_pid_ns(current));
6861 event->id = atomic64_inc_return(&perf_event_id);
6863 event->state = PERF_EVENT_STATE_INACTIVE;
6865 if (task) {
6866 event->attach_state = PERF_ATTACH_TASK;
6868 if (attr->type == PERF_TYPE_TRACEPOINT)
6869 event->hw.tp_target = task;
6870 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6872 * hw_breakpoint is a bit difficult here..
6874 else if (attr->type == PERF_TYPE_BREAKPOINT)
6875 event->hw.bp_target = task;
6876 #endif
6879 if (!overflow_handler && parent_event) {
6880 overflow_handler = parent_event->overflow_handler;
6881 context = parent_event->overflow_handler_context;
6884 event->overflow_handler = overflow_handler;
6885 event->overflow_handler_context = context;
6887 perf_event__state_init(event);
6889 pmu = NULL;
6891 hwc = &event->hw;
6892 hwc->sample_period = attr->sample_period;
6893 if (attr->freq && attr->sample_freq)
6894 hwc->sample_period = 1;
6895 hwc->last_period = hwc->sample_period;
6897 local64_set(&hwc->period_left, hwc->sample_period);
6900 * we currently do not support PERF_FORMAT_GROUP on inherited events
6902 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
6903 goto err_ns;
6905 pmu = perf_init_event(event);
6906 if (!pmu)
6907 goto err_ns;
6908 else if (IS_ERR(pmu)) {
6909 err = PTR_ERR(pmu);
6910 goto err_ns;
6913 if (!event->parent) {
6914 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
6915 err = get_callchain_buffers();
6916 if (err)
6917 goto err_pmu;
6921 return event;
6923 err_pmu:
6924 if (event->destroy)
6925 event->destroy(event);
6926 module_put(pmu->module);
6927 err_ns:
6928 if (event->ns)
6929 put_pid_ns(event->ns);
6930 kfree(event);
6932 return ERR_PTR(err);
6935 static int perf_copy_attr(struct perf_event_attr __user *uattr,
6936 struct perf_event_attr *attr)
6938 u32 size;
6939 int ret;
6941 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
6942 return -EFAULT;
6945 * zero the full structure, so that a short copy will be nice.
6947 memset(attr, 0, sizeof(*attr));
6949 ret = get_user(size, &uattr->size);
6950 if (ret)
6951 return ret;
6953 if (size > PAGE_SIZE) /* silly large */
6954 goto err_size;
6956 if (!size) /* abi compat */
6957 size = PERF_ATTR_SIZE_VER0;
6959 if (size < PERF_ATTR_SIZE_VER0)
6960 goto err_size;
6963 * If we're handed a bigger struct than we know of,
6964 * ensure all the unknown bits are 0 - i.e. new
6965 * user-space does not rely on any kernel feature
6966 * extensions we dont know about yet.
6968 if (size > sizeof(*attr)) {
6969 unsigned char __user *addr;
6970 unsigned char __user *end;
6971 unsigned char val;
6973 addr = (void __user *)uattr + sizeof(*attr);
6974 end = (void __user *)uattr + size;
6976 for (; addr < end; addr++) {
6977 ret = get_user(val, addr);
6978 if (ret)
6979 return ret;
6980 if (val)
6981 goto err_size;
6983 size = sizeof(*attr);
6986 ret = copy_from_user(attr, uattr, size);
6987 if (ret)
6988 return -EFAULT;
6990 if (attr->__reserved_1)
6991 return -EINVAL;
6993 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
6994 return -EINVAL;
6996 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
6997 return -EINVAL;
6999 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
7000 u64 mask = attr->branch_sample_type;
7002 /* only using defined bits */
7003 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
7004 return -EINVAL;
7006 /* at least one branch bit must be set */
7007 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
7008 return -EINVAL;
7010 /* propagate priv level, when not set for branch */
7011 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
7013 /* exclude_kernel checked on syscall entry */
7014 if (!attr->exclude_kernel)
7015 mask |= PERF_SAMPLE_BRANCH_KERNEL;
7017 if (!attr->exclude_user)
7018 mask |= PERF_SAMPLE_BRANCH_USER;
7020 if (!attr->exclude_hv)
7021 mask |= PERF_SAMPLE_BRANCH_HV;
7023 * adjust user setting (for HW filter setup)
7025 attr->branch_sample_type = mask;
7027 /* privileged levels capture (kernel, hv): check permissions */
7028 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
7029 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
7030 return -EACCES;
7033 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
7034 ret = perf_reg_validate(attr->sample_regs_user);
7035 if (ret)
7036 return ret;
7039 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
7040 if (!arch_perf_have_user_stack_dump())
7041 return -ENOSYS;
7044 * We have __u32 type for the size, but so far
7045 * we can only use __u16 as maximum due to the
7046 * __u16 sample size limit.
7048 if (attr->sample_stack_user >= USHRT_MAX)
7049 ret = -EINVAL;
7050 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
7051 ret = -EINVAL;
7054 out:
7055 return ret;
7057 err_size:
7058 put_user(sizeof(*attr), &uattr->size);
7059 ret = -E2BIG;
7060 goto out;
7063 static int
7064 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
7066 struct ring_buffer *rb = NULL;
7067 int ret = -EINVAL;
7069 if (!output_event)
7070 goto set;
7072 /* don't allow circular references */
7073 if (event == output_event)
7074 goto out;
7077 * Don't allow cross-cpu buffers
7079 if (output_event->cpu != event->cpu)
7080 goto out;
7083 * If its not a per-cpu rb, it must be the same task.
7085 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
7086 goto out;
7088 set:
7089 mutex_lock(&event->mmap_mutex);
7090 /* Can't redirect output if we've got an active mmap() */
7091 if (atomic_read(&event->mmap_count))
7092 goto unlock;
7094 if (output_event) {
7095 /* get the rb we want to redirect to */
7096 rb = ring_buffer_get(output_event);
7097 if (!rb)
7098 goto unlock;
7101 ring_buffer_attach(event, rb);
7103 ret = 0;
7104 unlock:
7105 mutex_unlock(&event->mmap_mutex);
7107 out:
7108 return ret;
7112 * sys_perf_event_open - open a performance event, associate it to a task/cpu
7114 * @attr_uptr: event_id type attributes for monitoring/sampling
7115 * @pid: target pid
7116 * @cpu: target cpu
7117 * @group_fd: group leader event fd
7119 SYSCALL_DEFINE5(perf_event_open,
7120 struct perf_event_attr __user *, attr_uptr,
7121 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
7123 struct perf_event *group_leader = NULL, *output_event = NULL;
7124 struct perf_event *event, *sibling;
7125 struct perf_event_attr attr;
7126 struct perf_event_context *ctx;
7127 struct file *event_file = NULL;
7128 struct fd group = {NULL, 0};
7129 struct task_struct *task = NULL;
7130 struct pmu *pmu;
7131 int event_fd;
7132 int move_group = 0;
7133 int err;
7134 int f_flags = O_RDWR;
7136 /* for future expandability... */
7137 if (flags & ~PERF_FLAG_ALL)
7138 return -EINVAL;
7140 err = perf_copy_attr(attr_uptr, &attr);
7141 if (err)
7142 return err;
7144 if (!attr.exclude_kernel) {
7145 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
7146 return -EACCES;
7149 if (attr.freq) {
7150 if (attr.sample_freq > sysctl_perf_event_sample_rate)
7151 return -EINVAL;
7152 } else {
7153 if (attr.sample_period & (1ULL << 63))
7154 return -EINVAL;
7158 * In cgroup mode, the pid argument is used to pass the fd
7159 * opened to the cgroup directory in cgroupfs. The cpu argument
7160 * designates the cpu on which to monitor threads from that
7161 * cgroup.
7163 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
7164 return -EINVAL;
7166 if (flags & PERF_FLAG_FD_CLOEXEC)
7167 f_flags |= O_CLOEXEC;
7169 event_fd = get_unused_fd_flags(f_flags);
7170 if (event_fd < 0)
7171 return event_fd;
7173 if (group_fd != -1) {
7174 err = perf_fget_light(group_fd, &group);
7175 if (err)
7176 goto err_fd;
7177 group_leader = group.file->private_data;
7178 if (flags & PERF_FLAG_FD_OUTPUT)
7179 output_event = group_leader;
7180 if (flags & PERF_FLAG_FD_NO_GROUP)
7181 group_leader = NULL;
7184 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
7185 task = find_lively_task_by_vpid(pid);
7186 if (IS_ERR(task)) {
7187 err = PTR_ERR(task);
7188 goto err_group_fd;
7192 if (task && group_leader &&
7193 group_leader->attr.inherit != attr.inherit) {
7194 err = -EINVAL;
7195 goto err_task;
7198 get_online_cpus();
7200 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
7201 NULL, NULL);
7202 if (IS_ERR(event)) {
7203 err = PTR_ERR(event);
7204 goto err_cpus;
7207 if (flags & PERF_FLAG_PID_CGROUP) {
7208 err = perf_cgroup_connect(pid, event, &attr, group_leader);
7209 if (err) {
7210 __free_event(event);
7211 goto err_cpus;
7215 if (is_sampling_event(event)) {
7216 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
7217 err = -ENOTSUPP;
7218 goto err_alloc;
7222 account_event(event);
7225 * Special case software events and allow them to be part of
7226 * any hardware group.
7228 pmu = event->pmu;
7230 if (group_leader &&
7231 (is_software_event(event) != is_software_event(group_leader))) {
7232 if (is_software_event(event)) {
7234 * If event and group_leader are not both a software
7235 * event, and event is, then group leader is not.
7237 * Allow the addition of software events to !software
7238 * groups, this is safe because software events never
7239 * fail to schedule.
7241 pmu = group_leader->pmu;
7242 } else if (is_software_event(group_leader) &&
7243 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
7245 * In case the group is a pure software group, and we
7246 * try to add a hardware event, move the whole group to
7247 * the hardware context.
7249 move_group = 1;
7254 * Get the target context (task or percpu):
7256 ctx = find_get_context(pmu, task, event->cpu);
7257 if (IS_ERR(ctx)) {
7258 err = PTR_ERR(ctx);
7259 goto err_alloc;
7262 if (task) {
7263 put_task_struct(task);
7264 task = NULL;
7268 * Look up the group leader (we will attach this event to it):
7270 if (group_leader) {
7271 err = -EINVAL;
7274 * Do not allow a recursive hierarchy (this new sibling
7275 * becoming part of another group-sibling):
7277 if (group_leader->group_leader != group_leader)
7278 goto err_context;
7280 * Do not allow to attach to a group in a different
7281 * task or CPU context:
7283 if (move_group) {
7284 if (group_leader->ctx->type != ctx->type)
7285 goto err_context;
7286 } else {
7287 if (group_leader->ctx != ctx)
7288 goto err_context;
7292 * Only a group leader can be exclusive or pinned
7294 if (attr.exclusive || attr.pinned)
7295 goto err_context;
7298 if (output_event) {
7299 err = perf_event_set_output(event, output_event);
7300 if (err)
7301 goto err_context;
7304 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
7305 f_flags);
7306 if (IS_ERR(event_file)) {
7307 err = PTR_ERR(event_file);
7308 goto err_context;
7311 if (move_group) {
7312 struct perf_event_context *gctx = group_leader->ctx;
7314 mutex_lock(&gctx->mutex);
7315 perf_remove_from_context(group_leader, false);
7318 * Removing from the context ends up with disabled
7319 * event. What we want here is event in the initial
7320 * startup state, ready to be add into new context.
7322 perf_event__state_init(group_leader);
7323 list_for_each_entry(sibling, &group_leader->sibling_list,
7324 group_entry) {
7325 perf_remove_from_context(sibling, false);
7326 perf_event__state_init(sibling);
7327 put_ctx(gctx);
7329 mutex_unlock(&gctx->mutex);
7330 put_ctx(gctx);
7333 WARN_ON_ONCE(ctx->parent_ctx);
7334 mutex_lock(&ctx->mutex);
7336 if (move_group) {
7337 synchronize_rcu();
7338 perf_install_in_context(ctx, group_leader, event->cpu);
7339 get_ctx(ctx);
7340 list_for_each_entry(sibling, &group_leader->sibling_list,
7341 group_entry) {
7342 perf_install_in_context(ctx, sibling, event->cpu);
7343 get_ctx(ctx);
7347 perf_install_in_context(ctx, event, event->cpu);
7348 perf_unpin_context(ctx);
7349 mutex_unlock(&ctx->mutex);
7351 put_online_cpus();
7353 event->owner = current;
7355 mutex_lock(&current->perf_event_mutex);
7356 list_add_tail(&event->owner_entry, &current->perf_event_list);
7357 mutex_unlock(&current->perf_event_mutex);
7360 * Precalculate sample_data sizes
7362 perf_event__header_size(event);
7363 perf_event__id_header_size(event);
7366 * Drop the reference on the group_event after placing the
7367 * new event on the sibling_list. This ensures destruction
7368 * of the group leader will find the pointer to itself in
7369 * perf_group_detach().
7371 fdput(group);
7372 fd_install(event_fd, event_file);
7373 return event_fd;
7375 err_context:
7376 perf_unpin_context(ctx);
7377 put_ctx(ctx);
7378 err_alloc:
7379 free_event(event);
7380 err_cpus:
7381 put_online_cpus();
7382 err_task:
7383 if (task)
7384 put_task_struct(task);
7385 err_group_fd:
7386 fdput(group);
7387 err_fd:
7388 put_unused_fd(event_fd);
7389 return err;
7393 * perf_event_create_kernel_counter
7395 * @attr: attributes of the counter to create
7396 * @cpu: cpu in which the counter is bound
7397 * @task: task to profile (NULL for percpu)
7399 struct perf_event *
7400 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
7401 struct task_struct *task,
7402 perf_overflow_handler_t overflow_handler,
7403 void *context)
7405 struct perf_event_context *ctx;
7406 struct perf_event *event;
7407 int err;
7410 * Get the target context (task or percpu):
7413 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
7414 overflow_handler, context);
7415 if (IS_ERR(event)) {
7416 err = PTR_ERR(event);
7417 goto err;
7420 account_event(event);
7422 ctx = find_get_context(event->pmu, task, cpu);
7423 if (IS_ERR(ctx)) {
7424 err = PTR_ERR(ctx);
7425 goto err_free;
7428 WARN_ON_ONCE(ctx->parent_ctx);
7429 mutex_lock(&ctx->mutex);
7430 perf_install_in_context(ctx, event, cpu);
7431 perf_unpin_context(ctx);
7432 mutex_unlock(&ctx->mutex);
7434 return event;
7436 err_free:
7437 free_event(event);
7438 err:
7439 return ERR_PTR(err);
7441 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
7443 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
7445 struct perf_event_context *src_ctx;
7446 struct perf_event_context *dst_ctx;
7447 struct perf_event *event, *tmp;
7448 LIST_HEAD(events);
7450 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
7451 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
7453 mutex_lock(&src_ctx->mutex);
7454 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
7455 event_entry) {
7456 perf_remove_from_context(event, false);
7457 unaccount_event_cpu(event, src_cpu);
7458 put_ctx(src_ctx);
7459 list_add(&event->migrate_entry, &events);
7461 mutex_unlock(&src_ctx->mutex);
7463 synchronize_rcu();
7465 mutex_lock(&dst_ctx->mutex);
7466 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
7467 list_del(&event->migrate_entry);
7468 if (event->state >= PERF_EVENT_STATE_OFF)
7469 event->state = PERF_EVENT_STATE_INACTIVE;
7470 account_event_cpu(event, dst_cpu);
7471 perf_install_in_context(dst_ctx, event, dst_cpu);
7472 get_ctx(dst_ctx);
7474 mutex_unlock(&dst_ctx->mutex);
7476 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
7478 static void sync_child_event(struct perf_event *child_event,
7479 struct task_struct *child)
7481 struct perf_event *parent_event = child_event->parent;
7482 u64 child_val;
7484 if (child_event->attr.inherit_stat)
7485 perf_event_read_event(child_event, child);
7487 child_val = perf_event_count(child_event);
7490 * Add back the child's count to the parent's count:
7492 atomic64_add(child_val, &parent_event->child_count);
7493 atomic64_add(child_event->total_time_enabled,
7494 &parent_event->child_total_time_enabled);
7495 atomic64_add(child_event->total_time_running,
7496 &parent_event->child_total_time_running);
7499 * Remove this event from the parent's list
7501 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7502 mutex_lock(&parent_event->child_mutex);
7503 list_del_init(&child_event->child_list);
7504 mutex_unlock(&parent_event->child_mutex);
7507 * Release the parent event, if this was the last
7508 * reference to it.
7510 put_event(parent_event);
7513 static void
7514 __perf_event_exit_task(struct perf_event *child_event,
7515 struct perf_event_context *child_ctx,
7516 struct task_struct *child)
7519 * Do not destroy the 'original' grouping; because of the context
7520 * switch optimization the original events could've ended up in a
7521 * random child task.
7523 * If we were to destroy the original group, all group related
7524 * operations would cease to function properly after this random
7525 * child dies.
7527 * Do destroy all inherited groups, we don't care about those
7528 * and being thorough is better.
7530 perf_remove_from_context(child_event, !!child_event->parent);
7533 * It can happen that the parent exits first, and has events
7534 * that are still around due to the child reference. These
7535 * events need to be zapped.
7537 if (child_event->parent) {
7538 sync_child_event(child_event, child);
7539 free_event(child_event);
7543 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
7545 struct perf_event *child_event, *next;
7546 struct perf_event_context *child_ctx, *clone_ctx = NULL;
7547 unsigned long flags;
7549 if (likely(!child->perf_event_ctxp[ctxn])) {
7550 perf_event_task(child, NULL, 0);
7551 return;
7554 local_irq_save(flags);
7556 * We can't reschedule here because interrupts are disabled,
7557 * and either child is current or it is a task that can't be
7558 * scheduled, so we are now safe from rescheduling changing
7559 * our context.
7561 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
7564 * Take the context lock here so that if find_get_context is
7565 * reading child->perf_event_ctxp, we wait until it has
7566 * incremented the context's refcount before we do put_ctx below.
7568 raw_spin_lock(&child_ctx->lock);
7569 task_ctx_sched_out(child_ctx);
7570 child->perf_event_ctxp[ctxn] = NULL;
7573 * If this context is a clone; unclone it so it can't get
7574 * swapped to another process while we're removing all
7575 * the events from it.
7577 clone_ctx = unclone_ctx(child_ctx);
7578 update_context_time(child_ctx);
7579 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7581 if (clone_ctx)
7582 put_ctx(clone_ctx);
7585 * Report the task dead after unscheduling the events so that we
7586 * won't get any samples after PERF_RECORD_EXIT. We can however still
7587 * get a few PERF_RECORD_READ events.
7589 perf_event_task(child, child_ctx, 0);
7592 * We can recurse on the same lock type through:
7594 * __perf_event_exit_task()
7595 * sync_child_event()
7596 * put_event()
7597 * mutex_lock(&ctx->mutex)
7599 * But since its the parent context it won't be the same instance.
7601 mutex_lock(&child_ctx->mutex);
7603 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
7604 __perf_event_exit_task(child_event, child_ctx, child);
7606 mutex_unlock(&child_ctx->mutex);
7608 put_ctx(child_ctx);
7612 * When a child task exits, feed back event values to parent events.
7614 void perf_event_exit_task(struct task_struct *child)
7616 struct perf_event *event, *tmp;
7617 int ctxn;
7619 mutex_lock(&child->perf_event_mutex);
7620 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
7621 owner_entry) {
7622 list_del_init(&event->owner_entry);
7625 * Ensure the list deletion is visible before we clear
7626 * the owner, closes a race against perf_release() where
7627 * we need to serialize on the owner->perf_event_mutex.
7629 smp_wmb();
7630 event->owner = NULL;
7632 mutex_unlock(&child->perf_event_mutex);
7634 for_each_task_context_nr(ctxn)
7635 perf_event_exit_task_context(child, ctxn);
7638 static void perf_free_event(struct perf_event *event,
7639 struct perf_event_context *ctx)
7641 struct perf_event *parent = event->parent;
7643 if (WARN_ON_ONCE(!parent))
7644 return;
7646 mutex_lock(&parent->child_mutex);
7647 list_del_init(&event->child_list);
7648 mutex_unlock(&parent->child_mutex);
7650 put_event(parent);
7652 perf_group_detach(event);
7653 list_del_event(event, ctx);
7654 free_event(event);
7658 * free an unexposed, unused context as created by inheritance by
7659 * perf_event_init_task below, used by fork() in case of fail.
7661 void perf_event_free_task(struct task_struct *task)
7663 struct perf_event_context *ctx;
7664 struct perf_event *event, *tmp;
7665 int ctxn;
7667 for_each_task_context_nr(ctxn) {
7668 ctx = task->perf_event_ctxp[ctxn];
7669 if (!ctx)
7670 continue;
7672 mutex_lock(&ctx->mutex);
7673 again:
7674 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
7675 group_entry)
7676 perf_free_event(event, ctx);
7678 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
7679 group_entry)
7680 perf_free_event(event, ctx);
7682 if (!list_empty(&ctx->pinned_groups) ||
7683 !list_empty(&ctx->flexible_groups))
7684 goto again;
7686 mutex_unlock(&ctx->mutex);
7688 put_ctx(ctx);
7692 void perf_event_delayed_put(struct task_struct *task)
7694 int ctxn;
7696 for_each_task_context_nr(ctxn)
7697 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
7701 * inherit a event from parent task to child task:
7703 static struct perf_event *
7704 inherit_event(struct perf_event *parent_event,
7705 struct task_struct *parent,
7706 struct perf_event_context *parent_ctx,
7707 struct task_struct *child,
7708 struct perf_event *group_leader,
7709 struct perf_event_context *child_ctx)
7711 struct perf_event *child_event;
7712 unsigned long flags;
7715 * Instead of creating recursive hierarchies of events,
7716 * we link inherited events back to the original parent,
7717 * which has a filp for sure, which we use as the reference
7718 * count:
7720 if (parent_event->parent)
7721 parent_event = parent_event->parent;
7723 child_event = perf_event_alloc(&parent_event->attr,
7724 parent_event->cpu,
7725 child,
7726 group_leader, parent_event,
7727 NULL, NULL);
7728 if (IS_ERR(child_event))
7729 return child_event;
7731 if (!atomic_long_inc_not_zero(&parent_event->refcount)) {
7732 free_event(child_event);
7733 return NULL;
7736 get_ctx(child_ctx);
7739 * Make the child state follow the state of the parent event,
7740 * not its attr.disabled bit. We hold the parent's mutex,
7741 * so we won't race with perf_event_{en, dis}able_family.
7743 if (parent_event->state >= PERF_EVENT_STATE_INACTIVE)
7744 child_event->state = PERF_EVENT_STATE_INACTIVE;
7745 else
7746 child_event->state = PERF_EVENT_STATE_OFF;
7748 if (parent_event->attr.freq) {
7749 u64 sample_period = parent_event->hw.sample_period;
7750 struct hw_perf_event *hwc = &child_event->hw;
7752 hwc->sample_period = sample_period;
7753 hwc->last_period = sample_period;
7755 local64_set(&hwc->period_left, sample_period);
7758 child_event->ctx = child_ctx;
7759 child_event->overflow_handler = parent_event->overflow_handler;
7760 child_event->overflow_handler_context
7761 = parent_event->overflow_handler_context;
7764 * Precalculate sample_data sizes
7766 perf_event__header_size(child_event);
7767 perf_event__id_header_size(child_event);
7770 * Link it up in the child's context:
7772 raw_spin_lock_irqsave(&child_ctx->lock, flags);
7773 add_event_to_ctx(child_event, child_ctx);
7774 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7777 * Link this into the parent event's child list
7779 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7780 mutex_lock(&parent_event->child_mutex);
7781 list_add_tail(&child_event->child_list, &parent_event->child_list);
7782 mutex_unlock(&parent_event->child_mutex);
7784 return child_event;
7787 static int inherit_group(struct perf_event *parent_event,
7788 struct task_struct *parent,
7789 struct perf_event_context *parent_ctx,
7790 struct task_struct *child,
7791 struct perf_event_context *child_ctx)
7793 struct perf_event *leader;
7794 struct perf_event *sub;
7795 struct perf_event *child_ctr;
7797 leader = inherit_event(parent_event, parent, parent_ctx,
7798 child, NULL, child_ctx);
7799 if (IS_ERR(leader))
7800 return PTR_ERR(leader);
7801 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
7802 child_ctr = inherit_event(sub, parent, parent_ctx,
7803 child, leader, child_ctx);
7804 if (IS_ERR(child_ctr))
7805 return PTR_ERR(child_ctr);
7807 return 0;
7810 static int
7811 inherit_task_group(struct perf_event *event, struct task_struct *parent,
7812 struct perf_event_context *parent_ctx,
7813 struct task_struct *child, int ctxn,
7814 int *inherited_all)
7816 int ret;
7817 struct perf_event_context *child_ctx;
7819 if (!event->attr.inherit) {
7820 *inherited_all = 0;
7821 return 0;
7824 child_ctx = child->perf_event_ctxp[ctxn];
7825 if (!child_ctx) {
7827 * This is executed from the parent task context, so
7828 * inherit events that have been marked for cloning.
7829 * First allocate and initialize a context for the
7830 * child.
7833 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
7834 if (!child_ctx)
7835 return -ENOMEM;
7837 child->perf_event_ctxp[ctxn] = child_ctx;
7840 ret = inherit_group(event, parent, parent_ctx,
7841 child, child_ctx);
7843 if (ret)
7844 *inherited_all = 0;
7846 return ret;
7850 * Initialize the perf_event context in task_struct
7852 static int perf_event_init_context(struct task_struct *child, int ctxn)
7854 struct perf_event_context *child_ctx, *parent_ctx;
7855 struct perf_event_context *cloned_ctx;
7856 struct perf_event *event;
7857 struct task_struct *parent = current;
7858 int inherited_all = 1;
7859 unsigned long flags;
7860 int ret = 0;
7862 if (likely(!parent->perf_event_ctxp[ctxn]))
7863 return 0;
7866 * If the parent's context is a clone, pin it so it won't get
7867 * swapped under us.
7869 parent_ctx = perf_pin_task_context(parent, ctxn);
7870 if (!parent_ctx)
7871 return 0;
7874 * No need to check if parent_ctx != NULL here; since we saw
7875 * it non-NULL earlier, the only reason for it to become NULL
7876 * is if we exit, and since we're currently in the middle of
7877 * a fork we can't be exiting at the same time.
7881 * Lock the parent list. No need to lock the child - not PID
7882 * hashed yet and not running, so nobody can access it.
7884 mutex_lock(&parent_ctx->mutex);
7887 * We dont have to disable NMIs - we are only looking at
7888 * the list, not manipulating it:
7890 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
7891 ret = inherit_task_group(event, parent, parent_ctx,
7892 child, ctxn, &inherited_all);
7893 if (ret)
7894 break;
7898 * We can't hold ctx->lock when iterating the ->flexible_group list due
7899 * to allocations, but we need to prevent rotation because
7900 * rotate_ctx() will change the list from interrupt context.
7902 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7903 parent_ctx->rotate_disable = 1;
7904 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7906 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
7907 ret = inherit_task_group(event, parent, parent_ctx,
7908 child, ctxn, &inherited_all);
7909 if (ret)
7910 break;
7913 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7914 parent_ctx->rotate_disable = 0;
7916 child_ctx = child->perf_event_ctxp[ctxn];
7918 if (child_ctx && inherited_all) {
7920 * Mark the child context as a clone of the parent
7921 * context, or of whatever the parent is a clone of.
7923 * Note that if the parent is a clone, the holding of
7924 * parent_ctx->lock avoids it from being uncloned.
7926 cloned_ctx = parent_ctx->parent_ctx;
7927 if (cloned_ctx) {
7928 child_ctx->parent_ctx = cloned_ctx;
7929 child_ctx->parent_gen = parent_ctx->parent_gen;
7930 } else {
7931 child_ctx->parent_ctx = parent_ctx;
7932 child_ctx->parent_gen = parent_ctx->generation;
7934 get_ctx(child_ctx->parent_ctx);
7937 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7938 mutex_unlock(&parent_ctx->mutex);
7940 perf_unpin_context(parent_ctx);
7941 put_ctx(parent_ctx);
7943 return ret;
7947 * Initialize the perf_event context in task_struct
7949 int perf_event_init_task(struct task_struct *child)
7951 int ctxn, ret;
7953 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
7954 mutex_init(&child->perf_event_mutex);
7955 INIT_LIST_HEAD(&child->perf_event_list);
7957 for_each_task_context_nr(ctxn) {
7958 ret = perf_event_init_context(child, ctxn);
7959 if (ret)
7960 return ret;
7963 return 0;
7966 static void __init perf_event_init_all_cpus(void)
7968 struct swevent_htable *swhash;
7969 int cpu;
7971 for_each_possible_cpu(cpu) {
7972 swhash = &per_cpu(swevent_htable, cpu);
7973 mutex_init(&swhash->hlist_mutex);
7974 INIT_LIST_HEAD(&per_cpu(rotation_list, cpu));
7978 static void perf_event_init_cpu(int cpu)
7980 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7982 mutex_lock(&swhash->hlist_mutex);
7983 swhash->online = true;
7984 if (swhash->hlist_refcount > 0) {
7985 struct swevent_hlist *hlist;
7987 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
7988 WARN_ON(!hlist);
7989 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7991 mutex_unlock(&swhash->hlist_mutex);
7994 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC
7995 static void perf_pmu_rotate_stop(struct pmu *pmu)
7997 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7999 WARN_ON(!irqs_disabled());
8001 list_del_init(&cpuctx->rotation_list);
8004 static void __perf_event_exit_context(void *__info)
8006 struct remove_event re = { .detach_group = false };
8007 struct perf_event_context *ctx = __info;
8009 perf_pmu_rotate_stop(ctx->pmu);
8011 rcu_read_lock();
8012 list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
8013 __perf_remove_from_context(&re);
8014 rcu_read_unlock();
8017 static void perf_event_exit_cpu_context(int cpu)
8019 struct perf_event_context *ctx;
8020 struct pmu *pmu;
8021 int idx;
8023 idx = srcu_read_lock(&pmus_srcu);
8024 list_for_each_entry_rcu(pmu, &pmus, entry) {
8025 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
8027 mutex_lock(&ctx->mutex);
8028 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
8029 mutex_unlock(&ctx->mutex);
8031 srcu_read_unlock(&pmus_srcu, idx);
8034 static void perf_event_exit_cpu(int cpu)
8036 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
8038 perf_event_exit_cpu_context(cpu);
8040 mutex_lock(&swhash->hlist_mutex);
8041 swhash->online = false;
8042 swevent_hlist_release(swhash);
8043 mutex_unlock(&swhash->hlist_mutex);
8045 #else
8046 static inline void perf_event_exit_cpu(int cpu) { }
8047 #endif
8049 static int
8050 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
8052 int cpu;
8054 for_each_online_cpu(cpu)
8055 perf_event_exit_cpu(cpu);
8057 return NOTIFY_OK;
8061 * Run the perf reboot notifier at the very last possible moment so that
8062 * the generic watchdog code runs as long as possible.
8064 static struct notifier_block perf_reboot_notifier = {
8065 .notifier_call = perf_reboot,
8066 .priority = INT_MIN,
8069 static int
8070 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
8072 unsigned int cpu = (long)hcpu;
8074 switch (action & ~CPU_TASKS_FROZEN) {
8076 case CPU_UP_PREPARE:
8077 case CPU_DOWN_FAILED:
8078 perf_event_init_cpu(cpu);
8079 break;
8081 case CPU_UP_CANCELED:
8082 case CPU_DOWN_PREPARE:
8083 perf_event_exit_cpu(cpu);
8084 break;
8085 default:
8086 break;
8089 return NOTIFY_OK;
8092 void __init perf_event_init(void)
8094 int ret;
8096 idr_init(&pmu_idr);
8098 perf_event_init_all_cpus();
8099 init_srcu_struct(&pmus_srcu);
8100 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
8101 perf_pmu_register(&perf_cpu_clock, NULL, -1);
8102 perf_pmu_register(&perf_task_clock, NULL, -1);
8103 perf_tp_register();
8104 perf_cpu_notifier(perf_cpu_notify);
8105 register_reboot_notifier(&perf_reboot_notifier);
8107 ret = init_hw_breakpoint();
8108 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
8110 /* do not patch jump label more than once per second */
8111 jump_label_rate_limit(&perf_sched_events, HZ);
8114 * Build time assertion that we keep the data_head at the intended
8115 * location. IOW, validation we got the __reserved[] size right.
8117 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
8118 != 1024);
8121 static int __init perf_event_sysfs_init(void)
8123 struct pmu *pmu;
8124 int ret;
8126 mutex_lock(&pmus_lock);
8128 ret = bus_register(&pmu_bus);
8129 if (ret)
8130 goto unlock;
8132 list_for_each_entry(pmu, &pmus, entry) {
8133 if (!pmu->name || pmu->type < 0)
8134 continue;
8136 ret = pmu_dev_alloc(pmu);
8137 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
8139 pmu_bus_running = 1;
8140 ret = 0;
8142 unlock:
8143 mutex_unlock(&pmus_lock);
8145 return ret;
8147 device_initcall(perf_event_sysfs_init);
8149 #ifdef CONFIG_CGROUP_PERF
8150 static struct cgroup_subsys_state *
8151 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
8153 struct perf_cgroup *jc;
8155 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
8156 if (!jc)
8157 return ERR_PTR(-ENOMEM);
8159 jc->info = alloc_percpu(struct perf_cgroup_info);
8160 if (!jc->info) {
8161 kfree(jc);
8162 return ERR_PTR(-ENOMEM);
8165 return &jc->css;
8168 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
8170 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
8172 free_percpu(jc->info);
8173 kfree(jc);
8176 static int __perf_cgroup_move(void *info)
8178 struct task_struct *task = info;
8179 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
8180 return 0;
8183 static void perf_cgroup_attach(struct cgroup_subsys_state *css,
8184 struct cgroup_taskset *tset)
8186 struct task_struct *task;
8188 cgroup_taskset_for_each(task, tset)
8189 task_function_call(task, __perf_cgroup_move, task);
8192 static void perf_cgroup_exit(struct cgroup_subsys_state *css,
8193 struct cgroup_subsys_state *old_css,
8194 struct task_struct *task)
8197 * cgroup_exit() is called in the copy_process() failure path.
8198 * Ignore this case since the task hasn't ran yet, this avoids
8199 * trying to poke a half freed task state from generic code.
8201 if (!(task->flags & PF_EXITING))
8202 return;
8204 task_function_call(task, __perf_cgroup_move, task);
8207 struct cgroup_subsys perf_event_cgrp_subsys = {
8208 .css_alloc = perf_cgroup_css_alloc,
8209 .css_free = perf_cgroup_css_free,
8210 .exit = perf_cgroup_exit,
8211 .attach = perf_cgroup_attach,
8213 #endif /* CONFIG_CGROUP_PERF */