x86/xen: resume timer irqs early
[linux/fpc-iii.git] / kernel / events / core.c
blob624befa90019059a85f815a6c2531c930e770541
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>
43 #include "internal.h"
45 #include <asm/irq_regs.h>
47 struct remote_function_call {
48 struct task_struct *p;
49 int (*func)(void *info);
50 void *info;
51 int ret;
54 static void remote_function(void *data)
56 struct remote_function_call *tfc = data;
57 struct task_struct *p = tfc->p;
59 if (p) {
60 tfc->ret = -EAGAIN;
61 if (task_cpu(p) != smp_processor_id() || !task_curr(p))
62 return;
65 tfc->ret = tfc->func(tfc->info);
68 /**
69 * task_function_call - call a function on the cpu on which a task runs
70 * @p: the task to evaluate
71 * @func: the function to be called
72 * @info: the function call argument
74 * Calls the function @func when the task is currently running. This might
75 * be on the current CPU, which just calls the function directly
77 * returns: @func return value, or
78 * -ESRCH - when the process isn't running
79 * -EAGAIN - when the process moved away
81 static int
82 task_function_call(struct task_struct *p, int (*func) (void *info), void *info)
84 struct remote_function_call data = {
85 .p = p,
86 .func = func,
87 .info = info,
88 .ret = -ESRCH, /* No such (running) process */
91 if (task_curr(p))
92 smp_call_function_single(task_cpu(p), remote_function, &data, 1);
94 return data.ret;
97 /**
98 * cpu_function_call - call a function on the cpu
99 * @func: the function to be called
100 * @info: the function call argument
102 * Calls the function @func on the remote cpu.
104 * returns: @func return value or -ENXIO when the cpu is offline
106 static int cpu_function_call(int cpu, int (*func) (void *info), void *info)
108 struct remote_function_call data = {
109 .p = NULL,
110 .func = func,
111 .info = info,
112 .ret = -ENXIO, /* No such CPU */
115 smp_call_function_single(cpu, remote_function, &data, 1);
117 return data.ret;
120 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
121 PERF_FLAG_FD_OUTPUT |\
122 PERF_FLAG_PID_CGROUP)
125 * branch priv levels that need permission checks
127 #define PERF_SAMPLE_BRANCH_PERM_PLM \
128 (PERF_SAMPLE_BRANCH_KERNEL |\
129 PERF_SAMPLE_BRANCH_HV)
131 enum event_type_t {
132 EVENT_FLEXIBLE = 0x1,
133 EVENT_PINNED = 0x2,
134 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
138 * perf_sched_events : >0 events exist
139 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
141 struct static_key_deferred perf_sched_events __read_mostly;
142 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
143 static DEFINE_PER_CPU(atomic_t, perf_branch_stack_events);
145 static atomic_t nr_mmap_events __read_mostly;
146 static atomic_t nr_comm_events __read_mostly;
147 static atomic_t nr_task_events __read_mostly;
148 static atomic_t nr_freq_events __read_mostly;
150 static LIST_HEAD(pmus);
151 static DEFINE_MUTEX(pmus_lock);
152 static struct srcu_struct pmus_srcu;
155 * perf event paranoia level:
156 * -1 - not paranoid at all
157 * 0 - disallow raw tracepoint access for unpriv
158 * 1 - disallow cpu events for unpriv
159 * 2 - disallow kernel profiling for unpriv
161 int sysctl_perf_event_paranoid __read_mostly = 1;
163 /* Minimum for 512 kiB + 1 user control page */
164 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
167 * max perf event sample rate
169 #define DEFAULT_MAX_SAMPLE_RATE 100000
170 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
171 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
173 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
175 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
176 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
178 static atomic_t perf_sample_allowed_ns __read_mostly =
179 ATOMIC_INIT( DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100);
181 void update_perf_cpu_limits(void)
183 u64 tmp = perf_sample_period_ns;
185 tmp *= sysctl_perf_cpu_time_max_percent;
186 do_div(tmp, 100);
187 atomic_set(&perf_sample_allowed_ns, tmp);
190 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
192 int perf_proc_update_handler(struct ctl_table *table, int write,
193 void __user *buffer, size_t *lenp,
194 loff_t *ppos)
196 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
198 if (ret || !write)
199 return ret;
201 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
202 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
203 update_perf_cpu_limits();
205 return 0;
208 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
210 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
211 void __user *buffer, size_t *lenp,
212 loff_t *ppos)
214 int ret = proc_dointvec(table, write, buffer, lenp, ppos);
216 if (ret || !write)
217 return ret;
219 update_perf_cpu_limits();
221 return 0;
225 * perf samples are done in some very critical code paths (NMIs).
226 * If they take too much CPU time, the system can lock up and not
227 * get any real work done. This will drop the sample rate when
228 * we detect that events are taking too long.
230 #define NR_ACCUMULATED_SAMPLES 128
231 DEFINE_PER_CPU(u64, running_sample_length);
233 void perf_sample_event_took(u64 sample_len_ns)
235 u64 avg_local_sample_len;
236 u64 local_samples_len;
238 if (atomic_read(&perf_sample_allowed_ns) == 0)
239 return;
241 /* decay the counter by 1 average sample */
242 local_samples_len = __get_cpu_var(running_sample_length);
243 local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES;
244 local_samples_len += sample_len_ns;
245 __get_cpu_var(running_sample_length) = local_samples_len;
248 * note: this will be biased artifically low until we have
249 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
250 * from having to maintain a count.
252 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
254 if (avg_local_sample_len <= atomic_read(&perf_sample_allowed_ns))
255 return;
257 if (max_samples_per_tick <= 1)
258 return;
260 max_samples_per_tick = DIV_ROUND_UP(max_samples_per_tick, 2);
261 sysctl_perf_event_sample_rate = max_samples_per_tick * HZ;
262 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
264 printk_ratelimited(KERN_WARNING
265 "perf samples too long (%lld > %d), lowering "
266 "kernel.perf_event_max_sample_rate to %d\n",
267 avg_local_sample_len,
268 atomic_read(&perf_sample_allowed_ns),
269 sysctl_perf_event_sample_rate);
271 update_perf_cpu_limits();
274 static atomic64_t perf_event_id;
276 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
277 enum event_type_t event_type);
279 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
280 enum event_type_t event_type,
281 struct task_struct *task);
283 static void update_context_time(struct perf_event_context *ctx);
284 static u64 perf_event_time(struct perf_event *event);
286 void __weak perf_event_print_debug(void) { }
288 extern __weak const char *perf_pmu_name(void)
290 return "pmu";
293 static inline u64 perf_clock(void)
295 return local_clock();
298 static inline struct perf_cpu_context *
299 __get_cpu_context(struct perf_event_context *ctx)
301 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
304 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
305 struct perf_event_context *ctx)
307 raw_spin_lock(&cpuctx->ctx.lock);
308 if (ctx)
309 raw_spin_lock(&ctx->lock);
312 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
313 struct perf_event_context *ctx)
315 if (ctx)
316 raw_spin_unlock(&ctx->lock);
317 raw_spin_unlock(&cpuctx->ctx.lock);
320 #ifdef CONFIG_CGROUP_PERF
323 * perf_cgroup_info keeps track of time_enabled for a cgroup.
324 * This is a per-cpu dynamically allocated data structure.
326 struct perf_cgroup_info {
327 u64 time;
328 u64 timestamp;
331 struct perf_cgroup {
332 struct cgroup_subsys_state css;
333 struct perf_cgroup_info __percpu *info;
337 * Must ensure cgroup is pinned (css_get) before calling
338 * this function. In other words, we cannot call this function
339 * if there is no cgroup event for the current CPU context.
341 static inline struct perf_cgroup *
342 perf_cgroup_from_task(struct task_struct *task)
344 return container_of(task_css(task, perf_subsys_id),
345 struct perf_cgroup, css);
348 static inline bool
349 perf_cgroup_match(struct perf_event *event)
351 struct perf_event_context *ctx = event->ctx;
352 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
354 /* @event doesn't care about cgroup */
355 if (!event->cgrp)
356 return true;
358 /* wants specific cgroup scope but @cpuctx isn't associated with any */
359 if (!cpuctx->cgrp)
360 return false;
363 * Cgroup scoping is recursive. An event enabled for a cgroup is
364 * also enabled for all its descendant cgroups. If @cpuctx's
365 * cgroup is a descendant of @event's (the test covers identity
366 * case), it's a match.
368 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
369 event->cgrp->css.cgroup);
372 static inline bool perf_tryget_cgroup(struct perf_event *event)
374 return css_tryget(&event->cgrp->css);
377 static inline void perf_put_cgroup(struct perf_event *event)
379 css_put(&event->cgrp->css);
382 static inline void perf_detach_cgroup(struct perf_event *event)
384 perf_put_cgroup(event);
385 event->cgrp = NULL;
388 static inline int is_cgroup_event(struct perf_event *event)
390 return event->cgrp != NULL;
393 static inline u64 perf_cgroup_event_time(struct perf_event *event)
395 struct perf_cgroup_info *t;
397 t = per_cpu_ptr(event->cgrp->info, event->cpu);
398 return t->time;
401 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
403 struct perf_cgroup_info *info;
404 u64 now;
406 now = perf_clock();
408 info = this_cpu_ptr(cgrp->info);
410 info->time += now - info->timestamp;
411 info->timestamp = now;
414 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
416 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
417 if (cgrp_out)
418 __update_cgrp_time(cgrp_out);
421 static inline void update_cgrp_time_from_event(struct perf_event *event)
423 struct perf_cgroup *cgrp;
426 * ensure we access cgroup data only when needed and
427 * when we know the cgroup is pinned (css_get)
429 if (!is_cgroup_event(event))
430 return;
432 cgrp = perf_cgroup_from_task(current);
434 * Do not update time when cgroup is not active
436 if (cgrp == event->cgrp)
437 __update_cgrp_time(event->cgrp);
440 static inline void
441 perf_cgroup_set_timestamp(struct task_struct *task,
442 struct perf_event_context *ctx)
444 struct perf_cgroup *cgrp;
445 struct perf_cgroup_info *info;
448 * ctx->lock held by caller
449 * ensure we do not access cgroup data
450 * unless we have the cgroup pinned (css_get)
452 if (!task || !ctx->nr_cgroups)
453 return;
455 cgrp = perf_cgroup_from_task(task);
456 info = this_cpu_ptr(cgrp->info);
457 info->timestamp = ctx->timestamp;
460 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
461 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
464 * reschedule events based on the cgroup constraint of task.
466 * mode SWOUT : schedule out everything
467 * mode SWIN : schedule in based on cgroup for next
469 void perf_cgroup_switch(struct task_struct *task, int mode)
471 struct perf_cpu_context *cpuctx;
472 struct pmu *pmu;
473 unsigned long flags;
476 * disable interrupts to avoid geting nr_cgroup
477 * changes via __perf_event_disable(). Also
478 * avoids preemption.
480 local_irq_save(flags);
483 * we reschedule only in the presence of cgroup
484 * constrained events.
486 rcu_read_lock();
488 list_for_each_entry_rcu(pmu, &pmus, entry) {
489 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
490 if (cpuctx->unique_pmu != pmu)
491 continue; /* ensure we process each cpuctx once */
494 * perf_cgroup_events says at least one
495 * context on this CPU has cgroup events.
497 * ctx->nr_cgroups reports the number of cgroup
498 * events for a context.
500 if (cpuctx->ctx.nr_cgroups > 0) {
501 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
502 perf_pmu_disable(cpuctx->ctx.pmu);
504 if (mode & PERF_CGROUP_SWOUT) {
505 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
507 * must not be done before ctxswout due
508 * to event_filter_match() in event_sched_out()
510 cpuctx->cgrp = NULL;
513 if (mode & PERF_CGROUP_SWIN) {
514 WARN_ON_ONCE(cpuctx->cgrp);
516 * set cgrp before ctxsw in to allow
517 * event_filter_match() to not have to pass
518 * task around
520 cpuctx->cgrp = perf_cgroup_from_task(task);
521 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
523 perf_pmu_enable(cpuctx->ctx.pmu);
524 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
528 rcu_read_unlock();
530 local_irq_restore(flags);
533 static inline void perf_cgroup_sched_out(struct task_struct *task,
534 struct task_struct *next)
536 struct perf_cgroup *cgrp1;
537 struct perf_cgroup *cgrp2 = NULL;
540 * we come here when we know perf_cgroup_events > 0
542 cgrp1 = perf_cgroup_from_task(task);
545 * next is NULL when called from perf_event_enable_on_exec()
546 * that will systematically cause a cgroup_switch()
548 if (next)
549 cgrp2 = perf_cgroup_from_task(next);
552 * only schedule out current cgroup events if we know
553 * that we are switching to a different cgroup. Otherwise,
554 * do no touch the cgroup events.
556 if (cgrp1 != cgrp2)
557 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
560 static inline void perf_cgroup_sched_in(struct task_struct *prev,
561 struct task_struct *task)
563 struct perf_cgroup *cgrp1;
564 struct perf_cgroup *cgrp2 = NULL;
567 * we come here when we know perf_cgroup_events > 0
569 cgrp1 = perf_cgroup_from_task(task);
571 /* prev can never be NULL */
572 cgrp2 = perf_cgroup_from_task(prev);
575 * only need to schedule in cgroup events if we are changing
576 * cgroup during ctxsw. Cgroup events were not scheduled
577 * out of ctxsw out if that was not the case.
579 if (cgrp1 != cgrp2)
580 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
583 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
584 struct perf_event_attr *attr,
585 struct perf_event *group_leader)
587 struct perf_cgroup *cgrp;
588 struct cgroup_subsys_state *css;
589 struct fd f = fdget(fd);
590 int ret = 0;
592 if (!f.file)
593 return -EBADF;
595 rcu_read_lock();
597 css = css_from_dir(f.file->f_dentry, &perf_subsys);
598 if (IS_ERR(css)) {
599 ret = PTR_ERR(css);
600 goto out;
603 cgrp = container_of(css, struct perf_cgroup, css);
604 event->cgrp = cgrp;
606 /* must be done before we fput() the file */
607 if (!perf_tryget_cgroup(event)) {
608 event->cgrp = NULL;
609 ret = -ENOENT;
610 goto out;
614 * all events in a group must monitor
615 * the same cgroup because a task belongs
616 * to only one perf cgroup at a time
618 if (group_leader && group_leader->cgrp != cgrp) {
619 perf_detach_cgroup(event);
620 ret = -EINVAL;
622 out:
623 rcu_read_unlock();
624 fdput(f);
625 return ret;
628 static inline void
629 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
631 struct perf_cgroup_info *t;
632 t = per_cpu_ptr(event->cgrp->info, event->cpu);
633 event->shadow_ctx_time = now - t->timestamp;
636 static inline void
637 perf_cgroup_defer_enabled(struct perf_event *event)
640 * when the current task's perf cgroup does not match
641 * the event's, we need to remember to call the
642 * perf_mark_enable() function the first time a task with
643 * a matching perf cgroup is scheduled in.
645 if (is_cgroup_event(event) && !perf_cgroup_match(event))
646 event->cgrp_defer_enabled = 1;
649 static inline void
650 perf_cgroup_mark_enabled(struct perf_event *event,
651 struct perf_event_context *ctx)
653 struct perf_event *sub;
654 u64 tstamp = perf_event_time(event);
656 if (!event->cgrp_defer_enabled)
657 return;
659 event->cgrp_defer_enabled = 0;
661 event->tstamp_enabled = tstamp - event->total_time_enabled;
662 list_for_each_entry(sub, &event->sibling_list, group_entry) {
663 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
664 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
665 sub->cgrp_defer_enabled = 0;
669 #else /* !CONFIG_CGROUP_PERF */
671 static inline bool
672 perf_cgroup_match(struct perf_event *event)
674 return true;
677 static inline void perf_detach_cgroup(struct perf_event *event)
680 static inline int is_cgroup_event(struct perf_event *event)
682 return 0;
685 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
687 return 0;
690 static inline void update_cgrp_time_from_event(struct perf_event *event)
694 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
698 static inline void perf_cgroup_sched_out(struct task_struct *task,
699 struct task_struct *next)
703 static inline void perf_cgroup_sched_in(struct task_struct *prev,
704 struct task_struct *task)
708 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
709 struct perf_event_attr *attr,
710 struct perf_event *group_leader)
712 return -EINVAL;
715 static inline void
716 perf_cgroup_set_timestamp(struct task_struct *task,
717 struct perf_event_context *ctx)
721 void
722 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
726 static inline void
727 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
731 static inline u64 perf_cgroup_event_time(struct perf_event *event)
733 return 0;
736 static inline void
737 perf_cgroup_defer_enabled(struct perf_event *event)
741 static inline void
742 perf_cgroup_mark_enabled(struct perf_event *event,
743 struct perf_event_context *ctx)
746 #endif
749 * set default to be dependent on timer tick just
750 * like original code
752 #define PERF_CPU_HRTIMER (1000 / HZ)
754 * function must be called with interrupts disbled
756 static enum hrtimer_restart perf_cpu_hrtimer_handler(struct hrtimer *hr)
758 struct perf_cpu_context *cpuctx;
759 enum hrtimer_restart ret = HRTIMER_NORESTART;
760 int rotations = 0;
762 WARN_ON(!irqs_disabled());
764 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
766 rotations = perf_rotate_context(cpuctx);
769 * arm timer if needed
771 if (rotations) {
772 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
773 ret = HRTIMER_RESTART;
776 return ret;
779 /* CPU is going down */
780 void perf_cpu_hrtimer_cancel(int cpu)
782 struct perf_cpu_context *cpuctx;
783 struct pmu *pmu;
784 unsigned long flags;
786 if (WARN_ON(cpu != smp_processor_id()))
787 return;
789 local_irq_save(flags);
791 rcu_read_lock();
793 list_for_each_entry_rcu(pmu, &pmus, entry) {
794 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
796 if (pmu->task_ctx_nr == perf_sw_context)
797 continue;
799 hrtimer_cancel(&cpuctx->hrtimer);
802 rcu_read_unlock();
804 local_irq_restore(flags);
807 static void __perf_cpu_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
809 struct hrtimer *hr = &cpuctx->hrtimer;
810 struct pmu *pmu = cpuctx->ctx.pmu;
811 int timer;
813 /* no multiplexing needed for SW PMU */
814 if (pmu->task_ctx_nr == perf_sw_context)
815 return;
818 * check default is sane, if not set then force to
819 * default interval (1/tick)
821 timer = pmu->hrtimer_interval_ms;
822 if (timer < 1)
823 timer = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
825 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
827 hrtimer_init(hr, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
828 hr->function = perf_cpu_hrtimer_handler;
831 static void perf_cpu_hrtimer_restart(struct perf_cpu_context *cpuctx)
833 struct hrtimer *hr = &cpuctx->hrtimer;
834 struct pmu *pmu = cpuctx->ctx.pmu;
836 /* not for SW PMU */
837 if (pmu->task_ctx_nr == perf_sw_context)
838 return;
840 if (hrtimer_active(hr))
841 return;
843 if (!hrtimer_callback_running(hr))
844 __hrtimer_start_range_ns(hr, cpuctx->hrtimer_interval,
845 0, HRTIMER_MODE_REL_PINNED, 0);
848 void perf_pmu_disable(struct pmu *pmu)
850 int *count = this_cpu_ptr(pmu->pmu_disable_count);
851 if (!(*count)++)
852 pmu->pmu_disable(pmu);
855 void perf_pmu_enable(struct pmu *pmu)
857 int *count = this_cpu_ptr(pmu->pmu_disable_count);
858 if (!--(*count))
859 pmu->pmu_enable(pmu);
862 static DEFINE_PER_CPU(struct list_head, rotation_list);
865 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
866 * because they're strictly cpu affine and rotate_start is called with IRQs
867 * disabled, while rotate_context is called from IRQ context.
869 static void perf_pmu_rotate_start(struct pmu *pmu)
871 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
872 struct list_head *head = &__get_cpu_var(rotation_list);
874 WARN_ON(!irqs_disabled());
876 if (list_empty(&cpuctx->rotation_list))
877 list_add(&cpuctx->rotation_list, head);
880 static void get_ctx(struct perf_event_context *ctx)
882 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
885 static void put_ctx(struct perf_event_context *ctx)
887 if (atomic_dec_and_test(&ctx->refcount)) {
888 if (ctx->parent_ctx)
889 put_ctx(ctx->parent_ctx);
890 if (ctx->task)
891 put_task_struct(ctx->task);
892 kfree_rcu(ctx, rcu_head);
896 static void unclone_ctx(struct perf_event_context *ctx)
898 if (ctx->parent_ctx) {
899 put_ctx(ctx->parent_ctx);
900 ctx->parent_ctx = NULL;
904 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
907 * only top level events have the pid namespace they were created in
909 if (event->parent)
910 event = event->parent;
912 return task_tgid_nr_ns(p, event->ns);
915 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
918 * only top level events have the pid namespace they were created in
920 if (event->parent)
921 event = event->parent;
923 return task_pid_nr_ns(p, event->ns);
927 * If we inherit events we want to return the parent event id
928 * to userspace.
930 static u64 primary_event_id(struct perf_event *event)
932 u64 id = event->id;
934 if (event->parent)
935 id = event->parent->id;
937 return id;
941 * Get the perf_event_context for a task and lock it.
942 * This has to cope with with the fact that until it is locked,
943 * the context could get moved to another task.
945 static struct perf_event_context *
946 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
948 struct perf_event_context *ctx;
950 retry:
952 * One of the few rules of preemptible RCU is that one cannot do
953 * rcu_read_unlock() while holding a scheduler (or nested) lock when
954 * part of the read side critical section was preemptible -- see
955 * rcu_read_unlock_special().
957 * Since ctx->lock nests under rq->lock we must ensure the entire read
958 * side critical section is non-preemptible.
960 preempt_disable();
961 rcu_read_lock();
962 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
963 if (ctx) {
965 * If this context is a clone of another, it might
966 * get swapped for another underneath us by
967 * perf_event_task_sched_out, though the
968 * rcu_read_lock() protects us from any context
969 * getting freed. Lock the context and check if it
970 * got swapped before we could get the lock, and retry
971 * if so. If we locked the right context, then it
972 * can't get swapped on us any more.
974 raw_spin_lock_irqsave(&ctx->lock, *flags);
975 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
976 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
977 rcu_read_unlock();
978 preempt_enable();
979 goto retry;
982 if (!atomic_inc_not_zero(&ctx->refcount)) {
983 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
984 ctx = NULL;
987 rcu_read_unlock();
988 preempt_enable();
989 return ctx;
993 * Get the context for a task and increment its pin_count so it
994 * can't get swapped to another task. This also increments its
995 * reference count so that the context can't get freed.
997 static struct perf_event_context *
998 perf_pin_task_context(struct task_struct *task, int ctxn)
1000 struct perf_event_context *ctx;
1001 unsigned long flags;
1003 ctx = perf_lock_task_context(task, ctxn, &flags);
1004 if (ctx) {
1005 ++ctx->pin_count;
1006 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1008 return ctx;
1011 static void perf_unpin_context(struct perf_event_context *ctx)
1013 unsigned long flags;
1015 raw_spin_lock_irqsave(&ctx->lock, flags);
1016 --ctx->pin_count;
1017 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1021 * Update the record of the current time in a context.
1023 static void update_context_time(struct perf_event_context *ctx)
1025 u64 now = perf_clock();
1027 ctx->time += now - ctx->timestamp;
1028 ctx->timestamp = now;
1031 static u64 perf_event_time(struct perf_event *event)
1033 struct perf_event_context *ctx = event->ctx;
1035 if (is_cgroup_event(event))
1036 return perf_cgroup_event_time(event);
1038 return ctx ? ctx->time : 0;
1042 * Update the total_time_enabled and total_time_running fields for a event.
1043 * The caller of this function needs to hold the ctx->lock.
1045 static void update_event_times(struct perf_event *event)
1047 struct perf_event_context *ctx = event->ctx;
1048 u64 run_end;
1050 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1051 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1052 return;
1054 * in cgroup mode, time_enabled represents
1055 * the time the event was enabled AND active
1056 * tasks were in the monitored cgroup. This is
1057 * independent of the activity of the context as
1058 * there may be a mix of cgroup and non-cgroup events.
1060 * That is why we treat cgroup events differently
1061 * here.
1063 if (is_cgroup_event(event))
1064 run_end = perf_cgroup_event_time(event);
1065 else if (ctx->is_active)
1066 run_end = ctx->time;
1067 else
1068 run_end = event->tstamp_stopped;
1070 event->total_time_enabled = run_end - event->tstamp_enabled;
1072 if (event->state == PERF_EVENT_STATE_INACTIVE)
1073 run_end = event->tstamp_stopped;
1074 else
1075 run_end = perf_event_time(event);
1077 event->total_time_running = run_end - event->tstamp_running;
1082 * Update total_time_enabled and total_time_running for all events in a group.
1084 static void update_group_times(struct perf_event *leader)
1086 struct perf_event *event;
1088 update_event_times(leader);
1089 list_for_each_entry(event, &leader->sibling_list, group_entry)
1090 update_event_times(event);
1093 static struct list_head *
1094 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1096 if (event->attr.pinned)
1097 return &ctx->pinned_groups;
1098 else
1099 return &ctx->flexible_groups;
1103 * Add a event from the lists for its context.
1104 * Must be called with ctx->mutex and ctx->lock held.
1106 static void
1107 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1109 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1110 event->attach_state |= PERF_ATTACH_CONTEXT;
1113 * If we're a stand alone event or group leader, we go to the context
1114 * list, group events are kept attached to the group so that
1115 * perf_group_detach can, at all times, locate all siblings.
1117 if (event->group_leader == event) {
1118 struct list_head *list;
1120 if (is_software_event(event))
1121 event->group_flags |= PERF_GROUP_SOFTWARE;
1123 list = ctx_group_list(event, ctx);
1124 list_add_tail(&event->group_entry, list);
1127 if (is_cgroup_event(event))
1128 ctx->nr_cgroups++;
1130 if (has_branch_stack(event))
1131 ctx->nr_branch_stack++;
1133 list_add_rcu(&event->event_entry, &ctx->event_list);
1134 if (!ctx->nr_events)
1135 perf_pmu_rotate_start(ctx->pmu);
1136 ctx->nr_events++;
1137 if (event->attr.inherit_stat)
1138 ctx->nr_stat++;
1142 * Initialize event state based on the perf_event_attr::disabled.
1144 static inline void perf_event__state_init(struct perf_event *event)
1146 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1147 PERF_EVENT_STATE_INACTIVE;
1151 * Called at perf_event creation and when events are attached/detached from a
1152 * group.
1154 static void perf_event__read_size(struct perf_event *event)
1156 int entry = sizeof(u64); /* value */
1157 int size = 0;
1158 int nr = 1;
1160 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1161 size += sizeof(u64);
1163 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1164 size += sizeof(u64);
1166 if (event->attr.read_format & PERF_FORMAT_ID)
1167 entry += sizeof(u64);
1169 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1170 nr += event->group_leader->nr_siblings;
1171 size += sizeof(u64);
1174 size += entry * nr;
1175 event->read_size = size;
1178 static void perf_event__header_size(struct perf_event *event)
1180 struct perf_sample_data *data;
1181 u64 sample_type = event->attr.sample_type;
1182 u16 size = 0;
1184 perf_event__read_size(event);
1186 if (sample_type & PERF_SAMPLE_IP)
1187 size += sizeof(data->ip);
1189 if (sample_type & PERF_SAMPLE_ADDR)
1190 size += sizeof(data->addr);
1192 if (sample_type & PERF_SAMPLE_PERIOD)
1193 size += sizeof(data->period);
1195 if (sample_type & PERF_SAMPLE_WEIGHT)
1196 size += sizeof(data->weight);
1198 if (sample_type & PERF_SAMPLE_READ)
1199 size += event->read_size;
1201 if (sample_type & PERF_SAMPLE_DATA_SRC)
1202 size += sizeof(data->data_src.val);
1204 event->header_size = size;
1207 static void perf_event__id_header_size(struct perf_event *event)
1209 struct perf_sample_data *data;
1210 u64 sample_type = event->attr.sample_type;
1211 u16 size = 0;
1213 if (sample_type & PERF_SAMPLE_TID)
1214 size += sizeof(data->tid_entry);
1216 if (sample_type & PERF_SAMPLE_TIME)
1217 size += sizeof(data->time);
1219 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1220 size += sizeof(data->id);
1222 if (sample_type & PERF_SAMPLE_ID)
1223 size += sizeof(data->id);
1225 if (sample_type & PERF_SAMPLE_STREAM_ID)
1226 size += sizeof(data->stream_id);
1228 if (sample_type & PERF_SAMPLE_CPU)
1229 size += sizeof(data->cpu_entry);
1231 event->id_header_size = size;
1234 static void perf_group_attach(struct perf_event *event)
1236 struct perf_event *group_leader = event->group_leader, *pos;
1239 * We can have double attach due to group movement in perf_event_open.
1241 if (event->attach_state & PERF_ATTACH_GROUP)
1242 return;
1244 event->attach_state |= PERF_ATTACH_GROUP;
1246 if (group_leader == event)
1247 return;
1249 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1250 !is_software_event(event))
1251 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1253 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1254 group_leader->nr_siblings++;
1256 perf_event__header_size(group_leader);
1258 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1259 perf_event__header_size(pos);
1263 * Remove a event from the lists for its context.
1264 * Must be called with ctx->mutex and ctx->lock held.
1266 static void
1267 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1269 struct perf_cpu_context *cpuctx;
1271 * We can have double detach due to exit/hot-unplug + close.
1273 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1274 return;
1276 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1278 if (is_cgroup_event(event)) {
1279 ctx->nr_cgroups--;
1280 cpuctx = __get_cpu_context(ctx);
1282 * if there are no more cgroup events
1283 * then cler cgrp to avoid stale pointer
1284 * in update_cgrp_time_from_cpuctx()
1286 if (!ctx->nr_cgroups)
1287 cpuctx->cgrp = NULL;
1290 if (has_branch_stack(event))
1291 ctx->nr_branch_stack--;
1293 ctx->nr_events--;
1294 if (event->attr.inherit_stat)
1295 ctx->nr_stat--;
1297 list_del_rcu(&event->event_entry);
1299 if (event->group_leader == event)
1300 list_del_init(&event->group_entry);
1302 update_group_times(event);
1305 * If event was in error state, then keep it
1306 * that way, otherwise bogus counts will be
1307 * returned on read(). The only way to get out
1308 * of error state is by explicit re-enabling
1309 * of the event
1311 if (event->state > PERF_EVENT_STATE_OFF)
1312 event->state = PERF_EVENT_STATE_OFF;
1315 static void perf_group_detach(struct perf_event *event)
1317 struct perf_event *sibling, *tmp;
1318 struct list_head *list = NULL;
1321 * We can have double detach due to exit/hot-unplug + close.
1323 if (!(event->attach_state & PERF_ATTACH_GROUP))
1324 return;
1326 event->attach_state &= ~PERF_ATTACH_GROUP;
1329 * If this is a sibling, remove it from its group.
1331 if (event->group_leader != event) {
1332 list_del_init(&event->group_entry);
1333 event->group_leader->nr_siblings--;
1334 goto out;
1337 if (!list_empty(&event->group_entry))
1338 list = &event->group_entry;
1341 * If this was a group event with sibling events then
1342 * upgrade the siblings to singleton events by adding them
1343 * to whatever list we are on.
1345 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1346 if (list)
1347 list_move_tail(&sibling->group_entry, list);
1348 sibling->group_leader = sibling;
1350 /* Inherit group flags from the previous leader */
1351 sibling->group_flags = event->group_flags;
1354 out:
1355 perf_event__header_size(event->group_leader);
1357 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1358 perf_event__header_size(tmp);
1361 static inline int
1362 event_filter_match(struct perf_event *event)
1364 return (event->cpu == -1 || event->cpu == smp_processor_id())
1365 && perf_cgroup_match(event);
1368 static void
1369 event_sched_out(struct perf_event *event,
1370 struct perf_cpu_context *cpuctx,
1371 struct perf_event_context *ctx)
1373 u64 tstamp = perf_event_time(event);
1374 u64 delta;
1376 * An event which could not be activated because of
1377 * filter mismatch still needs to have its timings
1378 * maintained, otherwise bogus information is return
1379 * via read() for time_enabled, time_running:
1381 if (event->state == PERF_EVENT_STATE_INACTIVE
1382 && !event_filter_match(event)) {
1383 delta = tstamp - event->tstamp_stopped;
1384 event->tstamp_running += delta;
1385 event->tstamp_stopped = tstamp;
1388 if (event->state != PERF_EVENT_STATE_ACTIVE)
1389 return;
1391 event->state = PERF_EVENT_STATE_INACTIVE;
1392 if (event->pending_disable) {
1393 event->pending_disable = 0;
1394 event->state = PERF_EVENT_STATE_OFF;
1396 event->tstamp_stopped = tstamp;
1397 event->pmu->del(event, 0);
1398 event->oncpu = -1;
1400 if (!is_software_event(event))
1401 cpuctx->active_oncpu--;
1402 ctx->nr_active--;
1403 if (event->attr.freq && event->attr.sample_freq)
1404 ctx->nr_freq--;
1405 if (event->attr.exclusive || !cpuctx->active_oncpu)
1406 cpuctx->exclusive = 0;
1409 static void
1410 group_sched_out(struct perf_event *group_event,
1411 struct perf_cpu_context *cpuctx,
1412 struct perf_event_context *ctx)
1414 struct perf_event *event;
1415 int state = group_event->state;
1417 event_sched_out(group_event, cpuctx, ctx);
1420 * Schedule out siblings (if any):
1422 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1423 event_sched_out(event, cpuctx, ctx);
1425 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1426 cpuctx->exclusive = 0;
1429 struct remove_event {
1430 struct perf_event *event;
1431 bool detach_group;
1435 * Cross CPU call to remove a performance event
1437 * We disable the event on the hardware level first. After that we
1438 * remove it from the context list.
1440 static int __perf_remove_from_context(void *info)
1442 struct remove_event *re = info;
1443 struct perf_event *event = re->event;
1444 struct perf_event_context *ctx = event->ctx;
1445 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1447 raw_spin_lock(&ctx->lock);
1448 event_sched_out(event, cpuctx, ctx);
1449 if (re->detach_group)
1450 perf_group_detach(event);
1451 list_del_event(event, ctx);
1452 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1453 ctx->is_active = 0;
1454 cpuctx->task_ctx = NULL;
1456 raw_spin_unlock(&ctx->lock);
1458 return 0;
1463 * Remove the event from a task's (or a CPU's) list of events.
1465 * CPU events are removed with a smp call. For task events we only
1466 * call when the task is on a CPU.
1468 * If event->ctx is a cloned context, callers must make sure that
1469 * every task struct that event->ctx->task could possibly point to
1470 * remains valid. This is OK when called from perf_release since
1471 * that only calls us on the top-level context, which can't be a clone.
1472 * When called from perf_event_exit_task, it's OK because the
1473 * context has been detached from its task.
1475 static void perf_remove_from_context(struct perf_event *event, bool detach_group)
1477 struct perf_event_context *ctx = event->ctx;
1478 struct task_struct *task = ctx->task;
1479 struct remove_event re = {
1480 .event = event,
1481 .detach_group = detach_group,
1484 lockdep_assert_held(&ctx->mutex);
1486 if (!task) {
1488 * Per cpu events are removed via an smp call and
1489 * the removal is always successful.
1491 cpu_function_call(event->cpu, __perf_remove_from_context, &re);
1492 return;
1495 retry:
1496 if (!task_function_call(task, __perf_remove_from_context, &re))
1497 return;
1499 raw_spin_lock_irq(&ctx->lock);
1501 * If we failed to find a running task, but find the context active now
1502 * that we've acquired the ctx->lock, retry.
1504 if (ctx->is_active) {
1505 raw_spin_unlock_irq(&ctx->lock);
1506 goto retry;
1510 * Since the task isn't running, its safe to remove the event, us
1511 * holding the ctx->lock ensures the task won't get scheduled in.
1513 if (detach_group)
1514 perf_group_detach(event);
1515 list_del_event(event, ctx);
1516 raw_spin_unlock_irq(&ctx->lock);
1520 * Cross CPU call to disable a performance event
1522 int __perf_event_disable(void *info)
1524 struct perf_event *event = info;
1525 struct perf_event_context *ctx = event->ctx;
1526 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1529 * If this is a per-task event, need to check whether this
1530 * event's task is the current task on this cpu.
1532 * Can trigger due to concurrent perf_event_context_sched_out()
1533 * flipping contexts around.
1535 if (ctx->task && cpuctx->task_ctx != ctx)
1536 return -EINVAL;
1538 raw_spin_lock(&ctx->lock);
1541 * If the event is on, turn it off.
1542 * If it is in error state, leave it in error state.
1544 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1545 update_context_time(ctx);
1546 update_cgrp_time_from_event(event);
1547 update_group_times(event);
1548 if (event == event->group_leader)
1549 group_sched_out(event, cpuctx, ctx);
1550 else
1551 event_sched_out(event, cpuctx, ctx);
1552 event->state = PERF_EVENT_STATE_OFF;
1555 raw_spin_unlock(&ctx->lock);
1557 return 0;
1561 * Disable a event.
1563 * If event->ctx is a cloned context, callers must make sure that
1564 * every task struct that event->ctx->task could possibly point to
1565 * remains valid. This condition is satisifed when called through
1566 * perf_event_for_each_child or perf_event_for_each because they
1567 * hold the top-level event's child_mutex, so any descendant that
1568 * goes to exit will block in sync_child_event.
1569 * When called from perf_pending_event it's OK because event->ctx
1570 * is the current context on this CPU and preemption is disabled,
1571 * hence we can't get into perf_event_task_sched_out for this context.
1573 void perf_event_disable(struct perf_event *event)
1575 struct perf_event_context *ctx = event->ctx;
1576 struct task_struct *task = ctx->task;
1578 if (!task) {
1580 * Disable the event on the cpu that it's on
1582 cpu_function_call(event->cpu, __perf_event_disable, event);
1583 return;
1586 retry:
1587 if (!task_function_call(task, __perf_event_disable, event))
1588 return;
1590 raw_spin_lock_irq(&ctx->lock);
1592 * If the event is still active, we need to retry the cross-call.
1594 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1595 raw_spin_unlock_irq(&ctx->lock);
1597 * Reload the task pointer, it might have been changed by
1598 * a concurrent perf_event_context_sched_out().
1600 task = ctx->task;
1601 goto retry;
1605 * Since we have the lock this context can't be scheduled
1606 * in, so we can change the state safely.
1608 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1609 update_group_times(event);
1610 event->state = PERF_EVENT_STATE_OFF;
1612 raw_spin_unlock_irq(&ctx->lock);
1614 EXPORT_SYMBOL_GPL(perf_event_disable);
1616 static void perf_set_shadow_time(struct perf_event *event,
1617 struct perf_event_context *ctx,
1618 u64 tstamp)
1621 * use the correct time source for the time snapshot
1623 * We could get by without this by leveraging the
1624 * fact that to get to this function, the caller
1625 * has most likely already called update_context_time()
1626 * and update_cgrp_time_xx() and thus both timestamp
1627 * are identical (or very close). Given that tstamp is,
1628 * already adjusted for cgroup, we could say that:
1629 * tstamp - ctx->timestamp
1630 * is equivalent to
1631 * tstamp - cgrp->timestamp.
1633 * Then, in perf_output_read(), the calculation would
1634 * work with no changes because:
1635 * - event is guaranteed scheduled in
1636 * - no scheduled out in between
1637 * - thus the timestamp would be the same
1639 * But this is a bit hairy.
1641 * So instead, we have an explicit cgroup call to remain
1642 * within the time time source all along. We believe it
1643 * is cleaner and simpler to understand.
1645 if (is_cgroup_event(event))
1646 perf_cgroup_set_shadow_time(event, tstamp);
1647 else
1648 event->shadow_ctx_time = tstamp - ctx->timestamp;
1651 #define MAX_INTERRUPTS (~0ULL)
1653 static void perf_log_throttle(struct perf_event *event, int enable);
1655 static int
1656 event_sched_in(struct perf_event *event,
1657 struct perf_cpu_context *cpuctx,
1658 struct perf_event_context *ctx)
1660 u64 tstamp = perf_event_time(event);
1662 if (event->state <= PERF_EVENT_STATE_OFF)
1663 return 0;
1665 event->state = PERF_EVENT_STATE_ACTIVE;
1666 event->oncpu = smp_processor_id();
1669 * Unthrottle events, since we scheduled we might have missed several
1670 * ticks already, also for a heavily scheduling task there is little
1671 * guarantee it'll get a tick in a timely manner.
1673 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1674 perf_log_throttle(event, 1);
1675 event->hw.interrupts = 0;
1679 * The new state must be visible before we turn it on in the hardware:
1681 smp_wmb();
1683 if (event->pmu->add(event, PERF_EF_START)) {
1684 event->state = PERF_EVENT_STATE_INACTIVE;
1685 event->oncpu = -1;
1686 return -EAGAIN;
1689 event->tstamp_running += tstamp - event->tstamp_stopped;
1691 perf_set_shadow_time(event, ctx, tstamp);
1693 if (!is_software_event(event))
1694 cpuctx->active_oncpu++;
1695 ctx->nr_active++;
1696 if (event->attr.freq && event->attr.sample_freq)
1697 ctx->nr_freq++;
1699 if (event->attr.exclusive)
1700 cpuctx->exclusive = 1;
1702 return 0;
1705 static int
1706 group_sched_in(struct perf_event *group_event,
1707 struct perf_cpu_context *cpuctx,
1708 struct perf_event_context *ctx)
1710 struct perf_event *event, *partial_group = NULL;
1711 struct pmu *pmu = group_event->pmu;
1712 u64 now = ctx->time;
1713 bool simulate = false;
1715 if (group_event->state == PERF_EVENT_STATE_OFF)
1716 return 0;
1718 pmu->start_txn(pmu);
1720 if (event_sched_in(group_event, cpuctx, ctx)) {
1721 pmu->cancel_txn(pmu);
1722 perf_cpu_hrtimer_restart(cpuctx);
1723 return -EAGAIN;
1727 * Schedule in siblings as one group (if any):
1729 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1730 if (event_sched_in(event, cpuctx, ctx)) {
1731 partial_group = event;
1732 goto group_error;
1736 if (!pmu->commit_txn(pmu))
1737 return 0;
1739 group_error:
1741 * Groups can be scheduled in as one unit only, so undo any
1742 * partial group before returning:
1743 * The events up to the failed event are scheduled out normally,
1744 * tstamp_stopped will be updated.
1746 * The failed events and the remaining siblings need to have
1747 * their timings updated as if they had gone thru event_sched_in()
1748 * and event_sched_out(). This is required to get consistent timings
1749 * across the group. This also takes care of the case where the group
1750 * could never be scheduled by ensuring tstamp_stopped is set to mark
1751 * the time the event was actually stopped, such that time delta
1752 * calculation in update_event_times() is correct.
1754 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1755 if (event == partial_group)
1756 simulate = true;
1758 if (simulate) {
1759 event->tstamp_running += now - event->tstamp_stopped;
1760 event->tstamp_stopped = now;
1761 } else {
1762 event_sched_out(event, cpuctx, ctx);
1765 event_sched_out(group_event, cpuctx, ctx);
1767 pmu->cancel_txn(pmu);
1769 perf_cpu_hrtimer_restart(cpuctx);
1771 return -EAGAIN;
1775 * Work out whether we can put this event group on the CPU now.
1777 static int group_can_go_on(struct perf_event *event,
1778 struct perf_cpu_context *cpuctx,
1779 int can_add_hw)
1782 * Groups consisting entirely of software events can always go on.
1784 if (event->group_flags & PERF_GROUP_SOFTWARE)
1785 return 1;
1787 * If an exclusive group is already on, no other hardware
1788 * events can go on.
1790 if (cpuctx->exclusive)
1791 return 0;
1793 * If this group is exclusive and there are already
1794 * events on the CPU, it can't go on.
1796 if (event->attr.exclusive && cpuctx->active_oncpu)
1797 return 0;
1799 * Otherwise, try to add it if all previous groups were able
1800 * to go on.
1802 return can_add_hw;
1805 static void add_event_to_ctx(struct perf_event *event,
1806 struct perf_event_context *ctx)
1808 u64 tstamp = perf_event_time(event);
1810 list_add_event(event, ctx);
1811 perf_group_attach(event);
1812 event->tstamp_enabled = tstamp;
1813 event->tstamp_running = tstamp;
1814 event->tstamp_stopped = tstamp;
1817 static void task_ctx_sched_out(struct perf_event_context *ctx);
1818 static void
1819 ctx_sched_in(struct perf_event_context *ctx,
1820 struct perf_cpu_context *cpuctx,
1821 enum event_type_t event_type,
1822 struct task_struct *task);
1824 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
1825 struct perf_event_context *ctx,
1826 struct task_struct *task)
1828 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
1829 if (ctx)
1830 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
1831 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
1832 if (ctx)
1833 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
1837 * Cross CPU call to install and enable a performance event
1839 * Must be called with ctx->mutex held
1841 static int __perf_install_in_context(void *info)
1843 struct perf_event *event = info;
1844 struct perf_event_context *ctx = event->ctx;
1845 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1846 struct perf_event_context *task_ctx = cpuctx->task_ctx;
1847 struct task_struct *task = current;
1849 perf_ctx_lock(cpuctx, task_ctx);
1850 perf_pmu_disable(cpuctx->ctx.pmu);
1853 * If there was an active task_ctx schedule it out.
1855 if (task_ctx)
1856 task_ctx_sched_out(task_ctx);
1859 * If the context we're installing events in is not the
1860 * active task_ctx, flip them.
1862 if (ctx->task && task_ctx != ctx) {
1863 if (task_ctx)
1864 raw_spin_unlock(&task_ctx->lock);
1865 raw_spin_lock(&ctx->lock);
1866 task_ctx = ctx;
1869 if (task_ctx) {
1870 cpuctx->task_ctx = task_ctx;
1871 task = task_ctx->task;
1874 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
1876 update_context_time(ctx);
1878 * update cgrp time only if current cgrp
1879 * matches event->cgrp. Must be done before
1880 * calling add_event_to_ctx()
1882 update_cgrp_time_from_event(event);
1884 add_event_to_ctx(event, ctx);
1887 * Schedule everything back in
1889 perf_event_sched_in(cpuctx, task_ctx, task);
1891 perf_pmu_enable(cpuctx->ctx.pmu);
1892 perf_ctx_unlock(cpuctx, task_ctx);
1894 return 0;
1898 * Attach a performance event to a context
1900 * First we add the event to the list with the hardware enable bit
1901 * in event->hw_config cleared.
1903 * If the event is attached to a task which is on a CPU we use a smp
1904 * call to enable it in the task context. The task might have been
1905 * scheduled away, but we check this in the smp call again.
1907 static void
1908 perf_install_in_context(struct perf_event_context *ctx,
1909 struct perf_event *event,
1910 int cpu)
1912 struct task_struct *task = ctx->task;
1914 lockdep_assert_held(&ctx->mutex);
1916 event->ctx = ctx;
1917 if (event->cpu != -1)
1918 event->cpu = cpu;
1920 if (!task) {
1922 * Per cpu events are installed via an smp call and
1923 * the install is always successful.
1925 cpu_function_call(cpu, __perf_install_in_context, event);
1926 return;
1929 retry:
1930 if (!task_function_call(task, __perf_install_in_context, event))
1931 return;
1933 raw_spin_lock_irq(&ctx->lock);
1935 * If we failed to find a running task, but find the context active now
1936 * that we've acquired the ctx->lock, retry.
1938 if (ctx->is_active) {
1939 raw_spin_unlock_irq(&ctx->lock);
1940 goto retry;
1944 * Since the task isn't running, its safe to add the event, us holding
1945 * the ctx->lock ensures the task won't get scheduled in.
1947 add_event_to_ctx(event, ctx);
1948 raw_spin_unlock_irq(&ctx->lock);
1952 * Put a event into inactive state and update time fields.
1953 * Enabling the leader of a group effectively enables all
1954 * the group members that aren't explicitly disabled, so we
1955 * have to update their ->tstamp_enabled also.
1956 * Note: this works for group members as well as group leaders
1957 * since the non-leader members' sibling_lists will be empty.
1959 static void __perf_event_mark_enabled(struct perf_event *event)
1961 struct perf_event *sub;
1962 u64 tstamp = perf_event_time(event);
1964 event->state = PERF_EVENT_STATE_INACTIVE;
1965 event->tstamp_enabled = tstamp - event->total_time_enabled;
1966 list_for_each_entry(sub, &event->sibling_list, group_entry) {
1967 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
1968 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
1973 * Cross CPU call to enable a performance event
1975 static int __perf_event_enable(void *info)
1977 struct perf_event *event = info;
1978 struct perf_event_context *ctx = event->ctx;
1979 struct perf_event *leader = event->group_leader;
1980 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1981 int err;
1984 * There's a time window between 'ctx->is_active' check
1985 * in perf_event_enable function and this place having:
1986 * - IRQs on
1987 * - ctx->lock unlocked
1989 * where the task could be killed and 'ctx' deactivated
1990 * by perf_event_exit_task.
1992 if (!ctx->is_active)
1993 return -EINVAL;
1995 raw_spin_lock(&ctx->lock);
1996 update_context_time(ctx);
1998 if (event->state >= PERF_EVENT_STATE_INACTIVE)
1999 goto unlock;
2002 * set current task's cgroup time reference point
2004 perf_cgroup_set_timestamp(current, ctx);
2006 __perf_event_mark_enabled(event);
2008 if (!event_filter_match(event)) {
2009 if (is_cgroup_event(event))
2010 perf_cgroup_defer_enabled(event);
2011 goto unlock;
2015 * If the event is in a group and isn't the group leader,
2016 * then don't put it on unless the group is on.
2018 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
2019 goto unlock;
2021 if (!group_can_go_on(event, cpuctx, 1)) {
2022 err = -EEXIST;
2023 } else {
2024 if (event == leader)
2025 err = group_sched_in(event, cpuctx, ctx);
2026 else
2027 err = event_sched_in(event, cpuctx, ctx);
2030 if (err) {
2032 * If this event can't go on and it's part of a
2033 * group, then the whole group has to come off.
2035 if (leader != event) {
2036 group_sched_out(leader, cpuctx, ctx);
2037 perf_cpu_hrtimer_restart(cpuctx);
2039 if (leader->attr.pinned) {
2040 update_group_times(leader);
2041 leader->state = PERF_EVENT_STATE_ERROR;
2045 unlock:
2046 raw_spin_unlock(&ctx->lock);
2048 return 0;
2052 * Enable a event.
2054 * If event->ctx is a cloned context, callers must make sure that
2055 * every task struct that event->ctx->task could possibly point to
2056 * remains valid. This condition is satisfied when called through
2057 * perf_event_for_each_child or perf_event_for_each as described
2058 * for perf_event_disable.
2060 void perf_event_enable(struct perf_event *event)
2062 struct perf_event_context *ctx = event->ctx;
2063 struct task_struct *task = ctx->task;
2065 if (!task) {
2067 * Enable the event on the cpu that it's on
2069 cpu_function_call(event->cpu, __perf_event_enable, event);
2070 return;
2073 raw_spin_lock_irq(&ctx->lock);
2074 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2075 goto out;
2078 * If the event is in error state, clear that first.
2079 * That way, if we see the event in error state below, we
2080 * know that it has gone back into error state, as distinct
2081 * from the task having been scheduled away before the
2082 * cross-call arrived.
2084 if (event->state == PERF_EVENT_STATE_ERROR)
2085 event->state = PERF_EVENT_STATE_OFF;
2087 retry:
2088 if (!ctx->is_active) {
2089 __perf_event_mark_enabled(event);
2090 goto out;
2093 raw_spin_unlock_irq(&ctx->lock);
2095 if (!task_function_call(task, __perf_event_enable, event))
2096 return;
2098 raw_spin_lock_irq(&ctx->lock);
2101 * If the context is active and the event is still off,
2102 * we need to retry the cross-call.
2104 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
2106 * task could have been flipped by a concurrent
2107 * perf_event_context_sched_out()
2109 task = ctx->task;
2110 goto retry;
2113 out:
2114 raw_spin_unlock_irq(&ctx->lock);
2116 EXPORT_SYMBOL_GPL(perf_event_enable);
2118 int perf_event_refresh(struct perf_event *event, int refresh)
2121 * not supported on inherited events
2123 if (event->attr.inherit || !is_sampling_event(event))
2124 return -EINVAL;
2126 atomic_add(refresh, &event->event_limit);
2127 perf_event_enable(event);
2129 return 0;
2131 EXPORT_SYMBOL_GPL(perf_event_refresh);
2133 static void ctx_sched_out(struct perf_event_context *ctx,
2134 struct perf_cpu_context *cpuctx,
2135 enum event_type_t event_type)
2137 struct perf_event *event;
2138 int is_active = ctx->is_active;
2140 ctx->is_active &= ~event_type;
2141 if (likely(!ctx->nr_events))
2142 return;
2144 update_context_time(ctx);
2145 update_cgrp_time_from_cpuctx(cpuctx);
2146 if (!ctx->nr_active)
2147 return;
2149 perf_pmu_disable(ctx->pmu);
2150 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2151 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2152 group_sched_out(event, cpuctx, ctx);
2155 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2156 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2157 group_sched_out(event, cpuctx, ctx);
2159 perf_pmu_enable(ctx->pmu);
2163 * Test whether two contexts are equivalent, i.e. whether they
2164 * have both been cloned from the same version of the same context
2165 * and they both have the same number of enabled events.
2166 * If the number of enabled events is the same, then the set
2167 * of enabled events should be the same, because these are both
2168 * inherited contexts, therefore we can't access individual events
2169 * in them directly with an fd; we can only enable/disable all
2170 * events via prctl, or enable/disable all events in a family
2171 * via ioctl, which will have the same effect on both contexts.
2173 static int context_equiv(struct perf_event_context *ctx1,
2174 struct perf_event_context *ctx2)
2176 return ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx
2177 && ctx1->parent_gen == ctx2->parent_gen
2178 && !ctx1->pin_count && !ctx2->pin_count;
2181 static void __perf_event_sync_stat(struct perf_event *event,
2182 struct perf_event *next_event)
2184 u64 value;
2186 if (!event->attr.inherit_stat)
2187 return;
2190 * Update the event value, we cannot use perf_event_read()
2191 * because we're in the middle of a context switch and have IRQs
2192 * disabled, which upsets smp_call_function_single(), however
2193 * we know the event must be on the current CPU, therefore we
2194 * don't need to use it.
2196 switch (event->state) {
2197 case PERF_EVENT_STATE_ACTIVE:
2198 event->pmu->read(event);
2199 /* fall-through */
2201 case PERF_EVENT_STATE_INACTIVE:
2202 update_event_times(event);
2203 break;
2205 default:
2206 break;
2210 * In order to keep per-task stats reliable we need to flip the event
2211 * values when we flip the contexts.
2213 value = local64_read(&next_event->count);
2214 value = local64_xchg(&event->count, value);
2215 local64_set(&next_event->count, value);
2217 swap(event->total_time_enabled, next_event->total_time_enabled);
2218 swap(event->total_time_running, next_event->total_time_running);
2221 * Since we swizzled the values, update the user visible data too.
2223 perf_event_update_userpage(event);
2224 perf_event_update_userpage(next_event);
2227 static void perf_event_sync_stat(struct perf_event_context *ctx,
2228 struct perf_event_context *next_ctx)
2230 struct perf_event *event, *next_event;
2232 if (!ctx->nr_stat)
2233 return;
2235 update_context_time(ctx);
2237 event = list_first_entry(&ctx->event_list,
2238 struct perf_event, event_entry);
2240 next_event = list_first_entry(&next_ctx->event_list,
2241 struct perf_event, event_entry);
2243 while (&event->event_entry != &ctx->event_list &&
2244 &next_event->event_entry != &next_ctx->event_list) {
2246 __perf_event_sync_stat(event, next_event);
2248 event = list_next_entry(event, event_entry);
2249 next_event = list_next_entry(next_event, event_entry);
2253 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2254 struct task_struct *next)
2256 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2257 struct perf_event_context *next_ctx;
2258 struct perf_event_context *parent;
2259 struct perf_cpu_context *cpuctx;
2260 int do_switch = 1;
2262 if (likely(!ctx))
2263 return;
2265 cpuctx = __get_cpu_context(ctx);
2266 if (!cpuctx->task_ctx)
2267 return;
2269 rcu_read_lock();
2270 parent = rcu_dereference(ctx->parent_ctx);
2271 next_ctx = next->perf_event_ctxp[ctxn];
2272 if (parent && next_ctx &&
2273 rcu_dereference(next_ctx->parent_ctx) == parent) {
2275 * Looks like the two contexts are clones, so we might be
2276 * able to optimize the context switch. We lock both
2277 * contexts and check that they are clones under the
2278 * lock (including re-checking that neither has been
2279 * uncloned in the meantime). It doesn't matter which
2280 * order we take the locks because no other cpu could
2281 * be trying to lock both of these tasks.
2283 raw_spin_lock(&ctx->lock);
2284 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2285 if (context_equiv(ctx, next_ctx)) {
2287 * XXX do we need a memory barrier of sorts
2288 * wrt to rcu_dereference() of perf_event_ctxp
2290 task->perf_event_ctxp[ctxn] = next_ctx;
2291 next->perf_event_ctxp[ctxn] = ctx;
2292 ctx->task = next;
2293 next_ctx->task = task;
2294 do_switch = 0;
2296 perf_event_sync_stat(ctx, next_ctx);
2298 raw_spin_unlock(&next_ctx->lock);
2299 raw_spin_unlock(&ctx->lock);
2301 rcu_read_unlock();
2303 if (do_switch) {
2304 raw_spin_lock(&ctx->lock);
2305 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2306 cpuctx->task_ctx = NULL;
2307 raw_spin_unlock(&ctx->lock);
2311 #define for_each_task_context_nr(ctxn) \
2312 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2315 * Called from scheduler to remove the events of the current task,
2316 * with interrupts disabled.
2318 * We stop each event and update the event value in event->count.
2320 * This does not protect us against NMI, but disable()
2321 * sets the disabled bit in the control field of event _before_
2322 * accessing the event control register. If a NMI hits, then it will
2323 * not restart the event.
2325 void __perf_event_task_sched_out(struct task_struct *task,
2326 struct task_struct *next)
2328 int ctxn;
2330 for_each_task_context_nr(ctxn)
2331 perf_event_context_sched_out(task, ctxn, next);
2334 * if cgroup events exist on this CPU, then we need
2335 * to check if we have to switch out PMU state.
2336 * cgroup event are system-wide mode only
2338 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2339 perf_cgroup_sched_out(task, next);
2342 static void task_ctx_sched_out(struct perf_event_context *ctx)
2344 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2346 if (!cpuctx->task_ctx)
2347 return;
2349 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2350 return;
2352 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2353 cpuctx->task_ctx = NULL;
2357 * Called with IRQs disabled
2359 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2360 enum event_type_t event_type)
2362 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2365 static void
2366 ctx_pinned_sched_in(struct perf_event_context *ctx,
2367 struct perf_cpu_context *cpuctx)
2369 struct perf_event *event;
2371 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2372 if (event->state <= PERF_EVENT_STATE_OFF)
2373 continue;
2374 if (!event_filter_match(event))
2375 continue;
2377 /* may need to reset tstamp_enabled */
2378 if (is_cgroup_event(event))
2379 perf_cgroup_mark_enabled(event, ctx);
2381 if (group_can_go_on(event, cpuctx, 1))
2382 group_sched_in(event, cpuctx, ctx);
2385 * If this pinned group hasn't been scheduled,
2386 * put it in error state.
2388 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2389 update_group_times(event);
2390 event->state = PERF_EVENT_STATE_ERROR;
2395 static void
2396 ctx_flexible_sched_in(struct perf_event_context *ctx,
2397 struct perf_cpu_context *cpuctx)
2399 struct perf_event *event;
2400 int can_add_hw = 1;
2402 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2403 /* Ignore events in OFF or ERROR state */
2404 if (event->state <= PERF_EVENT_STATE_OFF)
2405 continue;
2407 * Listen to the 'cpu' scheduling filter constraint
2408 * of events:
2410 if (!event_filter_match(event))
2411 continue;
2413 /* may need to reset tstamp_enabled */
2414 if (is_cgroup_event(event))
2415 perf_cgroup_mark_enabled(event, ctx);
2417 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2418 if (group_sched_in(event, cpuctx, ctx))
2419 can_add_hw = 0;
2424 static void
2425 ctx_sched_in(struct perf_event_context *ctx,
2426 struct perf_cpu_context *cpuctx,
2427 enum event_type_t event_type,
2428 struct task_struct *task)
2430 u64 now;
2431 int is_active = ctx->is_active;
2433 ctx->is_active |= event_type;
2434 if (likely(!ctx->nr_events))
2435 return;
2437 now = perf_clock();
2438 ctx->timestamp = now;
2439 perf_cgroup_set_timestamp(task, ctx);
2441 * First go through the list and put on any pinned groups
2442 * in order to give them the best chance of going on.
2444 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2445 ctx_pinned_sched_in(ctx, cpuctx);
2447 /* Then walk through the lower prio flexible groups */
2448 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2449 ctx_flexible_sched_in(ctx, cpuctx);
2452 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2453 enum event_type_t event_type,
2454 struct task_struct *task)
2456 struct perf_event_context *ctx = &cpuctx->ctx;
2458 ctx_sched_in(ctx, cpuctx, event_type, task);
2461 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2462 struct task_struct *task)
2464 struct perf_cpu_context *cpuctx;
2466 cpuctx = __get_cpu_context(ctx);
2467 if (cpuctx->task_ctx == ctx)
2468 return;
2470 perf_ctx_lock(cpuctx, ctx);
2471 perf_pmu_disable(ctx->pmu);
2473 * We want to keep the following priority order:
2474 * cpu pinned (that don't need to move), task pinned,
2475 * cpu flexible, task flexible.
2477 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2479 if (ctx->nr_events)
2480 cpuctx->task_ctx = ctx;
2482 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2484 perf_pmu_enable(ctx->pmu);
2485 perf_ctx_unlock(cpuctx, ctx);
2488 * Since these rotations are per-cpu, we need to ensure the
2489 * cpu-context we got scheduled on is actually rotating.
2491 perf_pmu_rotate_start(ctx->pmu);
2495 * When sampling the branck stack in system-wide, it may be necessary
2496 * to flush the stack on context switch. This happens when the branch
2497 * stack does not tag its entries with the pid of the current task.
2498 * Otherwise it becomes impossible to associate a branch entry with a
2499 * task. This ambiguity is more likely to appear when the branch stack
2500 * supports priv level filtering and the user sets it to monitor only
2501 * at the user level (which could be a useful measurement in system-wide
2502 * mode). In that case, the risk is high of having a branch stack with
2503 * branch from multiple tasks. Flushing may mean dropping the existing
2504 * entries or stashing them somewhere in the PMU specific code layer.
2506 * This function provides the context switch callback to the lower code
2507 * layer. It is invoked ONLY when there is at least one system-wide context
2508 * with at least one active event using taken branch sampling.
2510 static void perf_branch_stack_sched_in(struct task_struct *prev,
2511 struct task_struct *task)
2513 struct perf_cpu_context *cpuctx;
2514 struct pmu *pmu;
2515 unsigned long flags;
2517 /* no need to flush branch stack if not changing task */
2518 if (prev == task)
2519 return;
2521 local_irq_save(flags);
2523 rcu_read_lock();
2525 list_for_each_entry_rcu(pmu, &pmus, entry) {
2526 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2529 * check if the context has at least one
2530 * event using PERF_SAMPLE_BRANCH_STACK
2532 if (cpuctx->ctx.nr_branch_stack > 0
2533 && pmu->flush_branch_stack) {
2535 pmu = cpuctx->ctx.pmu;
2537 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2539 perf_pmu_disable(pmu);
2541 pmu->flush_branch_stack();
2543 perf_pmu_enable(pmu);
2545 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2549 rcu_read_unlock();
2551 local_irq_restore(flags);
2555 * Called from scheduler to add the events of the current task
2556 * with interrupts disabled.
2558 * We restore the event value and then enable it.
2560 * This does not protect us against NMI, but enable()
2561 * sets the enabled bit in the control field of event _before_
2562 * accessing the event control register. If a NMI hits, then it will
2563 * keep the event running.
2565 void __perf_event_task_sched_in(struct task_struct *prev,
2566 struct task_struct *task)
2568 struct perf_event_context *ctx;
2569 int ctxn;
2571 for_each_task_context_nr(ctxn) {
2572 ctx = task->perf_event_ctxp[ctxn];
2573 if (likely(!ctx))
2574 continue;
2576 perf_event_context_sched_in(ctx, task);
2579 * if cgroup events exist on this CPU, then we need
2580 * to check if we have to switch in PMU state.
2581 * cgroup event are system-wide mode only
2583 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2584 perf_cgroup_sched_in(prev, task);
2586 /* check for system-wide branch_stack events */
2587 if (atomic_read(&__get_cpu_var(perf_branch_stack_events)))
2588 perf_branch_stack_sched_in(prev, task);
2591 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2593 u64 frequency = event->attr.sample_freq;
2594 u64 sec = NSEC_PER_SEC;
2595 u64 divisor, dividend;
2597 int count_fls, nsec_fls, frequency_fls, sec_fls;
2599 count_fls = fls64(count);
2600 nsec_fls = fls64(nsec);
2601 frequency_fls = fls64(frequency);
2602 sec_fls = 30;
2605 * We got @count in @nsec, with a target of sample_freq HZ
2606 * the target period becomes:
2608 * @count * 10^9
2609 * period = -------------------
2610 * @nsec * sample_freq
2615 * Reduce accuracy by one bit such that @a and @b converge
2616 * to a similar magnitude.
2618 #define REDUCE_FLS(a, b) \
2619 do { \
2620 if (a##_fls > b##_fls) { \
2621 a >>= 1; \
2622 a##_fls--; \
2623 } else { \
2624 b >>= 1; \
2625 b##_fls--; \
2627 } while (0)
2630 * Reduce accuracy until either term fits in a u64, then proceed with
2631 * the other, so that finally we can do a u64/u64 division.
2633 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2634 REDUCE_FLS(nsec, frequency);
2635 REDUCE_FLS(sec, count);
2638 if (count_fls + sec_fls > 64) {
2639 divisor = nsec * frequency;
2641 while (count_fls + sec_fls > 64) {
2642 REDUCE_FLS(count, sec);
2643 divisor >>= 1;
2646 dividend = count * sec;
2647 } else {
2648 dividend = count * sec;
2650 while (nsec_fls + frequency_fls > 64) {
2651 REDUCE_FLS(nsec, frequency);
2652 dividend >>= 1;
2655 divisor = nsec * frequency;
2658 if (!divisor)
2659 return dividend;
2661 return div64_u64(dividend, divisor);
2664 static DEFINE_PER_CPU(int, perf_throttled_count);
2665 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2667 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2669 struct hw_perf_event *hwc = &event->hw;
2670 s64 period, sample_period;
2671 s64 delta;
2673 period = perf_calculate_period(event, nsec, count);
2675 delta = (s64)(period - hwc->sample_period);
2676 delta = (delta + 7) / 8; /* low pass filter */
2678 sample_period = hwc->sample_period + delta;
2680 if (!sample_period)
2681 sample_period = 1;
2683 hwc->sample_period = sample_period;
2685 if (local64_read(&hwc->period_left) > 8*sample_period) {
2686 if (disable)
2687 event->pmu->stop(event, PERF_EF_UPDATE);
2689 local64_set(&hwc->period_left, 0);
2691 if (disable)
2692 event->pmu->start(event, PERF_EF_RELOAD);
2697 * combine freq adjustment with unthrottling to avoid two passes over the
2698 * events. At the same time, make sure, having freq events does not change
2699 * the rate of unthrottling as that would introduce bias.
2701 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
2702 int needs_unthr)
2704 struct perf_event *event;
2705 struct hw_perf_event *hwc;
2706 u64 now, period = TICK_NSEC;
2707 s64 delta;
2710 * only need to iterate over all events iff:
2711 * - context have events in frequency mode (needs freq adjust)
2712 * - there are events to unthrottle on this cpu
2714 if (!(ctx->nr_freq || needs_unthr))
2715 return;
2717 raw_spin_lock(&ctx->lock);
2718 perf_pmu_disable(ctx->pmu);
2720 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
2721 if (event->state != PERF_EVENT_STATE_ACTIVE)
2722 continue;
2724 if (!event_filter_match(event))
2725 continue;
2727 hwc = &event->hw;
2729 if (hwc->interrupts == MAX_INTERRUPTS) {
2730 hwc->interrupts = 0;
2731 perf_log_throttle(event, 1);
2732 event->pmu->start(event, 0);
2735 if (!event->attr.freq || !event->attr.sample_freq)
2736 continue;
2739 * stop the event and update event->count
2741 event->pmu->stop(event, PERF_EF_UPDATE);
2743 now = local64_read(&event->count);
2744 delta = now - hwc->freq_count_stamp;
2745 hwc->freq_count_stamp = now;
2748 * restart the event
2749 * reload only if value has changed
2750 * we have stopped the event so tell that
2751 * to perf_adjust_period() to avoid stopping it
2752 * twice.
2754 if (delta > 0)
2755 perf_adjust_period(event, period, delta, false);
2757 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
2760 perf_pmu_enable(ctx->pmu);
2761 raw_spin_unlock(&ctx->lock);
2765 * Round-robin a context's events:
2767 static void rotate_ctx(struct perf_event_context *ctx)
2770 * Rotate the first entry last of non-pinned groups. Rotation might be
2771 * disabled by the inheritance code.
2773 if (!ctx->rotate_disable)
2774 list_rotate_left(&ctx->flexible_groups);
2778 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
2779 * because they're strictly cpu affine and rotate_start is called with IRQs
2780 * disabled, while rotate_context is called from IRQ context.
2782 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
2784 struct perf_event_context *ctx = NULL;
2785 int rotate = 0, remove = 1;
2787 if (cpuctx->ctx.nr_events) {
2788 remove = 0;
2789 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
2790 rotate = 1;
2793 ctx = cpuctx->task_ctx;
2794 if (ctx && ctx->nr_events) {
2795 remove = 0;
2796 if (ctx->nr_events != ctx->nr_active)
2797 rotate = 1;
2800 if (!rotate)
2801 goto done;
2803 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2804 perf_pmu_disable(cpuctx->ctx.pmu);
2806 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2807 if (ctx)
2808 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
2810 rotate_ctx(&cpuctx->ctx);
2811 if (ctx)
2812 rotate_ctx(ctx);
2814 perf_event_sched_in(cpuctx, ctx, current);
2816 perf_pmu_enable(cpuctx->ctx.pmu);
2817 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2818 done:
2819 if (remove)
2820 list_del_init(&cpuctx->rotation_list);
2822 return rotate;
2825 #ifdef CONFIG_NO_HZ_FULL
2826 bool perf_event_can_stop_tick(void)
2828 if (atomic_read(&nr_freq_events) ||
2829 __this_cpu_read(perf_throttled_count))
2830 return false;
2831 else
2832 return true;
2834 #endif
2836 void perf_event_task_tick(void)
2838 struct list_head *head = &__get_cpu_var(rotation_list);
2839 struct perf_cpu_context *cpuctx, *tmp;
2840 struct perf_event_context *ctx;
2841 int throttled;
2843 WARN_ON(!irqs_disabled());
2845 __this_cpu_inc(perf_throttled_seq);
2846 throttled = __this_cpu_xchg(perf_throttled_count, 0);
2848 list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) {
2849 ctx = &cpuctx->ctx;
2850 perf_adjust_freq_unthr_context(ctx, throttled);
2852 ctx = cpuctx->task_ctx;
2853 if (ctx)
2854 perf_adjust_freq_unthr_context(ctx, throttled);
2858 static int event_enable_on_exec(struct perf_event *event,
2859 struct perf_event_context *ctx)
2861 if (!event->attr.enable_on_exec)
2862 return 0;
2864 event->attr.enable_on_exec = 0;
2865 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2866 return 0;
2868 __perf_event_mark_enabled(event);
2870 return 1;
2874 * Enable all of a task's events that have been marked enable-on-exec.
2875 * This expects task == current.
2877 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
2879 struct perf_event *event;
2880 unsigned long flags;
2881 int enabled = 0;
2882 int ret;
2884 local_irq_save(flags);
2885 if (!ctx || !ctx->nr_events)
2886 goto out;
2889 * We must ctxsw out cgroup events to avoid conflict
2890 * when invoking perf_task_event_sched_in() later on
2891 * in this function. Otherwise we end up trying to
2892 * ctxswin cgroup events which are already scheduled
2893 * in.
2895 perf_cgroup_sched_out(current, NULL);
2897 raw_spin_lock(&ctx->lock);
2898 task_ctx_sched_out(ctx);
2900 list_for_each_entry(event, &ctx->event_list, event_entry) {
2901 ret = event_enable_on_exec(event, ctx);
2902 if (ret)
2903 enabled = 1;
2907 * Unclone this context if we enabled any event.
2909 if (enabled)
2910 unclone_ctx(ctx);
2912 raw_spin_unlock(&ctx->lock);
2915 * Also calls ctxswin for cgroup events, if any:
2917 perf_event_context_sched_in(ctx, ctx->task);
2918 out:
2919 local_irq_restore(flags);
2923 * Cross CPU call to read the hardware event
2925 static void __perf_event_read(void *info)
2927 struct perf_event *event = info;
2928 struct perf_event_context *ctx = event->ctx;
2929 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2932 * If this is a task context, we need to check whether it is
2933 * the current task context of this cpu. If not it has been
2934 * scheduled out before the smp call arrived. In that case
2935 * event->count would have been updated to a recent sample
2936 * when the event was scheduled out.
2938 if (ctx->task && cpuctx->task_ctx != ctx)
2939 return;
2941 raw_spin_lock(&ctx->lock);
2942 if (ctx->is_active) {
2943 update_context_time(ctx);
2944 update_cgrp_time_from_event(event);
2946 update_event_times(event);
2947 if (event->state == PERF_EVENT_STATE_ACTIVE)
2948 event->pmu->read(event);
2949 raw_spin_unlock(&ctx->lock);
2952 static inline u64 perf_event_count(struct perf_event *event)
2954 return local64_read(&event->count) + atomic64_read(&event->child_count);
2957 static u64 perf_event_read(struct perf_event *event)
2960 * If event is enabled and currently active on a CPU, update the
2961 * value in the event structure:
2963 if (event->state == PERF_EVENT_STATE_ACTIVE) {
2964 smp_call_function_single(event->oncpu,
2965 __perf_event_read, event, 1);
2966 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
2967 struct perf_event_context *ctx = event->ctx;
2968 unsigned long flags;
2970 raw_spin_lock_irqsave(&ctx->lock, flags);
2972 * may read while context is not active
2973 * (e.g., thread is blocked), in that case
2974 * we cannot update context time
2976 if (ctx->is_active) {
2977 update_context_time(ctx);
2978 update_cgrp_time_from_event(event);
2980 update_event_times(event);
2981 raw_spin_unlock_irqrestore(&ctx->lock, flags);
2984 return perf_event_count(event);
2988 * Initialize the perf_event context in a task_struct:
2990 static void __perf_event_init_context(struct perf_event_context *ctx)
2992 raw_spin_lock_init(&ctx->lock);
2993 mutex_init(&ctx->mutex);
2994 INIT_LIST_HEAD(&ctx->pinned_groups);
2995 INIT_LIST_HEAD(&ctx->flexible_groups);
2996 INIT_LIST_HEAD(&ctx->event_list);
2997 atomic_set(&ctx->refcount, 1);
3000 static struct perf_event_context *
3001 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3003 struct perf_event_context *ctx;
3005 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3006 if (!ctx)
3007 return NULL;
3009 __perf_event_init_context(ctx);
3010 if (task) {
3011 ctx->task = task;
3012 get_task_struct(task);
3014 ctx->pmu = pmu;
3016 return ctx;
3019 static struct task_struct *
3020 find_lively_task_by_vpid(pid_t vpid)
3022 struct task_struct *task;
3023 int err;
3025 rcu_read_lock();
3026 if (!vpid)
3027 task = current;
3028 else
3029 task = find_task_by_vpid(vpid);
3030 if (task)
3031 get_task_struct(task);
3032 rcu_read_unlock();
3034 if (!task)
3035 return ERR_PTR(-ESRCH);
3037 /* Reuse ptrace permission checks for now. */
3038 err = -EACCES;
3039 if (!ptrace_may_access(task, PTRACE_MODE_READ))
3040 goto errout;
3042 return task;
3043 errout:
3044 put_task_struct(task);
3045 return ERR_PTR(err);
3050 * Returns a matching context with refcount and pincount.
3052 static struct perf_event_context *
3053 find_get_context(struct pmu *pmu, struct task_struct *task, int cpu)
3055 struct perf_event_context *ctx;
3056 struct perf_cpu_context *cpuctx;
3057 unsigned long flags;
3058 int ctxn, err;
3060 if (!task) {
3061 /* Must be root to operate on a CPU event: */
3062 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3063 return ERR_PTR(-EACCES);
3066 * We could be clever and allow to attach a event to an
3067 * offline CPU and activate it when the CPU comes up, but
3068 * that's for later.
3070 if (!cpu_online(cpu))
3071 return ERR_PTR(-ENODEV);
3073 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3074 ctx = &cpuctx->ctx;
3075 get_ctx(ctx);
3076 ++ctx->pin_count;
3078 return ctx;
3081 err = -EINVAL;
3082 ctxn = pmu->task_ctx_nr;
3083 if (ctxn < 0)
3084 goto errout;
3086 retry:
3087 ctx = perf_lock_task_context(task, ctxn, &flags);
3088 if (ctx) {
3089 unclone_ctx(ctx);
3090 ++ctx->pin_count;
3091 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3092 } else {
3093 ctx = alloc_perf_context(pmu, task);
3094 err = -ENOMEM;
3095 if (!ctx)
3096 goto errout;
3098 err = 0;
3099 mutex_lock(&task->perf_event_mutex);
3101 * If it has already passed perf_event_exit_task().
3102 * we must see PF_EXITING, it takes this mutex too.
3104 if (task->flags & PF_EXITING)
3105 err = -ESRCH;
3106 else if (task->perf_event_ctxp[ctxn])
3107 err = -EAGAIN;
3108 else {
3109 get_ctx(ctx);
3110 ++ctx->pin_count;
3111 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3113 mutex_unlock(&task->perf_event_mutex);
3115 if (unlikely(err)) {
3116 put_ctx(ctx);
3118 if (err == -EAGAIN)
3119 goto retry;
3120 goto errout;
3124 return ctx;
3126 errout:
3127 return ERR_PTR(err);
3130 static void perf_event_free_filter(struct perf_event *event);
3132 static void free_event_rcu(struct rcu_head *head)
3134 struct perf_event *event;
3136 event = container_of(head, struct perf_event, rcu_head);
3137 if (event->ns)
3138 put_pid_ns(event->ns);
3139 perf_event_free_filter(event);
3140 kfree(event);
3143 static void ring_buffer_put(struct ring_buffer *rb);
3144 static void ring_buffer_detach(struct perf_event *event, struct ring_buffer *rb);
3146 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3148 if (event->parent)
3149 return;
3151 if (has_branch_stack(event)) {
3152 if (!(event->attach_state & PERF_ATTACH_TASK))
3153 atomic_dec(&per_cpu(perf_branch_stack_events, cpu));
3155 if (is_cgroup_event(event))
3156 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3159 static void unaccount_event(struct perf_event *event)
3161 if (event->parent)
3162 return;
3164 if (event->attach_state & PERF_ATTACH_TASK)
3165 static_key_slow_dec_deferred(&perf_sched_events);
3166 if (event->attr.mmap || event->attr.mmap_data)
3167 atomic_dec(&nr_mmap_events);
3168 if (event->attr.comm)
3169 atomic_dec(&nr_comm_events);
3170 if (event->attr.task)
3171 atomic_dec(&nr_task_events);
3172 if (event->attr.freq)
3173 atomic_dec(&nr_freq_events);
3174 if (is_cgroup_event(event))
3175 static_key_slow_dec_deferred(&perf_sched_events);
3176 if (has_branch_stack(event))
3177 static_key_slow_dec_deferred(&perf_sched_events);
3179 unaccount_event_cpu(event, event->cpu);
3182 static void __free_event(struct perf_event *event)
3184 if (!event->parent) {
3185 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3186 put_callchain_buffers();
3189 if (event->destroy)
3190 event->destroy(event);
3192 if (event->ctx)
3193 put_ctx(event->ctx);
3195 call_rcu(&event->rcu_head, free_event_rcu);
3197 static void free_event(struct perf_event *event)
3199 irq_work_sync(&event->pending);
3201 unaccount_event(event);
3203 if (event->rb) {
3204 struct ring_buffer *rb;
3207 * Can happen when we close an event with re-directed output.
3209 * Since we have a 0 refcount, perf_mmap_close() will skip
3210 * over us; possibly making our ring_buffer_put() the last.
3212 mutex_lock(&event->mmap_mutex);
3213 rb = event->rb;
3214 if (rb) {
3215 rcu_assign_pointer(event->rb, NULL);
3216 ring_buffer_detach(event, rb);
3217 ring_buffer_put(rb); /* could be last */
3219 mutex_unlock(&event->mmap_mutex);
3222 if (is_cgroup_event(event))
3223 perf_detach_cgroup(event);
3226 __free_event(event);
3229 int perf_event_release_kernel(struct perf_event *event)
3231 struct perf_event_context *ctx = event->ctx;
3233 WARN_ON_ONCE(ctx->parent_ctx);
3235 * There are two ways this annotation is useful:
3237 * 1) there is a lock recursion from perf_event_exit_task
3238 * see the comment there.
3240 * 2) there is a lock-inversion with mmap_sem through
3241 * perf_event_read_group(), which takes faults while
3242 * holding ctx->mutex, however this is called after
3243 * the last filedesc died, so there is no possibility
3244 * to trigger the AB-BA case.
3246 mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
3247 perf_remove_from_context(event, true);
3248 mutex_unlock(&ctx->mutex);
3250 free_event(event);
3252 return 0;
3254 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3257 * Called when the last reference to the file is gone.
3259 static void put_event(struct perf_event *event)
3261 struct task_struct *owner;
3263 if (!atomic_long_dec_and_test(&event->refcount))
3264 return;
3266 rcu_read_lock();
3267 owner = ACCESS_ONCE(event->owner);
3269 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3270 * !owner it means the list deletion is complete and we can indeed
3271 * free this event, otherwise we need to serialize on
3272 * owner->perf_event_mutex.
3274 smp_read_barrier_depends();
3275 if (owner) {
3277 * Since delayed_put_task_struct() also drops the last
3278 * task reference we can safely take a new reference
3279 * while holding the rcu_read_lock().
3281 get_task_struct(owner);
3283 rcu_read_unlock();
3285 if (owner) {
3286 mutex_lock(&owner->perf_event_mutex);
3288 * We have to re-check the event->owner field, if it is cleared
3289 * we raced with perf_event_exit_task(), acquiring the mutex
3290 * ensured they're done, and we can proceed with freeing the
3291 * event.
3293 if (event->owner)
3294 list_del_init(&event->owner_entry);
3295 mutex_unlock(&owner->perf_event_mutex);
3296 put_task_struct(owner);
3299 perf_event_release_kernel(event);
3302 static int perf_release(struct inode *inode, struct file *file)
3304 put_event(file->private_data);
3305 return 0;
3308 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3310 struct perf_event *child;
3311 u64 total = 0;
3313 *enabled = 0;
3314 *running = 0;
3316 mutex_lock(&event->child_mutex);
3317 total += perf_event_read(event);
3318 *enabled += event->total_time_enabled +
3319 atomic64_read(&event->child_total_time_enabled);
3320 *running += event->total_time_running +
3321 atomic64_read(&event->child_total_time_running);
3323 list_for_each_entry(child, &event->child_list, child_list) {
3324 total += perf_event_read(child);
3325 *enabled += child->total_time_enabled;
3326 *running += child->total_time_running;
3328 mutex_unlock(&event->child_mutex);
3330 return total;
3332 EXPORT_SYMBOL_GPL(perf_event_read_value);
3334 static int perf_event_read_group(struct perf_event *event,
3335 u64 read_format, char __user *buf)
3337 struct perf_event *leader = event->group_leader, *sub;
3338 int n = 0, size = 0, ret = -EFAULT;
3339 struct perf_event_context *ctx = leader->ctx;
3340 u64 values[5];
3341 u64 count, enabled, running;
3343 mutex_lock(&ctx->mutex);
3344 count = perf_event_read_value(leader, &enabled, &running);
3346 values[n++] = 1 + leader->nr_siblings;
3347 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3348 values[n++] = enabled;
3349 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3350 values[n++] = running;
3351 values[n++] = count;
3352 if (read_format & PERF_FORMAT_ID)
3353 values[n++] = primary_event_id(leader);
3355 size = n * sizeof(u64);
3357 if (copy_to_user(buf, values, size))
3358 goto unlock;
3360 ret = size;
3362 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3363 n = 0;
3365 values[n++] = perf_event_read_value(sub, &enabled, &running);
3366 if (read_format & PERF_FORMAT_ID)
3367 values[n++] = primary_event_id(sub);
3369 size = n * sizeof(u64);
3371 if (copy_to_user(buf + ret, values, size)) {
3372 ret = -EFAULT;
3373 goto unlock;
3376 ret += size;
3378 unlock:
3379 mutex_unlock(&ctx->mutex);
3381 return ret;
3384 static int perf_event_read_one(struct perf_event *event,
3385 u64 read_format, char __user *buf)
3387 u64 enabled, running;
3388 u64 values[4];
3389 int n = 0;
3391 values[n++] = perf_event_read_value(event, &enabled, &running);
3392 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3393 values[n++] = enabled;
3394 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3395 values[n++] = running;
3396 if (read_format & PERF_FORMAT_ID)
3397 values[n++] = primary_event_id(event);
3399 if (copy_to_user(buf, values, n * sizeof(u64)))
3400 return -EFAULT;
3402 return n * sizeof(u64);
3406 * Read the performance event - simple non blocking version for now
3408 static ssize_t
3409 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
3411 u64 read_format = event->attr.read_format;
3412 int ret;
3415 * Return end-of-file for a read on a event that is in
3416 * error state (i.e. because it was pinned but it couldn't be
3417 * scheduled on to the CPU at some point).
3419 if (event->state == PERF_EVENT_STATE_ERROR)
3420 return 0;
3422 if (count < event->read_size)
3423 return -ENOSPC;
3425 WARN_ON_ONCE(event->ctx->parent_ctx);
3426 if (read_format & PERF_FORMAT_GROUP)
3427 ret = perf_event_read_group(event, read_format, buf);
3428 else
3429 ret = perf_event_read_one(event, read_format, buf);
3431 return ret;
3434 static ssize_t
3435 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
3437 struct perf_event *event = file->private_data;
3439 return perf_read_hw(event, buf, count);
3442 static unsigned int perf_poll(struct file *file, poll_table *wait)
3444 struct perf_event *event = file->private_data;
3445 struct ring_buffer *rb;
3446 unsigned int events = POLL_HUP;
3449 * Pin the event->rb by taking event->mmap_mutex; otherwise
3450 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
3452 mutex_lock(&event->mmap_mutex);
3453 rb = event->rb;
3454 if (rb)
3455 events = atomic_xchg(&rb->poll, 0);
3456 mutex_unlock(&event->mmap_mutex);
3458 poll_wait(file, &event->waitq, wait);
3460 return events;
3463 static void perf_event_reset(struct perf_event *event)
3465 (void)perf_event_read(event);
3466 local64_set(&event->count, 0);
3467 perf_event_update_userpage(event);
3471 * Holding the top-level event's child_mutex means that any
3472 * descendant process that has inherited this event will block
3473 * in sync_child_event if it goes to exit, thus satisfying the
3474 * task existence requirements of perf_event_enable/disable.
3476 static void perf_event_for_each_child(struct perf_event *event,
3477 void (*func)(struct perf_event *))
3479 struct perf_event *child;
3481 WARN_ON_ONCE(event->ctx->parent_ctx);
3482 mutex_lock(&event->child_mutex);
3483 func(event);
3484 list_for_each_entry(child, &event->child_list, child_list)
3485 func(child);
3486 mutex_unlock(&event->child_mutex);
3489 static void perf_event_for_each(struct perf_event *event,
3490 void (*func)(struct perf_event *))
3492 struct perf_event_context *ctx = event->ctx;
3493 struct perf_event *sibling;
3495 WARN_ON_ONCE(ctx->parent_ctx);
3496 mutex_lock(&ctx->mutex);
3497 event = event->group_leader;
3499 perf_event_for_each_child(event, func);
3500 list_for_each_entry(sibling, &event->sibling_list, group_entry)
3501 perf_event_for_each_child(sibling, func);
3502 mutex_unlock(&ctx->mutex);
3505 static int perf_event_period(struct perf_event *event, u64 __user *arg)
3507 struct perf_event_context *ctx = event->ctx;
3508 int ret = 0;
3509 u64 value;
3511 if (!is_sampling_event(event))
3512 return -EINVAL;
3514 if (copy_from_user(&value, arg, sizeof(value)))
3515 return -EFAULT;
3517 if (!value)
3518 return -EINVAL;
3520 raw_spin_lock_irq(&ctx->lock);
3521 if (event->attr.freq) {
3522 if (value > sysctl_perf_event_sample_rate) {
3523 ret = -EINVAL;
3524 goto unlock;
3527 event->attr.sample_freq = value;
3528 } else {
3529 event->attr.sample_period = value;
3530 event->hw.sample_period = value;
3532 unlock:
3533 raw_spin_unlock_irq(&ctx->lock);
3535 return ret;
3538 static const struct file_operations perf_fops;
3540 static inline int perf_fget_light(int fd, struct fd *p)
3542 struct fd f = fdget(fd);
3543 if (!f.file)
3544 return -EBADF;
3546 if (f.file->f_op != &perf_fops) {
3547 fdput(f);
3548 return -EBADF;
3550 *p = f;
3551 return 0;
3554 static int perf_event_set_output(struct perf_event *event,
3555 struct perf_event *output_event);
3556 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
3558 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
3560 struct perf_event *event = file->private_data;
3561 void (*func)(struct perf_event *);
3562 u32 flags = arg;
3564 switch (cmd) {
3565 case PERF_EVENT_IOC_ENABLE:
3566 func = perf_event_enable;
3567 break;
3568 case PERF_EVENT_IOC_DISABLE:
3569 func = perf_event_disable;
3570 break;
3571 case PERF_EVENT_IOC_RESET:
3572 func = perf_event_reset;
3573 break;
3575 case PERF_EVENT_IOC_REFRESH:
3576 return perf_event_refresh(event, arg);
3578 case PERF_EVENT_IOC_PERIOD:
3579 return perf_event_period(event, (u64 __user *)arg);
3581 case PERF_EVENT_IOC_ID:
3583 u64 id = primary_event_id(event);
3585 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
3586 return -EFAULT;
3587 return 0;
3590 case PERF_EVENT_IOC_SET_OUTPUT:
3592 int ret;
3593 if (arg != -1) {
3594 struct perf_event *output_event;
3595 struct fd output;
3596 ret = perf_fget_light(arg, &output);
3597 if (ret)
3598 return ret;
3599 output_event = output.file->private_data;
3600 ret = perf_event_set_output(event, output_event);
3601 fdput(output);
3602 } else {
3603 ret = perf_event_set_output(event, NULL);
3605 return ret;
3608 case PERF_EVENT_IOC_SET_FILTER:
3609 return perf_event_set_filter(event, (void __user *)arg);
3611 default:
3612 return -ENOTTY;
3615 if (flags & PERF_IOC_FLAG_GROUP)
3616 perf_event_for_each(event, func);
3617 else
3618 perf_event_for_each_child(event, func);
3620 return 0;
3623 int perf_event_task_enable(void)
3625 struct perf_event *event;
3627 mutex_lock(&current->perf_event_mutex);
3628 list_for_each_entry(event, &current->perf_event_list, owner_entry)
3629 perf_event_for_each_child(event, perf_event_enable);
3630 mutex_unlock(&current->perf_event_mutex);
3632 return 0;
3635 int perf_event_task_disable(void)
3637 struct perf_event *event;
3639 mutex_lock(&current->perf_event_mutex);
3640 list_for_each_entry(event, &current->perf_event_list, owner_entry)
3641 perf_event_for_each_child(event, perf_event_disable);
3642 mutex_unlock(&current->perf_event_mutex);
3644 return 0;
3647 static int perf_event_index(struct perf_event *event)
3649 if (event->hw.state & PERF_HES_STOPPED)
3650 return 0;
3652 if (event->state != PERF_EVENT_STATE_ACTIVE)
3653 return 0;
3655 return event->pmu->event_idx(event);
3658 static void calc_timer_values(struct perf_event *event,
3659 u64 *now,
3660 u64 *enabled,
3661 u64 *running)
3663 u64 ctx_time;
3665 *now = perf_clock();
3666 ctx_time = event->shadow_ctx_time + *now;
3667 *enabled = ctx_time - event->tstamp_enabled;
3668 *running = ctx_time - event->tstamp_running;
3671 static void perf_event_init_userpage(struct perf_event *event)
3673 struct perf_event_mmap_page *userpg;
3674 struct ring_buffer *rb;
3676 rcu_read_lock();
3677 rb = rcu_dereference(event->rb);
3678 if (!rb)
3679 goto unlock;
3681 userpg = rb->user_page;
3683 /* Allow new userspace to detect that bit 0 is deprecated */
3684 userpg->cap_bit0_is_deprecated = 1;
3685 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
3687 unlock:
3688 rcu_read_unlock();
3691 void __weak arch_perf_update_userpage(struct perf_event_mmap_page *userpg, u64 now)
3696 * Callers need to ensure there can be no nesting of this function, otherwise
3697 * the seqlock logic goes bad. We can not serialize this because the arch
3698 * code calls this from NMI context.
3700 void perf_event_update_userpage(struct perf_event *event)
3702 struct perf_event_mmap_page *userpg;
3703 struct ring_buffer *rb;
3704 u64 enabled, running, now;
3706 rcu_read_lock();
3707 rb = rcu_dereference(event->rb);
3708 if (!rb)
3709 goto unlock;
3712 * compute total_time_enabled, total_time_running
3713 * based on snapshot values taken when the event
3714 * was last scheduled in.
3716 * we cannot simply called update_context_time()
3717 * because of locking issue as we can be called in
3718 * NMI context
3720 calc_timer_values(event, &now, &enabled, &running);
3722 userpg = rb->user_page;
3724 * Disable preemption so as to not let the corresponding user-space
3725 * spin too long if we get preempted.
3727 preempt_disable();
3728 ++userpg->lock;
3729 barrier();
3730 userpg->index = perf_event_index(event);
3731 userpg->offset = perf_event_count(event);
3732 if (userpg->index)
3733 userpg->offset -= local64_read(&event->hw.prev_count);
3735 userpg->time_enabled = enabled +
3736 atomic64_read(&event->child_total_time_enabled);
3738 userpg->time_running = running +
3739 atomic64_read(&event->child_total_time_running);
3741 arch_perf_update_userpage(userpg, now);
3743 barrier();
3744 ++userpg->lock;
3745 preempt_enable();
3746 unlock:
3747 rcu_read_unlock();
3750 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
3752 struct perf_event *event = vma->vm_file->private_data;
3753 struct ring_buffer *rb;
3754 int ret = VM_FAULT_SIGBUS;
3756 if (vmf->flags & FAULT_FLAG_MKWRITE) {
3757 if (vmf->pgoff == 0)
3758 ret = 0;
3759 return ret;
3762 rcu_read_lock();
3763 rb = rcu_dereference(event->rb);
3764 if (!rb)
3765 goto unlock;
3767 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
3768 goto unlock;
3770 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
3771 if (!vmf->page)
3772 goto unlock;
3774 get_page(vmf->page);
3775 vmf->page->mapping = vma->vm_file->f_mapping;
3776 vmf->page->index = vmf->pgoff;
3778 ret = 0;
3779 unlock:
3780 rcu_read_unlock();
3782 return ret;
3785 static void ring_buffer_attach(struct perf_event *event,
3786 struct ring_buffer *rb)
3788 unsigned long flags;
3790 if (!list_empty(&event->rb_entry))
3791 return;
3793 spin_lock_irqsave(&rb->event_lock, flags);
3794 if (list_empty(&event->rb_entry))
3795 list_add(&event->rb_entry, &rb->event_list);
3796 spin_unlock_irqrestore(&rb->event_lock, flags);
3799 static void ring_buffer_detach(struct perf_event *event, struct ring_buffer *rb)
3801 unsigned long flags;
3803 if (list_empty(&event->rb_entry))
3804 return;
3806 spin_lock_irqsave(&rb->event_lock, flags);
3807 list_del_init(&event->rb_entry);
3808 wake_up_all(&event->waitq);
3809 spin_unlock_irqrestore(&rb->event_lock, flags);
3812 static void ring_buffer_wakeup(struct perf_event *event)
3814 struct ring_buffer *rb;
3816 rcu_read_lock();
3817 rb = rcu_dereference(event->rb);
3818 if (rb) {
3819 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
3820 wake_up_all(&event->waitq);
3822 rcu_read_unlock();
3825 static void rb_free_rcu(struct rcu_head *rcu_head)
3827 struct ring_buffer *rb;
3829 rb = container_of(rcu_head, struct ring_buffer, rcu_head);
3830 rb_free(rb);
3833 static struct ring_buffer *ring_buffer_get(struct perf_event *event)
3835 struct ring_buffer *rb;
3837 rcu_read_lock();
3838 rb = rcu_dereference(event->rb);
3839 if (rb) {
3840 if (!atomic_inc_not_zero(&rb->refcount))
3841 rb = NULL;
3843 rcu_read_unlock();
3845 return rb;
3848 static void ring_buffer_put(struct ring_buffer *rb)
3850 if (!atomic_dec_and_test(&rb->refcount))
3851 return;
3853 WARN_ON_ONCE(!list_empty(&rb->event_list));
3855 call_rcu(&rb->rcu_head, rb_free_rcu);
3858 static void perf_mmap_open(struct vm_area_struct *vma)
3860 struct perf_event *event = vma->vm_file->private_data;
3862 atomic_inc(&event->mmap_count);
3863 atomic_inc(&event->rb->mmap_count);
3867 * A buffer can be mmap()ed multiple times; either directly through the same
3868 * event, or through other events by use of perf_event_set_output().
3870 * In order to undo the VM accounting done by perf_mmap() we need to destroy
3871 * the buffer here, where we still have a VM context. This means we need
3872 * to detach all events redirecting to us.
3874 static void perf_mmap_close(struct vm_area_struct *vma)
3876 struct perf_event *event = vma->vm_file->private_data;
3878 struct ring_buffer *rb = event->rb;
3879 struct user_struct *mmap_user = rb->mmap_user;
3880 int mmap_locked = rb->mmap_locked;
3881 unsigned long size = perf_data_size(rb);
3883 atomic_dec(&rb->mmap_count);
3885 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
3886 return;
3888 /* Detach current event from the buffer. */
3889 rcu_assign_pointer(event->rb, NULL);
3890 ring_buffer_detach(event, rb);
3891 mutex_unlock(&event->mmap_mutex);
3893 /* If there's still other mmap()s of this buffer, we're done. */
3894 if (atomic_read(&rb->mmap_count)) {
3895 ring_buffer_put(rb); /* can't be last */
3896 return;
3900 * No other mmap()s, detach from all other events that might redirect
3901 * into the now unreachable buffer. Somewhat complicated by the
3902 * fact that rb::event_lock otherwise nests inside mmap_mutex.
3904 again:
3905 rcu_read_lock();
3906 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
3907 if (!atomic_long_inc_not_zero(&event->refcount)) {
3909 * This event is en-route to free_event() which will
3910 * detach it and remove it from the list.
3912 continue;
3914 rcu_read_unlock();
3916 mutex_lock(&event->mmap_mutex);
3918 * Check we didn't race with perf_event_set_output() which can
3919 * swizzle the rb from under us while we were waiting to
3920 * acquire mmap_mutex.
3922 * If we find a different rb; ignore this event, a next
3923 * iteration will no longer find it on the list. We have to
3924 * still restart the iteration to make sure we're not now
3925 * iterating the wrong list.
3927 if (event->rb == rb) {
3928 rcu_assign_pointer(event->rb, NULL);
3929 ring_buffer_detach(event, rb);
3930 ring_buffer_put(rb); /* can't be last, we still have one */
3932 mutex_unlock(&event->mmap_mutex);
3933 put_event(event);
3936 * Restart the iteration; either we're on the wrong list or
3937 * destroyed its integrity by doing a deletion.
3939 goto again;
3941 rcu_read_unlock();
3944 * It could be there's still a few 0-ref events on the list; they'll
3945 * get cleaned up by free_event() -- they'll also still have their
3946 * ref on the rb and will free it whenever they are done with it.
3948 * Aside from that, this buffer is 'fully' detached and unmapped,
3949 * undo the VM accounting.
3952 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
3953 vma->vm_mm->pinned_vm -= mmap_locked;
3954 free_uid(mmap_user);
3956 ring_buffer_put(rb); /* could be last */
3959 static const struct vm_operations_struct perf_mmap_vmops = {
3960 .open = perf_mmap_open,
3961 .close = perf_mmap_close,
3962 .fault = perf_mmap_fault,
3963 .page_mkwrite = perf_mmap_fault,
3966 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
3968 struct perf_event *event = file->private_data;
3969 unsigned long user_locked, user_lock_limit;
3970 struct user_struct *user = current_user();
3971 unsigned long locked, lock_limit;
3972 struct ring_buffer *rb;
3973 unsigned long vma_size;
3974 unsigned long nr_pages;
3975 long user_extra, extra;
3976 int ret = 0, flags = 0;
3979 * Don't allow mmap() of inherited per-task counters. This would
3980 * create a performance issue due to all children writing to the
3981 * same rb.
3983 if (event->cpu == -1 && event->attr.inherit)
3984 return -EINVAL;
3986 if (!(vma->vm_flags & VM_SHARED))
3987 return -EINVAL;
3989 vma_size = vma->vm_end - vma->vm_start;
3990 nr_pages = (vma_size / PAGE_SIZE) - 1;
3993 * If we have rb pages ensure they're a power-of-two number, so we
3994 * can do bitmasks instead of modulo.
3996 if (nr_pages != 0 && !is_power_of_2(nr_pages))
3997 return -EINVAL;
3999 if (vma_size != PAGE_SIZE * (1 + nr_pages))
4000 return -EINVAL;
4002 if (vma->vm_pgoff != 0)
4003 return -EINVAL;
4005 WARN_ON_ONCE(event->ctx->parent_ctx);
4006 again:
4007 mutex_lock(&event->mmap_mutex);
4008 if (event->rb) {
4009 if (event->rb->nr_pages != nr_pages) {
4010 ret = -EINVAL;
4011 goto unlock;
4014 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4016 * Raced against perf_mmap_close() through
4017 * perf_event_set_output(). Try again, hope for better
4018 * luck.
4020 mutex_unlock(&event->mmap_mutex);
4021 goto again;
4024 goto unlock;
4027 user_extra = nr_pages + 1;
4028 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
4031 * Increase the limit linearly with more CPUs:
4033 user_lock_limit *= num_online_cpus();
4035 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
4037 extra = 0;
4038 if (user_locked > user_lock_limit)
4039 extra = user_locked - user_lock_limit;
4041 lock_limit = rlimit(RLIMIT_MEMLOCK);
4042 lock_limit >>= PAGE_SHIFT;
4043 locked = vma->vm_mm->pinned_vm + extra;
4045 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
4046 !capable(CAP_IPC_LOCK)) {
4047 ret = -EPERM;
4048 goto unlock;
4051 WARN_ON(event->rb);
4053 if (vma->vm_flags & VM_WRITE)
4054 flags |= RING_BUFFER_WRITABLE;
4056 rb = rb_alloc(nr_pages,
4057 event->attr.watermark ? event->attr.wakeup_watermark : 0,
4058 event->cpu, flags);
4060 if (!rb) {
4061 ret = -ENOMEM;
4062 goto unlock;
4065 atomic_set(&rb->mmap_count, 1);
4066 rb->mmap_locked = extra;
4067 rb->mmap_user = get_current_user();
4069 atomic_long_add(user_extra, &user->locked_vm);
4070 vma->vm_mm->pinned_vm += extra;
4072 ring_buffer_attach(event, rb);
4073 rcu_assign_pointer(event->rb, rb);
4075 perf_event_init_userpage(event);
4076 perf_event_update_userpage(event);
4078 unlock:
4079 if (!ret)
4080 atomic_inc(&event->mmap_count);
4081 mutex_unlock(&event->mmap_mutex);
4084 * Since pinned accounting is per vm we cannot allow fork() to copy our
4085 * vma.
4087 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
4088 vma->vm_ops = &perf_mmap_vmops;
4090 return ret;
4093 static int perf_fasync(int fd, struct file *filp, int on)
4095 struct inode *inode = file_inode(filp);
4096 struct perf_event *event = filp->private_data;
4097 int retval;
4099 mutex_lock(&inode->i_mutex);
4100 retval = fasync_helper(fd, filp, on, &event->fasync);
4101 mutex_unlock(&inode->i_mutex);
4103 if (retval < 0)
4104 return retval;
4106 return 0;
4109 static const struct file_operations perf_fops = {
4110 .llseek = no_llseek,
4111 .release = perf_release,
4112 .read = perf_read,
4113 .poll = perf_poll,
4114 .unlocked_ioctl = perf_ioctl,
4115 .compat_ioctl = perf_ioctl,
4116 .mmap = perf_mmap,
4117 .fasync = perf_fasync,
4121 * Perf event wakeup
4123 * If there's data, ensure we set the poll() state and publish everything
4124 * to user-space before waking everybody up.
4127 void perf_event_wakeup(struct perf_event *event)
4129 ring_buffer_wakeup(event);
4131 if (event->pending_kill) {
4132 kill_fasync(&event->fasync, SIGIO, event->pending_kill);
4133 event->pending_kill = 0;
4137 static void perf_pending_event(struct irq_work *entry)
4139 struct perf_event *event = container_of(entry,
4140 struct perf_event, pending);
4142 if (event->pending_disable) {
4143 event->pending_disable = 0;
4144 __perf_event_disable(event);
4147 if (event->pending_wakeup) {
4148 event->pending_wakeup = 0;
4149 perf_event_wakeup(event);
4154 * We assume there is only KVM supporting the callbacks.
4155 * Later on, we might change it to a list if there is
4156 * another virtualization implementation supporting the callbacks.
4158 struct perf_guest_info_callbacks *perf_guest_cbs;
4160 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4162 perf_guest_cbs = cbs;
4163 return 0;
4165 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
4167 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4169 perf_guest_cbs = NULL;
4170 return 0;
4172 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
4174 static void
4175 perf_output_sample_regs(struct perf_output_handle *handle,
4176 struct pt_regs *regs, u64 mask)
4178 int bit;
4180 for_each_set_bit(bit, (const unsigned long *) &mask,
4181 sizeof(mask) * BITS_PER_BYTE) {
4182 u64 val;
4184 val = perf_reg_value(regs, bit);
4185 perf_output_put(handle, val);
4189 static void perf_sample_regs_user(struct perf_regs_user *regs_user,
4190 struct pt_regs *regs)
4192 if (!user_mode(regs)) {
4193 if (current->mm)
4194 regs = task_pt_regs(current);
4195 else
4196 regs = NULL;
4199 if (regs) {
4200 regs_user->regs = regs;
4201 regs_user->abi = perf_reg_abi(current);
4206 * Get remaining task size from user stack pointer.
4208 * It'd be better to take stack vma map and limit this more
4209 * precisly, but there's no way to get it safely under interrupt,
4210 * so using TASK_SIZE as limit.
4212 static u64 perf_ustack_task_size(struct pt_regs *regs)
4214 unsigned long addr = perf_user_stack_pointer(regs);
4216 if (!addr || addr >= TASK_SIZE)
4217 return 0;
4219 return TASK_SIZE - addr;
4222 static u16
4223 perf_sample_ustack_size(u16 stack_size, u16 header_size,
4224 struct pt_regs *regs)
4226 u64 task_size;
4228 /* No regs, no stack pointer, no dump. */
4229 if (!regs)
4230 return 0;
4233 * Check if we fit in with the requested stack size into the:
4234 * - TASK_SIZE
4235 * If we don't, we limit the size to the TASK_SIZE.
4237 * - remaining sample size
4238 * If we don't, we customize the stack size to
4239 * fit in to the remaining sample size.
4242 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
4243 stack_size = min(stack_size, (u16) task_size);
4245 /* Current header size plus static size and dynamic size. */
4246 header_size += 2 * sizeof(u64);
4248 /* Do we fit in with the current stack dump size? */
4249 if ((u16) (header_size + stack_size) < header_size) {
4251 * If we overflow the maximum size for the sample,
4252 * we customize the stack dump size to fit in.
4254 stack_size = USHRT_MAX - header_size - sizeof(u64);
4255 stack_size = round_up(stack_size, sizeof(u64));
4258 return stack_size;
4261 static void
4262 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
4263 struct pt_regs *regs)
4265 /* Case of a kernel thread, nothing to dump */
4266 if (!regs) {
4267 u64 size = 0;
4268 perf_output_put(handle, size);
4269 } else {
4270 unsigned long sp;
4271 unsigned int rem;
4272 u64 dyn_size;
4275 * We dump:
4276 * static size
4277 * - the size requested by user or the best one we can fit
4278 * in to the sample max size
4279 * data
4280 * - user stack dump data
4281 * dynamic size
4282 * - the actual dumped size
4285 /* Static size. */
4286 perf_output_put(handle, dump_size);
4288 /* Data. */
4289 sp = perf_user_stack_pointer(regs);
4290 rem = __output_copy_user(handle, (void *) sp, dump_size);
4291 dyn_size = dump_size - rem;
4293 perf_output_skip(handle, rem);
4295 /* Dynamic size. */
4296 perf_output_put(handle, dyn_size);
4300 static void __perf_event_header__init_id(struct perf_event_header *header,
4301 struct perf_sample_data *data,
4302 struct perf_event *event)
4304 u64 sample_type = event->attr.sample_type;
4306 data->type = sample_type;
4307 header->size += event->id_header_size;
4309 if (sample_type & PERF_SAMPLE_TID) {
4310 /* namespace issues */
4311 data->tid_entry.pid = perf_event_pid(event, current);
4312 data->tid_entry.tid = perf_event_tid(event, current);
4315 if (sample_type & PERF_SAMPLE_TIME)
4316 data->time = perf_clock();
4318 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
4319 data->id = primary_event_id(event);
4321 if (sample_type & PERF_SAMPLE_STREAM_ID)
4322 data->stream_id = event->id;
4324 if (sample_type & PERF_SAMPLE_CPU) {
4325 data->cpu_entry.cpu = raw_smp_processor_id();
4326 data->cpu_entry.reserved = 0;
4330 void perf_event_header__init_id(struct perf_event_header *header,
4331 struct perf_sample_data *data,
4332 struct perf_event *event)
4334 if (event->attr.sample_id_all)
4335 __perf_event_header__init_id(header, data, event);
4338 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
4339 struct perf_sample_data *data)
4341 u64 sample_type = data->type;
4343 if (sample_type & PERF_SAMPLE_TID)
4344 perf_output_put(handle, data->tid_entry);
4346 if (sample_type & PERF_SAMPLE_TIME)
4347 perf_output_put(handle, data->time);
4349 if (sample_type & PERF_SAMPLE_ID)
4350 perf_output_put(handle, data->id);
4352 if (sample_type & PERF_SAMPLE_STREAM_ID)
4353 perf_output_put(handle, data->stream_id);
4355 if (sample_type & PERF_SAMPLE_CPU)
4356 perf_output_put(handle, data->cpu_entry);
4358 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4359 perf_output_put(handle, data->id);
4362 void perf_event__output_id_sample(struct perf_event *event,
4363 struct perf_output_handle *handle,
4364 struct perf_sample_data *sample)
4366 if (event->attr.sample_id_all)
4367 __perf_event__output_id_sample(handle, sample);
4370 static void perf_output_read_one(struct perf_output_handle *handle,
4371 struct perf_event *event,
4372 u64 enabled, u64 running)
4374 u64 read_format = event->attr.read_format;
4375 u64 values[4];
4376 int n = 0;
4378 values[n++] = perf_event_count(event);
4379 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4380 values[n++] = enabled +
4381 atomic64_read(&event->child_total_time_enabled);
4383 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4384 values[n++] = running +
4385 atomic64_read(&event->child_total_time_running);
4387 if (read_format & PERF_FORMAT_ID)
4388 values[n++] = primary_event_id(event);
4390 __output_copy(handle, values, n * sizeof(u64));
4394 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
4396 static void perf_output_read_group(struct perf_output_handle *handle,
4397 struct perf_event *event,
4398 u64 enabled, u64 running)
4400 struct perf_event *leader = event->group_leader, *sub;
4401 u64 read_format = event->attr.read_format;
4402 u64 values[5];
4403 int n = 0;
4405 values[n++] = 1 + leader->nr_siblings;
4407 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4408 values[n++] = enabled;
4410 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4411 values[n++] = running;
4413 if (leader != event)
4414 leader->pmu->read(leader);
4416 values[n++] = perf_event_count(leader);
4417 if (read_format & PERF_FORMAT_ID)
4418 values[n++] = primary_event_id(leader);
4420 __output_copy(handle, values, n * sizeof(u64));
4422 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4423 n = 0;
4425 if ((sub != event) &&
4426 (sub->state == PERF_EVENT_STATE_ACTIVE))
4427 sub->pmu->read(sub);
4429 values[n++] = perf_event_count(sub);
4430 if (read_format & PERF_FORMAT_ID)
4431 values[n++] = primary_event_id(sub);
4433 __output_copy(handle, values, n * sizeof(u64));
4437 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
4438 PERF_FORMAT_TOTAL_TIME_RUNNING)
4440 static void perf_output_read(struct perf_output_handle *handle,
4441 struct perf_event *event)
4443 u64 enabled = 0, running = 0, now;
4444 u64 read_format = event->attr.read_format;
4447 * compute total_time_enabled, total_time_running
4448 * based on snapshot values taken when the event
4449 * was last scheduled in.
4451 * we cannot simply called update_context_time()
4452 * because of locking issue as we are called in
4453 * NMI context
4455 if (read_format & PERF_FORMAT_TOTAL_TIMES)
4456 calc_timer_values(event, &now, &enabled, &running);
4458 if (event->attr.read_format & PERF_FORMAT_GROUP)
4459 perf_output_read_group(handle, event, enabled, running);
4460 else
4461 perf_output_read_one(handle, event, enabled, running);
4464 void perf_output_sample(struct perf_output_handle *handle,
4465 struct perf_event_header *header,
4466 struct perf_sample_data *data,
4467 struct perf_event *event)
4469 u64 sample_type = data->type;
4471 perf_output_put(handle, *header);
4473 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4474 perf_output_put(handle, data->id);
4476 if (sample_type & PERF_SAMPLE_IP)
4477 perf_output_put(handle, data->ip);
4479 if (sample_type & PERF_SAMPLE_TID)
4480 perf_output_put(handle, data->tid_entry);
4482 if (sample_type & PERF_SAMPLE_TIME)
4483 perf_output_put(handle, data->time);
4485 if (sample_type & PERF_SAMPLE_ADDR)
4486 perf_output_put(handle, data->addr);
4488 if (sample_type & PERF_SAMPLE_ID)
4489 perf_output_put(handle, data->id);
4491 if (sample_type & PERF_SAMPLE_STREAM_ID)
4492 perf_output_put(handle, data->stream_id);
4494 if (sample_type & PERF_SAMPLE_CPU)
4495 perf_output_put(handle, data->cpu_entry);
4497 if (sample_type & PERF_SAMPLE_PERIOD)
4498 perf_output_put(handle, data->period);
4500 if (sample_type & PERF_SAMPLE_READ)
4501 perf_output_read(handle, event);
4503 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4504 if (data->callchain) {
4505 int size = 1;
4507 if (data->callchain)
4508 size += data->callchain->nr;
4510 size *= sizeof(u64);
4512 __output_copy(handle, data->callchain, size);
4513 } else {
4514 u64 nr = 0;
4515 perf_output_put(handle, nr);
4519 if (sample_type & PERF_SAMPLE_RAW) {
4520 if (data->raw) {
4521 perf_output_put(handle, data->raw->size);
4522 __output_copy(handle, data->raw->data,
4523 data->raw->size);
4524 } else {
4525 struct {
4526 u32 size;
4527 u32 data;
4528 } raw = {
4529 .size = sizeof(u32),
4530 .data = 0,
4532 perf_output_put(handle, raw);
4536 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4537 if (data->br_stack) {
4538 size_t size;
4540 size = data->br_stack->nr
4541 * sizeof(struct perf_branch_entry);
4543 perf_output_put(handle, data->br_stack->nr);
4544 perf_output_copy(handle, data->br_stack->entries, size);
4545 } else {
4547 * we always store at least the value of nr
4549 u64 nr = 0;
4550 perf_output_put(handle, nr);
4554 if (sample_type & PERF_SAMPLE_REGS_USER) {
4555 u64 abi = data->regs_user.abi;
4558 * If there are no regs to dump, notice it through
4559 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
4561 perf_output_put(handle, abi);
4563 if (abi) {
4564 u64 mask = event->attr.sample_regs_user;
4565 perf_output_sample_regs(handle,
4566 data->regs_user.regs,
4567 mask);
4571 if (sample_type & PERF_SAMPLE_STACK_USER) {
4572 perf_output_sample_ustack(handle,
4573 data->stack_user_size,
4574 data->regs_user.regs);
4577 if (sample_type & PERF_SAMPLE_WEIGHT)
4578 perf_output_put(handle, data->weight);
4580 if (sample_type & PERF_SAMPLE_DATA_SRC)
4581 perf_output_put(handle, data->data_src.val);
4583 if (!event->attr.watermark) {
4584 int wakeup_events = event->attr.wakeup_events;
4586 if (wakeup_events) {
4587 struct ring_buffer *rb = handle->rb;
4588 int events = local_inc_return(&rb->events);
4590 if (events >= wakeup_events) {
4591 local_sub(wakeup_events, &rb->events);
4592 local_inc(&rb->wakeup);
4598 void perf_prepare_sample(struct perf_event_header *header,
4599 struct perf_sample_data *data,
4600 struct perf_event *event,
4601 struct pt_regs *regs)
4603 u64 sample_type = event->attr.sample_type;
4605 header->type = PERF_RECORD_SAMPLE;
4606 header->size = sizeof(*header) + event->header_size;
4608 header->misc = 0;
4609 header->misc |= perf_misc_flags(regs);
4611 __perf_event_header__init_id(header, data, event);
4613 if (sample_type & PERF_SAMPLE_IP)
4614 data->ip = perf_instruction_pointer(regs);
4616 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4617 int size = 1;
4619 data->callchain = perf_callchain(event, regs);
4621 if (data->callchain)
4622 size += data->callchain->nr;
4624 header->size += size * sizeof(u64);
4627 if (sample_type & PERF_SAMPLE_RAW) {
4628 int size = sizeof(u32);
4630 if (data->raw)
4631 size += data->raw->size;
4632 else
4633 size += sizeof(u32);
4635 WARN_ON_ONCE(size & (sizeof(u64)-1));
4636 header->size += size;
4639 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4640 int size = sizeof(u64); /* nr */
4641 if (data->br_stack) {
4642 size += data->br_stack->nr
4643 * sizeof(struct perf_branch_entry);
4645 header->size += size;
4648 if (sample_type & PERF_SAMPLE_REGS_USER) {
4649 /* regs dump ABI info */
4650 int size = sizeof(u64);
4652 perf_sample_regs_user(&data->regs_user, regs);
4654 if (data->regs_user.regs) {
4655 u64 mask = event->attr.sample_regs_user;
4656 size += hweight64(mask) * sizeof(u64);
4659 header->size += size;
4662 if (sample_type & PERF_SAMPLE_STACK_USER) {
4664 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
4665 * processed as the last one or have additional check added
4666 * in case new sample type is added, because we could eat
4667 * up the rest of the sample size.
4669 struct perf_regs_user *uregs = &data->regs_user;
4670 u16 stack_size = event->attr.sample_stack_user;
4671 u16 size = sizeof(u64);
4673 if (!uregs->abi)
4674 perf_sample_regs_user(uregs, regs);
4676 stack_size = perf_sample_ustack_size(stack_size, header->size,
4677 uregs->regs);
4680 * If there is something to dump, add space for the dump
4681 * itself and for the field that tells the dynamic size,
4682 * which is how many have been actually dumped.
4684 if (stack_size)
4685 size += sizeof(u64) + stack_size;
4687 data->stack_user_size = stack_size;
4688 header->size += size;
4692 static void perf_event_output(struct perf_event *event,
4693 struct perf_sample_data *data,
4694 struct pt_regs *regs)
4696 struct perf_output_handle handle;
4697 struct perf_event_header header;
4699 /* protect the callchain buffers */
4700 rcu_read_lock();
4702 perf_prepare_sample(&header, data, event, regs);
4704 if (perf_output_begin(&handle, event, header.size))
4705 goto exit;
4707 perf_output_sample(&handle, &header, data, event);
4709 perf_output_end(&handle);
4711 exit:
4712 rcu_read_unlock();
4716 * read event_id
4719 struct perf_read_event {
4720 struct perf_event_header header;
4722 u32 pid;
4723 u32 tid;
4726 static void
4727 perf_event_read_event(struct perf_event *event,
4728 struct task_struct *task)
4730 struct perf_output_handle handle;
4731 struct perf_sample_data sample;
4732 struct perf_read_event read_event = {
4733 .header = {
4734 .type = PERF_RECORD_READ,
4735 .misc = 0,
4736 .size = sizeof(read_event) + event->read_size,
4738 .pid = perf_event_pid(event, task),
4739 .tid = perf_event_tid(event, task),
4741 int ret;
4743 perf_event_header__init_id(&read_event.header, &sample, event);
4744 ret = perf_output_begin(&handle, event, read_event.header.size);
4745 if (ret)
4746 return;
4748 perf_output_put(&handle, read_event);
4749 perf_output_read(&handle, event);
4750 perf_event__output_id_sample(event, &handle, &sample);
4752 perf_output_end(&handle);
4755 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
4757 static void
4758 perf_event_aux_ctx(struct perf_event_context *ctx,
4759 perf_event_aux_output_cb output,
4760 void *data)
4762 struct perf_event *event;
4764 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4765 if (event->state < PERF_EVENT_STATE_INACTIVE)
4766 continue;
4767 if (!event_filter_match(event))
4768 continue;
4769 output(event, data);
4773 static void
4774 perf_event_aux(perf_event_aux_output_cb output, void *data,
4775 struct perf_event_context *task_ctx)
4777 struct perf_cpu_context *cpuctx;
4778 struct perf_event_context *ctx;
4779 struct pmu *pmu;
4780 int ctxn;
4782 rcu_read_lock();
4783 list_for_each_entry_rcu(pmu, &pmus, entry) {
4784 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4785 if (cpuctx->unique_pmu != pmu)
4786 goto next;
4787 perf_event_aux_ctx(&cpuctx->ctx, output, data);
4788 if (task_ctx)
4789 goto next;
4790 ctxn = pmu->task_ctx_nr;
4791 if (ctxn < 0)
4792 goto next;
4793 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4794 if (ctx)
4795 perf_event_aux_ctx(ctx, output, data);
4796 next:
4797 put_cpu_ptr(pmu->pmu_cpu_context);
4800 if (task_ctx) {
4801 preempt_disable();
4802 perf_event_aux_ctx(task_ctx, output, data);
4803 preempt_enable();
4805 rcu_read_unlock();
4809 * task tracking -- fork/exit
4811 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
4814 struct perf_task_event {
4815 struct task_struct *task;
4816 struct perf_event_context *task_ctx;
4818 struct {
4819 struct perf_event_header header;
4821 u32 pid;
4822 u32 ppid;
4823 u32 tid;
4824 u32 ptid;
4825 u64 time;
4826 } event_id;
4829 static int perf_event_task_match(struct perf_event *event)
4831 return event->attr.comm || event->attr.mmap ||
4832 event->attr.mmap2 || event->attr.mmap_data ||
4833 event->attr.task;
4836 static void perf_event_task_output(struct perf_event *event,
4837 void *data)
4839 struct perf_task_event *task_event = data;
4840 struct perf_output_handle handle;
4841 struct perf_sample_data sample;
4842 struct task_struct *task = task_event->task;
4843 int ret, size = task_event->event_id.header.size;
4845 if (!perf_event_task_match(event))
4846 return;
4848 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
4850 ret = perf_output_begin(&handle, event,
4851 task_event->event_id.header.size);
4852 if (ret)
4853 goto out;
4855 task_event->event_id.pid = perf_event_pid(event, task);
4856 task_event->event_id.ppid = perf_event_pid(event, current);
4858 task_event->event_id.tid = perf_event_tid(event, task);
4859 task_event->event_id.ptid = perf_event_tid(event, current);
4861 perf_output_put(&handle, task_event->event_id);
4863 perf_event__output_id_sample(event, &handle, &sample);
4865 perf_output_end(&handle);
4866 out:
4867 task_event->event_id.header.size = size;
4870 static void perf_event_task(struct task_struct *task,
4871 struct perf_event_context *task_ctx,
4872 int new)
4874 struct perf_task_event task_event;
4876 if (!atomic_read(&nr_comm_events) &&
4877 !atomic_read(&nr_mmap_events) &&
4878 !atomic_read(&nr_task_events))
4879 return;
4881 task_event = (struct perf_task_event){
4882 .task = task,
4883 .task_ctx = task_ctx,
4884 .event_id = {
4885 .header = {
4886 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
4887 .misc = 0,
4888 .size = sizeof(task_event.event_id),
4890 /* .pid */
4891 /* .ppid */
4892 /* .tid */
4893 /* .ptid */
4894 .time = perf_clock(),
4898 perf_event_aux(perf_event_task_output,
4899 &task_event,
4900 task_ctx);
4903 void perf_event_fork(struct task_struct *task)
4905 perf_event_task(task, NULL, 1);
4909 * comm tracking
4912 struct perf_comm_event {
4913 struct task_struct *task;
4914 char *comm;
4915 int comm_size;
4917 struct {
4918 struct perf_event_header header;
4920 u32 pid;
4921 u32 tid;
4922 } event_id;
4925 static int perf_event_comm_match(struct perf_event *event)
4927 return event->attr.comm;
4930 static void perf_event_comm_output(struct perf_event *event,
4931 void *data)
4933 struct perf_comm_event *comm_event = data;
4934 struct perf_output_handle handle;
4935 struct perf_sample_data sample;
4936 int size = comm_event->event_id.header.size;
4937 int ret;
4939 if (!perf_event_comm_match(event))
4940 return;
4942 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
4943 ret = perf_output_begin(&handle, event,
4944 comm_event->event_id.header.size);
4946 if (ret)
4947 goto out;
4949 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
4950 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
4952 perf_output_put(&handle, comm_event->event_id);
4953 __output_copy(&handle, comm_event->comm,
4954 comm_event->comm_size);
4956 perf_event__output_id_sample(event, &handle, &sample);
4958 perf_output_end(&handle);
4959 out:
4960 comm_event->event_id.header.size = size;
4963 static void perf_event_comm_event(struct perf_comm_event *comm_event)
4965 char comm[TASK_COMM_LEN];
4966 unsigned int size;
4968 memset(comm, 0, sizeof(comm));
4969 strlcpy(comm, comm_event->task->comm, sizeof(comm));
4970 size = ALIGN(strlen(comm)+1, sizeof(u64));
4972 comm_event->comm = comm;
4973 comm_event->comm_size = size;
4975 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
4977 perf_event_aux(perf_event_comm_output,
4978 comm_event,
4979 NULL);
4982 void perf_event_comm(struct task_struct *task)
4984 struct perf_comm_event comm_event;
4985 struct perf_event_context *ctx;
4986 int ctxn;
4988 rcu_read_lock();
4989 for_each_task_context_nr(ctxn) {
4990 ctx = task->perf_event_ctxp[ctxn];
4991 if (!ctx)
4992 continue;
4994 perf_event_enable_on_exec(ctx);
4996 rcu_read_unlock();
4998 if (!atomic_read(&nr_comm_events))
4999 return;
5001 comm_event = (struct perf_comm_event){
5002 .task = task,
5003 /* .comm */
5004 /* .comm_size */
5005 .event_id = {
5006 .header = {
5007 .type = PERF_RECORD_COMM,
5008 .misc = 0,
5009 /* .size */
5011 /* .pid */
5012 /* .tid */
5016 perf_event_comm_event(&comm_event);
5020 * mmap tracking
5023 struct perf_mmap_event {
5024 struct vm_area_struct *vma;
5026 const char *file_name;
5027 int file_size;
5028 int maj, min;
5029 u64 ino;
5030 u64 ino_generation;
5032 struct {
5033 struct perf_event_header header;
5035 u32 pid;
5036 u32 tid;
5037 u64 start;
5038 u64 len;
5039 u64 pgoff;
5040 } event_id;
5043 static int perf_event_mmap_match(struct perf_event *event,
5044 void *data)
5046 struct perf_mmap_event *mmap_event = data;
5047 struct vm_area_struct *vma = mmap_event->vma;
5048 int executable = vma->vm_flags & VM_EXEC;
5050 return (!executable && event->attr.mmap_data) ||
5051 (executable && (event->attr.mmap || event->attr.mmap2));
5054 static void perf_event_mmap_output(struct perf_event *event,
5055 void *data)
5057 struct perf_mmap_event *mmap_event = data;
5058 struct perf_output_handle handle;
5059 struct perf_sample_data sample;
5060 int size = mmap_event->event_id.header.size;
5061 int ret;
5063 if (!perf_event_mmap_match(event, data))
5064 return;
5066 if (event->attr.mmap2) {
5067 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
5068 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
5069 mmap_event->event_id.header.size += sizeof(mmap_event->min);
5070 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
5071 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
5074 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
5075 ret = perf_output_begin(&handle, event,
5076 mmap_event->event_id.header.size);
5077 if (ret)
5078 goto out;
5080 mmap_event->event_id.pid = perf_event_pid(event, current);
5081 mmap_event->event_id.tid = perf_event_tid(event, current);
5083 perf_output_put(&handle, mmap_event->event_id);
5085 if (event->attr.mmap2) {
5086 perf_output_put(&handle, mmap_event->maj);
5087 perf_output_put(&handle, mmap_event->min);
5088 perf_output_put(&handle, mmap_event->ino);
5089 perf_output_put(&handle, mmap_event->ino_generation);
5092 __output_copy(&handle, mmap_event->file_name,
5093 mmap_event->file_size);
5095 perf_event__output_id_sample(event, &handle, &sample);
5097 perf_output_end(&handle);
5098 out:
5099 mmap_event->event_id.header.size = size;
5102 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
5104 struct vm_area_struct *vma = mmap_event->vma;
5105 struct file *file = vma->vm_file;
5106 int maj = 0, min = 0;
5107 u64 ino = 0, gen = 0;
5108 unsigned int size;
5109 char tmp[16];
5110 char *buf = NULL;
5111 const char *name;
5113 memset(tmp, 0, sizeof(tmp));
5115 if (file) {
5116 struct inode *inode;
5117 dev_t dev;
5119 * d_path works from the end of the rb backwards, so we
5120 * need to add enough zero bytes after the string to handle
5121 * the 64bit alignment we do later.
5123 buf = kzalloc(PATH_MAX + sizeof(u64), GFP_KERNEL);
5124 if (!buf) {
5125 name = strncpy(tmp, "//enomem", sizeof(tmp));
5126 goto got_name;
5128 name = d_path(&file->f_path, buf, PATH_MAX);
5129 if (IS_ERR(name)) {
5130 name = strncpy(tmp, "//toolong", sizeof(tmp));
5131 goto got_name;
5133 inode = file_inode(vma->vm_file);
5134 dev = inode->i_sb->s_dev;
5135 ino = inode->i_ino;
5136 gen = inode->i_generation;
5137 maj = MAJOR(dev);
5138 min = MINOR(dev);
5140 } else {
5141 if (arch_vma_name(mmap_event->vma)) {
5142 name = strncpy(tmp, arch_vma_name(mmap_event->vma),
5143 sizeof(tmp) - 1);
5144 tmp[sizeof(tmp) - 1] = '\0';
5145 goto got_name;
5148 if (!vma->vm_mm) {
5149 name = strncpy(tmp, "[vdso]", sizeof(tmp));
5150 goto got_name;
5151 } else if (vma->vm_start <= vma->vm_mm->start_brk &&
5152 vma->vm_end >= vma->vm_mm->brk) {
5153 name = strncpy(tmp, "[heap]", sizeof(tmp));
5154 goto got_name;
5155 } else if (vma->vm_start <= vma->vm_mm->start_stack &&
5156 vma->vm_end >= vma->vm_mm->start_stack) {
5157 name = strncpy(tmp, "[stack]", sizeof(tmp));
5158 goto got_name;
5161 name = strncpy(tmp, "//anon", sizeof(tmp));
5162 goto got_name;
5165 got_name:
5166 size = ALIGN(strlen(name)+1, sizeof(u64));
5168 mmap_event->file_name = name;
5169 mmap_event->file_size = size;
5170 mmap_event->maj = maj;
5171 mmap_event->min = min;
5172 mmap_event->ino = ino;
5173 mmap_event->ino_generation = gen;
5175 if (!(vma->vm_flags & VM_EXEC))
5176 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
5178 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
5180 perf_event_aux(perf_event_mmap_output,
5181 mmap_event,
5182 NULL);
5184 kfree(buf);
5187 void perf_event_mmap(struct vm_area_struct *vma)
5189 struct perf_mmap_event mmap_event;
5191 if (!atomic_read(&nr_mmap_events))
5192 return;
5194 mmap_event = (struct perf_mmap_event){
5195 .vma = vma,
5196 /* .file_name */
5197 /* .file_size */
5198 .event_id = {
5199 .header = {
5200 .type = PERF_RECORD_MMAP,
5201 .misc = PERF_RECORD_MISC_USER,
5202 /* .size */
5204 /* .pid */
5205 /* .tid */
5206 .start = vma->vm_start,
5207 .len = vma->vm_end - vma->vm_start,
5208 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
5210 /* .maj (attr_mmap2 only) */
5211 /* .min (attr_mmap2 only) */
5212 /* .ino (attr_mmap2 only) */
5213 /* .ino_generation (attr_mmap2 only) */
5216 perf_event_mmap_event(&mmap_event);
5220 * IRQ throttle logging
5223 static void perf_log_throttle(struct perf_event *event, int enable)
5225 struct perf_output_handle handle;
5226 struct perf_sample_data sample;
5227 int ret;
5229 struct {
5230 struct perf_event_header header;
5231 u64 time;
5232 u64 id;
5233 u64 stream_id;
5234 } throttle_event = {
5235 .header = {
5236 .type = PERF_RECORD_THROTTLE,
5237 .misc = 0,
5238 .size = sizeof(throttle_event),
5240 .time = perf_clock(),
5241 .id = primary_event_id(event),
5242 .stream_id = event->id,
5245 if (enable)
5246 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
5248 perf_event_header__init_id(&throttle_event.header, &sample, event);
5250 ret = perf_output_begin(&handle, event,
5251 throttle_event.header.size);
5252 if (ret)
5253 return;
5255 perf_output_put(&handle, throttle_event);
5256 perf_event__output_id_sample(event, &handle, &sample);
5257 perf_output_end(&handle);
5261 * Generic event overflow handling, sampling.
5264 static int __perf_event_overflow(struct perf_event *event,
5265 int throttle, struct perf_sample_data *data,
5266 struct pt_regs *regs)
5268 int events = atomic_read(&event->event_limit);
5269 struct hw_perf_event *hwc = &event->hw;
5270 u64 seq;
5271 int ret = 0;
5274 * Non-sampling counters might still use the PMI to fold short
5275 * hardware counters, ignore those.
5277 if (unlikely(!is_sampling_event(event)))
5278 return 0;
5280 seq = __this_cpu_read(perf_throttled_seq);
5281 if (seq != hwc->interrupts_seq) {
5282 hwc->interrupts_seq = seq;
5283 hwc->interrupts = 1;
5284 } else {
5285 hwc->interrupts++;
5286 if (unlikely(throttle
5287 && hwc->interrupts >= max_samples_per_tick)) {
5288 __this_cpu_inc(perf_throttled_count);
5289 hwc->interrupts = MAX_INTERRUPTS;
5290 perf_log_throttle(event, 0);
5291 tick_nohz_full_kick();
5292 ret = 1;
5296 if (event->attr.freq) {
5297 u64 now = perf_clock();
5298 s64 delta = now - hwc->freq_time_stamp;
5300 hwc->freq_time_stamp = now;
5302 if (delta > 0 && delta < 2*TICK_NSEC)
5303 perf_adjust_period(event, delta, hwc->last_period, true);
5307 * XXX event_limit might not quite work as expected on inherited
5308 * events
5311 event->pending_kill = POLL_IN;
5312 if (events && atomic_dec_and_test(&event->event_limit)) {
5313 ret = 1;
5314 event->pending_kill = POLL_HUP;
5315 event->pending_disable = 1;
5316 irq_work_queue(&event->pending);
5319 if (event->overflow_handler)
5320 event->overflow_handler(event, data, regs);
5321 else
5322 perf_event_output(event, data, regs);
5324 if (event->fasync && event->pending_kill) {
5325 event->pending_wakeup = 1;
5326 irq_work_queue(&event->pending);
5329 return ret;
5332 int perf_event_overflow(struct perf_event *event,
5333 struct perf_sample_data *data,
5334 struct pt_regs *regs)
5336 return __perf_event_overflow(event, 1, data, regs);
5340 * Generic software event infrastructure
5343 struct swevent_htable {
5344 struct swevent_hlist *swevent_hlist;
5345 struct mutex hlist_mutex;
5346 int hlist_refcount;
5348 /* Recursion avoidance in each contexts */
5349 int recursion[PERF_NR_CONTEXTS];
5351 /* Keeps track of cpu being initialized/exited */
5352 bool online;
5355 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
5358 * We directly increment event->count and keep a second value in
5359 * event->hw.period_left to count intervals. This period event
5360 * is kept in the range [-sample_period, 0] so that we can use the
5361 * sign as trigger.
5364 u64 perf_swevent_set_period(struct perf_event *event)
5366 struct hw_perf_event *hwc = &event->hw;
5367 u64 period = hwc->last_period;
5368 u64 nr, offset;
5369 s64 old, val;
5371 hwc->last_period = hwc->sample_period;
5373 again:
5374 old = val = local64_read(&hwc->period_left);
5375 if (val < 0)
5376 return 0;
5378 nr = div64_u64(period + val, period);
5379 offset = nr * period;
5380 val -= offset;
5381 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
5382 goto again;
5384 return nr;
5387 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
5388 struct perf_sample_data *data,
5389 struct pt_regs *regs)
5391 struct hw_perf_event *hwc = &event->hw;
5392 int throttle = 0;
5394 if (!overflow)
5395 overflow = perf_swevent_set_period(event);
5397 if (hwc->interrupts == MAX_INTERRUPTS)
5398 return;
5400 for (; overflow; overflow--) {
5401 if (__perf_event_overflow(event, throttle,
5402 data, regs)) {
5404 * We inhibit the overflow from happening when
5405 * hwc->interrupts == MAX_INTERRUPTS.
5407 break;
5409 throttle = 1;
5413 static void perf_swevent_event(struct perf_event *event, u64 nr,
5414 struct perf_sample_data *data,
5415 struct pt_regs *regs)
5417 struct hw_perf_event *hwc = &event->hw;
5419 local64_add(nr, &event->count);
5421 if (!regs)
5422 return;
5424 if (!is_sampling_event(event))
5425 return;
5427 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
5428 data->period = nr;
5429 return perf_swevent_overflow(event, 1, data, regs);
5430 } else
5431 data->period = event->hw.last_period;
5433 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
5434 return perf_swevent_overflow(event, 1, data, regs);
5436 if (local64_add_negative(nr, &hwc->period_left))
5437 return;
5439 perf_swevent_overflow(event, 0, data, regs);
5442 static int perf_exclude_event(struct perf_event *event,
5443 struct pt_regs *regs)
5445 if (event->hw.state & PERF_HES_STOPPED)
5446 return 1;
5448 if (regs) {
5449 if (event->attr.exclude_user && user_mode(regs))
5450 return 1;
5452 if (event->attr.exclude_kernel && !user_mode(regs))
5453 return 1;
5456 return 0;
5459 static int perf_swevent_match(struct perf_event *event,
5460 enum perf_type_id type,
5461 u32 event_id,
5462 struct perf_sample_data *data,
5463 struct pt_regs *regs)
5465 if (event->attr.type != type)
5466 return 0;
5468 if (event->attr.config != event_id)
5469 return 0;
5471 if (perf_exclude_event(event, regs))
5472 return 0;
5474 return 1;
5477 static inline u64 swevent_hash(u64 type, u32 event_id)
5479 u64 val = event_id | (type << 32);
5481 return hash_64(val, SWEVENT_HLIST_BITS);
5484 static inline struct hlist_head *
5485 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
5487 u64 hash = swevent_hash(type, event_id);
5489 return &hlist->heads[hash];
5492 /* For the read side: events when they trigger */
5493 static inline struct hlist_head *
5494 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
5496 struct swevent_hlist *hlist;
5498 hlist = rcu_dereference(swhash->swevent_hlist);
5499 if (!hlist)
5500 return NULL;
5502 return __find_swevent_head(hlist, type, event_id);
5505 /* For the event head insertion and removal in the hlist */
5506 static inline struct hlist_head *
5507 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
5509 struct swevent_hlist *hlist;
5510 u32 event_id = event->attr.config;
5511 u64 type = event->attr.type;
5514 * Event scheduling is always serialized against hlist allocation
5515 * and release. Which makes the protected version suitable here.
5516 * The context lock guarantees that.
5518 hlist = rcu_dereference_protected(swhash->swevent_hlist,
5519 lockdep_is_held(&event->ctx->lock));
5520 if (!hlist)
5521 return NULL;
5523 return __find_swevent_head(hlist, type, event_id);
5526 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
5527 u64 nr,
5528 struct perf_sample_data *data,
5529 struct pt_regs *regs)
5531 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5532 struct perf_event *event;
5533 struct hlist_head *head;
5535 rcu_read_lock();
5536 head = find_swevent_head_rcu(swhash, type, event_id);
5537 if (!head)
5538 goto end;
5540 hlist_for_each_entry_rcu(event, head, hlist_entry) {
5541 if (perf_swevent_match(event, type, event_id, data, regs))
5542 perf_swevent_event(event, nr, data, regs);
5544 end:
5545 rcu_read_unlock();
5548 int perf_swevent_get_recursion_context(void)
5550 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5552 return get_recursion_context(swhash->recursion);
5554 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
5556 inline void perf_swevent_put_recursion_context(int rctx)
5558 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5560 put_recursion_context(swhash->recursion, rctx);
5563 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
5565 struct perf_sample_data data;
5566 int rctx;
5568 preempt_disable_notrace();
5569 rctx = perf_swevent_get_recursion_context();
5570 if (rctx < 0)
5571 return;
5573 perf_sample_data_init(&data, addr, 0);
5575 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
5577 perf_swevent_put_recursion_context(rctx);
5578 preempt_enable_notrace();
5581 static void perf_swevent_read(struct perf_event *event)
5585 static int perf_swevent_add(struct perf_event *event, int flags)
5587 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5588 struct hw_perf_event *hwc = &event->hw;
5589 struct hlist_head *head;
5591 if (is_sampling_event(event)) {
5592 hwc->last_period = hwc->sample_period;
5593 perf_swevent_set_period(event);
5596 hwc->state = !(flags & PERF_EF_START);
5598 head = find_swevent_head(swhash, event);
5599 if (!head) {
5601 * We can race with cpu hotplug code. Do not
5602 * WARN if the cpu just got unplugged.
5604 WARN_ON_ONCE(swhash->online);
5605 return -EINVAL;
5608 hlist_add_head_rcu(&event->hlist_entry, head);
5610 return 0;
5613 static void perf_swevent_del(struct perf_event *event, int flags)
5615 hlist_del_rcu(&event->hlist_entry);
5618 static void perf_swevent_start(struct perf_event *event, int flags)
5620 event->hw.state = 0;
5623 static void perf_swevent_stop(struct perf_event *event, int flags)
5625 event->hw.state = PERF_HES_STOPPED;
5628 /* Deref the hlist from the update side */
5629 static inline struct swevent_hlist *
5630 swevent_hlist_deref(struct swevent_htable *swhash)
5632 return rcu_dereference_protected(swhash->swevent_hlist,
5633 lockdep_is_held(&swhash->hlist_mutex));
5636 static void swevent_hlist_release(struct swevent_htable *swhash)
5638 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
5640 if (!hlist)
5641 return;
5643 rcu_assign_pointer(swhash->swevent_hlist, NULL);
5644 kfree_rcu(hlist, rcu_head);
5647 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
5649 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5651 mutex_lock(&swhash->hlist_mutex);
5653 if (!--swhash->hlist_refcount)
5654 swevent_hlist_release(swhash);
5656 mutex_unlock(&swhash->hlist_mutex);
5659 static void swevent_hlist_put(struct perf_event *event)
5661 int cpu;
5663 if (event->cpu != -1) {
5664 swevent_hlist_put_cpu(event, event->cpu);
5665 return;
5668 for_each_possible_cpu(cpu)
5669 swevent_hlist_put_cpu(event, cpu);
5672 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
5674 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5675 int err = 0;
5677 mutex_lock(&swhash->hlist_mutex);
5679 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
5680 struct swevent_hlist *hlist;
5682 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
5683 if (!hlist) {
5684 err = -ENOMEM;
5685 goto exit;
5687 rcu_assign_pointer(swhash->swevent_hlist, hlist);
5689 swhash->hlist_refcount++;
5690 exit:
5691 mutex_unlock(&swhash->hlist_mutex);
5693 return err;
5696 static int swevent_hlist_get(struct perf_event *event)
5698 int err;
5699 int cpu, failed_cpu;
5701 if (event->cpu != -1)
5702 return swevent_hlist_get_cpu(event, event->cpu);
5704 get_online_cpus();
5705 for_each_possible_cpu(cpu) {
5706 err = swevent_hlist_get_cpu(event, cpu);
5707 if (err) {
5708 failed_cpu = cpu;
5709 goto fail;
5712 put_online_cpus();
5714 return 0;
5715 fail:
5716 for_each_possible_cpu(cpu) {
5717 if (cpu == failed_cpu)
5718 break;
5719 swevent_hlist_put_cpu(event, cpu);
5722 put_online_cpus();
5723 return err;
5726 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
5728 static void sw_perf_event_destroy(struct perf_event *event)
5730 u64 event_id = event->attr.config;
5732 WARN_ON(event->parent);
5734 static_key_slow_dec(&perf_swevent_enabled[event_id]);
5735 swevent_hlist_put(event);
5738 static int perf_swevent_init(struct perf_event *event)
5740 u64 event_id = event->attr.config;
5742 if (event->attr.type != PERF_TYPE_SOFTWARE)
5743 return -ENOENT;
5746 * no branch sampling for software events
5748 if (has_branch_stack(event))
5749 return -EOPNOTSUPP;
5751 switch (event_id) {
5752 case PERF_COUNT_SW_CPU_CLOCK:
5753 case PERF_COUNT_SW_TASK_CLOCK:
5754 return -ENOENT;
5756 default:
5757 break;
5760 if (event_id >= PERF_COUNT_SW_MAX)
5761 return -ENOENT;
5763 if (!event->parent) {
5764 int err;
5766 err = swevent_hlist_get(event);
5767 if (err)
5768 return err;
5770 static_key_slow_inc(&perf_swevent_enabled[event_id]);
5771 event->destroy = sw_perf_event_destroy;
5774 return 0;
5777 static int perf_swevent_event_idx(struct perf_event *event)
5779 return 0;
5782 static struct pmu perf_swevent = {
5783 .task_ctx_nr = perf_sw_context,
5785 .event_init = perf_swevent_init,
5786 .add = perf_swevent_add,
5787 .del = perf_swevent_del,
5788 .start = perf_swevent_start,
5789 .stop = perf_swevent_stop,
5790 .read = perf_swevent_read,
5792 .event_idx = perf_swevent_event_idx,
5795 #ifdef CONFIG_EVENT_TRACING
5797 static int perf_tp_filter_match(struct perf_event *event,
5798 struct perf_sample_data *data)
5800 void *record = data->raw->data;
5802 if (likely(!event->filter) || filter_match_preds(event->filter, record))
5803 return 1;
5804 return 0;
5807 static int perf_tp_event_match(struct perf_event *event,
5808 struct perf_sample_data *data,
5809 struct pt_regs *regs)
5811 if (event->hw.state & PERF_HES_STOPPED)
5812 return 0;
5814 * All tracepoints are from kernel-space.
5816 if (event->attr.exclude_kernel)
5817 return 0;
5819 if (!perf_tp_filter_match(event, data))
5820 return 0;
5822 return 1;
5825 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
5826 struct pt_regs *regs, struct hlist_head *head, int rctx,
5827 struct task_struct *task)
5829 struct perf_sample_data data;
5830 struct perf_event *event;
5832 struct perf_raw_record raw = {
5833 .size = entry_size,
5834 .data = record,
5837 perf_sample_data_init(&data, addr, 0);
5838 data.raw = &raw;
5840 hlist_for_each_entry_rcu(event, head, hlist_entry) {
5841 if (perf_tp_event_match(event, &data, regs))
5842 perf_swevent_event(event, count, &data, regs);
5846 * If we got specified a target task, also iterate its context and
5847 * deliver this event there too.
5849 if (task && task != current) {
5850 struct perf_event_context *ctx;
5851 struct trace_entry *entry = record;
5853 rcu_read_lock();
5854 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
5855 if (!ctx)
5856 goto unlock;
5858 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5859 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5860 continue;
5861 if (event->attr.config != entry->type)
5862 continue;
5863 if (perf_tp_event_match(event, &data, regs))
5864 perf_swevent_event(event, count, &data, regs);
5866 unlock:
5867 rcu_read_unlock();
5870 perf_swevent_put_recursion_context(rctx);
5872 EXPORT_SYMBOL_GPL(perf_tp_event);
5874 static void tp_perf_event_destroy(struct perf_event *event)
5876 perf_trace_destroy(event);
5879 static int perf_tp_event_init(struct perf_event *event)
5881 int err;
5883 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5884 return -ENOENT;
5887 * no branch sampling for tracepoint events
5889 if (has_branch_stack(event))
5890 return -EOPNOTSUPP;
5892 err = perf_trace_init(event);
5893 if (err)
5894 return err;
5896 event->destroy = tp_perf_event_destroy;
5898 return 0;
5901 static struct pmu perf_tracepoint = {
5902 .task_ctx_nr = perf_sw_context,
5904 .event_init = perf_tp_event_init,
5905 .add = perf_trace_add,
5906 .del = perf_trace_del,
5907 .start = perf_swevent_start,
5908 .stop = perf_swevent_stop,
5909 .read = perf_swevent_read,
5911 .event_idx = perf_swevent_event_idx,
5914 static inline void perf_tp_register(void)
5916 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
5919 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
5921 char *filter_str;
5922 int ret;
5924 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5925 return -EINVAL;
5927 filter_str = strndup_user(arg, PAGE_SIZE);
5928 if (IS_ERR(filter_str))
5929 return PTR_ERR(filter_str);
5931 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
5933 kfree(filter_str);
5934 return ret;
5937 static void perf_event_free_filter(struct perf_event *event)
5939 ftrace_profile_free_filter(event);
5942 #else
5944 static inline void perf_tp_register(void)
5948 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
5950 return -ENOENT;
5953 static void perf_event_free_filter(struct perf_event *event)
5957 #endif /* CONFIG_EVENT_TRACING */
5959 #ifdef CONFIG_HAVE_HW_BREAKPOINT
5960 void perf_bp_event(struct perf_event *bp, void *data)
5962 struct perf_sample_data sample;
5963 struct pt_regs *regs = data;
5965 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
5967 if (!bp->hw.state && !perf_exclude_event(bp, regs))
5968 perf_swevent_event(bp, 1, &sample, regs);
5970 #endif
5973 * hrtimer based swevent callback
5976 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
5978 enum hrtimer_restart ret = HRTIMER_RESTART;
5979 struct perf_sample_data data;
5980 struct pt_regs *regs;
5981 struct perf_event *event;
5982 u64 period;
5984 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
5986 if (event->state != PERF_EVENT_STATE_ACTIVE)
5987 return HRTIMER_NORESTART;
5989 event->pmu->read(event);
5991 perf_sample_data_init(&data, 0, event->hw.last_period);
5992 regs = get_irq_regs();
5994 if (regs && !perf_exclude_event(event, regs)) {
5995 if (!(event->attr.exclude_idle && is_idle_task(current)))
5996 if (__perf_event_overflow(event, 1, &data, regs))
5997 ret = HRTIMER_NORESTART;
6000 period = max_t(u64, 10000, event->hw.sample_period);
6001 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
6003 return ret;
6006 static void perf_swevent_start_hrtimer(struct perf_event *event)
6008 struct hw_perf_event *hwc = &event->hw;
6009 s64 period;
6011 if (!is_sampling_event(event))
6012 return;
6014 period = local64_read(&hwc->period_left);
6015 if (period) {
6016 if (period < 0)
6017 period = 10000;
6019 local64_set(&hwc->period_left, 0);
6020 } else {
6021 period = max_t(u64, 10000, hwc->sample_period);
6023 __hrtimer_start_range_ns(&hwc->hrtimer,
6024 ns_to_ktime(period), 0,
6025 HRTIMER_MODE_REL_PINNED, 0);
6028 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
6030 struct hw_perf_event *hwc = &event->hw;
6032 if (is_sampling_event(event)) {
6033 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
6034 local64_set(&hwc->period_left, ktime_to_ns(remaining));
6036 hrtimer_cancel(&hwc->hrtimer);
6040 static void perf_swevent_init_hrtimer(struct perf_event *event)
6042 struct hw_perf_event *hwc = &event->hw;
6044 if (!is_sampling_event(event))
6045 return;
6047 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6048 hwc->hrtimer.function = perf_swevent_hrtimer;
6051 * Since hrtimers have a fixed rate, we can do a static freq->period
6052 * mapping and avoid the whole period adjust feedback stuff.
6054 if (event->attr.freq) {
6055 long freq = event->attr.sample_freq;
6057 event->attr.sample_period = NSEC_PER_SEC / freq;
6058 hwc->sample_period = event->attr.sample_period;
6059 local64_set(&hwc->period_left, hwc->sample_period);
6060 hwc->last_period = hwc->sample_period;
6061 event->attr.freq = 0;
6066 * Software event: cpu wall time clock
6069 static void cpu_clock_event_update(struct perf_event *event)
6071 s64 prev;
6072 u64 now;
6074 now = local_clock();
6075 prev = local64_xchg(&event->hw.prev_count, now);
6076 local64_add(now - prev, &event->count);
6079 static void cpu_clock_event_start(struct perf_event *event, int flags)
6081 local64_set(&event->hw.prev_count, local_clock());
6082 perf_swevent_start_hrtimer(event);
6085 static void cpu_clock_event_stop(struct perf_event *event, int flags)
6087 perf_swevent_cancel_hrtimer(event);
6088 cpu_clock_event_update(event);
6091 static int cpu_clock_event_add(struct perf_event *event, int flags)
6093 if (flags & PERF_EF_START)
6094 cpu_clock_event_start(event, flags);
6096 return 0;
6099 static void cpu_clock_event_del(struct perf_event *event, int flags)
6101 cpu_clock_event_stop(event, flags);
6104 static void cpu_clock_event_read(struct perf_event *event)
6106 cpu_clock_event_update(event);
6109 static int cpu_clock_event_init(struct perf_event *event)
6111 if (event->attr.type != PERF_TYPE_SOFTWARE)
6112 return -ENOENT;
6114 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
6115 return -ENOENT;
6118 * no branch sampling for software events
6120 if (has_branch_stack(event))
6121 return -EOPNOTSUPP;
6123 perf_swevent_init_hrtimer(event);
6125 return 0;
6128 static struct pmu perf_cpu_clock = {
6129 .task_ctx_nr = perf_sw_context,
6131 .event_init = cpu_clock_event_init,
6132 .add = cpu_clock_event_add,
6133 .del = cpu_clock_event_del,
6134 .start = cpu_clock_event_start,
6135 .stop = cpu_clock_event_stop,
6136 .read = cpu_clock_event_read,
6138 .event_idx = perf_swevent_event_idx,
6142 * Software event: task time clock
6145 static void task_clock_event_update(struct perf_event *event, u64 now)
6147 u64 prev;
6148 s64 delta;
6150 prev = local64_xchg(&event->hw.prev_count, now);
6151 delta = now - prev;
6152 local64_add(delta, &event->count);
6155 static void task_clock_event_start(struct perf_event *event, int flags)
6157 local64_set(&event->hw.prev_count, event->ctx->time);
6158 perf_swevent_start_hrtimer(event);
6161 static void task_clock_event_stop(struct perf_event *event, int flags)
6163 perf_swevent_cancel_hrtimer(event);
6164 task_clock_event_update(event, event->ctx->time);
6167 static int task_clock_event_add(struct perf_event *event, int flags)
6169 if (flags & PERF_EF_START)
6170 task_clock_event_start(event, flags);
6172 return 0;
6175 static void task_clock_event_del(struct perf_event *event, int flags)
6177 task_clock_event_stop(event, PERF_EF_UPDATE);
6180 static void task_clock_event_read(struct perf_event *event)
6182 u64 now = perf_clock();
6183 u64 delta = now - event->ctx->timestamp;
6184 u64 time = event->ctx->time + delta;
6186 task_clock_event_update(event, time);
6189 static int task_clock_event_init(struct perf_event *event)
6191 if (event->attr.type != PERF_TYPE_SOFTWARE)
6192 return -ENOENT;
6194 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
6195 return -ENOENT;
6198 * no branch sampling for software events
6200 if (has_branch_stack(event))
6201 return -EOPNOTSUPP;
6203 perf_swevent_init_hrtimer(event);
6205 return 0;
6208 static struct pmu perf_task_clock = {
6209 .task_ctx_nr = perf_sw_context,
6211 .event_init = task_clock_event_init,
6212 .add = task_clock_event_add,
6213 .del = task_clock_event_del,
6214 .start = task_clock_event_start,
6215 .stop = task_clock_event_stop,
6216 .read = task_clock_event_read,
6218 .event_idx = perf_swevent_event_idx,
6221 static void perf_pmu_nop_void(struct pmu *pmu)
6225 static int perf_pmu_nop_int(struct pmu *pmu)
6227 return 0;
6230 static void perf_pmu_start_txn(struct pmu *pmu)
6232 perf_pmu_disable(pmu);
6235 static int perf_pmu_commit_txn(struct pmu *pmu)
6237 perf_pmu_enable(pmu);
6238 return 0;
6241 static void perf_pmu_cancel_txn(struct pmu *pmu)
6243 perf_pmu_enable(pmu);
6246 static int perf_event_idx_default(struct perf_event *event)
6248 return event->hw.idx + 1;
6252 * Ensures all contexts with the same task_ctx_nr have the same
6253 * pmu_cpu_context too.
6255 static void *find_pmu_context(int ctxn)
6257 struct pmu *pmu;
6259 if (ctxn < 0)
6260 return NULL;
6262 list_for_each_entry(pmu, &pmus, entry) {
6263 if (pmu->task_ctx_nr == ctxn)
6264 return pmu->pmu_cpu_context;
6267 return NULL;
6270 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
6272 int cpu;
6274 for_each_possible_cpu(cpu) {
6275 struct perf_cpu_context *cpuctx;
6277 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6279 if (cpuctx->unique_pmu == old_pmu)
6280 cpuctx->unique_pmu = pmu;
6284 static void free_pmu_context(struct pmu *pmu)
6286 struct pmu *i;
6288 mutex_lock(&pmus_lock);
6290 * Like a real lame refcount.
6292 list_for_each_entry(i, &pmus, entry) {
6293 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
6294 update_pmu_context(i, pmu);
6295 goto out;
6299 free_percpu(pmu->pmu_cpu_context);
6300 out:
6301 mutex_unlock(&pmus_lock);
6303 static struct idr pmu_idr;
6305 static ssize_t
6306 type_show(struct device *dev, struct device_attribute *attr, char *page)
6308 struct pmu *pmu = dev_get_drvdata(dev);
6310 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
6313 static ssize_t
6314 perf_event_mux_interval_ms_show(struct device *dev,
6315 struct device_attribute *attr,
6316 char *page)
6318 struct pmu *pmu = dev_get_drvdata(dev);
6320 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
6323 static ssize_t
6324 perf_event_mux_interval_ms_store(struct device *dev,
6325 struct device_attribute *attr,
6326 const char *buf, size_t count)
6328 struct pmu *pmu = dev_get_drvdata(dev);
6329 int timer, cpu, ret;
6331 ret = kstrtoint(buf, 0, &timer);
6332 if (ret)
6333 return ret;
6335 if (timer < 1)
6336 return -EINVAL;
6338 /* same value, noting to do */
6339 if (timer == pmu->hrtimer_interval_ms)
6340 return count;
6342 pmu->hrtimer_interval_ms = timer;
6344 /* update all cpuctx for this PMU */
6345 for_each_possible_cpu(cpu) {
6346 struct perf_cpu_context *cpuctx;
6347 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6348 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
6350 if (hrtimer_active(&cpuctx->hrtimer))
6351 hrtimer_forward_now(&cpuctx->hrtimer, cpuctx->hrtimer_interval);
6354 return count;
6357 static struct device_attribute pmu_dev_attrs[] = {
6358 __ATTR_RO(type),
6359 __ATTR_RW(perf_event_mux_interval_ms),
6360 __ATTR_NULL,
6363 static int pmu_bus_running;
6364 static struct bus_type pmu_bus = {
6365 .name = "event_source",
6366 .dev_attrs = pmu_dev_attrs,
6369 static void pmu_dev_release(struct device *dev)
6371 kfree(dev);
6374 static int pmu_dev_alloc(struct pmu *pmu)
6376 int ret = -ENOMEM;
6378 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
6379 if (!pmu->dev)
6380 goto out;
6382 pmu->dev->groups = pmu->attr_groups;
6383 device_initialize(pmu->dev);
6384 ret = dev_set_name(pmu->dev, "%s", pmu->name);
6385 if (ret)
6386 goto free_dev;
6388 dev_set_drvdata(pmu->dev, pmu);
6389 pmu->dev->bus = &pmu_bus;
6390 pmu->dev->release = pmu_dev_release;
6391 ret = device_add(pmu->dev);
6392 if (ret)
6393 goto free_dev;
6395 out:
6396 return ret;
6398 free_dev:
6399 put_device(pmu->dev);
6400 goto out;
6403 static struct lock_class_key cpuctx_mutex;
6404 static struct lock_class_key cpuctx_lock;
6406 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
6408 int cpu, ret;
6410 mutex_lock(&pmus_lock);
6411 ret = -ENOMEM;
6412 pmu->pmu_disable_count = alloc_percpu(int);
6413 if (!pmu->pmu_disable_count)
6414 goto unlock;
6416 pmu->type = -1;
6417 if (!name)
6418 goto skip_type;
6419 pmu->name = name;
6421 if (type < 0) {
6422 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
6423 if (type < 0) {
6424 ret = type;
6425 goto free_pdc;
6428 pmu->type = type;
6430 if (pmu_bus_running) {
6431 ret = pmu_dev_alloc(pmu);
6432 if (ret)
6433 goto free_idr;
6436 skip_type:
6437 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
6438 if (pmu->pmu_cpu_context)
6439 goto got_cpu_context;
6441 ret = -ENOMEM;
6442 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
6443 if (!pmu->pmu_cpu_context)
6444 goto free_dev;
6446 for_each_possible_cpu(cpu) {
6447 struct perf_cpu_context *cpuctx;
6449 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6450 __perf_event_init_context(&cpuctx->ctx);
6451 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
6452 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
6453 cpuctx->ctx.type = cpu_context;
6454 cpuctx->ctx.pmu = pmu;
6456 __perf_cpu_hrtimer_init(cpuctx, cpu);
6458 INIT_LIST_HEAD(&cpuctx->rotation_list);
6459 cpuctx->unique_pmu = pmu;
6462 got_cpu_context:
6463 if (!pmu->start_txn) {
6464 if (pmu->pmu_enable) {
6466 * If we have pmu_enable/pmu_disable calls, install
6467 * transaction stubs that use that to try and batch
6468 * hardware accesses.
6470 pmu->start_txn = perf_pmu_start_txn;
6471 pmu->commit_txn = perf_pmu_commit_txn;
6472 pmu->cancel_txn = perf_pmu_cancel_txn;
6473 } else {
6474 pmu->start_txn = perf_pmu_nop_void;
6475 pmu->commit_txn = perf_pmu_nop_int;
6476 pmu->cancel_txn = perf_pmu_nop_void;
6480 if (!pmu->pmu_enable) {
6481 pmu->pmu_enable = perf_pmu_nop_void;
6482 pmu->pmu_disable = perf_pmu_nop_void;
6485 if (!pmu->event_idx)
6486 pmu->event_idx = perf_event_idx_default;
6488 list_add_rcu(&pmu->entry, &pmus);
6489 ret = 0;
6490 unlock:
6491 mutex_unlock(&pmus_lock);
6493 return ret;
6495 free_dev:
6496 device_del(pmu->dev);
6497 put_device(pmu->dev);
6499 free_idr:
6500 if (pmu->type >= PERF_TYPE_MAX)
6501 idr_remove(&pmu_idr, pmu->type);
6503 free_pdc:
6504 free_percpu(pmu->pmu_disable_count);
6505 goto unlock;
6508 void perf_pmu_unregister(struct pmu *pmu)
6510 mutex_lock(&pmus_lock);
6511 list_del_rcu(&pmu->entry);
6512 mutex_unlock(&pmus_lock);
6515 * We dereference the pmu list under both SRCU and regular RCU, so
6516 * synchronize against both of those.
6518 synchronize_srcu(&pmus_srcu);
6519 synchronize_rcu();
6521 free_percpu(pmu->pmu_disable_count);
6522 if (pmu->type >= PERF_TYPE_MAX)
6523 idr_remove(&pmu_idr, pmu->type);
6524 device_del(pmu->dev);
6525 put_device(pmu->dev);
6526 free_pmu_context(pmu);
6529 struct pmu *perf_init_event(struct perf_event *event)
6531 struct pmu *pmu = NULL;
6532 int idx;
6533 int ret;
6535 idx = srcu_read_lock(&pmus_srcu);
6537 rcu_read_lock();
6538 pmu = idr_find(&pmu_idr, event->attr.type);
6539 rcu_read_unlock();
6540 if (pmu) {
6541 event->pmu = pmu;
6542 ret = pmu->event_init(event);
6543 if (ret)
6544 pmu = ERR_PTR(ret);
6545 goto unlock;
6548 list_for_each_entry_rcu(pmu, &pmus, entry) {
6549 event->pmu = pmu;
6550 ret = pmu->event_init(event);
6551 if (!ret)
6552 goto unlock;
6554 if (ret != -ENOENT) {
6555 pmu = ERR_PTR(ret);
6556 goto unlock;
6559 pmu = ERR_PTR(-ENOENT);
6560 unlock:
6561 srcu_read_unlock(&pmus_srcu, idx);
6563 return pmu;
6566 static void account_event_cpu(struct perf_event *event, int cpu)
6568 if (event->parent)
6569 return;
6571 if (has_branch_stack(event)) {
6572 if (!(event->attach_state & PERF_ATTACH_TASK))
6573 atomic_inc(&per_cpu(perf_branch_stack_events, cpu));
6575 if (is_cgroup_event(event))
6576 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
6579 static void account_event(struct perf_event *event)
6581 if (event->parent)
6582 return;
6584 if (event->attach_state & PERF_ATTACH_TASK)
6585 static_key_slow_inc(&perf_sched_events.key);
6586 if (event->attr.mmap || event->attr.mmap_data)
6587 atomic_inc(&nr_mmap_events);
6588 if (event->attr.comm)
6589 atomic_inc(&nr_comm_events);
6590 if (event->attr.task)
6591 atomic_inc(&nr_task_events);
6592 if (event->attr.freq) {
6593 if (atomic_inc_return(&nr_freq_events) == 1)
6594 tick_nohz_full_kick_all();
6596 if (has_branch_stack(event))
6597 static_key_slow_inc(&perf_sched_events.key);
6598 if (is_cgroup_event(event))
6599 static_key_slow_inc(&perf_sched_events.key);
6601 account_event_cpu(event, event->cpu);
6605 * Allocate and initialize a event structure
6607 static struct perf_event *
6608 perf_event_alloc(struct perf_event_attr *attr, int cpu,
6609 struct task_struct *task,
6610 struct perf_event *group_leader,
6611 struct perf_event *parent_event,
6612 perf_overflow_handler_t overflow_handler,
6613 void *context)
6615 struct pmu *pmu;
6616 struct perf_event *event;
6617 struct hw_perf_event *hwc;
6618 long err = -EINVAL;
6620 if ((unsigned)cpu >= nr_cpu_ids) {
6621 if (!task || cpu != -1)
6622 return ERR_PTR(-EINVAL);
6625 event = kzalloc(sizeof(*event), GFP_KERNEL);
6626 if (!event)
6627 return ERR_PTR(-ENOMEM);
6630 * Single events are their own group leaders, with an
6631 * empty sibling list:
6633 if (!group_leader)
6634 group_leader = event;
6636 mutex_init(&event->child_mutex);
6637 INIT_LIST_HEAD(&event->child_list);
6639 INIT_LIST_HEAD(&event->group_entry);
6640 INIT_LIST_HEAD(&event->event_entry);
6641 INIT_LIST_HEAD(&event->sibling_list);
6642 INIT_LIST_HEAD(&event->rb_entry);
6644 init_waitqueue_head(&event->waitq);
6645 init_irq_work(&event->pending, perf_pending_event);
6647 mutex_init(&event->mmap_mutex);
6649 atomic_long_set(&event->refcount, 1);
6650 event->cpu = cpu;
6651 event->attr = *attr;
6652 event->group_leader = group_leader;
6653 event->pmu = NULL;
6654 event->oncpu = -1;
6656 event->parent = parent_event;
6658 event->ns = get_pid_ns(task_active_pid_ns(current));
6659 event->id = atomic64_inc_return(&perf_event_id);
6661 event->state = PERF_EVENT_STATE_INACTIVE;
6663 if (task) {
6664 event->attach_state = PERF_ATTACH_TASK;
6666 if (attr->type == PERF_TYPE_TRACEPOINT)
6667 event->hw.tp_target = task;
6668 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6670 * hw_breakpoint is a bit difficult here..
6672 else if (attr->type == PERF_TYPE_BREAKPOINT)
6673 event->hw.bp_target = task;
6674 #endif
6677 if (!overflow_handler && parent_event) {
6678 overflow_handler = parent_event->overflow_handler;
6679 context = parent_event->overflow_handler_context;
6682 event->overflow_handler = overflow_handler;
6683 event->overflow_handler_context = context;
6685 perf_event__state_init(event);
6687 pmu = NULL;
6689 hwc = &event->hw;
6690 hwc->sample_period = attr->sample_period;
6691 if (attr->freq && attr->sample_freq)
6692 hwc->sample_period = 1;
6693 hwc->last_period = hwc->sample_period;
6695 local64_set(&hwc->period_left, hwc->sample_period);
6698 * we currently do not support PERF_FORMAT_GROUP on inherited events
6700 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
6701 goto err_ns;
6703 pmu = perf_init_event(event);
6704 if (!pmu)
6705 goto err_ns;
6706 else if (IS_ERR(pmu)) {
6707 err = PTR_ERR(pmu);
6708 goto err_ns;
6711 if (!event->parent) {
6712 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
6713 err = get_callchain_buffers();
6714 if (err)
6715 goto err_pmu;
6719 return event;
6721 err_pmu:
6722 if (event->destroy)
6723 event->destroy(event);
6724 err_ns:
6725 if (event->ns)
6726 put_pid_ns(event->ns);
6727 kfree(event);
6729 return ERR_PTR(err);
6732 static int perf_copy_attr(struct perf_event_attr __user *uattr,
6733 struct perf_event_attr *attr)
6735 u32 size;
6736 int ret;
6738 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
6739 return -EFAULT;
6742 * zero the full structure, so that a short copy will be nice.
6744 memset(attr, 0, sizeof(*attr));
6746 ret = get_user(size, &uattr->size);
6747 if (ret)
6748 return ret;
6750 if (size > PAGE_SIZE) /* silly large */
6751 goto err_size;
6753 if (!size) /* abi compat */
6754 size = PERF_ATTR_SIZE_VER0;
6756 if (size < PERF_ATTR_SIZE_VER0)
6757 goto err_size;
6760 * If we're handed a bigger struct than we know of,
6761 * ensure all the unknown bits are 0 - i.e. new
6762 * user-space does not rely on any kernel feature
6763 * extensions we dont know about yet.
6765 if (size > sizeof(*attr)) {
6766 unsigned char __user *addr;
6767 unsigned char __user *end;
6768 unsigned char val;
6770 addr = (void __user *)uattr + sizeof(*attr);
6771 end = (void __user *)uattr + size;
6773 for (; addr < end; addr++) {
6774 ret = get_user(val, addr);
6775 if (ret)
6776 return ret;
6777 if (val)
6778 goto err_size;
6780 size = sizeof(*attr);
6783 ret = copy_from_user(attr, uattr, size);
6784 if (ret)
6785 return -EFAULT;
6787 /* disabled for now */
6788 if (attr->mmap2)
6789 return -EINVAL;
6791 if (attr->__reserved_1)
6792 return -EINVAL;
6794 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
6795 return -EINVAL;
6797 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
6798 return -EINVAL;
6800 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
6801 u64 mask = attr->branch_sample_type;
6803 /* only using defined bits */
6804 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
6805 return -EINVAL;
6807 /* at least one branch bit must be set */
6808 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
6809 return -EINVAL;
6811 /* propagate priv level, when not set for branch */
6812 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
6814 /* exclude_kernel checked on syscall entry */
6815 if (!attr->exclude_kernel)
6816 mask |= PERF_SAMPLE_BRANCH_KERNEL;
6818 if (!attr->exclude_user)
6819 mask |= PERF_SAMPLE_BRANCH_USER;
6821 if (!attr->exclude_hv)
6822 mask |= PERF_SAMPLE_BRANCH_HV;
6824 * adjust user setting (for HW filter setup)
6826 attr->branch_sample_type = mask;
6828 /* privileged levels capture (kernel, hv): check permissions */
6829 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
6830 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
6831 return -EACCES;
6834 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
6835 ret = perf_reg_validate(attr->sample_regs_user);
6836 if (ret)
6837 return ret;
6840 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
6841 if (!arch_perf_have_user_stack_dump())
6842 return -ENOSYS;
6845 * We have __u32 type for the size, but so far
6846 * we can only use __u16 as maximum due to the
6847 * __u16 sample size limit.
6849 if (attr->sample_stack_user >= USHRT_MAX)
6850 ret = -EINVAL;
6851 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
6852 ret = -EINVAL;
6855 out:
6856 return ret;
6858 err_size:
6859 put_user(sizeof(*attr), &uattr->size);
6860 ret = -E2BIG;
6861 goto out;
6864 static int
6865 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
6867 struct ring_buffer *rb = NULL, *old_rb = NULL;
6868 int ret = -EINVAL;
6870 if (!output_event)
6871 goto set;
6873 /* don't allow circular references */
6874 if (event == output_event)
6875 goto out;
6878 * Don't allow cross-cpu buffers
6880 if (output_event->cpu != event->cpu)
6881 goto out;
6884 * If its not a per-cpu rb, it must be the same task.
6886 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
6887 goto out;
6889 set:
6890 mutex_lock(&event->mmap_mutex);
6891 /* Can't redirect output if we've got an active mmap() */
6892 if (atomic_read(&event->mmap_count))
6893 goto unlock;
6895 old_rb = event->rb;
6897 if (output_event) {
6898 /* get the rb we want to redirect to */
6899 rb = ring_buffer_get(output_event);
6900 if (!rb)
6901 goto unlock;
6904 if (old_rb)
6905 ring_buffer_detach(event, old_rb);
6907 if (rb)
6908 ring_buffer_attach(event, rb);
6910 rcu_assign_pointer(event->rb, rb);
6912 if (old_rb) {
6913 ring_buffer_put(old_rb);
6915 * Since we detached before setting the new rb, so that we
6916 * could attach the new rb, we could have missed a wakeup.
6917 * Provide it now.
6919 wake_up_all(&event->waitq);
6922 ret = 0;
6923 unlock:
6924 mutex_unlock(&event->mmap_mutex);
6926 out:
6927 return ret;
6931 * sys_perf_event_open - open a performance event, associate it to a task/cpu
6933 * @attr_uptr: event_id type attributes for monitoring/sampling
6934 * @pid: target pid
6935 * @cpu: target cpu
6936 * @group_fd: group leader event fd
6938 SYSCALL_DEFINE5(perf_event_open,
6939 struct perf_event_attr __user *, attr_uptr,
6940 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
6942 struct perf_event *group_leader = NULL, *output_event = NULL;
6943 struct perf_event *event, *sibling;
6944 struct perf_event_attr attr;
6945 struct perf_event_context *ctx;
6946 struct file *event_file = NULL;
6947 struct fd group = {NULL, 0};
6948 struct task_struct *task = NULL;
6949 struct pmu *pmu;
6950 int event_fd;
6951 int move_group = 0;
6952 int err;
6954 /* for future expandability... */
6955 if (flags & ~PERF_FLAG_ALL)
6956 return -EINVAL;
6958 err = perf_copy_attr(attr_uptr, &attr);
6959 if (err)
6960 return err;
6962 if (!attr.exclude_kernel) {
6963 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
6964 return -EACCES;
6967 if (attr.freq) {
6968 if (attr.sample_freq > sysctl_perf_event_sample_rate)
6969 return -EINVAL;
6970 } else {
6971 if (attr.sample_period & (1ULL << 63))
6972 return -EINVAL;
6976 * In cgroup mode, the pid argument is used to pass the fd
6977 * opened to the cgroup directory in cgroupfs. The cpu argument
6978 * designates the cpu on which to monitor threads from that
6979 * cgroup.
6981 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
6982 return -EINVAL;
6984 event_fd = get_unused_fd();
6985 if (event_fd < 0)
6986 return event_fd;
6988 if (group_fd != -1) {
6989 err = perf_fget_light(group_fd, &group);
6990 if (err)
6991 goto err_fd;
6992 group_leader = group.file->private_data;
6993 if (flags & PERF_FLAG_FD_OUTPUT)
6994 output_event = group_leader;
6995 if (flags & PERF_FLAG_FD_NO_GROUP)
6996 group_leader = NULL;
6999 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
7000 task = find_lively_task_by_vpid(pid);
7001 if (IS_ERR(task)) {
7002 err = PTR_ERR(task);
7003 goto err_group_fd;
7007 get_online_cpus();
7009 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
7010 NULL, NULL);
7011 if (IS_ERR(event)) {
7012 err = PTR_ERR(event);
7013 goto err_task;
7016 if (flags & PERF_FLAG_PID_CGROUP) {
7017 err = perf_cgroup_connect(pid, event, &attr, group_leader);
7018 if (err) {
7019 __free_event(event);
7020 goto err_task;
7024 account_event(event);
7027 * Special case software events and allow them to be part of
7028 * any hardware group.
7030 pmu = event->pmu;
7032 if (group_leader &&
7033 (is_software_event(event) != is_software_event(group_leader))) {
7034 if (is_software_event(event)) {
7036 * If event and group_leader are not both a software
7037 * event, and event is, then group leader is not.
7039 * Allow the addition of software events to !software
7040 * groups, this is safe because software events never
7041 * fail to schedule.
7043 pmu = group_leader->pmu;
7044 } else if (is_software_event(group_leader) &&
7045 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
7047 * In case the group is a pure software group, and we
7048 * try to add a hardware event, move the whole group to
7049 * the hardware context.
7051 move_group = 1;
7056 * Get the target context (task or percpu):
7058 ctx = find_get_context(pmu, task, event->cpu);
7059 if (IS_ERR(ctx)) {
7060 err = PTR_ERR(ctx);
7061 goto err_alloc;
7064 if (task) {
7065 put_task_struct(task);
7066 task = NULL;
7070 * Look up the group leader (we will attach this event to it):
7072 if (group_leader) {
7073 err = -EINVAL;
7076 * Do not allow a recursive hierarchy (this new sibling
7077 * becoming part of another group-sibling):
7079 if (group_leader->group_leader != group_leader)
7080 goto err_context;
7082 * Do not allow to attach to a group in a different
7083 * task or CPU context:
7085 if (move_group) {
7086 if (group_leader->ctx->type != ctx->type)
7087 goto err_context;
7088 } else {
7089 if (group_leader->ctx != ctx)
7090 goto err_context;
7094 * Only a group leader can be exclusive or pinned
7096 if (attr.exclusive || attr.pinned)
7097 goto err_context;
7100 if (output_event) {
7101 err = perf_event_set_output(event, output_event);
7102 if (err)
7103 goto err_context;
7106 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, O_RDWR);
7107 if (IS_ERR(event_file)) {
7108 err = PTR_ERR(event_file);
7109 goto err_context;
7112 if (move_group) {
7113 struct perf_event_context *gctx = group_leader->ctx;
7115 mutex_lock(&gctx->mutex);
7116 perf_remove_from_context(group_leader, false);
7119 * Removing from the context ends up with disabled
7120 * event. What we want here is event in the initial
7121 * startup state, ready to be add into new context.
7123 perf_event__state_init(group_leader);
7124 list_for_each_entry(sibling, &group_leader->sibling_list,
7125 group_entry) {
7126 perf_remove_from_context(sibling, false);
7127 perf_event__state_init(sibling);
7128 put_ctx(gctx);
7130 mutex_unlock(&gctx->mutex);
7131 put_ctx(gctx);
7134 WARN_ON_ONCE(ctx->parent_ctx);
7135 mutex_lock(&ctx->mutex);
7137 if (move_group) {
7138 synchronize_rcu();
7139 perf_install_in_context(ctx, group_leader, event->cpu);
7140 get_ctx(ctx);
7141 list_for_each_entry(sibling, &group_leader->sibling_list,
7142 group_entry) {
7143 perf_install_in_context(ctx, sibling, event->cpu);
7144 get_ctx(ctx);
7148 perf_install_in_context(ctx, event, event->cpu);
7149 ++ctx->generation;
7150 perf_unpin_context(ctx);
7151 mutex_unlock(&ctx->mutex);
7153 put_online_cpus();
7155 event->owner = current;
7157 mutex_lock(&current->perf_event_mutex);
7158 list_add_tail(&event->owner_entry, &current->perf_event_list);
7159 mutex_unlock(&current->perf_event_mutex);
7162 * Precalculate sample_data sizes
7164 perf_event__header_size(event);
7165 perf_event__id_header_size(event);
7168 * Drop the reference on the group_event after placing the
7169 * new event on the sibling_list. This ensures destruction
7170 * of the group leader will find the pointer to itself in
7171 * perf_group_detach().
7173 fdput(group);
7174 fd_install(event_fd, event_file);
7175 return event_fd;
7177 err_context:
7178 perf_unpin_context(ctx);
7179 put_ctx(ctx);
7180 err_alloc:
7181 free_event(event);
7182 err_task:
7183 put_online_cpus();
7184 if (task)
7185 put_task_struct(task);
7186 err_group_fd:
7187 fdput(group);
7188 err_fd:
7189 put_unused_fd(event_fd);
7190 return err;
7194 * perf_event_create_kernel_counter
7196 * @attr: attributes of the counter to create
7197 * @cpu: cpu in which the counter is bound
7198 * @task: task to profile (NULL for percpu)
7200 struct perf_event *
7201 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
7202 struct task_struct *task,
7203 perf_overflow_handler_t overflow_handler,
7204 void *context)
7206 struct perf_event_context *ctx;
7207 struct perf_event *event;
7208 int err;
7211 * Get the target context (task or percpu):
7214 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
7215 overflow_handler, context);
7216 if (IS_ERR(event)) {
7217 err = PTR_ERR(event);
7218 goto err;
7221 account_event(event);
7223 ctx = find_get_context(event->pmu, task, cpu);
7224 if (IS_ERR(ctx)) {
7225 err = PTR_ERR(ctx);
7226 goto err_free;
7229 WARN_ON_ONCE(ctx->parent_ctx);
7230 mutex_lock(&ctx->mutex);
7231 perf_install_in_context(ctx, event, cpu);
7232 ++ctx->generation;
7233 perf_unpin_context(ctx);
7234 mutex_unlock(&ctx->mutex);
7236 return event;
7238 err_free:
7239 free_event(event);
7240 err:
7241 return ERR_PTR(err);
7243 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
7245 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
7247 struct perf_event_context *src_ctx;
7248 struct perf_event_context *dst_ctx;
7249 struct perf_event *event, *tmp;
7250 LIST_HEAD(events);
7252 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
7253 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
7255 mutex_lock(&src_ctx->mutex);
7256 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
7257 event_entry) {
7258 perf_remove_from_context(event, false);
7259 unaccount_event_cpu(event, src_cpu);
7260 put_ctx(src_ctx);
7261 list_add(&event->migrate_entry, &events);
7263 mutex_unlock(&src_ctx->mutex);
7265 synchronize_rcu();
7267 mutex_lock(&dst_ctx->mutex);
7268 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
7269 list_del(&event->migrate_entry);
7270 if (event->state >= PERF_EVENT_STATE_OFF)
7271 event->state = PERF_EVENT_STATE_INACTIVE;
7272 account_event_cpu(event, dst_cpu);
7273 perf_install_in_context(dst_ctx, event, dst_cpu);
7274 get_ctx(dst_ctx);
7276 mutex_unlock(&dst_ctx->mutex);
7278 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
7280 static void sync_child_event(struct perf_event *child_event,
7281 struct task_struct *child)
7283 struct perf_event *parent_event = child_event->parent;
7284 u64 child_val;
7286 if (child_event->attr.inherit_stat)
7287 perf_event_read_event(child_event, child);
7289 child_val = perf_event_count(child_event);
7292 * Add back the child's count to the parent's count:
7294 atomic64_add(child_val, &parent_event->child_count);
7295 atomic64_add(child_event->total_time_enabled,
7296 &parent_event->child_total_time_enabled);
7297 atomic64_add(child_event->total_time_running,
7298 &parent_event->child_total_time_running);
7301 * Remove this event from the parent's list
7303 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7304 mutex_lock(&parent_event->child_mutex);
7305 list_del_init(&child_event->child_list);
7306 mutex_unlock(&parent_event->child_mutex);
7309 * Release the parent event, if this was the last
7310 * reference to it.
7312 put_event(parent_event);
7315 static void
7316 __perf_event_exit_task(struct perf_event *child_event,
7317 struct perf_event_context *child_ctx,
7318 struct task_struct *child)
7320 perf_remove_from_context(child_event, !!child_event->parent);
7323 * It can happen that the parent exits first, and has events
7324 * that are still around due to the child reference. These
7325 * events need to be zapped.
7327 if (child_event->parent) {
7328 sync_child_event(child_event, child);
7329 free_event(child_event);
7333 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
7335 struct perf_event *child_event, *tmp;
7336 struct perf_event_context *child_ctx;
7337 unsigned long flags;
7339 if (likely(!child->perf_event_ctxp[ctxn])) {
7340 perf_event_task(child, NULL, 0);
7341 return;
7344 local_irq_save(flags);
7346 * We can't reschedule here because interrupts are disabled,
7347 * and either child is current or it is a task that can't be
7348 * scheduled, so we are now safe from rescheduling changing
7349 * our context.
7351 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
7354 * Take the context lock here so that if find_get_context is
7355 * reading child->perf_event_ctxp, we wait until it has
7356 * incremented the context's refcount before we do put_ctx below.
7358 raw_spin_lock(&child_ctx->lock);
7359 task_ctx_sched_out(child_ctx);
7360 child->perf_event_ctxp[ctxn] = NULL;
7362 * If this context is a clone; unclone it so it can't get
7363 * swapped to another process while we're removing all
7364 * the events from it.
7366 unclone_ctx(child_ctx);
7367 update_context_time(child_ctx);
7368 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7371 * Report the task dead after unscheduling the events so that we
7372 * won't get any samples after PERF_RECORD_EXIT. We can however still
7373 * get a few PERF_RECORD_READ events.
7375 perf_event_task(child, child_ctx, 0);
7378 * We can recurse on the same lock type through:
7380 * __perf_event_exit_task()
7381 * sync_child_event()
7382 * put_event()
7383 * mutex_lock(&ctx->mutex)
7385 * But since its the parent context it won't be the same instance.
7387 mutex_lock(&child_ctx->mutex);
7389 again:
7390 list_for_each_entry_safe(child_event, tmp, &child_ctx->pinned_groups,
7391 group_entry)
7392 __perf_event_exit_task(child_event, child_ctx, child);
7394 list_for_each_entry_safe(child_event, tmp, &child_ctx->flexible_groups,
7395 group_entry)
7396 __perf_event_exit_task(child_event, child_ctx, child);
7399 * If the last event was a group event, it will have appended all
7400 * its siblings to the list, but we obtained 'tmp' before that which
7401 * will still point to the list head terminating the iteration.
7403 if (!list_empty(&child_ctx->pinned_groups) ||
7404 !list_empty(&child_ctx->flexible_groups))
7405 goto again;
7407 mutex_unlock(&child_ctx->mutex);
7409 put_ctx(child_ctx);
7413 * When a child task exits, feed back event values to parent events.
7415 void perf_event_exit_task(struct task_struct *child)
7417 struct perf_event *event, *tmp;
7418 int ctxn;
7420 mutex_lock(&child->perf_event_mutex);
7421 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
7422 owner_entry) {
7423 list_del_init(&event->owner_entry);
7426 * Ensure the list deletion is visible before we clear
7427 * the owner, closes a race against perf_release() where
7428 * we need to serialize on the owner->perf_event_mutex.
7430 smp_wmb();
7431 event->owner = NULL;
7433 mutex_unlock(&child->perf_event_mutex);
7435 for_each_task_context_nr(ctxn)
7436 perf_event_exit_task_context(child, ctxn);
7439 static void perf_free_event(struct perf_event *event,
7440 struct perf_event_context *ctx)
7442 struct perf_event *parent = event->parent;
7444 if (WARN_ON_ONCE(!parent))
7445 return;
7447 mutex_lock(&parent->child_mutex);
7448 list_del_init(&event->child_list);
7449 mutex_unlock(&parent->child_mutex);
7451 put_event(parent);
7453 perf_group_detach(event);
7454 list_del_event(event, ctx);
7455 free_event(event);
7459 * free an unexposed, unused context as created by inheritance by
7460 * perf_event_init_task below, used by fork() in case of fail.
7462 void perf_event_free_task(struct task_struct *task)
7464 struct perf_event_context *ctx;
7465 struct perf_event *event, *tmp;
7466 int ctxn;
7468 for_each_task_context_nr(ctxn) {
7469 ctx = task->perf_event_ctxp[ctxn];
7470 if (!ctx)
7471 continue;
7473 mutex_lock(&ctx->mutex);
7474 again:
7475 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
7476 group_entry)
7477 perf_free_event(event, ctx);
7479 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
7480 group_entry)
7481 perf_free_event(event, ctx);
7483 if (!list_empty(&ctx->pinned_groups) ||
7484 !list_empty(&ctx->flexible_groups))
7485 goto again;
7487 mutex_unlock(&ctx->mutex);
7489 put_ctx(ctx);
7493 void perf_event_delayed_put(struct task_struct *task)
7495 int ctxn;
7497 for_each_task_context_nr(ctxn)
7498 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
7502 * inherit a event from parent task to child task:
7504 static struct perf_event *
7505 inherit_event(struct perf_event *parent_event,
7506 struct task_struct *parent,
7507 struct perf_event_context *parent_ctx,
7508 struct task_struct *child,
7509 struct perf_event *group_leader,
7510 struct perf_event_context *child_ctx)
7512 struct perf_event *child_event;
7513 unsigned long flags;
7516 * Instead of creating recursive hierarchies of events,
7517 * we link inherited events back to the original parent,
7518 * which has a filp for sure, which we use as the reference
7519 * count:
7521 if (parent_event->parent)
7522 parent_event = parent_event->parent;
7524 child_event = perf_event_alloc(&parent_event->attr,
7525 parent_event->cpu,
7526 child,
7527 group_leader, parent_event,
7528 NULL, NULL);
7529 if (IS_ERR(child_event))
7530 return child_event;
7532 if (!atomic_long_inc_not_zero(&parent_event->refcount)) {
7533 free_event(child_event);
7534 return NULL;
7537 get_ctx(child_ctx);
7540 * Make the child state follow the state of the parent event,
7541 * not its attr.disabled bit. We hold the parent's mutex,
7542 * so we won't race with perf_event_{en, dis}able_family.
7544 if (parent_event->state >= PERF_EVENT_STATE_INACTIVE)
7545 child_event->state = PERF_EVENT_STATE_INACTIVE;
7546 else
7547 child_event->state = PERF_EVENT_STATE_OFF;
7549 if (parent_event->attr.freq) {
7550 u64 sample_period = parent_event->hw.sample_period;
7551 struct hw_perf_event *hwc = &child_event->hw;
7553 hwc->sample_period = sample_period;
7554 hwc->last_period = sample_period;
7556 local64_set(&hwc->period_left, sample_period);
7559 child_event->ctx = child_ctx;
7560 child_event->overflow_handler = parent_event->overflow_handler;
7561 child_event->overflow_handler_context
7562 = parent_event->overflow_handler_context;
7565 * Precalculate sample_data sizes
7567 perf_event__header_size(child_event);
7568 perf_event__id_header_size(child_event);
7571 * Link it up in the child's context:
7573 raw_spin_lock_irqsave(&child_ctx->lock, flags);
7574 add_event_to_ctx(child_event, child_ctx);
7575 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7578 * Link this into the parent event's child list
7580 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7581 mutex_lock(&parent_event->child_mutex);
7582 list_add_tail(&child_event->child_list, &parent_event->child_list);
7583 mutex_unlock(&parent_event->child_mutex);
7585 return child_event;
7588 static int inherit_group(struct perf_event *parent_event,
7589 struct task_struct *parent,
7590 struct perf_event_context *parent_ctx,
7591 struct task_struct *child,
7592 struct perf_event_context *child_ctx)
7594 struct perf_event *leader;
7595 struct perf_event *sub;
7596 struct perf_event *child_ctr;
7598 leader = inherit_event(parent_event, parent, parent_ctx,
7599 child, NULL, child_ctx);
7600 if (IS_ERR(leader))
7601 return PTR_ERR(leader);
7602 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
7603 child_ctr = inherit_event(sub, parent, parent_ctx,
7604 child, leader, child_ctx);
7605 if (IS_ERR(child_ctr))
7606 return PTR_ERR(child_ctr);
7608 return 0;
7611 static int
7612 inherit_task_group(struct perf_event *event, struct task_struct *parent,
7613 struct perf_event_context *parent_ctx,
7614 struct task_struct *child, int ctxn,
7615 int *inherited_all)
7617 int ret;
7618 struct perf_event_context *child_ctx;
7620 if (!event->attr.inherit) {
7621 *inherited_all = 0;
7622 return 0;
7625 child_ctx = child->perf_event_ctxp[ctxn];
7626 if (!child_ctx) {
7628 * This is executed from the parent task context, so
7629 * inherit events that have been marked for cloning.
7630 * First allocate and initialize a context for the
7631 * child.
7634 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
7635 if (!child_ctx)
7636 return -ENOMEM;
7638 child->perf_event_ctxp[ctxn] = child_ctx;
7641 ret = inherit_group(event, parent, parent_ctx,
7642 child, child_ctx);
7644 if (ret)
7645 *inherited_all = 0;
7647 return ret;
7651 * Initialize the perf_event context in task_struct
7653 int perf_event_init_context(struct task_struct *child, int ctxn)
7655 struct perf_event_context *child_ctx, *parent_ctx;
7656 struct perf_event_context *cloned_ctx;
7657 struct perf_event *event;
7658 struct task_struct *parent = current;
7659 int inherited_all = 1;
7660 unsigned long flags;
7661 int ret = 0;
7663 if (likely(!parent->perf_event_ctxp[ctxn]))
7664 return 0;
7667 * If the parent's context is a clone, pin it so it won't get
7668 * swapped under us.
7670 parent_ctx = perf_pin_task_context(parent, ctxn);
7673 * No need to check if parent_ctx != NULL here; since we saw
7674 * it non-NULL earlier, the only reason for it to become NULL
7675 * is if we exit, and since we're currently in the middle of
7676 * a fork we can't be exiting at the same time.
7680 * Lock the parent list. No need to lock the child - not PID
7681 * hashed yet and not running, so nobody can access it.
7683 mutex_lock(&parent_ctx->mutex);
7686 * We dont have to disable NMIs - we are only looking at
7687 * the list, not manipulating it:
7689 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
7690 ret = inherit_task_group(event, parent, parent_ctx,
7691 child, ctxn, &inherited_all);
7692 if (ret)
7693 break;
7697 * We can't hold ctx->lock when iterating the ->flexible_group list due
7698 * to allocations, but we need to prevent rotation because
7699 * rotate_ctx() will change the list from interrupt context.
7701 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7702 parent_ctx->rotate_disable = 1;
7703 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7705 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
7706 ret = inherit_task_group(event, parent, parent_ctx,
7707 child, ctxn, &inherited_all);
7708 if (ret)
7709 break;
7712 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7713 parent_ctx->rotate_disable = 0;
7715 child_ctx = child->perf_event_ctxp[ctxn];
7717 if (child_ctx && inherited_all) {
7719 * Mark the child context as a clone of the parent
7720 * context, or of whatever the parent is a clone of.
7722 * Note that if the parent is a clone, the holding of
7723 * parent_ctx->lock avoids it from being uncloned.
7725 cloned_ctx = parent_ctx->parent_ctx;
7726 if (cloned_ctx) {
7727 child_ctx->parent_ctx = cloned_ctx;
7728 child_ctx->parent_gen = parent_ctx->parent_gen;
7729 } else {
7730 child_ctx->parent_ctx = parent_ctx;
7731 child_ctx->parent_gen = parent_ctx->generation;
7733 get_ctx(child_ctx->parent_ctx);
7736 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7737 mutex_unlock(&parent_ctx->mutex);
7739 perf_unpin_context(parent_ctx);
7740 put_ctx(parent_ctx);
7742 return ret;
7746 * Initialize the perf_event context in task_struct
7748 int perf_event_init_task(struct task_struct *child)
7750 int ctxn, ret;
7752 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
7753 mutex_init(&child->perf_event_mutex);
7754 INIT_LIST_HEAD(&child->perf_event_list);
7756 for_each_task_context_nr(ctxn) {
7757 ret = perf_event_init_context(child, ctxn);
7758 if (ret)
7759 return ret;
7762 return 0;
7765 static void __init perf_event_init_all_cpus(void)
7767 struct swevent_htable *swhash;
7768 int cpu;
7770 for_each_possible_cpu(cpu) {
7771 swhash = &per_cpu(swevent_htable, cpu);
7772 mutex_init(&swhash->hlist_mutex);
7773 INIT_LIST_HEAD(&per_cpu(rotation_list, cpu));
7777 static void perf_event_init_cpu(int cpu)
7779 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7781 mutex_lock(&swhash->hlist_mutex);
7782 swhash->online = true;
7783 if (swhash->hlist_refcount > 0) {
7784 struct swevent_hlist *hlist;
7786 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
7787 WARN_ON(!hlist);
7788 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7790 mutex_unlock(&swhash->hlist_mutex);
7793 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC
7794 static void perf_pmu_rotate_stop(struct pmu *pmu)
7796 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7798 WARN_ON(!irqs_disabled());
7800 list_del_init(&cpuctx->rotation_list);
7803 static void __perf_event_exit_context(void *__info)
7805 struct remove_event re = { .detach_group = false };
7806 struct perf_event_context *ctx = __info;
7808 perf_pmu_rotate_stop(ctx->pmu);
7810 rcu_read_lock();
7811 list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
7812 __perf_remove_from_context(&re);
7813 rcu_read_unlock();
7816 static void perf_event_exit_cpu_context(int cpu)
7818 struct perf_event_context *ctx;
7819 struct pmu *pmu;
7820 int idx;
7822 idx = srcu_read_lock(&pmus_srcu);
7823 list_for_each_entry_rcu(pmu, &pmus, entry) {
7824 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
7826 mutex_lock(&ctx->mutex);
7827 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
7828 mutex_unlock(&ctx->mutex);
7830 srcu_read_unlock(&pmus_srcu, idx);
7833 static void perf_event_exit_cpu(int cpu)
7835 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7837 perf_event_exit_cpu_context(cpu);
7839 mutex_lock(&swhash->hlist_mutex);
7840 swhash->online = false;
7841 swevent_hlist_release(swhash);
7842 mutex_unlock(&swhash->hlist_mutex);
7844 #else
7845 static inline void perf_event_exit_cpu(int cpu) { }
7846 #endif
7848 static int
7849 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
7851 int cpu;
7853 for_each_online_cpu(cpu)
7854 perf_event_exit_cpu(cpu);
7856 return NOTIFY_OK;
7860 * Run the perf reboot notifier at the very last possible moment so that
7861 * the generic watchdog code runs as long as possible.
7863 static struct notifier_block perf_reboot_notifier = {
7864 .notifier_call = perf_reboot,
7865 .priority = INT_MIN,
7868 static int
7869 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
7871 unsigned int cpu = (long)hcpu;
7873 switch (action & ~CPU_TASKS_FROZEN) {
7875 case CPU_UP_PREPARE:
7876 case CPU_DOWN_FAILED:
7877 perf_event_init_cpu(cpu);
7878 break;
7880 case CPU_UP_CANCELED:
7881 case CPU_DOWN_PREPARE:
7882 perf_event_exit_cpu(cpu);
7883 break;
7884 default:
7885 break;
7888 return NOTIFY_OK;
7891 void __init perf_event_init(void)
7893 int ret;
7895 idr_init(&pmu_idr);
7897 perf_event_init_all_cpus();
7898 init_srcu_struct(&pmus_srcu);
7899 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
7900 perf_pmu_register(&perf_cpu_clock, NULL, -1);
7901 perf_pmu_register(&perf_task_clock, NULL, -1);
7902 perf_tp_register();
7903 perf_cpu_notifier(perf_cpu_notify);
7904 register_reboot_notifier(&perf_reboot_notifier);
7906 ret = init_hw_breakpoint();
7907 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
7909 /* do not patch jump label more than once per second */
7910 jump_label_rate_limit(&perf_sched_events, HZ);
7913 * Build time assertion that we keep the data_head at the intended
7914 * location. IOW, validation we got the __reserved[] size right.
7916 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
7917 != 1024);
7920 static int __init perf_event_sysfs_init(void)
7922 struct pmu *pmu;
7923 int ret;
7925 mutex_lock(&pmus_lock);
7927 ret = bus_register(&pmu_bus);
7928 if (ret)
7929 goto unlock;
7931 list_for_each_entry(pmu, &pmus, entry) {
7932 if (!pmu->name || pmu->type < 0)
7933 continue;
7935 ret = pmu_dev_alloc(pmu);
7936 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
7938 pmu_bus_running = 1;
7939 ret = 0;
7941 unlock:
7942 mutex_unlock(&pmus_lock);
7944 return ret;
7946 device_initcall(perf_event_sysfs_init);
7948 #ifdef CONFIG_CGROUP_PERF
7949 static struct cgroup_subsys_state *
7950 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
7952 struct perf_cgroup *jc;
7954 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
7955 if (!jc)
7956 return ERR_PTR(-ENOMEM);
7958 jc->info = alloc_percpu(struct perf_cgroup_info);
7959 if (!jc->info) {
7960 kfree(jc);
7961 return ERR_PTR(-ENOMEM);
7964 return &jc->css;
7967 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
7969 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
7971 free_percpu(jc->info);
7972 kfree(jc);
7975 static int __perf_cgroup_move(void *info)
7977 struct task_struct *task = info;
7978 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
7979 return 0;
7982 static void perf_cgroup_attach(struct cgroup_subsys_state *css,
7983 struct cgroup_taskset *tset)
7985 struct task_struct *task;
7987 cgroup_taskset_for_each(task, css, tset)
7988 task_function_call(task, __perf_cgroup_move, task);
7991 static void perf_cgroup_exit(struct cgroup_subsys_state *css,
7992 struct cgroup_subsys_state *old_css,
7993 struct task_struct *task)
7996 * cgroup_exit() is called in the copy_process() failure path.
7997 * Ignore this case since the task hasn't ran yet, this avoids
7998 * trying to poke a half freed task state from generic code.
8000 if (!(task->flags & PF_EXITING))
8001 return;
8003 task_function_call(task, __perf_cgroup_move, task);
8006 struct cgroup_subsys perf_subsys = {
8007 .name = "perf_event",
8008 .subsys_id = perf_subsys_id,
8009 .css_alloc = perf_cgroup_css_alloc,
8010 .css_free = perf_cgroup_css_free,
8011 .exit = perf_cgroup_exit,
8012 .attach = perf_cgroup_attach,
8014 #endif /* CONFIG_CGROUP_PERF */