Merge branch 'for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/viro/vfs
[linux/fpc-iii.git] / kernel / events / core.c
blob56003c6edfd38c03e8dd523f1efb01d99bcf2e84
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 |\
123 PERF_FLAG_FD_CLOEXEC)
126 * branch priv levels that need permission checks
128 #define PERF_SAMPLE_BRANCH_PERM_PLM \
129 (PERF_SAMPLE_BRANCH_KERNEL |\
130 PERF_SAMPLE_BRANCH_HV)
132 enum event_type_t {
133 EVENT_FLEXIBLE = 0x1,
134 EVENT_PINNED = 0x2,
135 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
139 * perf_sched_events : >0 events exist
140 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
142 struct static_key_deferred perf_sched_events __read_mostly;
143 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
144 static DEFINE_PER_CPU(atomic_t, perf_branch_stack_events);
146 static atomic_t nr_mmap_events __read_mostly;
147 static atomic_t nr_comm_events __read_mostly;
148 static atomic_t nr_task_events __read_mostly;
149 static atomic_t nr_freq_events __read_mostly;
151 static LIST_HEAD(pmus);
152 static DEFINE_MUTEX(pmus_lock);
153 static struct srcu_struct pmus_srcu;
156 * perf event paranoia level:
157 * -1 - not paranoid at all
158 * 0 - disallow raw tracepoint access for unpriv
159 * 1 - disallow cpu events for unpriv
160 * 2 - disallow kernel profiling for unpriv
162 int sysctl_perf_event_paranoid __read_mostly = 1;
164 /* Minimum for 512 kiB + 1 user control page */
165 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
168 * max perf event sample rate
170 #define DEFAULT_MAX_SAMPLE_RATE 100000
171 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
172 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
174 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
176 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
177 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
179 static int perf_sample_allowed_ns __read_mostly =
180 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
182 void update_perf_cpu_limits(void)
184 u64 tmp = perf_sample_period_ns;
186 tmp *= sysctl_perf_cpu_time_max_percent;
187 do_div(tmp, 100);
188 ACCESS_ONCE(perf_sample_allowed_ns) = tmp;
191 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
193 int perf_proc_update_handler(struct ctl_table *table, int write,
194 void __user *buffer, size_t *lenp,
195 loff_t *ppos)
197 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
199 if (ret || !write)
200 return ret;
202 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
203 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
204 update_perf_cpu_limits();
206 return 0;
209 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
211 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
212 void __user *buffer, size_t *lenp,
213 loff_t *ppos)
215 int ret = proc_dointvec(table, write, buffer, lenp, ppos);
217 if (ret || !write)
218 return ret;
220 update_perf_cpu_limits();
222 return 0;
226 * perf samples are done in some very critical code paths (NMIs).
227 * If they take too much CPU time, the system can lock up and not
228 * get any real work done. This will drop the sample rate when
229 * we detect that events are taking too long.
231 #define NR_ACCUMULATED_SAMPLES 128
232 static DEFINE_PER_CPU(u64, running_sample_length);
234 void perf_sample_event_took(u64 sample_len_ns)
236 u64 avg_local_sample_len;
237 u64 local_samples_len;
238 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
240 if (allowed_ns == 0)
241 return;
243 /* decay the counter by 1 average sample */
244 local_samples_len = __get_cpu_var(running_sample_length);
245 local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES;
246 local_samples_len += sample_len_ns;
247 __get_cpu_var(running_sample_length) = local_samples_len;
250 * note: this will be biased artifically low until we have
251 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
252 * from having to maintain a count.
254 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
256 if (avg_local_sample_len <= allowed_ns)
257 return;
259 if (max_samples_per_tick <= 1)
260 return;
262 max_samples_per_tick = DIV_ROUND_UP(max_samples_per_tick, 2);
263 sysctl_perf_event_sample_rate = max_samples_per_tick * HZ;
264 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
266 printk_ratelimited(KERN_WARNING
267 "perf samples too long (%lld > %lld), lowering "
268 "kernel.perf_event_max_sample_rate to %d\n",
269 avg_local_sample_len, allowed_ns,
270 sysctl_perf_event_sample_rate);
272 update_perf_cpu_limits();
275 static atomic64_t perf_event_id;
277 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
278 enum event_type_t event_type);
280 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
281 enum event_type_t event_type,
282 struct task_struct *task);
284 static void update_context_time(struct perf_event_context *ctx);
285 static u64 perf_event_time(struct perf_event *event);
287 void __weak perf_event_print_debug(void) { }
289 extern __weak const char *perf_pmu_name(void)
291 return "pmu";
294 static inline u64 perf_clock(void)
296 return local_clock();
299 static inline struct perf_cpu_context *
300 __get_cpu_context(struct perf_event_context *ctx)
302 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
305 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
306 struct perf_event_context *ctx)
308 raw_spin_lock(&cpuctx->ctx.lock);
309 if (ctx)
310 raw_spin_lock(&ctx->lock);
313 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
314 struct perf_event_context *ctx)
316 if (ctx)
317 raw_spin_unlock(&ctx->lock);
318 raw_spin_unlock(&cpuctx->ctx.lock);
321 #ifdef CONFIG_CGROUP_PERF
324 * perf_cgroup_info keeps track of time_enabled for a cgroup.
325 * This is a per-cpu dynamically allocated data structure.
327 struct perf_cgroup_info {
328 u64 time;
329 u64 timestamp;
332 struct perf_cgroup {
333 struct cgroup_subsys_state css;
334 struct perf_cgroup_info __percpu *info;
338 * Must ensure cgroup is pinned (css_get) before calling
339 * this function. In other words, we cannot call this function
340 * if there is no cgroup event for the current CPU context.
342 static inline struct perf_cgroup *
343 perf_cgroup_from_task(struct task_struct *task)
345 return container_of(task_css(task, perf_subsys_id),
346 struct perf_cgroup, css);
349 static inline bool
350 perf_cgroup_match(struct perf_event *event)
352 struct perf_event_context *ctx = event->ctx;
353 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
355 /* @event doesn't care about cgroup */
356 if (!event->cgrp)
357 return true;
359 /* wants specific cgroup scope but @cpuctx isn't associated with any */
360 if (!cpuctx->cgrp)
361 return false;
364 * Cgroup scoping is recursive. An event enabled for a cgroup is
365 * also enabled for all its descendant cgroups. If @cpuctx's
366 * cgroup is a descendant of @event's (the test covers identity
367 * case), it's a match.
369 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
370 event->cgrp->css.cgroup);
373 static inline bool perf_tryget_cgroup(struct perf_event *event)
375 return css_tryget(&event->cgrp->css);
378 static inline void perf_put_cgroup(struct perf_event *event)
380 css_put(&event->cgrp->css);
383 static inline void perf_detach_cgroup(struct perf_event *event)
385 perf_put_cgroup(event);
386 event->cgrp = NULL;
389 static inline int is_cgroup_event(struct perf_event *event)
391 return event->cgrp != NULL;
394 static inline u64 perf_cgroup_event_time(struct perf_event *event)
396 struct perf_cgroup_info *t;
398 t = per_cpu_ptr(event->cgrp->info, event->cpu);
399 return t->time;
402 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
404 struct perf_cgroup_info *info;
405 u64 now;
407 now = perf_clock();
409 info = this_cpu_ptr(cgrp->info);
411 info->time += now - info->timestamp;
412 info->timestamp = now;
415 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
417 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
418 if (cgrp_out)
419 __update_cgrp_time(cgrp_out);
422 static inline void update_cgrp_time_from_event(struct perf_event *event)
424 struct perf_cgroup *cgrp;
427 * ensure we access cgroup data only when needed and
428 * when we know the cgroup is pinned (css_get)
430 if (!is_cgroup_event(event))
431 return;
433 cgrp = perf_cgroup_from_task(current);
435 * Do not update time when cgroup is not active
437 if (cgrp == event->cgrp)
438 __update_cgrp_time(event->cgrp);
441 static inline void
442 perf_cgroup_set_timestamp(struct task_struct *task,
443 struct perf_event_context *ctx)
445 struct perf_cgroup *cgrp;
446 struct perf_cgroup_info *info;
449 * ctx->lock held by caller
450 * ensure we do not access cgroup data
451 * unless we have the cgroup pinned (css_get)
453 if (!task || !ctx->nr_cgroups)
454 return;
456 cgrp = perf_cgroup_from_task(task);
457 info = this_cpu_ptr(cgrp->info);
458 info->timestamp = ctx->timestamp;
461 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
462 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
465 * reschedule events based on the cgroup constraint of task.
467 * mode SWOUT : schedule out everything
468 * mode SWIN : schedule in based on cgroup for next
470 void perf_cgroup_switch(struct task_struct *task, int mode)
472 struct perf_cpu_context *cpuctx;
473 struct pmu *pmu;
474 unsigned long flags;
477 * disable interrupts to avoid geting nr_cgroup
478 * changes via __perf_event_disable(). Also
479 * avoids preemption.
481 local_irq_save(flags);
484 * we reschedule only in the presence of cgroup
485 * constrained events.
487 rcu_read_lock();
489 list_for_each_entry_rcu(pmu, &pmus, entry) {
490 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
491 if (cpuctx->unique_pmu != pmu)
492 continue; /* ensure we process each cpuctx once */
495 * perf_cgroup_events says at least one
496 * context on this CPU has cgroup events.
498 * ctx->nr_cgroups reports the number of cgroup
499 * events for a context.
501 if (cpuctx->ctx.nr_cgroups > 0) {
502 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
503 perf_pmu_disable(cpuctx->ctx.pmu);
505 if (mode & PERF_CGROUP_SWOUT) {
506 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
508 * must not be done before ctxswout due
509 * to event_filter_match() in event_sched_out()
511 cpuctx->cgrp = NULL;
514 if (mode & PERF_CGROUP_SWIN) {
515 WARN_ON_ONCE(cpuctx->cgrp);
517 * set cgrp before ctxsw in to allow
518 * event_filter_match() to not have to pass
519 * task around
521 cpuctx->cgrp = perf_cgroup_from_task(task);
522 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
524 perf_pmu_enable(cpuctx->ctx.pmu);
525 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
529 rcu_read_unlock();
531 local_irq_restore(flags);
534 static inline void perf_cgroup_sched_out(struct task_struct *task,
535 struct task_struct *next)
537 struct perf_cgroup *cgrp1;
538 struct perf_cgroup *cgrp2 = NULL;
541 * we come here when we know perf_cgroup_events > 0
543 cgrp1 = perf_cgroup_from_task(task);
546 * next is NULL when called from perf_event_enable_on_exec()
547 * that will systematically cause a cgroup_switch()
549 if (next)
550 cgrp2 = perf_cgroup_from_task(next);
553 * only schedule out current cgroup events if we know
554 * that we are switching to a different cgroup. Otherwise,
555 * do no touch the cgroup events.
557 if (cgrp1 != cgrp2)
558 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
561 static inline void perf_cgroup_sched_in(struct task_struct *prev,
562 struct task_struct *task)
564 struct perf_cgroup *cgrp1;
565 struct perf_cgroup *cgrp2 = NULL;
568 * we come here when we know perf_cgroup_events > 0
570 cgrp1 = perf_cgroup_from_task(task);
572 /* prev can never be NULL */
573 cgrp2 = perf_cgroup_from_task(prev);
576 * only need to schedule in cgroup events if we are changing
577 * cgroup during ctxsw. Cgroup events were not scheduled
578 * out of ctxsw out if that was not the case.
580 if (cgrp1 != cgrp2)
581 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
584 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
585 struct perf_event_attr *attr,
586 struct perf_event *group_leader)
588 struct perf_cgroup *cgrp;
589 struct cgroup_subsys_state *css;
590 struct fd f = fdget(fd);
591 int ret = 0;
593 if (!f.file)
594 return -EBADF;
596 rcu_read_lock();
598 css = css_from_dir(f.file->f_dentry, &perf_subsys);
599 if (IS_ERR(css)) {
600 ret = PTR_ERR(css);
601 goto out;
604 cgrp = container_of(css, struct perf_cgroup, css);
605 event->cgrp = cgrp;
607 /* must be done before we fput() the file */
608 if (!perf_tryget_cgroup(event)) {
609 event->cgrp = NULL;
610 ret = -ENOENT;
611 goto out;
615 * all events in a group must monitor
616 * the same cgroup because a task belongs
617 * to only one perf cgroup at a time
619 if (group_leader && group_leader->cgrp != cgrp) {
620 perf_detach_cgroup(event);
621 ret = -EINVAL;
623 out:
624 rcu_read_unlock();
625 fdput(f);
626 return ret;
629 static inline void
630 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
632 struct perf_cgroup_info *t;
633 t = per_cpu_ptr(event->cgrp->info, event->cpu);
634 event->shadow_ctx_time = now - t->timestamp;
637 static inline void
638 perf_cgroup_defer_enabled(struct perf_event *event)
641 * when the current task's perf cgroup does not match
642 * the event's, we need to remember to call the
643 * perf_mark_enable() function the first time a task with
644 * a matching perf cgroup is scheduled in.
646 if (is_cgroup_event(event) && !perf_cgroup_match(event))
647 event->cgrp_defer_enabled = 1;
650 static inline void
651 perf_cgroup_mark_enabled(struct perf_event *event,
652 struct perf_event_context *ctx)
654 struct perf_event *sub;
655 u64 tstamp = perf_event_time(event);
657 if (!event->cgrp_defer_enabled)
658 return;
660 event->cgrp_defer_enabled = 0;
662 event->tstamp_enabled = tstamp - event->total_time_enabled;
663 list_for_each_entry(sub, &event->sibling_list, group_entry) {
664 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
665 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
666 sub->cgrp_defer_enabled = 0;
670 #else /* !CONFIG_CGROUP_PERF */
672 static inline bool
673 perf_cgroup_match(struct perf_event *event)
675 return true;
678 static inline void perf_detach_cgroup(struct perf_event *event)
681 static inline int is_cgroup_event(struct perf_event *event)
683 return 0;
686 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
688 return 0;
691 static inline void update_cgrp_time_from_event(struct perf_event *event)
695 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
699 static inline void perf_cgroup_sched_out(struct task_struct *task,
700 struct task_struct *next)
704 static inline void perf_cgroup_sched_in(struct task_struct *prev,
705 struct task_struct *task)
709 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
710 struct perf_event_attr *attr,
711 struct perf_event *group_leader)
713 return -EINVAL;
716 static inline void
717 perf_cgroup_set_timestamp(struct task_struct *task,
718 struct perf_event_context *ctx)
722 void
723 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
727 static inline void
728 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
732 static inline u64 perf_cgroup_event_time(struct perf_event *event)
734 return 0;
737 static inline void
738 perf_cgroup_defer_enabled(struct perf_event *event)
742 static inline void
743 perf_cgroup_mark_enabled(struct perf_event *event,
744 struct perf_event_context *ctx)
747 #endif
750 * set default to be dependent on timer tick just
751 * like original code
753 #define PERF_CPU_HRTIMER (1000 / HZ)
755 * function must be called with interrupts disbled
757 static enum hrtimer_restart perf_cpu_hrtimer_handler(struct hrtimer *hr)
759 struct perf_cpu_context *cpuctx;
760 enum hrtimer_restart ret = HRTIMER_NORESTART;
761 int rotations = 0;
763 WARN_ON(!irqs_disabled());
765 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
767 rotations = perf_rotate_context(cpuctx);
770 * arm timer if needed
772 if (rotations) {
773 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
774 ret = HRTIMER_RESTART;
777 return ret;
780 /* CPU is going down */
781 void perf_cpu_hrtimer_cancel(int cpu)
783 struct perf_cpu_context *cpuctx;
784 struct pmu *pmu;
785 unsigned long flags;
787 if (WARN_ON(cpu != smp_processor_id()))
788 return;
790 local_irq_save(flags);
792 rcu_read_lock();
794 list_for_each_entry_rcu(pmu, &pmus, entry) {
795 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
797 if (pmu->task_ctx_nr == perf_sw_context)
798 continue;
800 hrtimer_cancel(&cpuctx->hrtimer);
803 rcu_read_unlock();
805 local_irq_restore(flags);
808 static void __perf_cpu_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
810 struct hrtimer *hr = &cpuctx->hrtimer;
811 struct pmu *pmu = cpuctx->ctx.pmu;
812 int timer;
814 /* no multiplexing needed for SW PMU */
815 if (pmu->task_ctx_nr == perf_sw_context)
816 return;
819 * check default is sane, if not set then force to
820 * default interval (1/tick)
822 timer = pmu->hrtimer_interval_ms;
823 if (timer < 1)
824 timer = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
826 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
828 hrtimer_init(hr, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
829 hr->function = perf_cpu_hrtimer_handler;
832 static void perf_cpu_hrtimer_restart(struct perf_cpu_context *cpuctx)
834 struct hrtimer *hr = &cpuctx->hrtimer;
835 struct pmu *pmu = cpuctx->ctx.pmu;
837 /* not for SW PMU */
838 if (pmu->task_ctx_nr == perf_sw_context)
839 return;
841 if (hrtimer_active(hr))
842 return;
844 if (!hrtimer_callback_running(hr))
845 __hrtimer_start_range_ns(hr, cpuctx->hrtimer_interval,
846 0, HRTIMER_MODE_REL_PINNED, 0);
849 void perf_pmu_disable(struct pmu *pmu)
851 int *count = this_cpu_ptr(pmu->pmu_disable_count);
852 if (!(*count)++)
853 pmu->pmu_disable(pmu);
856 void perf_pmu_enable(struct pmu *pmu)
858 int *count = this_cpu_ptr(pmu->pmu_disable_count);
859 if (!--(*count))
860 pmu->pmu_enable(pmu);
863 static DEFINE_PER_CPU(struct list_head, rotation_list);
866 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
867 * because they're strictly cpu affine and rotate_start is called with IRQs
868 * disabled, while rotate_context is called from IRQ context.
870 static void perf_pmu_rotate_start(struct pmu *pmu)
872 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
873 struct list_head *head = &__get_cpu_var(rotation_list);
875 WARN_ON(!irqs_disabled());
877 if (list_empty(&cpuctx->rotation_list))
878 list_add(&cpuctx->rotation_list, head);
881 static void get_ctx(struct perf_event_context *ctx)
883 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
886 static void put_ctx(struct perf_event_context *ctx)
888 if (atomic_dec_and_test(&ctx->refcount)) {
889 if (ctx->parent_ctx)
890 put_ctx(ctx->parent_ctx);
891 if (ctx->task)
892 put_task_struct(ctx->task);
893 kfree_rcu(ctx, rcu_head);
897 static void unclone_ctx(struct perf_event_context *ctx)
899 if (ctx->parent_ctx) {
900 put_ctx(ctx->parent_ctx);
901 ctx->parent_ctx = NULL;
903 ctx->generation++;
906 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
909 * only top level events have the pid namespace they were created in
911 if (event->parent)
912 event = event->parent;
914 return task_tgid_nr_ns(p, event->ns);
917 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
920 * only top level events have the pid namespace they were created in
922 if (event->parent)
923 event = event->parent;
925 return task_pid_nr_ns(p, event->ns);
929 * If we inherit events we want to return the parent event id
930 * to userspace.
932 static u64 primary_event_id(struct perf_event *event)
934 u64 id = event->id;
936 if (event->parent)
937 id = event->parent->id;
939 return id;
943 * Get the perf_event_context for a task and lock it.
944 * This has to cope with with the fact that until it is locked,
945 * the context could get moved to another task.
947 static struct perf_event_context *
948 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
950 struct perf_event_context *ctx;
952 retry:
954 * One of the few rules of preemptible RCU is that one cannot do
955 * rcu_read_unlock() while holding a scheduler (or nested) lock when
956 * part of the read side critical section was preemptible -- see
957 * rcu_read_unlock_special().
959 * Since ctx->lock nests under rq->lock we must ensure the entire read
960 * side critical section is non-preemptible.
962 preempt_disable();
963 rcu_read_lock();
964 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
965 if (ctx) {
967 * If this context is a clone of another, it might
968 * get swapped for another underneath us by
969 * perf_event_task_sched_out, though the
970 * rcu_read_lock() protects us from any context
971 * getting freed. Lock the context and check if it
972 * got swapped before we could get the lock, and retry
973 * if so. If we locked the right context, then it
974 * can't get swapped on us any more.
976 raw_spin_lock_irqsave(&ctx->lock, *flags);
977 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
978 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
979 rcu_read_unlock();
980 preempt_enable();
981 goto retry;
984 if (!atomic_inc_not_zero(&ctx->refcount)) {
985 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
986 ctx = NULL;
989 rcu_read_unlock();
990 preempt_enable();
991 return ctx;
995 * Get the context for a task and increment its pin_count so it
996 * can't get swapped to another task. This also increments its
997 * reference count so that the context can't get freed.
999 static struct perf_event_context *
1000 perf_pin_task_context(struct task_struct *task, int ctxn)
1002 struct perf_event_context *ctx;
1003 unsigned long flags;
1005 ctx = perf_lock_task_context(task, ctxn, &flags);
1006 if (ctx) {
1007 ++ctx->pin_count;
1008 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1010 return ctx;
1013 static void perf_unpin_context(struct perf_event_context *ctx)
1015 unsigned long flags;
1017 raw_spin_lock_irqsave(&ctx->lock, flags);
1018 --ctx->pin_count;
1019 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1023 * Update the record of the current time in a context.
1025 static void update_context_time(struct perf_event_context *ctx)
1027 u64 now = perf_clock();
1029 ctx->time += now - ctx->timestamp;
1030 ctx->timestamp = now;
1033 static u64 perf_event_time(struct perf_event *event)
1035 struct perf_event_context *ctx = event->ctx;
1037 if (is_cgroup_event(event))
1038 return perf_cgroup_event_time(event);
1040 return ctx ? ctx->time : 0;
1044 * Update the total_time_enabled and total_time_running fields for a event.
1045 * The caller of this function needs to hold the ctx->lock.
1047 static void update_event_times(struct perf_event *event)
1049 struct perf_event_context *ctx = event->ctx;
1050 u64 run_end;
1052 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1053 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1054 return;
1056 * in cgroup mode, time_enabled represents
1057 * the time the event was enabled AND active
1058 * tasks were in the monitored cgroup. This is
1059 * independent of the activity of the context as
1060 * there may be a mix of cgroup and non-cgroup events.
1062 * That is why we treat cgroup events differently
1063 * here.
1065 if (is_cgroup_event(event))
1066 run_end = perf_cgroup_event_time(event);
1067 else if (ctx->is_active)
1068 run_end = ctx->time;
1069 else
1070 run_end = event->tstamp_stopped;
1072 event->total_time_enabled = run_end - event->tstamp_enabled;
1074 if (event->state == PERF_EVENT_STATE_INACTIVE)
1075 run_end = event->tstamp_stopped;
1076 else
1077 run_end = perf_event_time(event);
1079 event->total_time_running = run_end - event->tstamp_running;
1084 * Update total_time_enabled and total_time_running for all events in a group.
1086 static void update_group_times(struct perf_event *leader)
1088 struct perf_event *event;
1090 update_event_times(leader);
1091 list_for_each_entry(event, &leader->sibling_list, group_entry)
1092 update_event_times(event);
1095 static struct list_head *
1096 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1098 if (event->attr.pinned)
1099 return &ctx->pinned_groups;
1100 else
1101 return &ctx->flexible_groups;
1105 * Add a event from the lists for its context.
1106 * Must be called with ctx->mutex and ctx->lock held.
1108 static void
1109 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1111 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1112 event->attach_state |= PERF_ATTACH_CONTEXT;
1115 * If we're a stand alone event or group leader, we go to the context
1116 * list, group events are kept attached to the group so that
1117 * perf_group_detach can, at all times, locate all siblings.
1119 if (event->group_leader == event) {
1120 struct list_head *list;
1122 if (is_software_event(event))
1123 event->group_flags |= PERF_GROUP_SOFTWARE;
1125 list = ctx_group_list(event, ctx);
1126 list_add_tail(&event->group_entry, list);
1129 if (is_cgroup_event(event))
1130 ctx->nr_cgroups++;
1132 if (has_branch_stack(event))
1133 ctx->nr_branch_stack++;
1135 list_add_rcu(&event->event_entry, &ctx->event_list);
1136 if (!ctx->nr_events)
1137 perf_pmu_rotate_start(ctx->pmu);
1138 ctx->nr_events++;
1139 if (event->attr.inherit_stat)
1140 ctx->nr_stat++;
1142 ctx->generation++;
1146 * Initialize event state based on the perf_event_attr::disabled.
1148 static inline void perf_event__state_init(struct perf_event *event)
1150 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1151 PERF_EVENT_STATE_INACTIVE;
1155 * Called at perf_event creation and when events are attached/detached from a
1156 * group.
1158 static void perf_event__read_size(struct perf_event *event)
1160 int entry = sizeof(u64); /* value */
1161 int size = 0;
1162 int nr = 1;
1164 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1165 size += sizeof(u64);
1167 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1168 size += sizeof(u64);
1170 if (event->attr.read_format & PERF_FORMAT_ID)
1171 entry += sizeof(u64);
1173 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1174 nr += event->group_leader->nr_siblings;
1175 size += sizeof(u64);
1178 size += entry * nr;
1179 event->read_size = size;
1182 static void perf_event__header_size(struct perf_event *event)
1184 struct perf_sample_data *data;
1185 u64 sample_type = event->attr.sample_type;
1186 u16 size = 0;
1188 perf_event__read_size(event);
1190 if (sample_type & PERF_SAMPLE_IP)
1191 size += sizeof(data->ip);
1193 if (sample_type & PERF_SAMPLE_ADDR)
1194 size += sizeof(data->addr);
1196 if (sample_type & PERF_SAMPLE_PERIOD)
1197 size += sizeof(data->period);
1199 if (sample_type & PERF_SAMPLE_WEIGHT)
1200 size += sizeof(data->weight);
1202 if (sample_type & PERF_SAMPLE_READ)
1203 size += event->read_size;
1205 if (sample_type & PERF_SAMPLE_DATA_SRC)
1206 size += sizeof(data->data_src.val);
1208 if (sample_type & PERF_SAMPLE_TRANSACTION)
1209 size += sizeof(data->txn);
1211 event->header_size = size;
1214 static void perf_event__id_header_size(struct perf_event *event)
1216 struct perf_sample_data *data;
1217 u64 sample_type = event->attr.sample_type;
1218 u16 size = 0;
1220 if (sample_type & PERF_SAMPLE_TID)
1221 size += sizeof(data->tid_entry);
1223 if (sample_type & PERF_SAMPLE_TIME)
1224 size += sizeof(data->time);
1226 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1227 size += sizeof(data->id);
1229 if (sample_type & PERF_SAMPLE_ID)
1230 size += sizeof(data->id);
1232 if (sample_type & PERF_SAMPLE_STREAM_ID)
1233 size += sizeof(data->stream_id);
1235 if (sample_type & PERF_SAMPLE_CPU)
1236 size += sizeof(data->cpu_entry);
1238 event->id_header_size = size;
1241 static void perf_group_attach(struct perf_event *event)
1243 struct perf_event *group_leader = event->group_leader, *pos;
1246 * We can have double attach due to group movement in perf_event_open.
1248 if (event->attach_state & PERF_ATTACH_GROUP)
1249 return;
1251 event->attach_state |= PERF_ATTACH_GROUP;
1253 if (group_leader == event)
1254 return;
1256 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1257 !is_software_event(event))
1258 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1260 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1261 group_leader->nr_siblings++;
1263 perf_event__header_size(group_leader);
1265 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1266 perf_event__header_size(pos);
1270 * Remove a event from the lists for its context.
1271 * Must be called with ctx->mutex and ctx->lock held.
1273 static void
1274 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1276 struct perf_cpu_context *cpuctx;
1278 * We can have double detach due to exit/hot-unplug + close.
1280 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1281 return;
1283 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1285 if (is_cgroup_event(event)) {
1286 ctx->nr_cgroups--;
1287 cpuctx = __get_cpu_context(ctx);
1289 * if there are no more cgroup events
1290 * then cler cgrp to avoid stale pointer
1291 * in update_cgrp_time_from_cpuctx()
1293 if (!ctx->nr_cgroups)
1294 cpuctx->cgrp = NULL;
1297 if (has_branch_stack(event))
1298 ctx->nr_branch_stack--;
1300 ctx->nr_events--;
1301 if (event->attr.inherit_stat)
1302 ctx->nr_stat--;
1304 list_del_rcu(&event->event_entry);
1306 if (event->group_leader == event)
1307 list_del_init(&event->group_entry);
1309 update_group_times(event);
1312 * If event was in error state, then keep it
1313 * that way, otherwise bogus counts will be
1314 * returned on read(). The only way to get out
1315 * of error state is by explicit re-enabling
1316 * of the event
1318 if (event->state > PERF_EVENT_STATE_OFF)
1319 event->state = PERF_EVENT_STATE_OFF;
1321 ctx->generation++;
1324 static void perf_group_detach(struct perf_event *event)
1326 struct perf_event *sibling, *tmp;
1327 struct list_head *list = NULL;
1330 * We can have double detach due to exit/hot-unplug + close.
1332 if (!(event->attach_state & PERF_ATTACH_GROUP))
1333 return;
1335 event->attach_state &= ~PERF_ATTACH_GROUP;
1338 * If this is a sibling, remove it from its group.
1340 if (event->group_leader != event) {
1341 list_del_init(&event->group_entry);
1342 event->group_leader->nr_siblings--;
1343 goto out;
1346 if (!list_empty(&event->group_entry))
1347 list = &event->group_entry;
1350 * If this was a group event with sibling events then
1351 * upgrade the siblings to singleton events by adding them
1352 * to whatever list we are on.
1354 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1355 if (list)
1356 list_move_tail(&sibling->group_entry, list);
1357 sibling->group_leader = sibling;
1359 /* Inherit group flags from the previous leader */
1360 sibling->group_flags = event->group_flags;
1363 out:
1364 perf_event__header_size(event->group_leader);
1366 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1367 perf_event__header_size(tmp);
1370 static inline int
1371 event_filter_match(struct perf_event *event)
1373 return (event->cpu == -1 || event->cpu == smp_processor_id())
1374 && perf_cgroup_match(event);
1377 static void
1378 event_sched_out(struct perf_event *event,
1379 struct perf_cpu_context *cpuctx,
1380 struct perf_event_context *ctx)
1382 u64 tstamp = perf_event_time(event);
1383 u64 delta;
1385 * An event which could not be activated because of
1386 * filter mismatch still needs to have its timings
1387 * maintained, otherwise bogus information is return
1388 * via read() for time_enabled, time_running:
1390 if (event->state == PERF_EVENT_STATE_INACTIVE
1391 && !event_filter_match(event)) {
1392 delta = tstamp - event->tstamp_stopped;
1393 event->tstamp_running += delta;
1394 event->tstamp_stopped = tstamp;
1397 if (event->state != PERF_EVENT_STATE_ACTIVE)
1398 return;
1400 perf_pmu_disable(event->pmu);
1402 event->state = PERF_EVENT_STATE_INACTIVE;
1403 if (event->pending_disable) {
1404 event->pending_disable = 0;
1405 event->state = PERF_EVENT_STATE_OFF;
1407 event->tstamp_stopped = tstamp;
1408 event->pmu->del(event, 0);
1409 event->oncpu = -1;
1411 if (!is_software_event(event))
1412 cpuctx->active_oncpu--;
1413 ctx->nr_active--;
1414 if (event->attr.freq && event->attr.sample_freq)
1415 ctx->nr_freq--;
1416 if (event->attr.exclusive || !cpuctx->active_oncpu)
1417 cpuctx->exclusive = 0;
1419 perf_pmu_enable(event->pmu);
1422 static void
1423 group_sched_out(struct perf_event *group_event,
1424 struct perf_cpu_context *cpuctx,
1425 struct perf_event_context *ctx)
1427 struct perf_event *event;
1428 int state = group_event->state;
1430 event_sched_out(group_event, cpuctx, ctx);
1433 * Schedule out siblings (if any):
1435 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1436 event_sched_out(event, cpuctx, ctx);
1438 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1439 cpuctx->exclusive = 0;
1443 * Cross CPU call to remove a performance event
1445 * We disable the event on the hardware level first. After that we
1446 * remove it from the context list.
1448 static int __perf_remove_from_context(void *info)
1450 struct perf_event *event = info;
1451 struct perf_event_context *ctx = event->ctx;
1452 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1454 raw_spin_lock(&ctx->lock);
1455 event_sched_out(event, cpuctx, ctx);
1456 list_del_event(event, ctx);
1457 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1458 ctx->is_active = 0;
1459 cpuctx->task_ctx = NULL;
1461 raw_spin_unlock(&ctx->lock);
1463 return 0;
1468 * Remove the event from a task's (or a CPU's) list of events.
1470 * CPU events are removed with a smp call. For task events we only
1471 * call when the task is on a CPU.
1473 * If event->ctx is a cloned context, callers must make sure that
1474 * every task struct that event->ctx->task could possibly point to
1475 * remains valid. This is OK when called from perf_release since
1476 * that only calls us on the top-level context, which can't be a clone.
1477 * When called from perf_event_exit_task, it's OK because the
1478 * context has been detached from its task.
1480 static void perf_remove_from_context(struct perf_event *event)
1482 struct perf_event_context *ctx = event->ctx;
1483 struct task_struct *task = ctx->task;
1485 lockdep_assert_held(&ctx->mutex);
1487 if (!task) {
1489 * Per cpu events are removed via an smp call and
1490 * the removal is always successful.
1492 cpu_function_call(event->cpu, __perf_remove_from_context, event);
1493 return;
1496 retry:
1497 if (!task_function_call(task, __perf_remove_from_context, event))
1498 return;
1500 raw_spin_lock_irq(&ctx->lock);
1502 * If we failed to find a running task, but find the context active now
1503 * that we've acquired the ctx->lock, retry.
1505 if (ctx->is_active) {
1506 raw_spin_unlock_irq(&ctx->lock);
1507 goto retry;
1511 * Since the task isn't running, its safe to remove the event, us
1512 * holding the ctx->lock ensures the task won't get scheduled in.
1514 list_del_event(event, ctx);
1515 raw_spin_unlock_irq(&ctx->lock);
1519 * Cross CPU call to disable a performance event
1521 int __perf_event_disable(void *info)
1523 struct perf_event *event = info;
1524 struct perf_event_context *ctx = event->ctx;
1525 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1528 * If this is a per-task event, need to check whether this
1529 * event's task is the current task on this cpu.
1531 * Can trigger due to concurrent perf_event_context_sched_out()
1532 * flipping contexts around.
1534 if (ctx->task && cpuctx->task_ctx != ctx)
1535 return -EINVAL;
1537 raw_spin_lock(&ctx->lock);
1540 * If the event is on, turn it off.
1541 * If it is in error state, leave it in error state.
1543 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1544 update_context_time(ctx);
1545 update_cgrp_time_from_event(event);
1546 update_group_times(event);
1547 if (event == event->group_leader)
1548 group_sched_out(event, cpuctx, ctx);
1549 else
1550 event_sched_out(event, cpuctx, ctx);
1551 event->state = PERF_EVENT_STATE_OFF;
1554 raw_spin_unlock(&ctx->lock);
1556 return 0;
1560 * Disable a event.
1562 * If event->ctx is a cloned context, callers must make sure that
1563 * every task struct that event->ctx->task could possibly point to
1564 * remains valid. This condition is satisifed when called through
1565 * perf_event_for_each_child or perf_event_for_each because they
1566 * hold the top-level event's child_mutex, so any descendant that
1567 * goes to exit will block in sync_child_event.
1568 * When called from perf_pending_event it's OK because event->ctx
1569 * is the current context on this CPU and preemption is disabled,
1570 * hence we can't get into perf_event_task_sched_out for this context.
1572 void perf_event_disable(struct perf_event *event)
1574 struct perf_event_context *ctx = event->ctx;
1575 struct task_struct *task = ctx->task;
1577 if (!task) {
1579 * Disable the event on the cpu that it's on
1581 cpu_function_call(event->cpu, __perf_event_disable, event);
1582 return;
1585 retry:
1586 if (!task_function_call(task, __perf_event_disable, event))
1587 return;
1589 raw_spin_lock_irq(&ctx->lock);
1591 * If the event is still active, we need to retry the cross-call.
1593 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1594 raw_spin_unlock_irq(&ctx->lock);
1596 * Reload the task pointer, it might have been changed by
1597 * a concurrent perf_event_context_sched_out().
1599 task = ctx->task;
1600 goto retry;
1604 * Since we have the lock this context can't be scheduled
1605 * in, so we can change the state safely.
1607 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1608 update_group_times(event);
1609 event->state = PERF_EVENT_STATE_OFF;
1611 raw_spin_unlock_irq(&ctx->lock);
1613 EXPORT_SYMBOL_GPL(perf_event_disable);
1615 static void perf_set_shadow_time(struct perf_event *event,
1616 struct perf_event_context *ctx,
1617 u64 tstamp)
1620 * use the correct time source for the time snapshot
1622 * We could get by without this by leveraging the
1623 * fact that to get to this function, the caller
1624 * has most likely already called update_context_time()
1625 * and update_cgrp_time_xx() and thus both timestamp
1626 * are identical (or very close). Given that tstamp is,
1627 * already adjusted for cgroup, we could say that:
1628 * tstamp - ctx->timestamp
1629 * is equivalent to
1630 * tstamp - cgrp->timestamp.
1632 * Then, in perf_output_read(), the calculation would
1633 * work with no changes because:
1634 * - event is guaranteed scheduled in
1635 * - no scheduled out in between
1636 * - thus the timestamp would be the same
1638 * But this is a bit hairy.
1640 * So instead, we have an explicit cgroup call to remain
1641 * within the time time source all along. We believe it
1642 * is cleaner and simpler to understand.
1644 if (is_cgroup_event(event))
1645 perf_cgroup_set_shadow_time(event, tstamp);
1646 else
1647 event->shadow_ctx_time = tstamp - ctx->timestamp;
1650 #define MAX_INTERRUPTS (~0ULL)
1652 static void perf_log_throttle(struct perf_event *event, int enable);
1654 static int
1655 event_sched_in(struct perf_event *event,
1656 struct perf_cpu_context *cpuctx,
1657 struct perf_event_context *ctx)
1659 u64 tstamp = perf_event_time(event);
1660 int ret = 0;
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 perf_pmu_disable(event->pmu);
1685 if (event->pmu->add(event, PERF_EF_START)) {
1686 event->state = PERF_EVENT_STATE_INACTIVE;
1687 event->oncpu = -1;
1688 ret = -EAGAIN;
1689 goto out;
1692 event->tstamp_running += tstamp - event->tstamp_stopped;
1694 perf_set_shadow_time(event, ctx, tstamp);
1696 if (!is_software_event(event))
1697 cpuctx->active_oncpu++;
1698 ctx->nr_active++;
1699 if (event->attr.freq && event->attr.sample_freq)
1700 ctx->nr_freq++;
1702 if (event->attr.exclusive)
1703 cpuctx->exclusive = 1;
1705 out:
1706 perf_pmu_enable(event->pmu);
1708 return ret;
1711 static int
1712 group_sched_in(struct perf_event *group_event,
1713 struct perf_cpu_context *cpuctx,
1714 struct perf_event_context *ctx)
1716 struct perf_event *event, *partial_group = NULL;
1717 struct pmu *pmu = group_event->pmu;
1718 u64 now = ctx->time;
1719 bool simulate = false;
1721 if (group_event->state == PERF_EVENT_STATE_OFF)
1722 return 0;
1724 pmu->start_txn(pmu);
1726 if (event_sched_in(group_event, cpuctx, ctx)) {
1727 pmu->cancel_txn(pmu);
1728 perf_cpu_hrtimer_restart(cpuctx);
1729 return -EAGAIN;
1733 * Schedule in siblings as one group (if any):
1735 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1736 if (event_sched_in(event, cpuctx, ctx)) {
1737 partial_group = event;
1738 goto group_error;
1742 if (!pmu->commit_txn(pmu))
1743 return 0;
1745 group_error:
1747 * Groups can be scheduled in as one unit only, so undo any
1748 * partial group before returning:
1749 * The events up to the failed event are scheduled out normally,
1750 * tstamp_stopped will be updated.
1752 * The failed events and the remaining siblings need to have
1753 * their timings updated as if they had gone thru event_sched_in()
1754 * and event_sched_out(). This is required to get consistent timings
1755 * across the group. This also takes care of the case where the group
1756 * could never be scheduled by ensuring tstamp_stopped is set to mark
1757 * the time the event was actually stopped, such that time delta
1758 * calculation in update_event_times() is correct.
1760 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1761 if (event == partial_group)
1762 simulate = true;
1764 if (simulate) {
1765 event->tstamp_running += now - event->tstamp_stopped;
1766 event->tstamp_stopped = now;
1767 } else {
1768 event_sched_out(event, cpuctx, ctx);
1771 event_sched_out(group_event, cpuctx, ctx);
1773 pmu->cancel_txn(pmu);
1775 perf_cpu_hrtimer_restart(cpuctx);
1777 return -EAGAIN;
1781 * Work out whether we can put this event group on the CPU now.
1783 static int group_can_go_on(struct perf_event *event,
1784 struct perf_cpu_context *cpuctx,
1785 int can_add_hw)
1788 * Groups consisting entirely of software events can always go on.
1790 if (event->group_flags & PERF_GROUP_SOFTWARE)
1791 return 1;
1793 * If an exclusive group is already on, no other hardware
1794 * events can go on.
1796 if (cpuctx->exclusive)
1797 return 0;
1799 * If this group is exclusive and there are already
1800 * events on the CPU, it can't go on.
1802 if (event->attr.exclusive && cpuctx->active_oncpu)
1803 return 0;
1805 * Otherwise, try to add it if all previous groups were able
1806 * to go on.
1808 return can_add_hw;
1811 static void add_event_to_ctx(struct perf_event *event,
1812 struct perf_event_context *ctx)
1814 u64 tstamp = perf_event_time(event);
1816 list_add_event(event, ctx);
1817 perf_group_attach(event);
1818 event->tstamp_enabled = tstamp;
1819 event->tstamp_running = tstamp;
1820 event->tstamp_stopped = tstamp;
1823 static void task_ctx_sched_out(struct perf_event_context *ctx);
1824 static void
1825 ctx_sched_in(struct perf_event_context *ctx,
1826 struct perf_cpu_context *cpuctx,
1827 enum event_type_t event_type,
1828 struct task_struct *task);
1830 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
1831 struct perf_event_context *ctx,
1832 struct task_struct *task)
1834 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
1835 if (ctx)
1836 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
1837 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
1838 if (ctx)
1839 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
1843 * Cross CPU call to install and enable a performance event
1845 * Must be called with ctx->mutex held
1847 static int __perf_install_in_context(void *info)
1849 struct perf_event *event = info;
1850 struct perf_event_context *ctx = event->ctx;
1851 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1852 struct perf_event_context *task_ctx = cpuctx->task_ctx;
1853 struct task_struct *task = current;
1855 perf_ctx_lock(cpuctx, task_ctx);
1856 perf_pmu_disable(cpuctx->ctx.pmu);
1859 * If there was an active task_ctx schedule it out.
1861 if (task_ctx)
1862 task_ctx_sched_out(task_ctx);
1865 * If the context we're installing events in is not the
1866 * active task_ctx, flip them.
1868 if (ctx->task && task_ctx != ctx) {
1869 if (task_ctx)
1870 raw_spin_unlock(&task_ctx->lock);
1871 raw_spin_lock(&ctx->lock);
1872 task_ctx = ctx;
1875 if (task_ctx) {
1876 cpuctx->task_ctx = task_ctx;
1877 task = task_ctx->task;
1880 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
1882 update_context_time(ctx);
1884 * update cgrp time only if current cgrp
1885 * matches event->cgrp. Must be done before
1886 * calling add_event_to_ctx()
1888 update_cgrp_time_from_event(event);
1890 add_event_to_ctx(event, ctx);
1893 * Schedule everything back in
1895 perf_event_sched_in(cpuctx, task_ctx, task);
1897 perf_pmu_enable(cpuctx->ctx.pmu);
1898 perf_ctx_unlock(cpuctx, task_ctx);
1900 return 0;
1904 * Attach a performance event to a context
1906 * First we add the event to the list with the hardware enable bit
1907 * in event->hw_config cleared.
1909 * If the event is attached to a task which is on a CPU we use a smp
1910 * call to enable it in the task context. The task might have been
1911 * scheduled away, but we check this in the smp call again.
1913 static void
1914 perf_install_in_context(struct perf_event_context *ctx,
1915 struct perf_event *event,
1916 int cpu)
1918 struct task_struct *task = ctx->task;
1920 lockdep_assert_held(&ctx->mutex);
1922 event->ctx = ctx;
1923 if (event->cpu != -1)
1924 event->cpu = cpu;
1926 if (!task) {
1928 * Per cpu events are installed via an smp call and
1929 * the install is always successful.
1931 cpu_function_call(cpu, __perf_install_in_context, event);
1932 return;
1935 retry:
1936 if (!task_function_call(task, __perf_install_in_context, event))
1937 return;
1939 raw_spin_lock_irq(&ctx->lock);
1941 * If we failed to find a running task, but find the context active now
1942 * that we've acquired the ctx->lock, retry.
1944 if (ctx->is_active) {
1945 raw_spin_unlock_irq(&ctx->lock);
1946 goto retry;
1950 * Since the task isn't running, its safe to add the event, us holding
1951 * the ctx->lock ensures the task won't get scheduled in.
1953 add_event_to_ctx(event, ctx);
1954 raw_spin_unlock_irq(&ctx->lock);
1958 * Put a event into inactive state and update time fields.
1959 * Enabling the leader of a group effectively enables all
1960 * the group members that aren't explicitly disabled, so we
1961 * have to update their ->tstamp_enabled also.
1962 * Note: this works for group members as well as group leaders
1963 * since the non-leader members' sibling_lists will be empty.
1965 static void __perf_event_mark_enabled(struct perf_event *event)
1967 struct perf_event *sub;
1968 u64 tstamp = perf_event_time(event);
1970 event->state = PERF_EVENT_STATE_INACTIVE;
1971 event->tstamp_enabled = tstamp - event->total_time_enabled;
1972 list_for_each_entry(sub, &event->sibling_list, group_entry) {
1973 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
1974 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
1979 * Cross CPU call to enable a performance event
1981 static int __perf_event_enable(void *info)
1983 struct perf_event *event = info;
1984 struct perf_event_context *ctx = event->ctx;
1985 struct perf_event *leader = event->group_leader;
1986 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1987 int err;
1990 * There's a time window between 'ctx->is_active' check
1991 * in perf_event_enable function and this place having:
1992 * - IRQs on
1993 * - ctx->lock unlocked
1995 * where the task could be killed and 'ctx' deactivated
1996 * by perf_event_exit_task.
1998 if (!ctx->is_active)
1999 return -EINVAL;
2001 raw_spin_lock(&ctx->lock);
2002 update_context_time(ctx);
2004 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2005 goto unlock;
2008 * set current task's cgroup time reference point
2010 perf_cgroup_set_timestamp(current, ctx);
2012 __perf_event_mark_enabled(event);
2014 if (!event_filter_match(event)) {
2015 if (is_cgroup_event(event))
2016 perf_cgroup_defer_enabled(event);
2017 goto unlock;
2021 * If the event is in a group and isn't the group leader,
2022 * then don't put it on unless the group is on.
2024 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
2025 goto unlock;
2027 if (!group_can_go_on(event, cpuctx, 1)) {
2028 err = -EEXIST;
2029 } else {
2030 if (event == leader)
2031 err = group_sched_in(event, cpuctx, ctx);
2032 else
2033 err = event_sched_in(event, cpuctx, ctx);
2036 if (err) {
2038 * If this event can't go on and it's part of a
2039 * group, then the whole group has to come off.
2041 if (leader != event) {
2042 group_sched_out(leader, cpuctx, ctx);
2043 perf_cpu_hrtimer_restart(cpuctx);
2045 if (leader->attr.pinned) {
2046 update_group_times(leader);
2047 leader->state = PERF_EVENT_STATE_ERROR;
2051 unlock:
2052 raw_spin_unlock(&ctx->lock);
2054 return 0;
2058 * Enable a event.
2060 * If event->ctx is a cloned context, callers must make sure that
2061 * every task struct that event->ctx->task could possibly point to
2062 * remains valid. This condition is satisfied when called through
2063 * perf_event_for_each_child or perf_event_for_each as described
2064 * for perf_event_disable.
2066 void perf_event_enable(struct perf_event *event)
2068 struct perf_event_context *ctx = event->ctx;
2069 struct task_struct *task = ctx->task;
2071 if (!task) {
2073 * Enable the event on the cpu that it's on
2075 cpu_function_call(event->cpu, __perf_event_enable, event);
2076 return;
2079 raw_spin_lock_irq(&ctx->lock);
2080 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2081 goto out;
2084 * If the event is in error state, clear that first.
2085 * That way, if we see the event in error state below, we
2086 * know that it has gone back into error state, as distinct
2087 * from the task having been scheduled away before the
2088 * cross-call arrived.
2090 if (event->state == PERF_EVENT_STATE_ERROR)
2091 event->state = PERF_EVENT_STATE_OFF;
2093 retry:
2094 if (!ctx->is_active) {
2095 __perf_event_mark_enabled(event);
2096 goto out;
2099 raw_spin_unlock_irq(&ctx->lock);
2101 if (!task_function_call(task, __perf_event_enable, event))
2102 return;
2104 raw_spin_lock_irq(&ctx->lock);
2107 * If the context is active and the event is still off,
2108 * we need to retry the cross-call.
2110 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
2112 * task could have been flipped by a concurrent
2113 * perf_event_context_sched_out()
2115 task = ctx->task;
2116 goto retry;
2119 out:
2120 raw_spin_unlock_irq(&ctx->lock);
2122 EXPORT_SYMBOL_GPL(perf_event_enable);
2124 int perf_event_refresh(struct perf_event *event, int refresh)
2127 * not supported on inherited events
2129 if (event->attr.inherit || !is_sampling_event(event))
2130 return -EINVAL;
2132 atomic_add(refresh, &event->event_limit);
2133 perf_event_enable(event);
2135 return 0;
2137 EXPORT_SYMBOL_GPL(perf_event_refresh);
2139 static void ctx_sched_out(struct perf_event_context *ctx,
2140 struct perf_cpu_context *cpuctx,
2141 enum event_type_t event_type)
2143 struct perf_event *event;
2144 int is_active = ctx->is_active;
2146 ctx->is_active &= ~event_type;
2147 if (likely(!ctx->nr_events))
2148 return;
2150 update_context_time(ctx);
2151 update_cgrp_time_from_cpuctx(cpuctx);
2152 if (!ctx->nr_active)
2153 return;
2155 perf_pmu_disable(ctx->pmu);
2156 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2157 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2158 group_sched_out(event, cpuctx, ctx);
2161 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2162 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2163 group_sched_out(event, cpuctx, ctx);
2165 perf_pmu_enable(ctx->pmu);
2169 * Test whether two contexts are equivalent, i.e. whether they have both been
2170 * cloned from the same version of the same context.
2172 * Equivalence is measured using a generation number in the context that is
2173 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2174 * and list_del_event().
2176 static int context_equiv(struct perf_event_context *ctx1,
2177 struct perf_event_context *ctx2)
2179 /* Pinning disables the swap optimization */
2180 if (ctx1->pin_count || ctx2->pin_count)
2181 return 0;
2183 /* If ctx1 is the parent of ctx2 */
2184 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2185 return 1;
2187 /* If ctx2 is the parent of ctx1 */
2188 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2189 return 1;
2192 * If ctx1 and ctx2 have the same parent; we flatten the parent
2193 * hierarchy, see perf_event_init_context().
2195 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2196 ctx1->parent_gen == ctx2->parent_gen)
2197 return 1;
2199 /* Unmatched */
2200 return 0;
2203 static void __perf_event_sync_stat(struct perf_event *event,
2204 struct perf_event *next_event)
2206 u64 value;
2208 if (!event->attr.inherit_stat)
2209 return;
2212 * Update the event value, we cannot use perf_event_read()
2213 * because we're in the middle of a context switch and have IRQs
2214 * disabled, which upsets smp_call_function_single(), however
2215 * we know the event must be on the current CPU, therefore we
2216 * don't need to use it.
2218 switch (event->state) {
2219 case PERF_EVENT_STATE_ACTIVE:
2220 event->pmu->read(event);
2221 /* fall-through */
2223 case PERF_EVENT_STATE_INACTIVE:
2224 update_event_times(event);
2225 break;
2227 default:
2228 break;
2232 * In order to keep per-task stats reliable we need to flip the event
2233 * values when we flip the contexts.
2235 value = local64_read(&next_event->count);
2236 value = local64_xchg(&event->count, value);
2237 local64_set(&next_event->count, value);
2239 swap(event->total_time_enabled, next_event->total_time_enabled);
2240 swap(event->total_time_running, next_event->total_time_running);
2243 * Since we swizzled the values, update the user visible data too.
2245 perf_event_update_userpage(event);
2246 perf_event_update_userpage(next_event);
2249 static void perf_event_sync_stat(struct perf_event_context *ctx,
2250 struct perf_event_context *next_ctx)
2252 struct perf_event *event, *next_event;
2254 if (!ctx->nr_stat)
2255 return;
2257 update_context_time(ctx);
2259 event = list_first_entry(&ctx->event_list,
2260 struct perf_event, event_entry);
2262 next_event = list_first_entry(&next_ctx->event_list,
2263 struct perf_event, event_entry);
2265 while (&event->event_entry != &ctx->event_list &&
2266 &next_event->event_entry != &next_ctx->event_list) {
2268 __perf_event_sync_stat(event, next_event);
2270 event = list_next_entry(event, event_entry);
2271 next_event = list_next_entry(next_event, event_entry);
2275 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2276 struct task_struct *next)
2278 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2279 struct perf_event_context *next_ctx;
2280 struct perf_event_context *parent, *next_parent;
2281 struct perf_cpu_context *cpuctx;
2282 int do_switch = 1;
2284 if (likely(!ctx))
2285 return;
2287 cpuctx = __get_cpu_context(ctx);
2288 if (!cpuctx->task_ctx)
2289 return;
2291 rcu_read_lock();
2292 next_ctx = next->perf_event_ctxp[ctxn];
2293 if (!next_ctx)
2294 goto unlock;
2296 parent = rcu_dereference(ctx->parent_ctx);
2297 next_parent = rcu_dereference(next_ctx->parent_ctx);
2299 /* If neither context have a parent context; they cannot be clones. */
2300 if (!parent && !next_parent)
2301 goto unlock;
2303 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2305 * Looks like the two contexts are clones, so we might be
2306 * able to optimize the context switch. We lock both
2307 * contexts and check that they are clones under the
2308 * lock (including re-checking that neither has been
2309 * uncloned in the meantime). It doesn't matter which
2310 * order we take the locks because no other cpu could
2311 * be trying to lock both of these tasks.
2313 raw_spin_lock(&ctx->lock);
2314 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2315 if (context_equiv(ctx, next_ctx)) {
2317 * XXX do we need a memory barrier of sorts
2318 * wrt to rcu_dereference() of perf_event_ctxp
2320 task->perf_event_ctxp[ctxn] = next_ctx;
2321 next->perf_event_ctxp[ctxn] = ctx;
2322 ctx->task = next;
2323 next_ctx->task = task;
2324 do_switch = 0;
2326 perf_event_sync_stat(ctx, next_ctx);
2328 raw_spin_unlock(&next_ctx->lock);
2329 raw_spin_unlock(&ctx->lock);
2331 unlock:
2332 rcu_read_unlock();
2334 if (do_switch) {
2335 raw_spin_lock(&ctx->lock);
2336 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2337 cpuctx->task_ctx = NULL;
2338 raw_spin_unlock(&ctx->lock);
2342 #define for_each_task_context_nr(ctxn) \
2343 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2346 * Called from scheduler to remove the events of the current task,
2347 * with interrupts disabled.
2349 * We stop each event and update the event value in event->count.
2351 * This does not protect us against NMI, but disable()
2352 * sets the disabled bit in the control field of event _before_
2353 * accessing the event control register. If a NMI hits, then it will
2354 * not restart the event.
2356 void __perf_event_task_sched_out(struct task_struct *task,
2357 struct task_struct *next)
2359 int ctxn;
2361 for_each_task_context_nr(ctxn)
2362 perf_event_context_sched_out(task, ctxn, next);
2365 * if cgroup events exist on this CPU, then we need
2366 * to check if we have to switch out PMU state.
2367 * cgroup event are system-wide mode only
2369 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2370 perf_cgroup_sched_out(task, next);
2373 static void task_ctx_sched_out(struct perf_event_context *ctx)
2375 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2377 if (!cpuctx->task_ctx)
2378 return;
2380 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2381 return;
2383 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2384 cpuctx->task_ctx = NULL;
2388 * Called with IRQs disabled
2390 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2391 enum event_type_t event_type)
2393 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2396 static void
2397 ctx_pinned_sched_in(struct perf_event_context *ctx,
2398 struct perf_cpu_context *cpuctx)
2400 struct perf_event *event;
2402 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2403 if (event->state <= PERF_EVENT_STATE_OFF)
2404 continue;
2405 if (!event_filter_match(event))
2406 continue;
2408 /* may need to reset tstamp_enabled */
2409 if (is_cgroup_event(event))
2410 perf_cgroup_mark_enabled(event, ctx);
2412 if (group_can_go_on(event, cpuctx, 1))
2413 group_sched_in(event, cpuctx, ctx);
2416 * If this pinned group hasn't been scheduled,
2417 * put it in error state.
2419 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2420 update_group_times(event);
2421 event->state = PERF_EVENT_STATE_ERROR;
2426 static void
2427 ctx_flexible_sched_in(struct perf_event_context *ctx,
2428 struct perf_cpu_context *cpuctx)
2430 struct perf_event *event;
2431 int can_add_hw = 1;
2433 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2434 /* Ignore events in OFF or ERROR state */
2435 if (event->state <= PERF_EVENT_STATE_OFF)
2436 continue;
2438 * Listen to the 'cpu' scheduling filter constraint
2439 * of events:
2441 if (!event_filter_match(event))
2442 continue;
2444 /* may need to reset tstamp_enabled */
2445 if (is_cgroup_event(event))
2446 perf_cgroup_mark_enabled(event, ctx);
2448 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2449 if (group_sched_in(event, cpuctx, ctx))
2450 can_add_hw = 0;
2455 static void
2456 ctx_sched_in(struct perf_event_context *ctx,
2457 struct perf_cpu_context *cpuctx,
2458 enum event_type_t event_type,
2459 struct task_struct *task)
2461 u64 now;
2462 int is_active = ctx->is_active;
2464 ctx->is_active |= event_type;
2465 if (likely(!ctx->nr_events))
2466 return;
2468 now = perf_clock();
2469 ctx->timestamp = now;
2470 perf_cgroup_set_timestamp(task, ctx);
2472 * First go through the list and put on any pinned groups
2473 * in order to give them the best chance of going on.
2475 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2476 ctx_pinned_sched_in(ctx, cpuctx);
2478 /* Then walk through the lower prio flexible groups */
2479 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2480 ctx_flexible_sched_in(ctx, cpuctx);
2483 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2484 enum event_type_t event_type,
2485 struct task_struct *task)
2487 struct perf_event_context *ctx = &cpuctx->ctx;
2489 ctx_sched_in(ctx, cpuctx, event_type, task);
2492 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2493 struct task_struct *task)
2495 struct perf_cpu_context *cpuctx;
2497 cpuctx = __get_cpu_context(ctx);
2498 if (cpuctx->task_ctx == ctx)
2499 return;
2501 perf_ctx_lock(cpuctx, ctx);
2502 perf_pmu_disable(ctx->pmu);
2504 * We want to keep the following priority order:
2505 * cpu pinned (that don't need to move), task pinned,
2506 * cpu flexible, task flexible.
2508 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2510 if (ctx->nr_events)
2511 cpuctx->task_ctx = ctx;
2513 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2515 perf_pmu_enable(ctx->pmu);
2516 perf_ctx_unlock(cpuctx, ctx);
2519 * Since these rotations are per-cpu, we need to ensure the
2520 * cpu-context we got scheduled on is actually rotating.
2522 perf_pmu_rotate_start(ctx->pmu);
2526 * When sampling the branck stack in system-wide, it may be necessary
2527 * to flush the stack on context switch. This happens when the branch
2528 * stack does not tag its entries with the pid of the current task.
2529 * Otherwise it becomes impossible to associate a branch entry with a
2530 * task. This ambiguity is more likely to appear when the branch stack
2531 * supports priv level filtering and the user sets it to monitor only
2532 * at the user level (which could be a useful measurement in system-wide
2533 * mode). In that case, the risk is high of having a branch stack with
2534 * branch from multiple tasks. Flushing may mean dropping the existing
2535 * entries or stashing them somewhere in the PMU specific code layer.
2537 * This function provides the context switch callback to the lower code
2538 * layer. It is invoked ONLY when there is at least one system-wide context
2539 * with at least one active event using taken branch sampling.
2541 static void perf_branch_stack_sched_in(struct task_struct *prev,
2542 struct task_struct *task)
2544 struct perf_cpu_context *cpuctx;
2545 struct pmu *pmu;
2546 unsigned long flags;
2548 /* no need to flush branch stack if not changing task */
2549 if (prev == task)
2550 return;
2552 local_irq_save(flags);
2554 rcu_read_lock();
2556 list_for_each_entry_rcu(pmu, &pmus, entry) {
2557 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2560 * check if the context has at least one
2561 * event using PERF_SAMPLE_BRANCH_STACK
2563 if (cpuctx->ctx.nr_branch_stack > 0
2564 && pmu->flush_branch_stack) {
2566 pmu = cpuctx->ctx.pmu;
2568 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2570 perf_pmu_disable(pmu);
2572 pmu->flush_branch_stack();
2574 perf_pmu_enable(pmu);
2576 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2580 rcu_read_unlock();
2582 local_irq_restore(flags);
2586 * Called from scheduler to add the events of the current task
2587 * with interrupts disabled.
2589 * We restore the event value and then enable it.
2591 * This does not protect us against NMI, but enable()
2592 * sets the enabled bit in the control field of event _before_
2593 * accessing the event control register. If a NMI hits, then it will
2594 * keep the event running.
2596 void __perf_event_task_sched_in(struct task_struct *prev,
2597 struct task_struct *task)
2599 struct perf_event_context *ctx;
2600 int ctxn;
2602 for_each_task_context_nr(ctxn) {
2603 ctx = task->perf_event_ctxp[ctxn];
2604 if (likely(!ctx))
2605 continue;
2607 perf_event_context_sched_in(ctx, task);
2610 * if cgroup events exist on this CPU, then we need
2611 * to check if we have to switch in PMU state.
2612 * cgroup event are system-wide mode only
2614 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2615 perf_cgroup_sched_in(prev, task);
2617 /* check for system-wide branch_stack events */
2618 if (atomic_read(&__get_cpu_var(perf_branch_stack_events)))
2619 perf_branch_stack_sched_in(prev, task);
2622 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2624 u64 frequency = event->attr.sample_freq;
2625 u64 sec = NSEC_PER_SEC;
2626 u64 divisor, dividend;
2628 int count_fls, nsec_fls, frequency_fls, sec_fls;
2630 count_fls = fls64(count);
2631 nsec_fls = fls64(nsec);
2632 frequency_fls = fls64(frequency);
2633 sec_fls = 30;
2636 * We got @count in @nsec, with a target of sample_freq HZ
2637 * the target period becomes:
2639 * @count * 10^9
2640 * period = -------------------
2641 * @nsec * sample_freq
2646 * Reduce accuracy by one bit such that @a and @b converge
2647 * to a similar magnitude.
2649 #define REDUCE_FLS(a, b) \
2650 do { \
2651 if (a##_fls > b##_fls) { \
2652 a >>= 1; \
2653 a##_fls--; \
2654 } else { \
2655 b >>= 1; \
2656 b##_fls--; \
2658 } while (0)
2661 * Reduce accuracy until either term fits in a u64, then proceed with
2662 * the other, so that finally we can do a u64/u64 division.
2664 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2665 REDUCE_FLS(nsec, frequency);
2666 REDUCE_FLS(sec, count);
2669 if (count_fls + sec_fls > 64) {
2670 divisor = nsec * frequency;
2672 while (count_fls + sec_fls > 64) {
2673 REDUCE_FLS(count, sec);
2674 divisor >>= 1;
2677 dividend = count * sec;
2678 } else {
2679 dividend = count * sec;
2681 while (nsec_fls + frequency_fls > 64) {
2682 REDUCE_FLS(nsec, frequency);
2683 dividend >>= 1;
2686 divisor = nsec * frequency;
2689 if (!divisor)
2690 return dividend;
2692 return div64_u64(dividend, divisor);
2695 static DEFINE_PER_CPU(int, perf_throttled_count);
2696 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2698 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2700 struct hw_perf_event *hwc = &event->hw;
2701 s64 period, sample_period;
2702 s64 delta;
2704 period = perf_calculate_period(event, nsec, count);
2706 delta = (s64)(period - hwc->sample_period);
2707 delta = (delta + 7) / 8; /* low pass filter */
2709 sample_period = hwc->sample_period + delta;
2711 if (!sample_period)
2712 sample_period = 1;
2714 hwc->sample_period = sample_period;
2716 if (local64_read(&hwc->period_left) > 8*sample_period) {
2717 if (disable)
2718 event->pmu->stop(event, PERF_EF_UPDATE);
2720 local64_set(&hwc->period_left, 0);
2722 if (disable)
2723 event->pmu->start(event, PERF_EF_RELOAD);
2728 * combine freq adjustment with unthrottling to avoid two passes over the
2729 * events. At the same time, make sure, having freq events does not change
2730 * the rate of unthrottling as that would introduce bias.
2732 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
2733 int needs_unthr)
2735 struct perf_event *event;
2736 struct hw_perf_event *hwc;
2737 u64 now, period = TICK_NSEC;
2738 s64 delta;
2741 * only need to iterate over all events iff:
2742 * - context have events in frequency mode (needs freq adjust)
2743 * - there are events to unthrottle on this cpu
2745 if (!(ctx->nr_freq || needs_unthr))
2746 return;
2748 raw_spin_lock(&ctx->lock);
2749 perf_pmu_disable(ctx->pmu);
2751 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
2752 if (event->state != PERF_EVENT_STATE_ACTIVE)
2753 continue;
2755 if (!event_filter_match(event))
2756 continue;
2758 perf_pmu_disable(event->pmu);
2760 hwc = &event->hw;
2762 if (hwc->interrupts == MAX_INTERRUPTS) {
2763 hwc->interrupts = 0;
2764 perf_log_throttle(event, 1);
2765 event->pmu->start(event, 0);
2768 if (!event->attr.freq || !event->attr.sample_freq)
2769 goto next;
2772 * stop the event and update event->count
2774 event->pmu->stop(event, PERF_EF_UPDATE);
2776 now = local64_read(&event->count);
2777 delta = now - hwc->freq_count_stamp;
2778 hwc->freq_count_stamp = now;
2781 * restart the event
2782 * reload only if value has changed
2783 * we have stopped the event so tell that
2784 * to perf_adjust_period() to avoid stopping it
2785 * twice.
2787 if (delta > 0)
2788 perf_adjust_period(event, period, delta, false);
2790 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
2791 next:
2792 perf_pmu_enable(event->pmu);
2795 perf_pmu_enable(ctx->pmu);
2796 raw_spin_unlock(&ctx->lock);
2800 * Round-robin a context's events:
2802 static void rotate_ctx(struct perf_event_context *ctx)
2805 * Rotate the first entry last of non-pinned groups. Rotation might be
2806 * disabled by the inheritance code.
2808 if (!ctx->rotate_disable)
2809 list_rotate_left(&ctx->flexible_groups);
2813 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
2814 * because they're strictly cpu affine and rotate_start is called with IRQs
2815 * disabled, while rotate_context is called from IRQ context.
2817 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
2819 struct perf_event_context *ctx = NULL;
2820 int rotate = 0, remove = 1;
2822 if (cpuctx->ctx.nr_events) {
2823 remove = 0;
2824 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
2825 rotate = 1;
2828 ctx = cpuctx->task_ctx;
2829 if (ctx && ctx->nr_events) {
2830 remove = 0;
2831 if (ctx->nr_events != ctx->nr_active)
2832 rotate = 1;
2835 if (!rotate)
2836 goto done;
2838 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2839 perf_pmu_disable(cpuctx->ctx.pmu);
2841 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2842 if (ctx)
2843 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
2845 rotate_ctx(&cpuctx->ctx);
2846 if (ctx)
2847 rotate_ctx(ctx);
2849 perf_event_sched_in(cpuctx, ctx, current);
2851 perf_pmu_enable(cpuctx->ctx.pmu);
2852 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2853 done:
2854 if (remove)
2855 list_del_init(&cpuctx->rotation_list);
2857 return rotate;
2860 #ifdef CONFIG_NO_HZ_FULL
2861 bool perf_event_can_stop_tick(void)
2863 if (atomic_read(&nr_freq_events) ||
2864 __this_cpu_read(perf_throttled_count))
2865 return false;
2866 else
2867 return true;
2869 #endif
2871 void perf_event_task_tick(void)
2873 struct list_head *head = &__get_cpu_var(rotation_list);
2874 struct perf_cpu_context *cpuctx, *tmp;
2875 struct perf_event_context *ctx;
2876 int throttled;
2878 WARN_ON(!irqs_disabled());
2880 __this_cpu_inc(perf_throttled_seq);
2881 throttled = __this_cpu_xchg(perf_throttled_count, 0);
2883 list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) {
2884 ctx = &cpuctx->ctx;
2885 perf_adjust_freq_unthr_context(ctx, throttled);
2887 ctx = cpuctx->task_ctx;
2888 if (ctx)
2889 perf_adjust_freq_unthr_context(ctx, throttled);
2893 static int event_enable_on_exec(struct perf_event *event,
2894 struct perf_event_context *ctx)
2896 if (!event->attr.enable_on_exec)
2897 return 0;
2899 event->attr.enable_on_exec = 0;
2900 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2901 return 0;
2903 __perf_event_mark_enabled(event);
2905 return 1;
2909 * Enable all of a task's events that have been marked enable-on-exec.
2910 * This expects task == current.
2912 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
2914 struct perf_event *event;
2915 unsigned long flags;
2916 int enabled = 0;
2917 int ret;
2919 local_irq_save(flags);
2920 if (!ctx || !ctx->nr_events)
2921 goto out;
2924 * We must ctxsw out cgroup events to avoid conflict
2925 * when invoking perf_task_event_sched_in() later on
2926 * in this function. Otherwise we end up trying to
2927 * ctxswin cgroup events which are already scheduled
2928 * in.
2930 perf_cgroup_sched_out(current, NULL);
2932 raw_spin_lock(&ctx->lock);
2933 task_ctx_sched_out(ctx);
2935 list_for_each_entry(event, &ctx->event_list, event_entry) {
2936 ret = event_enable_on_exec(event, ctx);
2937 if (ret)
2938 enabled = 1;
2942 * Unclone this context if we enabled any event.
2944 if (enabled)
2945 unclone_ctx(ctx);
2947 raw_spin_unlock(&ctx->lock);
2950 * Also calls ctxswin for cgroup events, if any:
2952 perf_event_context_sched_in(ctx, ctx->task);
2953 out:
2954 local_irq_restore(flags);
2958 * Cross CPU call to read the hardware event
2960 static void __perf_event_read(void *info)
2962 struct perf_event *event = info;
2963 struct perf_event_context *ctx = event->ctx;
2964 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2967 * If this is a task context, we need to check whether it is
2968 * the current task context of this cpu. If not it has been
2969 * scheduled out before the smp call arrived. In that case
2970 * event->count would have been updated to a recent sample
2971 * when the event was scheduled out.
2973 if (ctx->task && cpuctx->task_ctx != ctx)
2974 return;
2976 raw_spin_lock(&ctx->lock);
2977 if (ctx->is_active) {
2978 update_context_time(ctx);
2979 update_cgrp_time_from_event(event);
2981 update_event_times(event);
2982 if (event->state == PERF_EVENT_STATE_ACTIVE)
2983 event->pmu->read(event);
2984 raw_spin_unlock(&ctx->lock);
2987 static inline u64 perf_event_count(struct perf_event *event)
2989 return local64_read(&event->count) + atomic64_read(&event->child_count);
2992 static u64 perf_event_read(struct perf_event *event)
2995 * If event is enabled and currently active on a CPU, update the
2996 * value in the event structure:
2998 if (event->state == PERF_EVENT_STATE_ACTIVE) {
2999 smp_call_function_single(event->oncpu,
3000 __perf_event_read, event, 1);
3001 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3002 struct perf_event_context *ctx = event->ctx;
3003 unsigned long flags;
3005 raw_spin_lock_irqsave(&ctx->lock, flags);
3007 * may read while context is not active
3008 * (e.g., thread is blocked), in that case
3009 * we cannot update context time
3011 if (ctx->is_active) {
3012 update_context_time(ctx);
3013 update_cgrp_time_from_event(event);
3015 update_event_times(event);
3016 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3019 return perf_event_count(event);
3023 * Initialize the perf_event context in a task_struct:
3025 static void __perf_event_init_context(struct perf_event_context *ctx)
3027 raw_spin_lock_init(&ctx->lock);
3028 mutex_init(&ctx->mutex);
3029 INIT_LIST_HEAD(&ctx->pinned_groups);
3030 INIT_LIST_HEAD(&ctx->flexible_groups);
3031 INIT_LIST_HEAD(&ctx->event_list);
3032 atomic_set(&ctx->refcount, 1);
3035 static struct perf_event_context *
3036 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3038 struct perf_event_context *ctx;
3040 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3041 if (!ctx)
3042 return NULL;
3044 __perf_event_init_context(ctx);
3045 if (task) {
3046 ctx->task = task;
3047 get_task_struct(task);
3049 ctx->pmu = pmu;
3051 return ctx;
3054 static struct task_struct *
3055 find_lively_task_by_vpid(pid_t vpid)
3057 struct task_struct *task;
3058 int err;
3060 rcu_read_lock();
3061 if (!vpid)
3062 task = current;
3063 else
3064 task = find_task_by_vpid(vpid);
3065 if (task)
3066 get_task_struct(task);
3067 rcu_read_unlock();
3069 if (!task)
3070 return ERR_PTR(-ESRCH);
3072 /* Reuse ptrace permission checks for now. */
3073 err = -EACCES;
3074 if (!ptrace_may_access(task, PTRACE_MODE_READ))
3075 goto errout;
3077 return task;
3078 errout:
3079 put_task_struct(task);
3080 return ERR_PTR(err);
3085 * Returns a matching context with refcount and pincount.
3087 static struct perf_event_context *
3088 find_get_context(struct pmu *pmu, struct task_struct *task, int cpu)
3090 struct perf_event_context *ctx;
3091 struct perf_cpu_context *cpuctx;
3092 unsigned long flags;
3093 int ctxn, err;
3095 if (!task) {
3096 /* Must be root to operate on a CPU event: */
3097 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3098 return ERR_PTR(-EACCES);
3101 * We could be clever and allow to attach a event to an
3102 * offline CPU and activate it when the CPU comes up, but
3103 * that's for later.
3105 if (!cpu_online(cpu))
3106 return ERR_PTR(-ENODEV);
3108 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3109 ctx = &cpuctx->ctx;
3110 get_ctx(ctx);
3111 ++ctx->pin_count;
3113 return ctx;
3116 err = -EINVAL;
3117 ctxn = pmu->task_ctx_nr;
3118 if (ctxn < 0)
3119 goto errout;
3121 retry:
3122 ctx = perf_lock_task_context(task, ctxn, &flags);
3123 if (ctx) {
3124 unclone_ctx(ctx);
3125 ++ctx->pin_count;
3126 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3127 } else {
3128 ctx = alloc_perf_context(pmu, task);
3129 err = -ENOMEM;
3130 if (!ctx)
3131 goto errout;
3133 err = 0;
3134 mutex_lock(&task->perf_event_mutex);
3136 * If it has already passed perf_event_exit_task().
3137 * we must see PF_EXITING, it takes this mutex too.
3139 if (task->flags & PF_EXITING)
3140 err = -ESRCH;
3141 else if (task->perf_event_ctxp[ctxn])
3142 err = -EAGAIN;
3143 else {
3144 get_ctx(ctx);
3145 ++ctx->pin_count;
3146 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3148 mutex_unlock(&task->perf_event_mutex);
3150 if (unlikely(err)) {
3151 put_ctx(ctx);
3153 if (err == -EAGAIN)
3154 goto retry;
3155 goto errout;
3159 return ctx;
3161 errout:
3162 return ERR_PTR(err);
3165 static void perf_event_free_filter(struct perf_event *event);
3167 static void free_event_rcu(struct rcu_head *head)
3169 struct perf_event *event;
3171 event = container_of(head, struct perf_event, rcu_head);
3172 if (event->ns)
3173 put_pid_ns(event->ns);
3174 perf_event_free_filter(event);
3175 kfree(event);
3178 static void ring_buffer_put(struct ring_buffer *rb);
3179 static void ring_buffer_detach(struct perf_event *event, struct ring_buffer *rb);
3181 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3183 if (event->parent)
3184 return;
3186 if (has_branch_stack(event)) {
3187 if (!(event->attach_state & PERF_ATTACH_TASK))
3188 atomic_dec(&per_cpu(perf_branch_stack_events, cpu));
3190 if (is_cgroup_event(event))
3191 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3194 static void unaccount_event(struct perf_event *event)
3196 if (event->parent)
3197 return;
3199 if (event->attach_state & PERF_ATTACH_TASK)
3200 static_key_slow_dec_deferred(&perf_sched_events);
3201 if (event->attr.mmap || event->attr.mmap_data)
3202 atomic_dec(&nr_mmap_events);
3203 if (event->attr.comm)
3204 atomic_dec(&nr_comm_events);
3205 if (event->attr.task)
3206 atomic_dec(&nr_task_events);
3207 if (event->attr.freq)
3208 atomic_dec(&nr_freq_events);
3209 if (is_cgroup_event(event))
3210 static_key_slow_dec_deferred(&perf_sched_events);
3211 if (has_branch_stack(event))
3212 static_key_slow_dec_deferred(&perf_sched_events);
3214 unaccount_event_cpu(event, event->cpu);
3217 static void __free_event(struct perf_event *event)
3219 if (!event->parent) {
3220 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3221 put_callchain_buffers();
3224 if (event->destroy)
3225 event->destroy(event);
3227 if (event->ctx)
3228 put_ctx(event->ctx);
3230 call_rcu(&event->rcu_head, free_event_rcu);
3232 static void free_event(struct perf_event *event)
3234 irq_work_sync(&event->pending);
3236 unaccount_event(event);
3238 if (event->rb) {
3239 struct ring_buffer *rb;
3242 * Can happen when we close an event with re-directed output.
3244 * Since we have a 0 refcount, perf_mmap_close() will skip
3245 * over us; possibly making our ring_buffer_put() the last.
3247 mutex_lock(&event->mmap_mutex);
3248 rb = event->rb;
3249 if (rb) {
3250 rcu_assign_pointer(event->rb, NULL);
3251 ring_buffer_detach(event, rb);
3252 ring_buffer_put(rb); /* could be last */
3254 mutex_unlock(&event->mmap_mutex);
3257 if (is_cgroup_event(event))
3258 perf_detach_cgroup(event);
3261 __free_event(event);
3264 int perf_event_release_kernel(struct perf_event *event)
3266 struct perf_event_context *ctx = event->ctx;
3268 WARN_ON_ONCE(ctx->parent_ctx);
3270 * There are two ways this annotation is useful:
3272 * 1) there is a lock recursion from perf_event_exit_task
3273 * see the comment there.
3275 * 2) there is a lock-inversion with mmap_sem through
3276 * perf_event_read_group(), which takes faults while
3277 * holding ctx->mutex, however this is called after
3278 * the last filedesc died, so there is no possibility
3279 * to trigger the AB-BA case.
3281 mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
3282 raw_spin_lock_irq(&ctx->lock);
3283 perf_group_detach(event);
3284 raw_spin_unlock_irq(&ctx->lock);
3285 perf_remove_from_context(event);
3286 mutex_unlock(&ctx->mutex);
3288 free_event(event);
3290 return 0;
3292 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3295 * Called when the last reference to the file is gone.
3297 static void put_event(struct perf_event *event)
3299 struct task_struct *owner;
3301 if (!atomic_long_dec_and_test(&event->refcount))
3302 return;
3304 rcu_read_lock();
3305 owner = ACCESS_ONCE(event->owner);
3307 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3308 * !owner it means the list deletion is complete and we can indeed
3309 * free this event, otherwise we need to serialize on
3310 * owner->perf_event_mutex.
3312 smp_read_barrier_depends();
3313 if (owner) {
3315 * Since delayed_put_task_struct() also drops the last
3316 * task reference we can safely take a new reference
3317 * while holding the rcu_read_lock().
3319 get_task_struct(owner);
3321 rcu_read_unlock();
3323 if (owner) {
3324 mutex_lock(&owner->perf_event_mutex);
3326 * We have to re-check the event->owner field, if it is cleared
3327 * we raced with perf_event_exit_task(), acquiring the mutex
3328 * ensured they're done, and we can proceed with freeing the
3329 * event.
3331 if (event->owner)
3332 list_del_init(&event->owner_entry);
3333 mutex_unlock(&owner->perf_event_mutex);
3334 put_task_struct(owner);
3337 perf_event_release_kernel(event);
3340 static int perf_release(struct inode *inode, struct file *file)
3342 put_event(file->private_data);
3343 return 0;
3346 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3348 struct perf_event *child;
3349 u64 total = 0;
3351 *enabled = 0;
3352 *running = 0;
3354 mutex_lock(&event->child_mutex);
3355 total += perf_event_read(event);
3356 *enabled += event->total_time_enabled +
3357 atomic64_read(&event->child_total_time_enabled);
3358 *running += event->total_time_running +
3359 atomic64_read(&event->child_total_time_running);
3361 list_for_each_entry(child, &event->child_list, child_list) {
3362 total += perf_event_read(child);
3363 *enabled += child->total_time_enabled;
3364 *running += child->total_time_running;
3366 mutex_unlock(&event->child_mutex);
3368 return total;
3370 EXPORT_SYMBOL_GPL(perf_event_read_value);
3372 static int perf_event_read_group(struct perf_event *event,
3373 u64 read_format, char __user *buf)
3375 struct perf_event *leader = event->group_leader, *sub;
3376 int n = 0, size = 0, ret = -EFAULT;
3377 struct perf_event_context *ctx = leader->ctx;
3378 u64 values[5];
3379 u64 count, enabled, running;
3381 mutex_lock(&ctx->mutex);
3382 count = perf_event_read_value(leader, &enabled, &running);
3384 values[n++] = 1 + leader->nr_siblings;
3385 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3386 values[n++] = enabled;
3387 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3388 values[n++] = running;
3389 values[n++] = count;
3390 if (read_format & PERF_FORMAT_ID)
3391 values[n++] = primary_event_id(leader);
3393 size = n * sizeof(u64);
3395 if (copy_to_user(buf, values, size))
3396 goto unlock;
3398 ret = size;
3400 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3401 n = 0;
3403 values[n++] = perf_event_read_value(sub, &enabled, &running);
3404 if (read_format & PERF_FORMAT_ID)
3405 values[n++] = primary_event_id(sub);
3407 size = n * sizeof(u64);
3409 if (copy_to_user(buf + ret, values, size)) {
3410 ret = -EFAULT;
3411 goto unlock;
3414 ret += size;
3416 unlock:
3417 mutex_unlock(&ctx->mutex);
3419 return ret;
3422 static int perf_event_read_one(struct perf_event *event,
3423 u64 read_format, char __user *buf)
3425 u64 enabled, running;
3426 u64 values[4];
3427 int n = 0;
3429 values[n++] = perf_event_read_value(event, &enabled, &running);
3430 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3431 values[n++] = enabled;
3432 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3433 values[n++] = running;
3434 if (read_format & PERF_FORMAT_ID)
3435 values[n++] = primary_event_id(event);
3437 if (copy_to_user(buf, values, n * sizeof(u64)))
3438 return -EFAULT;
3440 return n * sizeof(u64);
3444 * Read the performance event - simple non blocking version for now
3446 static ssize_t
3447 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
3449 u64 read_format = event->attr.read_format;
3450 int ret;
3453 * Return end-of-file for a read on a event that is in
3454 * error state (i.e. because it was pinned but it couldn't be
3455 * scheduled on to the CPU at some point).
3457 if (event->state == PERF_EVENT_STATE_ERROR)
3458 return 0;
3460 if (count < event->read_size)
3461 return -ENOSPC;
3463 WARN_ON_ONCE(event->ctx->parent_ctx);
3464 if (read_format & PERF_FORMAT_GROUP)
3465 ret = perf_event_read_group(event, read_format, buf);
3466 else
3467 ret = perf_event_read_one(event, read_format, buf);
3469 return ret;
3472 static ssize_t
3473 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
3475 struct perf_event *event = file->private_data;
3477 return perf_read_hw(event, buf, count);
3480 static unsigned int perf_poll(struct file *file, poll_table *wait)
3482 struct perf_event *event = file->private_data;
3483 struct ring_buffer *rb;
3484 unsigned int events = POLL_HUP;
3487 * Pin the event->rb by taking event->mmap_mutex; otherwise
3488 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
3490 mutex_lock(&event->mmap_mutex);
3491 rb = event->rb;
3492 if (rb)
3493 events = atomic_xchg(&rb->poll, 0);
3494 mutex_unlock(&event->mmap_mutex);
3496 poll_wait(file, &event->waitq, wait);
3498 return events;
3501 static void perf_event_reset(struct perf_event *event)
3503 (void)perf_event_read(event);
3504 local64_set(&event->count, 0);
3505 perf_event_update_userpage(event);
3509 * Holding the top-level event's child_mutex means that any
3510 * descendant process that has inherited this event will block
3511 * in sync_child_event if it goes to exit, thus satisfying the
3512 * task existence requirements of perf_event_enable/disable.
3514 static void perf_event_for_each_child(struct perf_event *event,
3515 void (*func)(struct perf_event *))
3517 struct perf_event *child;
3519 WARN_ON_ONCE(event->ctx->parent_ctx);
3520 mutex_lock(&event->child_mutex);
3521 func(event);
3522 list_for_each_entry(child, &event->child_list, child_list)
3523 func(child);
3524 mutex_unlock(&event->child_mutex);
3527 static void perf_event_for_each(struct perf_event *event,
3528 void (*func)(struct perf_event *))
3530 struct perf_event_context *ctx = event->ctx;
3531 struct perf_event *sibling;
3533 WARN_ON_ONCE(ctx->parent_ctx);
3534 mutex_lock(&ctx->mutex);
3535 event = event->group_leader;
3537 perf_event_for_each_child(event, func);
3538 list_for_each_entry(sibling, &event->sibling_list, group_entry)
3539 perf_event_for_each_child(sibling, func);
3540 mutex_unlock(&ctx->mutex);
3543 static int perf_event_period(struct perf_event *event, u64 __user *arg)
3545 struct perf_event_context *ctx = event->ctx;
3546 int ret = 0, active;
3547 u64 value;
3549 if (!is_sampling_event(event))
3550 return -EINVAL;
3552 if (copy_from_user(&value, arg, sizeof(value)))
3553 return -EFAULT;
3555 if (!value)
3556 return -EINVAL;
3558 raw_spin_lock_irq(&ctx->lock);
3559 if (event->attr.freq) {
3560 if (value > sysctl_perf_event_sample_rate) {
3561 ret = -EINVAL;
3562 goto unlock;
3565 event->attr.sample_freq = value;
3566 } else {
3567 event->attr.sample_period = value;
3568 event->hw.sample_period = value;
3571 active = (event->state == PERF_EVENT_STATE_ACTIVE);
3572 if (active) {
3573 perf_pmu_disable(ctx->pmu);
3574 event->pmu->stop(event, PERF_EF_UPDATE);
3577 local64_set(&event->hw.period_left, 0);
3579 if (active) {
3580 event->pmu->start(event, PERF_EF_RELOAD);
3581 perf_pmu_enable(ctx->pmu);
3584 unlock:
3585 raw_spin_unlock_irq(&ctx->lock);
3587 return ret;
3590 static const struct file_operations perf_fops;
3592 static inline int perf_fget_light(int fd, struct fd *p)
3594 struct fd f = fdget(fd);
3595 if (!f.file)
3596 return -EBADF;
3598 if (f.file->f_op != &perf_fops) {
3599 fdput(f);
3600 return -EBADF;
3602 *p = f;
3603 return 0;
3606 static int perf_event_set_output(struct perf_event *event,
3607 struct perf_event *output_event);
3608 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
3610 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
3612 struct perf_event *event = file->private_data;
3613 void (*func)(struct perf_event *);
3614 u32 flags = arg;
3616 switch (cmd) {
3617 case PERF_EVENT_IOC_ENABLE:
3618 func = perf_event_enable;
3619 break;
3620 case PERF_EVENT_IOC_DISABLE:
3621 func = perf_event_disable;
3622 break;
3623 case PERF_EVENT_IOC_RESET:
3624 func = perf_event_reset;
3625 break;
3627 case PERF_EVENT_IOC_REFRESH:
3628 return perf_event_refresh(event, arg);
3630 case PERF_EVENT_IOC_PERIOD:
3631 return perf_event_period(event, (u64 __user *)arg);
3633 case PERF_EVENT_IOC_ID:
3635 u64 id = primary_event_id(event);
3637 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
3638 return -EFAULT;
3639 return 0;
3642 case PERF_EVENT_IOC_SET_OUTPUT:
3644 int ret;
3645 if (arg != -1) {
3646 struct perf_event *output_event;
3647 struct fd output;
3648 ret = perf_fget_light(arg, &output);
3649 if (ret)
3650 return ret;
3651 output_event = output.file->private_data;
3652 ret = perf_event_set_output(event, output_event);
3653 fdput(output);
3654 } else {
3655 ret = perf_event_set_output(event, NULL);
3657 return ret;
3660 case PERF_EVENT_IOC_SET_FILTER:
3661 return perf_event_set_filter(event, (void __user *)arg);
3663 default:
3664 return -ENOTTY;
3667 if (flags & PERF_IOC_FLAG_GROUP)
3668 perf_event_for_each(event, func);
3669 else
3670 perf_event_for_each_child(event, func);
3672 return 0;
3675 int perf_event_task_enable(void)
3677 struct perf_event *event;
3679 mutex_lock(&current->perf_event_mutex);
3680 list_for_each_entry(event, &current->perf_event_list, owner_entry)
3681 perf_event_for_each_child(event, perf_event_enable);
3682 mutex_unlock(&current->perf_event_mutex);
3684 return 0;
3687 int perf_event_task_disable(void)
3689 struct perf_event *event;
3691 mutex_lock(&current->perf_event_mutex);
3692 list_for_each_entry(event, &current->perf_event_list, owner_entry)
3693 perf_event_for_each_child(event, perf_event_disable);
3694 mutex_unlock(&current->perf_event_mutex);
3696 return 0;
3699 static int perf_event_index(struct perf_event *event)
3701 if (event->hw.state & PERF_HES_STOPPED)
3702 return 0;
3704 if (event->state != PERF_EVENT_STATE_ACTIVE)
3705 return 0;
3707 return event->pmu->event_idx(event);
3710 static void calc_timer_values(struct perf_event *event,
3711 u64 *now,
3712 u64 *enabled,
3713 u64 *running)
3715 u64 ctx_time;
3717 *now = perf_clock();
3718 ctx_time = event->shadow_ctx_time + *now;
3719 *enabled = ctx_time - event->tstamp_enabled;
3720 *running = ctx_time - event->tstamp_running;
3723 static void perf_event_init_userpage(struct perf_event *event)
3725 struct perf_event_mmap_page *userpg;
3726 struct ring_buffer *rb;
3728 rcu_read_lock();
3729 rb = rcu_dereference(event->rb);
3730 if (!rb)
3731 goto unlock;
3733 userpg = rb->user_page;
3735 /* Allow new userspace to detect that bit 0 is deprecated */
3736 userpg->cap_bit0_is_deprecated = 1;
3737 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
3739 unlock:
3740 rcu_read_unlock();
3743 void __weak arch_perf_update_userpage(struct perf_event_mmap_page *userpg, u64 now)
3748 * Callers need to ensure there can be no nesting of this function, otherwise
3749 * the seqlock logic goes bad. We can not serialize this because the arch
3750 * code calls this from NMI context.
3752 void perf_event_update_userpage(struct perf_event *event)
3754 struct perf_event_mmap_page *userpg;
3755 struct ring_buffer *rb;
3756 u64 enabled, running, now;
3758 rcu_read_lock();
3759 rb = rcu_dereference(event->rb);
3760 if (!rb)
3761 goto unlock;
3764 * compute total_time_enabled, total_time_running
3765 * based on snapshot values taken when the event
3766 * was last scheduled in.
3768 * we cannot simply called update_context_time()
3769 * because of locking issue as we can be called in
3770 * NMI context
3772 calc_timer_values(event, &now, &enabled, &running);
3774 userpg = rb->user_page;
3776 * Disable preemption so as to not let the corresponding user-space
3777 * spin too long if we get preempted.
3779 preempt_disable();
3780 ++userpg->lock;
3781 barrier();
3782 userpg->index = perf_event_index(event);
3783 userpg->offset = perf_event_count(event);
3784 if (userpg->index)
3785 userpg->offset -= local64_read(&event->hw.prev_count);
3787 userpg->time_enabled = enabled +
3788 atomic64_read(&event->child_total_time_enabled);
3790 userpg->time_running = running +
3791 atomic64_read(&event->child_total_time_running);
3793 arch_perf_update_userpage(userpg, now);
3795 barrier();
3796 ++userpg->lock;
3797 preempt_enable();
3798 unlock:
3799 rcu_read_unlock();
3802 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
3804 struct perf_event *event = vma->vm_file->private_data;
3805 struct ring_buffer *rb;
3806 int ret = VM_FAULT_SIGBUS;
3808 if (vmf->flags & FAULT_FLAG_MKWRITE) {
3809 if (vmf->pgoff == 0)
3810 ret = 0;
3811 return ret;
3814 rcu_read_lock();
3815 rb = rcu_dereference(event->rb);
3816 if (!rb)
3817 goto unlock;
3819 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
3820 goto unlock;
3822 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
3823 if (!vmf->page)
3824 goto unlock;
3826 get_page(vmf->page);
3827 vmf->page->mapping = vma->vm_file->f_mapping;
3828 vmf->page->index = vmf->pgoff;
3830 ret = 0;
3831 unlock:
3832 rcu_read_unlock();
3834 return ret;
3837 static void ring_buffer_attach(struct perf_event *event,
3838 struct ring_buffer *rb)
3840 unsigned long flags;
3842 if (!list_empty(&event->rb_entry))
3843 return;
3845 spin_lock_irqsave(&rb->event_lock, flags);
3846 if (list_empty(&event->rb_entry))
3847 list_add(&event->rb_entry, &rb->event_list);
3848 spin_unlock_irqrestore(&rb->event_lock, flags);
3851 static void ring_buffer_detach(struct perf_event *event, struct ring_buffer *rb)
3853 unsigned long flags;
3855 if (list_empty(&event->rb_entry))
3856 return;
3858 spin_lock_irqsave(&rb->event_lock, flags);
3859 list_del_init(&event->rb_entry);
3860 wake_up_all(&event->waitq);
3861 spin_unlock_irqrestore(&rb->event_lock, flags);
3864 static void ring_buffer_wakeup(struct perf_event *event)
3866 struct ring_buffer *rb;
3868 rcu_read_lock();
3869 rb = rcu_dereference(event->rb);
3870 if (rb) {
3871 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
3872 wake_up_all(&event->waitq);
3874 rcu_read_unlock();
3877 static void rb_free_rcu(struct rcu_head *rcu_head)
3879 struct ring_buffer *rb;
3881 rb = container_of(rcu_head, struct ring_buffer, rcu_head);
3882 rb_free(rb);
3885 static struct ring_buffer *ring_buffer_get(struct perf_event *event)
3887 struct ring_buffer *rb;
3889 rcu_read_lock();
3890 rb = rcu_dereference(event->rb);
3891 if (rb) {
3892 if (!atomic_inc_not_zero(&rb->refcount))
3893 rb = NULL;
3895 rcu_read_unlock();
3897 return rb;
3900 static void ring_buffer_put(struct ring_buffer *rb)
3902 if (!atomic_dec_and_test(&rb->refcount))
3903 return;
3905 WARN_ON_ONCE(!list_empty(&rb->event_list));
3907 call_rcu(&rb->rcu_head, rb_free_rcu);
3910 static void perf_mmap_open(struct vm_area_struct *vma)
3912 struct perf_event *event = vma->vm_file->private_data;
3914 atomic_inc(&event->mmap_count);
3915 atomic_inc(&event->rb->mmap_count);
3919 * A buffer can be mmap()ed multiple times; either directly through the same
3920 * event, or through other events by use of perf_event_set_output().
3922 * In order to undo the VM accounting done by perf_mmap() we need to destroy
3923 * the buffer here, where we still have a VM context. This means we need
3924 * to detach all events redirecting to us.
3926 static void perf_mmap_close(struct vm_area_struct *vma)
3928 struct perf_event *event = vma->vm_file->private_data;
3930 struct ring_buffer *rb = event->rb;
3931 struct user_struct *mmap_user = rb->mmap_user;
3932 int mmap_locked = rb->mmap_locked;
3933 unsigned long size = perf_data_size(rb);
3935 atomic_dec(&rb->mmap_count);
3937 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
3938 return;
3940 /* Detach current event from the buffer. */
3941 rcu_assign_pointer(event->rb, NULL);
3942 ring_buffer_detach(event, rb);
3943 mutex_unlock(&event->mmap_mutex);
3945 /* If there's still other mmap()s of this buffer, we're done. */
3946 if (atomic_read(&rb->mmap_count)) {
3947 ring_buffer_put(rb); /* can't be last */
3948 return;
3952 * No other mmap()s, detach from all other events that might redirect
3953 * into the now unreachable buffer. Somewhat complicated by the
3954 * fact that rb::event_lock otherwise nests inside mmap_mutex.
3956 again:
3957 rcu_read_lock();
3958 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
3959 if (!atomic_long_inc_not_zero(&event->refcount)) {
3961 * This event is en-route to free_event() which will
3962 * detach it and remove it from the list.
3964 continue;
3966 rcu_read_unlock();
3968 mutex_lock(&event->mmap_mutex);
3970 * Check we didn't race with perf_event_set_output() which can
3971 * swizzle the rb from under us while we were waiting to
3972 * acquire mmap_mutex.
3974 * If we find a different rb; ignore this event, a next
3975 * iteration will no longer find it on the list. We have to
3976 * still restart the iteration to make sure we're not now
3977 * iterating the wrong list.
3979 if (event->rb == rb) {
3980 rcu_assign_pointer(event->rb, NULL);
3981 ring_buffer_detach(event, rb);
3982 ring_buffer_put(rb); /* can't be last, we still have one */
3984 mutex_unlock(&event->mmap_mutex);
3985 put_event(event);
3988 * Restart the iteration; either we're on the wrong list or
3989 * destroyed its integrity by doing a deletion.
3991 goto again;
3993 rcu_read_unlock();
3996 * It could be there's still a few 0-ref events on the list; they'll
3997 * get cleaned up by free_event() -- they'll also still have their
3998 * ref on the rb and will free it whenever they are done with it.
4000 * Aside from that, this buffer is 'fully' detached and unmapped,
4001 * undo the VM accounting.
4004 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4005 vma->vm_mm->pinned_vm -= mmap_locked;
4006 free_uid(mmap_user);
4008 ring_buffer_put(rb); /* could be last */
4011 static const struct vm_operations_struct perf_mmap_vmops = {
4012 .open = perf_mmap_open,
4013 .close = perf_mmap_close,
4014 .fault = perf_mmap_fault,
4015 .page_mkwrite = perf_mmap_fault,
4018 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
4020 struct perf_event *event = file->private_data;
4021 unsigned long user_locked, user_lock_limit;
4022 struct user_struct *user = current_user();
4023 unsigned long locked, lock_limit;
4024 struct ring_buffer *rb;
4025 unsigned long vma_size;
4026 unsigned long nr_pages;
4027 long user_extra, extra;
4028 int ret = 0, flags = 0;
4031 * Don't allow mmap() of inherited per-task counters. This would
4032 * create a performance issue due to all children writing to the
4033 * same rb.
4035 if (event->cpu == -1 && event->attr.inherit)
4036 return -EINVAL;
4038 if (!(vma->vm_flags & VM_SHARED))
4039 return -EINVAL;
4041 vma_size = vma->vm_end - vma->vm_start;
4042 nr_pages = (vma_size / PAGE_SIZE) - 1;
4045 * If we have rb pages ensure they're a power-of-two number, so we
4046 * can do bitmasks instead of modulo.
4048 if (nr_pages != 0 && !is_power_of_2(nr_pages))
4049 return -EINVAL;
4051 if (vma_size != PAGE_SIZE * (1 + nr_pages))
4052 return -EINVAL;
4054 if (vma->vm_pgoff != 0)
4055 return -EINVAL;
4057 WARN_ON_ONCE(event->ctx->parent_ctx);
4058 again:
4059 mutex_lock(&event->mmap_mutex);
4060 if (event->rb) {
4061 if (event->rb->nr_pages != nr_pages) {
4062 ret = -EINVAL;
4063 goto unlock;
4066 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4068 * Raced against perf_mmap_close() through
4069 * perf_event_set_output(). Try again, hope for better
4070 * luck.
4072 mutex_unlock(&event->mmap_mutex);
4073 goto again;
4076 goto unlock;
4079 user_extra = nr_pages + 1;
4080 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
4083 * Increase the limit linearly with more CPUs:
4085 user_lock_limit *= num_online_cpus();
4087 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
4089 extra = 0;
4090 if (user_locked > user_lock_limit)
4091 extra = user_locked - user_lock_limit;
4093 lock_limit = rlimit(RLIMIT_MEMLOCK);
4094 lock_limit >>= PAGE_SHIFT;
4095 locked = vma->vm_mm->pinned_vm + extra;
4097 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
4098 !capable(CAP_IPC_LOCK)) {
4099 ret = -EPERM;
4100 goto unlock;
4103 WARN_ON(event->rb);
4105 if (vma->vm_flags & VM_WRITE)
4106 flags |= RING_BUFFER_WRITABLE;
4108 rb = rb_alloc(nr_pages,
4109 event->attr.watermark ? event->attr.wakeup_watermark : 0,
4110 event->cpu, flags);
4112 if (!rb) {
4113 ret = -ENOMEM;
4114 goto unlock;
4117 atomic_set(&rb->mmap_count, 1);
4118 rb->mmap_locked = extra;
4119 rb->mmap_user = get_current_user();
4121 atomic_long_add(user_extra, &user->locked_vm);
4122 vma->vm_mm->pinned_vm += extra;
4124 ring_buffer_attach(event, rb);
4125 rcu_assign_pointer(event->rb, rb);
4127 perf_event_init_userpage(event);
4128 perf_event_update_userpage(event);
4130 unlock:
4131 if (!ret)
4132 atomic_inc(&event->mmap_count);
4133 mutex_unlock(&event->mmap_mutex);
4136 * Since pinned accounting is per vm we cannot allow fork() to copy our
4137 * vma.
4139 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
4140 vma->vm_ops = &perf_mmap_vmops;
4142 return ret;
4145 static int perf_fasync(int fd, struct file *filp, int on)
4147 struct inode *inode = file_inode(filp);
4148 struct perf_event *event = filp->private_data;
4149 int retval;
4151 mutex_lock(&inode->i_mutex);
4152 retval = fasync_helper(fd, filp, on, &event->fasync);
4153 mutex_unlock(&inode->i_mutex);
4155 if (retval < 0)
4156 return retval;
4158 return 0;
4161 static const struct file_operations perf_fops = {
4162 .llseek = no_llseek,
4163 .release = perf_release,
4164 .read = perf_read,
4165 .poll = perf_poll,
4166 .unlocked_ioctl = perf_ioctl,
4167 .compat_ioctl = perf_ioctl,
4168 .mmap = perf_mmap,
4169 .fasync = perf_fasync,
4173 * Perf event wakeup
4175 * If there's data, ensure we set the poll() state and publish everything
4176 * to user-space before waking everybody up.
4179 void perf_event_wakeup(struct perf_event *event)
4181 ring_buffer_wakeup(event);
4183 if (event->pending_kill) {
4184 kill_fasync(&event->fasync, SIGIO, event->pending_kill);
4185 event->pending_kill = 0;
4189 static void perf_pending_event(struct irq_work *entry)
4191 struct perf_event *event = container_of(entry,
4192 struct perf_event, pending);
4194 if (event->pending_disable) {
4195 event->pending_disable = 0;
4196 __perf_event_disable(event);
4199 if (event->pending_wakeup) {
4200 event->pending_wakeup = 0;
4201 perf_event_wakeup(event);
4206 * We assume there is only KVM supporting the callbacks.
4207 * Later on, we might change it to a list if there is
4208 * another virtualization implementation supporting the callbacks.
4210 struct perf_guest_info_callbacks *perf_guest_cbs;
4212 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4214 perf_guest_cbs = cbs;
4215 return 0;
4217 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
4219 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4221 perf_guest_cbs = NULL;
4222 return 0;
4224 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
4226 static void
4227 perf_output_sample_regs(struct perf_output_handle *handle,
4228 struct pt_regs *regs, u64 mask)
4230 int bit;
4232 for_each_set_bit(bit, (const unsigned long *) &mask,
4233 sizeof(mask) * BITS_PER_BYTE) {
4234 u64 val;
4236 val = perf_reg_value(regs, bit);
4237 perf_output_put(handle, val);
4241 static void perf_sample_regs_user(struct perf_regs_user *regs_user,
4242 struct pt_regs *regs)
4244 if (!user_mode(regs)) {
4245 if (current->mm)
4246 regs = task_pt_regs(current);
4247 else
4248 regs = NULL;
4251 if (regs) {
4252 regs_user->regs = regs;
4253 regs_user->abi = perf_reg_abi(current);
4258 * Get remaining task size from user stack pointer.
4260 * It'd be better to take stack vma map and limit this more
4261 * precisly, but there's no way to get it safely under interrupt,
4262 * so using TASK_SIZE as limit.
4264 static u64 perf_ustack_task_size(struct pt_regs *regs)
4266 unsigned long addr = perf_user_stack_pointer(regs);
4268 if (!addr || addr >= TASK_SIZE)
4269 return 0;
4271 return TASK_SIZE - addr;
4274 static u16
4275 perf_sample_ustack_size(u16 stack_size, u16 header_size,
4276 struct pt_regs *regs)
4278 u64 task_size;
4280 /* No regs, no stack pointer, no dump. */
4281 if (!regs)
4282 return 0;
4285 * Check if we fit in with the requested stack size into the:
4286 * - TASK_SIZE
4287 * If we don't, we limit the size to the TASK_SIZE.
4289 * - remaining sample size
4290 * If we don't, we customize the stack size to
4291 * fit in to the remaining sample size.
4294 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
4295 stack_size = min(stack_size, (u16) task_size);
4297 /* Current header size plus static size and dynamic size. */
4298 header_size += 2 * sizeof(u64);
4300 /* Do we fit in with the current stack dump size? */
4301 if ((u16) (header_size + stack_size) < header_size) {
4303 * If we overflow the maximum size for the sample,
4304 * we customize the stack dump size to fit in.
4306 stack_size = USHRT_MAX - header_size - sizeof(u64);
4307 stack_size = round_up(stack_size, sizeof(u64));
4310 return stack_size;
4313 static void
4314 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
4315 struct pt_regs *regs)
4317 /* Case of a kernel thread, nothing to dump */
4318 if (!regs) {
4319 u64 size = 0;
4320 perf_output_put(handle, size);
4321 } else {
4322 unsigned long sp;
4323 unsigned int rem;
4324 u64 dyn_size;
4327 * We dump:
4328 * static size
4329 * - the size requested by user or the best one we can fit
4330 * in to the sample max size
4331 * data
4332 * - user stack dump data
4333 * dynamic size
4334 * - the actual dumped size
4337 /* Static size. */
4338 perf_output_put(handle, dump_size);
4340 /* Data. */
4341 sp = perf_user_stack_pointer(regs);
4342 rem = __output_copy_user(handle, (void *) sp, dump_size);
4343 dyn_size = dump_size - rem;
4345 perf_output_skip(handle, rem);
4347 /* Dynamic size. */
4348 perf_output_put(handle, dyn_size);
4352 static void __perf_event_header__init_id(struct perf_event_header *header,
4353 struct perf_sample_data *data,
4354 struct perf_event *event)
4356 u64 sample_type = event->attr.sample_type;
4358 data->type = sample_type;
4359 header->size += event->id_header_size;
4361 if (sample_type & PERF_SAMPLE_TID) {
4362 /* namespace issues */
4363 data->tid_entry.pid = perf_event_pid(event, current);
4364 data->tid_entry.tid = perf_event_tid(event, current);
4367 if (sample_type & PERF_SAMPLE_TIME)
4368 data->time = perf_clock();
4370 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
4371 data->id = primary_event_id(event);
4373 if (sample_type & PERF_SAMPLE_STREAM_ID)
4374 data->stream_id = event->id;
4376 if (sample_type & PERF_SAMPLE_CPU) {
4377 data->cpu_entry.cpu = raw_smp_processor_id();
4378 data->cpu_entry.reserved = 0;
4382 void perf_event_header__init_id(struct perf_event_header *header,
4383 struct perf_sample_data *data,
4384 struct perf_event *event)
4386 if (event->attr.sample_id_all)
4387 __perf_event_header__init_id(header, data, event);
4390 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
4391 struct perf_sample_data *data)
4393 u64 sample_type = data->type;
4395 if (sample_type & PERF_SAMPLE_TID)
4396 perf_output_put(handle, data->tid_entry);
4398 if (sample_type & PERF_SAMPLE_TIME)
4399 perf_output_put(handle, data->time);
4401 if (sample_type & PERF_SAMPLE_ID)
4402 perf_output_put(handle, data->id);
4404 if (sample_type & PERF_SAMPLE_STREAM_ID)
4405 perf_output_put(handle, data->stream_id);
4407 if (sample_type & PERF_SAMPLE_CPU)
4408 perf_output_put(handle, data->cpu_entry);
4410 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4411 perf_output_put(handle, data->id);
4414 void perf_event__output_id_sample(struct perf_event *event,
4415 struct perf_output_handle *handle,
4416 struct perf_sample_data *sample)
4418 if (event->attr.sample_id_all)
4419 __perf_event__output_id_sample(handle, sample);
4422 static void perf_output_read_one(struct perf_output_handle *handle,
4423 struct perf_event *event,
4424 u64 enabled, u64 running)
4426 u64 read_format = event->attr.read_format;
4427 u64 values[4];
4428 int n = 0;
4430 values[n++] = perf_event_count(event);
4431 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4432 values[n++] = enabled +
4433 atomic64_read(&event->child_total_time_enabled);
4435 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4436 values[n++] = running +
4437 atomic64_read(&event->child_total_time_running);
4439 if (read_format & PERF_FORMAT_ID)
4440 values[n++] = primary_event_id(event);
4442 __output_copy(handle, values, n * sizeof(u64));
4446 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
4448 static void perf_output_read_group(struct perf_output_handle *handle,
4449 struct perf_event *event,
4450 u64 enabled, u64 running)
4452 struct perf_event *leader = event->group_leader, *sub;
4453 u64 read_format = event->attr.read_format;
4454 u64 values[5];
4455 int n = 0;
4457 values[n++] = 1 + leader->nr_siblings;
4459 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4460 values[n++] = enabled;
4462 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4463 values[n++] = running;
4465 if (leader != event)
4466 leader->pmu->read(leader);
4468 values[n++] = perf_event_count(leader);
4469 if (read_format & PERF_FORMAT_ID)
4470 values[n++] = primary_event_id(leader);
4472 __output_copy(handle, values, n * sizeof(u64));
4474 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4475 n = 0;
4477 if ((sub != event) &&
4478 (sub->state == PERF_EVENT_STATE_ACTIVE))
4479 sub->pmu->read(sub);
4481 values[n++] = perf_event_count(sub);
4482 if (read_format & PERF_FORMAT_ID)
4483 values[n++] = primary_event_id(sub);
4485 __output_copy(handle, values, n * sizeof(u64));
4489 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
4490 PERF_FORMAT_TOTAL_TIME_RUNNING)
4492 static void perf_output_read(struct perf_output_handle *handle,
4493 struct perf_event *event)
4495 u64 enabled = 0, running = 0, now;
4496 u64 read_format = event->attr.read_format;
4499 * compute total_time_enabled, total_time_running
4500 * based on snapshot values taken when the event
4501 * was last scheduled in.
4503 * we cannot simply called update_context_time()
4504 * because of locking issue as we are called in
4505 * NMI context
4507 if (read_format & PERF_FORMAT_TOTAL_TIMES)
4508 calc_timer_values(event, &now, &enabled, &running);
4510 if (event->attr.read_format & PERF_FORMAT_GROUP)
4511 perf_output_read_group(handle, event, enabled, running);
4512 else
4513 perf_output_read_one(handle, event, enabled, running);
4516 void perf_output_sample(struct perf_output_handle *handle,
4517 struct perf_event_header *header,
4518 struct perf_sample_data *data,
4519 struct perf_event *event)
4521 u64 sample_type = data->type;
4523 perf_output_put(handle, *header);
4525 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4526 perf_output_put(handle, data->id);
4528 if (sample_type & PERF_SAMPLE_IP)
4529 perf_output_put(handle, data->ip);
4531 if (sample_type & PERF_SAMPLE_TID)
4532 perf_output_put(handle, data->tid_entry);
4534 if (sample_type & PERF_SAMPLE_TIME)
4535 perf_output_put(handle, data->time);
4537 if (sample_type & PERF_SAMPLE_ADDR)
4538 perf_output_put(handle, data->addr);
4540 if (sample_type & PERF_SAMPLE_ID)
4541 perf_output_put(handle, data->id);
4543 if (sample_type & PERF_SAMPLE_STREAM_ID)
4544 perf_output_put(handle, data->stream_id);
4546 if (sample_type & PERF_SAMPLE_CPU)
4547 perf_output_put(handle, data->cpu_entry);
4549 if (sample_type & PERF_SAMPLE_PERIOD)
4550 perf_output_put(handle, data->period);
4552 if (sample_type & PERF_SAMPLE_READ)
4553 perf_output_read(handle, event);
4555 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4556 if (data->callchain) {
4557 int size = 1;
4559 if (data->callchain)
4560 size += data->callchain->nr;
4562 size *= sizeof(u64);
4564 __output_copy(handle, data->callchain, size);
4565 } else {
4566 u64 nr = 0;
4567 perf_output_put(handle, nr);
4571 if (sample_type & PERF_SAMPLE_RAW) {
4572 if (data->raw) {
4573 perf_output_put(handle, data->raw->size);
4574 __output_copy(handle, data->raw->data,
4575 data->raw->size);
4576 } else {
4577 struct {
4578 u32 size;
4579 u32 data;
4580 } raw = {
4581 .size = sizeof(u32),
4582 .data = 0,
4584 perf_output_put(handle, raw);
4588 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4589 if (data->br_stack) {
4590 size_t size;
4592 size = data->br_stack->nr
4593 * sizeof(struct perf_branch_entry);
4595 perf_output_put(handle, data->br_stack->nr);
4596 perf_output_copy(handle, data->br_stack->entries, size);
4597 } else {
4599 * we always store at least the value of nr
4601 u64 nr = 0;
4602 perf_output_put(handle, nr);
4606 if (sample_type & PERF_SAMPLE_REGS_USER) {
4607 u64 abi = data->regs_user.abi;
4610 * If there are no regs to dump, notice it through
4611 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
4613 perf_output_put(handle, abi);
4615 if (abi) {
4616 u64 mask = event->attr.sample_regs_user;
4617 perf_output_sample_regs(handle,
4618 data->regs_user.regs,
4619 mask);
4623 if (sample_type & PERF_SAMPLE_STACK_USER) {
4624 perf_output_sample_ustack(handle,
4625 data->stack_user_size,
4626 data->regs_user.regs);
4629 if (sample_type & PERF_SAMPLE_WEIGHT)
4630 perf_output_put(handle, data->weight);
4632 if (sample_type & PERF_SAMPLE_DATA_SRC)
4633 perf_output_put(handle, data->data_src.val);
4635 if (sample_type & PERF_SAMPLE_TRANSACTION)
4636 perf_output_put(handle, data->txn);
4638 if (!event->attr.watermark) {
4639 int wakeup_events = event->attr.wakeup_events;
4641 if (wakeup_events) {
4642 struct ring_buffer *rb = handle->rb;
4643 int events = local_inc_return(&rb->events);
4645 if (events >= wakeup_events) {
4646 local_sub(wakeup_events, &rb->events);
4647 local_inc(&rb->wakeup);
4653 void perf_prepare_sample(struct perf_event_header *header,
4654 struct perf_sample_data *data,
4655 struct perf_event *event,
4656 struct pt_regs *regs)
4658 u64 sample_type = event->attr.sample_type;
4660 header->type = PERF_RECORD_SAMPLE;
4661 header->size = sizeof(*header) + event->header_size;
4663 header->misc = 0;
4664 header->misc |= perf_misc_flags(regs);
4666 __perf_event_header__init_id(header, data, event);
4668 if (sample_type & PERF_SAMPLE_IP)
4669 data->ip = perf_instruction_pointer(regs);
4671 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4672 int size = 1;
4674 data->callchain = perf_callchain(event, regs);
4676 if (data->callchain)
4677 size += data->callchain->nr;
4679 header->size += size * sizeof(u64);
4682 if (sample_type & PERF_SAMPLE_RAW) {
4683 int size = sizeof(u32);
4685 if (data->raw)
4686 size += data->raw->size;
4687 else
4688 size += sizeof(u32);
4690 WARN_ON_ONCE(size & (sizeof(u64)-1));
4691 header->size += size;
4694 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4695 int size = sizeof(u64); /* nr */
4696 if (data->br_stack) {
4697 size += data->br_stack->nr
4698 * sizeof(struct perf_branch_entry);
4700 header->size += size;
4703 if (sample_type & PERF_SAMPLE_REGS_USER) {
4704 /* regs dump ABI info */
4705 int size = sizeof(u64);
4707 perf_sample_regs_user(&data->regs_user, regs);
4709 if (data->regs_user.regs) {
4710 u64 mask = event->attr.sample_regs_user;
4711 size += hweight64(mask) * sizeof(u64);
4714 header->size += size;
4717 if (sample_type & PERF_SAMPLE_STACK_USER) {
4719 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
4720 * processed as the last one or have additional check added
4721 * in case new sample type is added, because we could eat
4722 * up the rest of the sample size.
4724 struct perf_regs_user *uregs = &data->regs_user;
4725 u16 stack_size = event->attr.sample_stack_user;
4726 u16 size = sizeof(u64);
4728 if (!uregs->abi)
4729 perf_sample_regs_user(uregs, regs);
4731 stack_size = perf_sample_ustack_size(stack_size, header->size,
4732 uregs->regs);
4735 * If there is something to dump, add space for the dump
4736 * itself and for the field that tells the dynamic size,
4737 * which is how many have been actually dumped.
4739 if (stack_size)
4740 size += sizeof(u64) + stack_size;
4742 data->stack_user_size = stack_size;
4743 header->size += size;
4747 static void perf_event_output(struct perf_event *event,
4748 struct perf_sample_data *data,
4749 struct pt_regs *regs)
4751 struct perf_output_handle handle;
4752 struct perf_event_header header;
4754 /* protect the callchain buffers */
4755 rcu_read_lock();
4757 perf_prepare_sample(&header, data, event, regs);
4759 if (perf_output_begin(&handle, event, header.size))
4760 goto exit;
4762 perf_output_sample(&handle, &header, data, event);
4764 perf_output_end(&handle);
4766 exit:
4767 rcu_read_unlock();
4771 * read event_id
4774 struct perf_read_event {
4775 struct perf_event_header header;
4777 u32 pid;
4778 u32 tid;
4781 static void
4782 perf_event_read_event(struct perf_event *event,
4783 struct task_struct *task)
4785 struct perf_output_handle handle;
4786 struct perf_sample_data sample;
4787 struct perf_read_event read_event = {
4788 .header = {
4789 .type = PERF_RECORD_READ,
4790 .misc = 0,
4791 .size = sizeof(read_event) + event->read_size,
4793 .pid = perf_event_pid(event, task),
4794 .tid = perf_event_tid(event, task),
4796 int ret;
4798 perf_event_header__init_id(&read_event.header, &sample, event);
4799 ret = perf_output_begin(&handle, event, read_event.header.size);
4800 if (ret)
4801 return;
4803 perf_output_put(&handle, read_event);
4804 perf_output_read(&handle, event);
4805 perf_event__output_id_sample(event, &handle, &sample);
4807 perf_output_end(&handle);
4810 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
4812 static void
4813 perf_event_aux_ctx(struct perf_event_context *ctx,
4814 perf_event_aux_output_cb output,
4815 void *data)
4817 struct perf_event *event;
4819 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4820 if (event->state < PERF_EVENT_STATE_INACTIVE)
4821 continue;
4822 if (!event_filter_match(event))
4823 continue;
4824 output(event, data);
4828 static void
4829 perf_event_aux(perf_event_aux_output_cb output, void *data,
4830 struct perf_event_context *task_ctx)
4832 struct perf_cpu_context *cpuctx;
4833 struct perf_event_context *ctx;
4834 struct pmu *pmu;
4835 int ctxn;
4837 rcu_read_lock();
4838 list_for_each_entry_rcu(pmu, &pmus, entry) {
4839 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4840 if (cpuctx->unique_pmu != pmu)
4841 goto next;
4842 perf_event_aux_ctx(&cpuctx->ctx, output, data);
4843 if (task_ctx)
4844 goto next;
4845 ctxn = pmu->task_ctx_nr;
4846 if (ctxn < 0)
4847 goto next;
4848 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4849 if (ctx)
4850 perf_event_aux_ctx(ctx, output, data);
4851 next:
4852 put_cpu_ptr(pmu->pmu_cpu_context);
4855 if (task_ctx) {
4856 preempt_disable();
4857 perf_event_aux_ctx(task_ctx, output, data);
4858 preempt_enable();
4860 rcu_read_unlock();
4864 * task tracking -- fork/exit
4866 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
4869 struct perf_task_event {
4870 struct task_struct *task;
4871 struct perf_event_context *task_ctx;
4873 struct {
4874 struct perf_event_header header;
4876 u32 pid;
4877 u32 ppid;
4878 u32 tid;
4879 u32 ptid;
4880 u64 time;
4881 } event_id;
4884 static int perf_event_task_match(struct perf_event *event)
4886 return event->attr.comm || event->attr.mmap ||
4887 event->attr.mmap2 || event->attr.mmap_data ||
4888 event->attr.task;
4891 static void perf_event_task_output(struct perf_event *event,
4892 void *data)
4894 struct perf_task_event *task_event = data;
4895 struct perf_output_handle handle;
4896 struct perf_sample_data sample;
4897 struct task_struct *task = task_event->task;
4898 int ret, size = task_event->event_id.header.size;
4900 if (!perf_event_task_match(event))
4901 return;
4903 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
4905 ret = perf_output_begin(&handle, event,
4906 task_event->event_id.header.size);
4907 if (ret)
4908 goto out;
4910 task_event->event_id.pid = perf_event_pid(event, task);
4911 task_event->event_id.ppid = perf_event_pid(event, current);
4913 task_event->event_id.tid = perf_event_tid(event, task);
4914 task_event->event_id.ptid = perf_event_tid(event, current);
4916 perf_output_put(&handle, task_event->event_id);
4918 perf_event__output_id_sample(event, &handle, &sample);
4920 perf_output_end(&handle);
4921 out:
4922 task_event->event_id.header.size = size;
4925 static void perf_event_task(struct task_struct *task,
4926 struct perf_event_context *task_ctx,
4927 int new)
4929 struct perf_task_event task_event;
4931 if (!atomic_read(&nr_comm_events) &&
4932 !atomic_read(&nr_mmap_events) &&
4933 !atomic_read(&nr_task_events))
4934 return;
4936 task_event = (struct perf_task_event){
4937 .task = task,
4938 .task_ctx = task_ctx,
4939 .event_id = {
4940 .header = {
4941 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
4942 .misc = 0,
4943 .size = sizeof(task_event.event_id),
4945 /* .pid */
4946 /* .ppid */
4947 /* .tid */
4948 /* .ptid */
4949 .time = perf_clock(),
4953 perf_event_aux(perf_event_task_output,
4954 &task_event,
4955 task_ctx);
4958 void perf_event_fork(struct task_struct *task)
4960 perf_event_task(task, NULL, 1);
4964 * comm tracking
4967 struct perf_comm_event {
4968 struct task_struct *task;
4969 char *comm;
4970 int comm_size;
4972 struct {
4973 struct perf_event_header header;
4975 u32 pid;
4976 u32 tid;
4977 } event_id;
4980 static int perf_event_comm_match(struct perf_event *event)
4982 return event->attr.comm;
4985 static void perf_event_comm_output(struct perf_event *event,
4986 void *data)
4988 struct perf_comm_event *comm_event = data;
4989 struct perf_output_handle handle;
4990 struct perf_sample_data sample;
4991 int size = comm_event->event_id.header.size;
4992 int ret;
4994 if (!perf_event_comm_match(event))
4995 return;
4997 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
4998 ret = perf_output_begin(&handle, event,
4999 comm_event->event_id.header.size);
5001 if (ret)
5002 goto out;
5004 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
5005 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
5007 perf_output_put(&handle, comm_event->event_id);
5008 __output_copy(&handle, comm_event->comm,
5009 comm_event->comm_size);
5011 perf_event__output_id_sample(event, &handle, &sample);
5013 perf_output_end(&handle);
5014 out:
5015 comm_event->event_id.header.size = size;
5018 static void perf_event_comm_event(struct perf_comm_event *comm_event)
5020 char comm[TASK_COMM_LEN];
5021 unsigned int size;
5023 memset(comm, 0, sizeof(comm));
5024 strlcpy(comm, comm_event->task->comm, sizeof(comm));
5025 size = ALIGN(strlen(comm)+1, sizeof(u64));
5027 comm_event->comm = comm;
5028 comm_event->comm_size = size;
5030 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
5032 perf_event_aux(perf_event_comm_output,
5033 comm_event,
5034 NULL);
5037 void perf_event_comm(struct task_struct *task)
5039 struct perf_comm_event comm_event;
5040 struct perf_event_context *ctx;
5041 int ctxn;
5043 rcu_read_lock();
5044 for_each_task_context_nr(ctxn) {
5045 ctx = task->perf_event_ctxp[ctxn];
5046 if (!ctx)
5047 continue;
5049 perf_event_enable_on_exec(ctx);
5051 rcu_read_unlock();
5053 if (!atomic_read(&nr_comm_events))
5054 return;
5056 comm_event = (struct perf_comm_event){
5057 .task = task,
5058 /* .comm */
5059 /* .comm_size */
5060 .event_id = {
5061 .header = {
5062 .type = PERF_RECORD_COMM,
5063 .misc = 0,
5064 /* .size */
5066 /* .pid */
5067 /* .tid */
5071 perf_event_comm_event(&comm_event);
5075 * mmap tracking
5078 struct perf_mmap_event {
5079 struct vm_area_struct *vma;
5081 const char *file_name;
5082 int file_size;
5083 int maj, min;
5084 u64 ino;
5085 u64 ino_generation;
5087 struct {
5088 struct perf_event_header header;
5090 u32 pid;
5091 u32 tid;
5092 u64 start;
5093 u64 len;
5094 u64 pgoff;
5095 } event_id;
5098 static int perf_event_mmap_match(struct perf_event *event,
5099 void *data)
5101 struct perf_mmap_event *mmap_event = data;
5102 struct vm_area_struct *vma = mmap_event->vma;
5103 int executable = vma->vm_flags & VM_EXEC;
5105 return (!executable && event->attr.mmap_data) ||
5106 (executable && (event->attr.mmap || event->attr.mmap2));
5109 static void perf_event_mmap_output(struct perf_event *event,
5110 void *data)
5112 struct perf_mmap_event *mmap_event = data;
5113 struct perf_output_handle handle;
5114 struct perf_sample_data sample;
5115 int size = mmap_event->event_id.header.size;
5116 int ret;
5118 if (!perf_event_mmap_match(event, data))
5119 return;
5121 if (event->attr.mmap2) {
5122 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
5123 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
5124 mmap_event->event_id.header.size += sizeof(mmap_event->min);
5125 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
5126 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
5129 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
5130 ret = perf_output_begin(&handle, event,
5131 mmap_event->event_id.header.size);
5132 if (ret)
5133 goto out;
5135 mmap_event->event_id.pid = perf_event_pid(event, current);
5136 mmap_event->event_id.tid = perf_event_tid(event, current);
5138 perf_output_put(&handle, mmap_event->event_id);
5140 if (event->attr.mmap2) {
5141 perf_output_put(&handle, mmap_event->maj);
5142 perf_output_put(&handle, mmap_event->min);
5143 perf_output_put(&handle, mmap_event->ino);
5144 perf_output_put(&handle, mmap_event->ino_generation);
5147 __output_copy(&handle, mmap_event->file_name,
5148 mmap_event->file_size);
5150 perf_event__output_id_sample(event, &handle, &sample);
5152 perf_output_end(&handle);
5153 out:
5154 mmap_event->event_id.header.size = size;
5157 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
5159 struct vm_area_struct *vma = mmap_event->vma;
5160 struct file *file = vma->vm_file;
5161 int maj = 0, min = 0;
5162 u64 ino = 0, gen = 0;
5163 unsigned int size;
5164 char tmp[16];
5165 char *buf = NULL;
5166 char *name;
5168 if (file) {
5169 struct inode *inode;
5170 dev_t dev;
5172 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5173 if (!buf) {
5174 name = "//enomem";
5175 goto cpy_name;
5178 * d_path() works from the end of the rb backwards, so we
5179 * need to add enough zero bytes after the string to handle
5180 * the 64bit alignment we do later.
5182 name = d_path(&file->f_path, buf, PATH_MAX - sizeof(u64));
5183 if (IS_ERR(name)) {
5184 name = "//toolong";
5185 goto cpy_name;
5187 inode = file_inode(vma->vm_file);
5188 dev = inode->i_sb->s_dev;
5189 ino = inode->i_ino;
5190 gen = inode->i_generation;
5191 maj = MAJOR(dev);
5192 min = MINOR(dev);
5193 goto got_name;
5194 } else {
5195 name = (char *)arch_vma_name(vma);
5196 if (name)
5197 goto cpy_name;
5199 if (vma->vm_start <= vma->vm_mm->start_brk &&
5200 vma->vm_end >= vma->vm_mm->brk) {
5201 name = "[heap]";
5202 goto cpy_name;
5204 if (vma->vm_start <= vma->vm_mm->start_stack &&
5205 vma->vm_end >= vma->vm_mm->start_stack) {
5206 name = "[stack]";
5207 goto cpy_name;
5210 name = "//anon";
5211 goto cpy_name;
5214 cpy_name:
5215 strlcpy(tmp, name, sizeof(tmp));
5216 name = tmp;
5217 got_name:
5219 * Since our buffer works in 8 byte units we need to align our string
5220 * size to a multiple of 8. However, we must guarantee the tail end is
5221 * zero'd out to avoid leaking random bits to userspace.
5223 size = strlen(name)+1;
5224 while (!IS_ALIGNED(size, sizeof(u64)))
5225 name[size++] = '\0';
5227 mmap_event->file_name = name;
5228 mmap_event->file_size = size;
5229 mmap_event->maj = maj;
5230 mmap_event->min = min;
5231 mmap_event->ino = ino;
5232 mmap_event->ino_generation = gen;
5234 if (!(vma->vm_flags & VM_EXEC))
5235 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
5237 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
5239 perf_event_aux(perf_event_mmap_output,
5240 mmap_event,
5241 NULL);
5243 kfree(buf);
5246 void perf_event_mmap(struct vm_area_struct *vma)
5248 struct perf_mmap_event mmap_event;
5250 if (!atomic_read(&nr_mmap_events))
5251 return;
5253 mmap_event = (struct perf_mmap_event){
5254 .vma = vma,
5255 /* .file_name */
5256 /* .file_size */
5257 .event_id = {
5258 .header = {
5259 .type = PERF_RECORD_MMAP,
5260 .misc = PERF_RECORD_MISC_USER,
5261 /* .size */
5263 /* .pid */
5264 /* .tid */
5265 .start = vma->vm_start,
5266 .len = vma->vm_end - vma->vm_start,
5267 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
5269 /* .maj (attr_mmap2 only) */
5270 /* .min (attr_mmap2 only) */
5271 /* .ino (attr_mmap2 only) */
5272 /* .ino_generation (attr_mmap2 only) */
5275 perf_event_mmap_event(&mmap_event);
5279 * IRQ throttle logging
5282 static void perf_log_throttle(struct perf_event *event, int enable)
5284 struct perf_output_handle handle;
5285 struct perf_sample_data sample;
5286 int ret;
5288 struct {
5289 struct perf_event_header header;
5290 u64 time;
5291 u64 id;
5292 u64 stream_id;
5293 } throttle_event = {
5294 .header = {
5295 .type = PERF_RECORD_THROTTLE,
5296 .misc = 0,
5297 .size = sizeof(throttle_event),
5299 .time = perf_clock(),
5300 .id = primary_event_id(event),
5301 .stream_id = event->id,
5304 if (enable)
5305 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
5307 perf_event_header__init_id(&throttle_event.header, &sample, event);
5309 ret = perf_output_begin(&handle, event,
5310 throttle_event.header.size);
5311 if (ret)
5312 return;
5314 perf_output_put(&handle, throttle_event);
5315 perf_event__output_id_sample(event, &handle, &sample);
5316 perf_output_end(&handle);
5320 * Generic event overflow handling, sampling.
5323 static int __perf_event_overflow(struct perf_event *event,
5324 int throttle, struct perf_sample_data *data,
5325 struct pt_regs *regs)
5327 int events = atomic_read(&event->event_limit);
5328 struct hw_perf_event *hwc = &event->hw;
5329 u64 seq;
5330 int ret = 0;
5333 * Non-sampling counters might still use the PMI to fold short
5334 * hardware counters, ignore those.
5336 if (unlikely(!is_sampling_event(event)))
5337 return 0;
5339 seq = __this_cpu_read(perf_throttled_seq);
5340 if (seq != hwc->interrupts_seq) {
5341 hwc->interrupts_seq = seq;
5342 hwc->interrupts = 1;
5343 } else {
5344 hwc->interrupts++;
5345 if (unlikely(throttle
5346 && hwc->interrupts >= max_samples_per_tick)) {
5347 __this_cpu_inc(perf_throttled_count);
5348 hwc->interrupts = MAX_INTERRUPTS;
5349 perf_log_throttle(event, 0);
5350 tick_nohz_full_kick();
5351 ret = 1;
5355 if (event->attr.freq) {
5356 u64 now = perf_clock();
5357 s64 delta = now - hwc->freq_time_stamp;
5359 hwc->freq_time_stamp = now;
5361 if (delta > 0 && delta < 2*TICK_NSEC)
5362 perf_adjust_period(event, delta, hwc->last_period, true);
5366 * XXX event_limit might not quite work as expected on inherited
5367 * events
5370 event->pending_kill = POLL_IN;
5371 if (events && atomic_dec_and_test(&event->event_limit)) {
5372 ret = 1;
5373 event->pending_kill = POLL_HUP;
5374 event->pending_disable = 1;
5375 irq_work_queue(&event->pending);
5378 if (event->overflow_handler)
5379 event->overflow_handler(event, data, regs);
5380 else
5381 perf_event_output(event, data, regs);
5383 if (event->fasync && event->pending_kill) {
5384 event->pending_wakeup = 1;
5385 irq_work_queue(&event->pending);
5388 return ret;
5391 int perf_event_overflow(struct perf_event *event,
5392 struct perf_sample_data *data,
5393 struct pt_regs *regs)
5395 return __perf_event_overflow(event, 1, data, regs);
5399 * Generic software event infrastructure
5402 struct swevent_htable {
5403 struct swevent_hlist *swevent_hlist;
5404 struct mutex hlist_mutex;
5405 int hlist_refcount;
5407 /* Recursion avoidance in each contexts */
5408 int recursion[PERF_NR_CONTEXTS];
5411 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
5414 * We directly increment event->count and keep a second value in
5415 * event->hw.period_left to count intervals. This period event
5416 * is kept in the range [-sample_period, 0] so that we can use the
5417 * sign as trigger.
5420 u64 perf_swevent_set_period(struct perf_event *event)
5422 struct hw_perf_event *hwc = &event->hw;
5423 u64 period = hwc->last_period;
5424 u64 nr, offset;
5425 s64 old, val;
5427 hwc->last_period = hwc->sample_period;
5429 again:
5430 old = val = local64_read(&hwc->period_left);
5431 if (val < 0)
5432 return 0;
5434 nr = div64_u64(period + val, period);
5435 offset = nr * period;
5436 val -= offset;
5437 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
5438 goto again;
5440 return nr;
5443 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
5444 struct perf_sample_data *data,
5445 struct pt_regs *regs)
5447 struct hw_perf_event *hwc = &event->hw;
5448 int throttle = 0;
5450 if (!overflow)
5451 overflow = perf_swevent_set_period(event);
5453 if (hwc->interrupts == MAX_INTERRUPTS)
5454 return;
5456 for (; overflow; overflow--) {
5457 if (__perf_event_overflow(event, throttle,
5458 data, regs)) {
5460 * We inhibit the overflow from happening when
5461 * hwc->interrupts == MAX_INTERRUPTS.
5463 break;
5465 throttle = 1;
5469 static void perf_swevent_event(struct perf_event *event, u64 nr,
5470 struct perf_sample_data *data,
5471 struct pt_regs *regs)
5473 struct hw_perf_event *hwc = &event->hw;
5475 local64_add(nr, &event->count);
5477 if (!regs)
5478 return;
5480 if (!is_sampling_event(event))
5481 return;
5483 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
5484 data->period = nr;
5485 return perf_swevent_overflow(event, 1, data, regs);
5486 } else
5487 data->period = event->hw.last_period;
5489 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
5490 return perf_swevent_overflow(event, 1, data, regs);
5492 if (local64_add_negative(nr, &hwc->period_left))
5493 return;
5495 perf_swevent_overflow(event, 0, data, regs);
5498 static int perf_exclude_event(struct perf_event *event,
5499 struct pt_regs *regs)
5501 if (event->hw.state & PERF_HES_STOPPED)
5502 return 1;
5504 if (regs) {
5505 if (event->attr.exclude_user && user_mode(regs))
5506 return 1;
5508 if (event->attr.exclude_kernel && !user_mode(regs))
5509 return 1;
5512 return 0;
5515 static int perf_swevent_match(struct perf_event *event,
5516 enum perf_type_id type,
5517 u32 event_id,
5518 struct perf_sample_data *data,
5519 struct pt_regs *regs)
5521 if (event->attr.type != type)
5522 return 0;
5524 if (event->attr.config != event_id)
5525 return 0;
5527 if (perf_exclude_event(event, regs))
5528 return 0;
5530 return 1;
5533 static inline u64 swevent_hash(u64 type, u32 event_id)
5535 u64 val = event_id | (type << 32);
5537 return hash_64(val, SWEVENT_HLIST_BITS);
5540 static inline struct hlist_head *
5541 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
5543 u64 hash = swevent_hash(type, event_id);
5545 return &hlist->heads[hash];
5548 /* For the read side: events when they trigger */
5549 static inline struct hlist_head *
5550 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
5552 struct swevent_hlist *hlist;
5554 hlist = rcu_dereference(swhash->swevent_hlist);
5555 if (!hlist)
5556 return NULL;
5558 return __find_swevent_head(hlist, type, event_id);
5561 /* For the event head insertion and removal in the hlist */
5562 static inline struct hlist_head *
5563 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
5565 struct swevent_hlist *hlist;
5566 u32 event_id = event->attr.config;
5567 u64 type = event->attr.type;
5570 * Event scheduling is always serialized against hlist allocation
5571 * and release. Which makes the protected version suitable here.
5572 * The context lock guarantees that.
5574 hlist = rcu_dereference_protected(swhash->swevent_hlist,
5575 lockdep_is_held(&event->ctx->lock));
5576 if (!hlist)
5577 return NULL;
5579 return __find_swevent_head(hlist, type, event_id);
5582 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
5583 u64 nr,
5584 struct perf_sample_data *data,
5585 struct pt_regs *regs)
5587 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5588 struct perf_event *event;
5589 struct hlist_head *head;
5591 rcu_read_lock();
5592 head = find_swevent_head_rcu(swhash, type, event_id);
5593 if (!head)
5594 goto end;
5596 hlist_for_each_entry_rcu(event, head, hlist_entry) {
5597 if (perf_swevent_match(event, type, event_id, data, regs))
5598 perf_swevent_event(event, nr, data, regs);
5600 end:
5601 rcu_read_unlock();
5604 int perf_swevent_get_recursion_context(void)
5606 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5608 return get_recursion_context(swhash->recursion);
5610 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
5612 inline void perf_swevent_put_recursion_context(int rctx)
5614 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5616 put_recursion_context(swhash->recursion, rctx);
5619 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
5621 struct perf_sample_data data;
5622 int rctx;
5624 preempt_disable_notrace();
5625 rctx = perf_swevent_get_recursion_context();
5626 if (rctx < 0)
5627 return;
5629 perf_sample_data_init(&data, addr, 0);
5631 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
5633 perf_swevent_put_recursion_context(rctx);
5634 preempt_enable_notrace();
5637 static void perf_swevent_read(struct perf_event *event)
5641 static int perf_swevent_add(struct perf_event *event, int flags)
5643 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5644 struct hw_perf_event *hwc = &event->hw;
5645 struct hlist_head *head;
5647 if (is_sampling_event(event)) {
5648 hwc->last_period = hwc->sample_period;
5649 perf_swevent_set_period(event);
5652 hwc->state = !(flags & PERF_EF_START);
5654 head = find_swevent_head(swhash, event);
5655 if (WARN_ON_ONCE(!head))
5656 return -EINVAL;
5658 hlist_add_head_rcu(&event->hlist_entry, head);
5660 return 0;
5663 static void perf_swevent_del(struct perf_event *event, int flags)
5665 hlist_del_rcu(&event->hlist_entry);
5668 static void perf_swevent_start(struct perf_event *event, int flags)
5670 event->hw.state = 0;
5673 static void perf_swevent_stop(struct perf_event *event, int flags)
5675 event->hw.state = PERF_HES_STOPPED;
5678 /* Deref the hlist from the update side */
5679 static inline struct swevent_hlist *
5680 swevent_hlist_deref(struct swevent_htable *swhash)
5682 return rcu_dereference_protected(swhash->swevent_hlist,
5683 lockdep_is_held(&swhash->hlist_mutex));
5686 static void swevent_hlist_release(struct swevent_htable *swhash)
5688 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
5690 if (!hlist)
5691 return;
5693 rcu_assign_pointer(swhash->swevent_hlist, NULL);
5694 kfree_rcu(hlist, rcu_head);
5697 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
5699 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5701 mutex_lock(&swhash->hlist_mutex);
5703 if (!--swhash->hlist_refcount)
5704 swevent_hlist_release(swhash);
5706 mutex_unlock(&swhash->hlist_mutex);
5709 static void swevent_hlist_put(struct perf_event *event)
5711 int cpu;
5713 for_each_possible_cpu(cpu)
5714 swevent_hlist_put_cpu(event, cpu);
5717 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
5719 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5720 int err = 0;
5722 mutex_lock(&swhash->hlist_mutex);
5724 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
5725 struct swevent_hlist *hlist;
5727 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
5728 if (!hlist) {
5729 err = -ENOMEM;
5730 goto exit;
5732 rcu_assign_pointer(swhash->swevent_hlist, hlist);
5734 swhash->hlist_refcount++;
5735 exit:
5736 mutex_unlock(&swhash->hlist_mutex);
5738 return err;
5741 static int swevent_hlist_get(struct perf_event *event)
5743 int err;
5744 int cpu, failed_cpu;
5746 get_online_cpus();
5747 for_each_possible_cpu(cpu) {
5748 err = swevent_hlist_get_cpu(event, cpu);
5749 if (err) {
5750 failed_cpu = cpu;
5751 goto fail;
5754 put_online_cpus();
5756 return 0;
5757 fail:
5758 for_each_possible_cpu(cpu) {
5759 if (cpu == failed_cpu)
5760 break;
5761 swevent_hlist_put_cpu(event, cpu);
5764 put_online_cpus();
5765 return err;
5768 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
5770 static void sw_perf_event_destroy(struct perf_event *event)
5772 u64 event_id = event->attr.config;
5774 WARN_ON(event->parent);
5776 static_key_slow_dec(&perf_swevent_enabled[event_id]);
5777 swevent_hlist_put(event);
5780 static int perf_swevent_init(struct perf_event *event)
5782 u64 event_id = event->attr.config;
5784 if (event->attr.type != PERF_TYPE_SOFTWARE)
5785 return -ENOENT;
5788 * no branch sampling for software events
5790 if (has_branch_stack(event))
5791 return -EOPNOTSUPP;
5793 switch (event_id) {
5794 case PERF_COUNT_SW_CPU_CLOCK:
5795 case PERF_COUNT_SW_TASK_CLOCK:
5796 return -ENOENT;
5798 default:
5799 break;
5802 if (event_id >= PERF_COUNT_SW_MAX)
5803 return -ENOENT;
5805 if (!event->parent) {
5806 int err;
5808 err = swevent_hlist_get(event);
5809 if (err)
5810 return err;
5812 static_key_slow_inc(&perf_swevent_enabled[event_id]);
5813 event->destroy = sw_perf_event_destroy;
5816 return 0;
5819 static int perf_swevent_event_idx(struct perf_event *event)
5821 return 0;
5824 static struct pmu perf_swevent = {
5825 .task_ctx_nr = perf_sw_context,
5827 .event_init = perf_swevent_init,
5828 .add = perf_swevent_add,
5829 .del = perf_swevent_del,
5830 .start = perf_swevent_start,
5831 .stop = perf_swevent_stop,
5832 .read = perf_swevent_read,
5834 .event_idx = perf_swevent_event_idx,
5837 #ifdef CONFIG_EVENT_TRACING
5839 static int perf_tp_filter_match(struct perf_event *event,
5840 struct perf_sample_data *data)
5842 void *record = data->raw->data;
5844 if (likely(!event->filter) || filter_match_preds(event->filter, record))
5845 return 1;
5846 return 0;
5849 static int perf_tp_event_match(struct perf_event *event,
5850 struct perf_sample_data *data,
5851 struct pt_regs *regs)
5853 if (event->hw.state & PERF_HES_STOPPED)
5854 return 0;
5856 * All tracepoints are from kernel-space.
5858 if (event->attr.exclude_kernel)
5859 return 0;
5861 if (!perf_tp_filter_match(event, data))
5862 return 0;
5864 return 1;
5867 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
5868 struct pt_regs *regs, struct hlist_head *head, int rctx,
5869 struct task_struct *task)
5871 struct perf_sample_data data;
5872 struct perf_event *event;
5874 struct perf_raw_record raw = {
5875 .size = entry_size,
5876 .data = record,
5879 perf_sample_data_init(&data, addr, 0);
5880 data.raw = &raw;
5882 hlist_for_each_entry_rcu(event, head, hlist_entry) {
5883 if (perf_tp_event_match(event, &data, regs))
5884 perf_swevent_event(event, count, &data, regs);
5888 * If we got specified a target task, also iterate its context and
5889 * deliver this event there too.
5891 if (task && task != current) {
5892 struct perf_event_context *ctx;
5893 struct trace_entry *entry = record;
5895 rcu_read_lock();
5896 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
5897 if (!ctx)
5898 goto unlock;
5900 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5901 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5902 continue;
5903 if (event->attr.config != entry->type)
5904 continue;
5905 if (perf_tp_event_match(event, &data, regs))
5906 perf_swevent_event(event, count, &data, regs);
5908 unlock:
5909 rcu_read_unlock();
5912 perf_swevent_put_recursion_context(rctx);
5914 EXPORT_SYMBOL_GPL(perf_tp_event);
5916 static void tp_perf_event_destroy(struct perf_event *event)
5918 perf_trace_destroy(event);
5921 static int perf_tp_event_init(struct perf_event *event)
5923 int err;
5925 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5926 return -ENOENT;
5929 * no branch sampling for tracepoint events
5931 if (has_branch_stack(event))
5932 return -EOPNOTSUPP;
5934 err = perf_trace_init(event);
5935 if (err)
5936 return err;
5938 event->destroy = tp_perf_event_destroy;
5940 return 0;
5943 static struct pmu perf_tracepoint = {
5944 .task_ctx_nr = perf_sw_context,
5946 .event_init = perf_tp_event_init,
5947 .add = perf_trace_add,
5948 .del = perf_trace_del,
5949 .start = perf_swevent_start,
5950 .stop = perf_swevent_stop,
5951 .read = perf_swevent_read,
5953 .event_idx = perf_swevent_event_idx,
5956 static inline void perf_tp_register(void)
5958 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
5961 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
5963 char *filter_str;
5964 int ret;
5966 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5967 return -EINVAL;
5969 filter_str = strndup_user(arg, PAGE_SIZE);
5970 if (IS_ERR(filter_str))
5971 return PTR_ERR(filter_str);
5973 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
5975 kfree(filter_str);
5976 return ret;
5979 static void perf_event_free_filter(struct perf_event *event)
5981 ftrace_profile_free_filter(event);
5984 #else
5986 static inline void perf_tp_register(void)
5990 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
5992 return -ENOENT;
5995 static void perf_event_free_filter(struct perf_event *event)
5999 #endif /* CONFIG_EVENT_TRACING */
6001 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6002 void perf_bp_event(struct perf_event *bp, void *data)
6004 struct perf_sample_data sample;
6005 struct pt_regs *regs = data;
6007 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
6009 if (!bp->hw.state && !perf_exclude_event(bp, regs))
6010 perf_swevent_event(bp, 1, &sample, regs);
6012 #endif
6015 * hrtimer based swevent callback
6018 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
6020 enum hrtimer_restart ret = HRTIMER_RESTART;
6021 struct perf_sample_data data;
6022 struct pt_regs *regs;
6023 struct perf_event *event;
6024 u64 period;
6026 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
6028 if (event->state != PERF_EVENT_STATE_ACTIVE)
6029 return HRTIMER_NORESTART;
6031 event->pmu->read(event);
6033 perf_sample_data_init(&data, 0, event->hw.last_period);
6034 regs = get_irq_regs();
6036 if (regs && !perf_exclude_event(event, regs)) {
6037 if (!(event->attr.exclude_idle && is_idle_task(current)))
6038 if (__perf_event_overflow(event, 1, &data, regs))
6039 ret = HRTIMER_NORESTART;
6042 period = max_t(u64, 10000, event->hw.sample_period);
6043 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
6045 return ret;
6048 static void perf_swevent_start_hrtimer(struct perf_event *event)
6050 struct hw_perf_event *hwc = &event->hw;
6051 s64 period;
6053 if (!is_sampling_event(event))
6054 return;
6056 period = local64_read(&hwc->period_left);
6057 if (period) {
6058 if (period < 0)
6059 period = 10000;
6061 local64_set(&hwc->period_left, 0);
6062 } else {
6063 period = max_t(u64, 10000, hwc->sample_period);
6065 __hrtimer_start_range_ns(&hwc->hrtimer,
6066 ns_to_ktime(period), 0,
6067 HRTIMER_MODE_REL_PINNED, 0);
6070 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
6072 struct hw_perf_event *hwc = &event->hw;
6074 if (is_sampling_event(event)) {
6075 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
6076 local64_set(&hwc->period_left, ktime_to_ns(remaining));
6078 hrtimer_cancel(&hwc->hrtimer);
6082 static void perf_swevent_init_hrtimer(struct perf_event *event)
6084 struct hw_perf_event *hwc = &event->hw;
6086 if (!is_sampling_event(event))
6087 return;
6089 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6090 hwc->hrtimer.function = perf_swevent_hrtimer;
6093 * Since hrtimers have a fixed rate, we can do a static freq->period
6094 * mapping and avoid the whole period adjust feedback stuff.
6096 if (event->attr.freq) {
6097 long freq = event->attr.sample_freq;
6099 event->attr.sample_period = NSEC_PER_SEC / freq;
6100 hwc->sample_period = event->attr.sample_period;
6101 local64_set(&hwc->period_left, hwc->sample_period);
6102 hwc->last_period = hwc->sample_period;
6103 event->attr.freq = 0;
6108 * Software event: cpu wall time clock
6111 static void cpu_clock_event_update(struct perf_event *event)
6113 s64 prev;
6114 u64 now;
6116 now = local_clock();
6117 prev = local64_xchg(&event->hw.prev_count, now);
6118 local64_add(now - prev, &event->count);
6121 static void cpu_clock_event_start(struct perf_event *event, int flags)
6123 local64_set(&event->hw.prev_count, local_clock());
6124 perf_swevent_start_hrtimer(event);
6127 static void cpu_clock_event_stop(struct perf_event *event, int flags)
6129 perf_swevent_cancel_hrtimer(event);
6130 cpu_clock_event_update(event);
6133 static int cpu_clock_event_add(struct perf_event *event, int flags)
6135 if (flags & PERF_EF_START)
6136 cpu_clock_event_start(event, flags);
6138 return 0;
6141 static void cpu_clock_event_del(struct perf_event *event, int flags)
6143 cpu_clock_event_stop(event, flags);
6146 static void cpu_clock_event_read(struct perf_event *event)
6148 cpu_clock_event_update(event);
6151 static int cpu_clock_event_init(struct perf_event *event)
6153 if (event->attr.type != PERF_TYPE_SOFTWARE)
6154 return -ENOENT;
6156 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
6157 return -ENOENT;
6160 * no branch sampling for software events
6162 if (has_branch_stack(event))
6163 return -EOPNOTSUPP;
6165 perf_swevent_init_hrtimer(event);
6167 return 0;
6170 static struct pmu perf_cpu_clock = {
6171 .task_ctx_nr = perf_sw_context,
6173 .event_init = cpu_clock_event_init,
6174 .add = cpu_clock_event_add,
6175 .del = cpu_clock_event_del,
6176 .start = cpu_clock_event_start,
6177 .stop = cpu_clock_event_stop,
6178 .read = cpu_clock_event_read,
6180 .event_idx = perf_swevent_event_idx,
6184 * Software event: task time clock
6187 static void task_clock_event_update(struct perf_event *event, u64 now)
6189 u64 prev;
6190 s64 delta;
6192 prev = local64_xchg(&event->hw.prev_count, now);
6193 delta = now - prev;
6194 local64_add(delta, &event->count);
6197 static void task_clock_event_start(struct perf_event *event, int flags)
6199 local64_set(&event->hw.prev_count, event->ctx->time);
6200 perf_swevent_start_hrtimer(event);
6203 static void task_clock_event_stop(struct perf_event *event, int flags)
6205 perf_swevent_cancel_hrtimer(event);
6206 task_clock_event_update(event, event->ctx->time);
6209 static int task_clock_event_add(struct perf_event *event, int flags)
6211 if (flags & PERF_EF_START)
6212 task_clock_event_start(event, flags);
6214 return 0;
6217 static void task_clock_event_del(struct perf_event *event, int flags)
6219 task_clock_event_stop(event, PERF_EF_UPDATE);
6222 static void task_clock_event_read(struct perf_event *event)
6224 u64 now = perf_clock();
6225 u64 delta = now - event->ctx->timestamp;
6226 u64 time = event->ctx->time + delta;
6228 task_clock_event_update(event, time);
6231 static int task_clock_event_init(struct perf_event *event)
6233 if (event->attr.type != PERF_TYPE_SOFTWARE)
6234 return -ENOENT;
6236 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
6237 return -ENOENT;
6240 * no branch sampling for software events
6242 if (has_branch_stack(event))
6243 return -EOPNOTSUPP;
6245 perf_swevent_init_hrtimer(event);
6247 return 0;
6250 static struct pmu perf_task_clock = {
6251 .task_ctx_nr = perf_sw_context,
6253 .event_init = task_clock_event_init,
6254 .add = task_clock_event_add,
6255 .del = task_clock_event_del,
6256 .start = task_clock_event_start,
6257 .stop = task_clock_event_stop,
6258 .read = task_clock_event_read,
6260 .event_idx = perf_swevent_event_idx,
6263 static void perf_pmu_nop_void(struct pmu *pmu)
6267 static int perf_pmu_nop_int(struct pmu *pmu)
6269 return 0;
6272 static void perf_pmu_start_txn(struct pmu *pmu)
6274 perf_pmu_disable(pmu);
6277 static int perf_pmu_commit_txn(struct pmu *pmu)
6279 perf_pmu_enable(pmu);
6280 return 0;
6283 static void perf_pmu_cancel_txn(struct pmu *pmu)
6285 perf_pmu_enable(pmu);
6288 static int perf_event_idx_default(struct perf_event *event)
6290 return event->hw.idx + 1;
6294 * Ensures all contexts with the same task_ctx_nr have the same
6295 * pmu_cpu_context too.
6297 static void *find_pmu_context(int ctxn)
6299 struct pmu *pmu;
6301 if (ctxn < 0)
6302 return NULL;
6304 list_for_each_entry(pmu, &pmus, entry) {
6305 if (pmu->task_ctx_nr == ctxn)
6306 return pmu->pmu_cpu_context;
6309 return NULL;
6312 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
6314 int cpu;
6316 for_each_possible_cpu(cpu) {
6317 struct perf_cpu_context *cpuctx;
6319 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6321 if (cpuctx->unique_pmu == old_pmu)
6322 cpuctx->unique_pmu = pmu;
6326 static void free_pmu_context(struct pmu *pmu)
6328 struct pmu *i;
6330 mutex_lock(&pmus_lock);
6332 * Like a real lame refcount.
6334 list_for_each_entry(i, &pmus, entry) {
6335 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
6336 update_pmu_context(i, pmu);
6337 goto out;
6341 free_percpu(pmu->pmu_cpu_context);
6342 out:
6343 mutex_unlock(&pmus_lock);
6345 static struct idr pmu_idr;
6347 static ssize_t
6348 type_show(struct device *dev, struct device_attribute *attr, char *page)
6350 struct pmu *pmu = dev_get_drvdata(dev);
6352 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
6354 static DEVICE_ATTR_RO(type);
6356 static ssize_t
6357 perf_event_mux_interval_ms_show(struct device *dev,
6358 struct device_attribute *attr,
6359 char *page)
6361 struct pmu *pmu = dev_get_drvdata(dev);
6363 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
6366 static ssize_t
6367 perf_event_mux_interval_ms_store(struct device *dev,
6368 struct device_attribute *attr,
6369 const char *buf, size_t count)
6371 struct pmu *pmu = dev_get_drvdata(dev);
6372 int timer, cpu, ret;
6374 ret = kstrtoint(buf, 0, &timer);
6375 if (ret)
6376 return ret;
6378 if (timer < 1)
6379 return -EINVAL;
6381 /* same value, noting to do */
6382 if (timer == pmu->hrtimer_interval_ms)
6383 return count;
6385 pmu->hrtimer_interval_ms = timer;
6387 /* update all cpuctx for this PMU */
6388 for_each_possible_cpu(cpu) {
6389 struct perf_cpu_context *cpuctx;
6390 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6391 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
6393 if (hrtimer_active(&cpuctx->hrtimer))
6394 hrtimer_forward_now(&cpuctx->hrtimer, cpuctx->hrtimer_interval);
6397 return count;
6399 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
6401 static struct attribute *pmu_dev_attrs[] = {
6402 &dev_attr_type.attr,
6403 &dev_attr_perf_event_mux_interval_ms.attr,
6404 NULL,
6406 ATTRIBUTE_GROUPS(pmu_dev);
6408 static int pmu_bus_running;
6409 static struct bus_type pmu_bus = {
6410 .name = "event_source",
6411 .dev_groups = pmu_dev_groups,
6414 static void pmu_dev_release(struct device *dev)
6416 kfree(dev);
6419 static int pmu_dev_alloc(struct pmu *pmu)
6421 int ret = -ENOMEM;
6423 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
6424 if (!pmu->dev)
6425 goto out;
6427 pmu->dev->groups = pmu->attr_groups;
6428 device_initialize(pmu->dev);
6429 ret = dev_set_name(pmu->dev, "%s", pmu->name);
6430 if (ret)
6431 goto free_dev;
6433 dev_set_drvdata(pmu->dev, pmu);
6434 pmu->dev->bus = &pmu_bus;
6435 pmu->dev->release = pmu_dev_release;
6436 ret = device_add(pmu->dev);
6437 if (ret)
6438 goto free_dev;
6440 out:
6441 return ret;
6443 free_dev:
6444 put_device(pmu->dev);
6445 goto out;
6448 static struct lock_class_key cpuctx_mutex;
6449 static struct lock_class_key cpuctx_lock;
6451 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
6453 int cpu, ret;
6455 mutex_lock(&pmus_lock);
6456 ret = -ENOMEM;
6457 pmu->pmu_disable_count = alloc_percpu(int);
6458 if (!pmu->pmu_disable_count)
6459 goto unlock;
6461 pmu->type = -1;
6462 if (!name)
6463 goto skip_type;
6464 pmu->name = name;
6466 if (type < 0) {
6467 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
6468 if (type < 0) {
6469 ret = type;
6470 goto free_pdc;
6473 pmu->type = type;
6475 if (pmu_bus_running) {
6476 ret = pmu_dev_alloc(pmu);
6477 if (ret)
6478 goto free_idr;
6481 skip_type:
6482 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
6483 if (pmu->pmu_cpu_context)
6484 goto got_cpu_context;
6486 ret = -ENOMEM;
6487 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
6488 if (!pmu->pmu_cpu_context)
6489 goto free_dev;
6491 for_each_possible_cpu(cpu) {
6492 struct perf_cpu_context *cpuctx;
6494 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6495 __perf_event_init_context(&cpuctx->ctx);
6496 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
6497 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
6498 cpuctx->ctx.type = cpu_context;
6499 cpuctx->ctx.pmu = pmu;
6501 __perf_cpu_hrtimer_init(cpuctx, cpu);
6503 INIT_LIST_HEAD(&cpuctx->rotation_list);
6504 cpuctx->unique_pmu = pmu;
6507 got_cpu_context:
6508 if (!pmu->start_txn) {
6509 if (pmu->pmu_enable) {
6511 * If we have pmu_enable/pmu_disable calls, install
6512 * transaction stubs that use that to try and batch
6513 * hardware accesses.
6515 pmu->start_txn = perf_pmu_start_txn;
6516 pmu->commit_txn = perf_pmu_commit_txn;
6517 pmu->cancel_txn = perf_pmu_cancel_txn;
6518 } else {
6519 pmu->start_txn = perf_pmu_nop_void;
6520 pmu->commit_txn = perf_pmu_nop_int;
6521 pmu->cancel_txn = perf_pmu_nop_void;
6525 if (!pmu->pmu_enable) {
6526 pmu->pmu_enable = perf_pmu_nop_void;
6527 pmu->pmu_disable = perf_pmu_nop_void;
6530 if (!pmu->event_idx)
6531 pmu->event_idx = perf_event_idx_default;
6533 list_add_rcu(&pmu->entry, &pmus);
6534 ret = 0;
6535 unlock:
6536 mutex_unlock(&pmus_lock);
6538 return ret;
6540 free_dev:
6541 device_del(pmu->dev);
6542 put_device(pmu->dev);
6544 free_idr:
6545 if (pmu->type >= PERF_TYPE_MAX)
6546 idr_remove(&pmu_idr, pmu->type);
6548 free_pdc:
6549 free_percpu(pmu->pmu_disable_count);
6550 goto unlock;
6553 void perf_pmu_unregister(struct pmu *pmu)
6555 mutex_lock(&pmus_lock);
6556 list_del_rcu(&pmu->entry);
6557 mutex_unlock(&pmus_lock);
6560 * We dereference the pmu list under both SRCU and regular RCU, so
6561 * synchronize against both of those.
6563 synchronize_srcu(&pmus_srcu);
6564 synchronize_rcu();
6566 free_percpu(pmu->pmu_disable_count);
6567 if (pmu->type >= PERF_TYPE_MAX)
6568 idr_remove(&pmu_idr, pmu->type);
6569 device_del(pmu->dev);
6570 put_device(pmu->dev);
6571 free_pmu_context(pmu);
6574 struct pmu *perf_init_event(struct perf_event *event)
6576 struct pmu *pmu = NULL;
6577 int idx;
6578 int ret;
6580 idx = srcu_read_lock(&pmus_srcu);
6582 rcu_read_lock();
6583 pmu = idr_find(&pmu_idr, event->attr.type);
6584 rcu_read_unlock();
6585 if (pmu) {
6586 event->pmu = pmu;
6587 ret = pmu->event_init(event);
6588 if (ret)
6589 pmu = ERR_PTR(ret);
6590 goto unlock;
6593 list_for_each_entry_rcu(pmu, &pmus, entry) {
6594 event->pmu = pmu;
6595 ret = pmu->event_init(event);
6596 if (!ret)
6597 goto unlock;
6599 if (ret != -ENOENT) {
6600 pmu = ERR_PTR(ret);
6601 goto unlock;
6604 pmu = ERR_PTR(-ENOENT);
6605 unlock:
6606 srcu_read_unlock(&pmus_srcu, idx);
6608 return pmu;
6611 static void account_event_cpu(struct perf_event *event, int cpu)
6613 if (event->parent)
6614 return;
6616 if (has_branch_stack(event)) {
6617 if (!(event->attach_state & PERF_ATTACH_TASK))
6618 atomic_inc(&per_cpu(perf_branch_stack_events, cpu));
6620 if (is_cgroup_event(event))
6621 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
6624 static void account_event(struct perf_event *event)
6626 if (event->parent)
6627 return;
6629 if (event->attach_state & PERF_ATTACH_TASK)
6630 static_key_slow_inc(&perf_sched_events.key);
6631 if (event->attr.mmap || event->attr.mmap_data)
6632 atomic_inc(&nr_mmap_events);
6633 if (event->attr.comm)
6634 atomic_inc(&nr_comm_events);
6635 if (event->attr.task)
6636 atomic_inc(&nr_task_events);
6637 if (event->attr.freq) {
6638 if (atomic_inc_return(&nr_freq_events) == 1)
6639 tick_nohz_full_kick_all();
6641 if (has_branch_stack(event))
6642 static_key_slow_inc(&perf_sched_events.key);
6643 if (is_cgroup_event(event))
6644 static_key_slow_inc(&perf_sched_events.key);
6646 account_event_cpu(event, event->cpu);
6650 * Allocate and initialize a event structure
6652 static struct perf_event *
6653 perf_event_alloc(struct perf_event_attr *attr, int cpu,
6654 struct task_struct *task,
6655 struct perf_event *group_leader,
6656 struct perf_event *parent_event,
6657 perf_overflow_handler_t overflow_handler,
6658 void *context)
6660 struct pmu *pmu;
6661 struct perf_event *event;
6662 struct hw_perf_event *hwc;
6663 long err = -EINVAL;
6665 if ((unsigned)cpu >= nr_cpu_ids) {
6666 if (!task || cpu != -1)
6667 return ERR_PTR(-EINVAL);
6670 event = kzalloc(sizeof(*event), GFP_KERNEL);
6671 if (!event)
6672 return ERR_PTR(-ENOMEM);
6675 * Single events are their own group leaders, with an
6676 * empty sibling list:
6678 if (!group_leader)
6679 group_leader = event;
6681 mutex_init(&event->child_mutex);
6682 INIT_LIST_HEAD(&event->child_list);
6684 INIT_LIST_HEAD(&event->group_entry);
6685 INIT_LIST_HEAD(&event->event_entry);
6686 INIT_LIST_HEAD(&event->sibling_list);
6687 INIT_LIST_HEAD(&event->rb_entry);
6688 INIT_LIST_HEAD(&event->active_entry);
6689 INIT_HLIST_NODE(&event->hlist_entry);
6692 init_waitqueue_head(&event->waitq);
6693 init_irq_work(&event->pending, perf_pending_event);
6695 mutex_init(&event->mmap_mutex);
6697 atomic_long_set(&event->refcount, 1);
6698 event->cpu = cpu;
6699 event->attr = *attr;
6700 event->group_leader = group_leader;
6701 event->pmu = NULL;
6702 event->oncpu = -1;
6704 event->parent = parent_event;
6706 event->ns = get_pid_ns(task_active_pid_ns(current));
6707 event->id = atomic64_inc_return(&perf_event_id);
6709 event->state = PERF_EVENT_STATE_INACTIVE;
6711 if (task) {
6712 event->attach_state = PERF_ATTACH_TASK;
6714 if (attr->type == PERF_TYPE_TRACEPOINT)
6715 event->hw.tp_target = task;
6716 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6718 * hw_breakpoint is a bit difficult here..
6720 else if (attr->type == PERF_TYPE_BREAKPOINT)
6721 event->hw.bp_target = task;
6722 #endif
6725 if (!overflow_handler && parent_event) {
6726 overflow_handler = parent_event->overflow_handler;
6727 context = parent_event->overflow_handler_context;
6730 event->overflow_handler = overflow_handler;
6731 event->overflow_handler_context = context;
6733 perf_event__state_init(event);
6735 pmu = NULL;
6737 hwc = &event->hw;
6738 hwc->sample_period = attr->sample_period;
6739 if (attr->freq && attr->sample_freq)
6740 hwc->sample_period = 1;
6741 hwc->last_period = hwc->sample_period;
6743 local64_set(&hwc->period_left, hwc->sample_period);
6746 * we currently do not support PERF_FORMAT_GROUP on inherited events
6748 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
6749 goto err_ns;
6751 pmu = perf_init_event(event);
6752 if (!pmu)
6753 goto err_ns;
6754 else if (IS_ERR(pmu)) {
6755 err = PTR_ERR(pmu);
6756 goto err_ns;
6759 if (!event->parent) {
6760 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
6761 err = get_callchain_buffers();
6762 if (err)
6763 goto err_pmu;
6767 return event;
6769 err_pmu:
6770 if (event->destroy)
6771 event->destroy(event);
6772 err_ns:
6773 if (event->ns)
6774 put_pid_ns(event->ns);
6775 kfree(event);
6777 return ERR_PTR(err);
6780 static int perf_copy_attr(struct perf_event_attr __user *uattr,
6781 struct perf_event_attr *attr)
6783 u32 size;
6784 int ret;
6786 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
6787 return -EFAULT;
6790 * zero the full structure, so that a short copy will be nice.
6792 memset(attr, 0, sizeof(*attr));
6794 ret = get_user(size, &uattr->size);
6795 if (ret)
6796 return ret;
6798 if (size > PAGE_SIZE) /* silly large */
6799 goto err_size;
6801 if (!size) /* abi compat */
6802 size = PERF_ATTR_SIZE_VER0;
6804 if (size < PERF_ATTR_SIZE_VER0)
6805 goto err_size;
6808 * If we're handed a bigger struct than we know of,
6809 * ensure all the unknown bits are 0 - i.e. new
6810 * user-space does not rely on any kernel feature
6811 * extensions we dont know about yet.
6813 if (size > sizeof(*attr)) {
6814 unsigned char __user *addr;
6815 unsigned char __user *end;
6816 unsigned char val;
6818 addr = (void __user *)uattr + sizeof(*attr);
6819 end = (void __user *)uattr + size;
6821 for (; addr < end; addr++) {
6822 ret = get_user(val, addr);
6823 if (ret)
6824 return ret;
6825 if (val)
6826 goto err_size;
6828 size = sizeof(*attr);
6831 ret = copy_from_user(attr, uattr, size);
6832 if (ret)
6833 return -EFAULT;
6835 /* disabled for now */
6836 if (attr->mmap2)
6837 return -EINVAL;
6839 if (attr->__reserved_1)
6840 return -EINVAL;
6842 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
6843 return -EINVAL;
6845 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
6846 return -EINVAL;
6848 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
6849 u64 mask = attr->branch_sample_type;
6851 /* only using defined bits */
6852 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
6853 return -EINVAL;
6855 /* at least one branch bit must be set */
6856 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
6857 return -EINVAL;
6859 /* propagate priv level, when not set for branch */
6860 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
6862 /* exclude_kernel checked on syscall entry */
6863 if (!attr->exclude_kernel)
6864 mask |= PERF_SAMPLE_BRANCH_KERNEL;
6866 if (!attr->exclude_user)
6867 mask |= PERF_SAMPLE_BRANCH_USER;
6869 if (!attr->exclude_hv)
6870 mask |= PERF_SAMPLE_BRANCH_HV;
6872 * adjust user setting (for HW filter setup)
6874 attr->branch_sample_type = mask;
6876 /* privileged levels capture (kernel, hv): check permissions */
6877 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
6878 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
6879 return -EACCES;
6882 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
6883 ret = perf_reg_validate(attr->sample_regs_user);
6884 if (ret)
6885 return ret;
6888 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
6889 if (!arch_perf_have_user_stack_dump())
6890 return -ENOSYS;
6893 * We have __u32 type for the size, but so far
6894 * we can only use __u16 as maximum due to the
6895 * __u16 sample size limit.
6897 if (attr->sample_stack_user >= USHRT_MAX)
6898 ret = -EINVAL;
6899 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
6900 ret = -EINVAL;
6903 out:
6904 return ret;
6906 err_size:
6907 put_user(sizeof(*attr), &uattr->size);
6908 ret = -E2BIG;
6909 goto out;
6912 static int
6913 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
6915 struct ring_buffer *rb = NULL, *old_rb = NULL;
6916 int ret = -EINVAL;
6918 if (!output_event)
6919 goto set;
6921 /* don't allow circular references */
6922 if (event == output_event)
6923 goto out;
6926 * Don't allow cross-cpu buffers
6928 if (output_event->cpu != event->cpu)
6929 goto out;
6932 * If its not a per-cpu rb, it must be the same task.
6934 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
6935 goto out;
6937 set:
6938 mutex_lock(&event->mmap_mutex);
6939 /* Can't redirect output if we've got an active mmap() */
6940 if (atomic_read(&event->mmap_count))
6941 goto unlock;
6943 old_rb = event->rb;
6945 if (output_event) {
6946 /* get the rb we want to redirect to */
6947 rb = ring_buffer_get(output_event);
6948 if (!rb)
6949 goto unlock;
6952 if (old_rb)
6953 ring_buffer_detach(event, old_rb);
6955 if (rb)
6956 ring_buffer_attach(event, rb);
6958 rcu_assign_pointer(event->rb, rb);
6960 if (old_rb) {
6961 ring_buffer_put(old_rb);
6963 * Since we detached before setting the new rb, so that we
6964 * could attach the new rb, we could have missed a wakeup.
6965 * Provide it now.
6967 wake_up_all(&event->waitq);
6970 ret = 0;
6971 unlock:
6972 mutex_unlock(&event->mmap_mutex);
6974 out:
6975 return ret;
6979 * sys_perf_event_open - open a performance event, associate it to a task/cpu
6981 * @attr_uptr: event_id type attributes for monitoring/sampling
6982 * @pid: target pid
6983 * @cpu: target cpu
6984 * @group_fd: group leader event fd
6986 SYSCALL_DEFINE5(perf_event_open,
6987 struct perf_event_attr __user *, attr_uptr,
6988 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
6990 struct perf_event *group_leader = NULL, *output_event = NULL;
6991 struct perf_event *event, *sibling;
6992 struct perf_event_attr attr;
6993 struct perf_event_context *ctx;
6994 struct file *event_file = NULL;
6995 struct fd group = {NULL, 0};
6996 struct task_struct *task = NULL;
6997 struct pmu *pmu;
6998 int event_fd;
6999 int move_group = 0;
7000 int err;
7001 int f_flags = O_RDWR;
7003 /* for future expandability... */
7004 if (flags & ~PERF_FLAG_ALL)
7005 return -EINVAL;
7007 err = perf_copy_attr(attr_uptr, &attr);
7008 if (err)
7009 return err;
7011 if (!attr.exclude_kernel) {
7012 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
7013 return -EACCES;
7016 if (attr.freq) {
7017 if (attr.sample_freq > sysctl_perf_event_sample_rate)
7018 return -EINVAL;
7022 * In cgroup mode, the pid argument is used to pass the fd
7023 * opened to the cgroup directory in cgroupfs. The cpu argument
7024 * designates the cpu on which to monitor threads from that
7025 * cgroup.
7027 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
7028 return -EINVAL;
7030 if (flags & PERF_FLAG_FD_CLOEXEC)
7031 f_flags |= O_CLOEXEC;
7033 event_fd = get_unused_fd_flags(f_flags);
7034 if (event_fd < 0)
7035 return event_fd;
7037 if (group_fd != -1) {
7038 err = perf_fget_light(group_fd, &group);
7039 if (err)
7040 goto err_fd;
7041 group_leader = group.file->private_data;
7042 if (flags & PERF_FLAG_FD_OUTPUT)
7043 output_event = group_leader;
7044 if (flags & PERF_FLAG_FD_NO_GROUP)
7045 group_leader = NULL;
7048 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
7049 task = find_lively_task_by_vpid(pid);
7050 if (IS_ERR(task)) {
7051 err = PTR_ERR(task);
7052 goto err_group_fd;
7056 get_online_cpus();
7058 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
7059 NULL, NULL);
7060 if (IS_ERR(event)) {
7061 err = PTR_ERR(event);
7062 goto err_task;
7065 if (flags & PERF_FLAG_PID_CGROUP) {
7066 err = perf_cgroup_connect(pid, event, &attr, group_leader);
7067 if (err) {
7068 __free_event(event);
7069 goto err_task;
7073 account_event(event);
7076 * Special case software events and allow them to be part of
7077 * any hardware group.
7079 pmu = event->pmu;
7081 if (group_leader &&
7082 (is_software_event(event) != is_software_event(group_leader))) {
7083 if (is_software_event(event)) {
7085 * If event and group_leader are not both a software
7086 * event, and event is, then group leader is not.
7088 * Allow the addition of software events to !software
7089 * groups, this is safe because software events never
7090 * fail to schedule.
7092 pmu = group_leader->pmu;
7093 } else if (is_software_event(group_leader) &&
7094 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
7096 * In case the group is a pure software group, and we
7097 * try to add a hardware event, move the whole group to
7098 * the hardware context.
7100 move_group = 1;
7105 * Get the target context (task or percpu):
7107 ctx = find_get_context(pmu, task, event->cpu);
7108 if (IS_ERR(ctx)) {
7109 err = PTR_ERR(ctx);
7110 goto err_alloc;
7113 if (task) {
7114 put_task_struct(task);
7115 task = NULL;
7119 * Look up the group leader (we will attach this event to it):
7121 if (group_leader) {
7122 err = -EINVAL;
7125 * Do not allow a recursive hierarchy (this new sibling
7126 * becoming part of another group-sibling):
7128 if (group_leader->group_leader != group_leader)
7129 goto err_context;
7131 * Do not allow to attach to a group in a different
7132 * task or CPU context:
7134 if (move_group) {
7135 if (group_leader->ctx->type != ctx->type)
7136 goto err_context;
7137 } else {
7138 if (group_leader->ctx != ctx)
7139 goto err_context;
7143 * Only a group leader can be exclusive or pinned
7145 if (attr.exclusive || attr.pinned)
7146 goto err_context;
7149 if (output_event) {
7150 err = perf_event_set_output(event, output_event);
7151 if (err)
7152 goto err_context;
7155 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
7156 f_flags);
7157 if (IS_ERR(event_file)) {
7158 err = PTR_ERR(event_file);
7159 goto err_context;
7162 if (move_group) {
7163 struct perf_event_context *gctx = group_leader->ctx;
7165 mutex_lock(&gctx->mutex);
7166 perf_remove_from_context(group_leader);
7169 * Removing from the context ends up with disabled
7170 * event. What we want here is event in the initial
7171 * startup state, ready to be add into new context.
7173 perf_event__state_init(group_leader);
7174 list_for_each_entry(sibling, &group_leader->sibling_list,
7175 group_entry) {
7176 perf_remove_from_context(sibling);
7177 perf_event__state_init(sibling);
7178 put_ctx(gctx);
7180 mutex_unlock(&gctx->mutex);
7181 put_ctx(gctx);
7184 WARN_ON_ONCE(ctx->parent_ctx);
7185 mutex_lock(&ctx->mutex);
7187 if (move_group) {
7188 synchronize_rcu();
7189 perf_install_in_context(ctx, group_leader, event->cpu);
7190 get_ctx(ctx);
7191 list_for_each_entry(sibling, &group_leader->sibling_list,
7192 group_entry) {
7193 perf_install_in_context(ctx, sibling, event->cpu);
7194 get_ctx(ctx);
7198 perf_install_in_context(ctx, event, event->cpu);
7199 perf_unpin_context(ctx);
7200 mutex_unlock(&ctx->mutex);
7202 put_online_cpus();
7204 event->owner = current;
7206 mutex_lock(&current->perf_event_mutex);
7207 list_add_tail(&event->owner_entry, &current->perf_event_list);
7208 mutex_unlock(&current->perf_event_mutex);
7211 * Precalculate sample_data sizes
7213 perf_event__header_size(event);
7214 perf_event__id_header_size(event);
7217 * Drop the reference on the group_event after placing the
7218 * new event on the sibling_list. This ensures destruction
7219 * of the group leader will find the pointer to itself in
7220 * perf_group_detach().
7222 fdput(group);
7223 fd_install(event_fd, event_file);
7224 return event_fd;
7226 err_context:
7227 perf_unpin_context(ctx);
7228 put_ctx(ctx);
7229 err_alloc:
7230 free_event(event);
7231 err_task:
7232 put_online_cpus();
7233 if (task)
7234 put_task_struct(task);
7235 err_group_fd:
7236 fdput(group);
7237 err_fd:
7238 put_unused_fd(event_fd);
7239 return err;
7243 * perf_event_create_kernel_counter
7245 * @attr: attributes of the counter to create
7246 * @cpu: cpu in which the counter is bound
7247 * @task: task to profile (NULL for percpu)
7249 struct perf_event *
7250 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
7251 struct task_struct *task,
7252 perf_overflow_handler_t overflow_handler,
7253 void *context)
7255 struct perf_event_context *ctx;
7256 struct perf_event *event;
7257 int err;
7260 * Get the target context (task or percpu):
7263 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
7264 overflow_handler, context);
7265 if (IS_ERR(event)) {
7266 err = PTR_ERR(event);
7267 goto err;
7270 account_event(event);
7272 ctx = find_get_context(event->pmu, task, cpu);
7273 if (IS_ERR(ctx)) {
7274 err = PTR_ERR(ctx);
7275 goto err_free;
7278 WARN_ON_ONCE(ctx->parent_ctx);
7279 mutex_lock(&ctx->mutex);
7280 perf_install_in_context(ctx, event, cpu);
7281 perf_unpin_context(ctx);
7282 mutex_unlock(&ctx->mutex);
7284 return event;
7286 err_free:
7287 free_event(event);
7288 err:
7289 return ERR_PTR(err);
7291 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
7293 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
7295 struct perf_event_context *src_ctx;
7296 struct perf_event_context *dst_ctx;
7297 struct perf_event *event, *tmp;
7298 LIST_HEAD(events);
7300 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
7301 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
7303 mutex_lock(&src_ctx->mutex);
7304 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
7305 event_entry) {
7306 perf_remove_from_context(event);
7307 unaccount_event_cpu(event, src_cpu);
7308 put_ctx(src_ctx);
7309 list_add(&event->migrate_entry, &events);
7311 mutex_unlock(&src_ctx->mutex);
7313 synchronize_rcu();
7315 mutex_lock(&dst_ctx->mutex);
7316 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
7317 list_del(&event->migrate_entry);
7318 if (event->state >= PERF_EVENT_STATE_OFF)
7319 event->state = PERF_EVENT_STATE_INACTIVE;
7320 account_event_cpu(event, dst_cpu);
7321 perf_install_in_context(dst_ctx, event, dst_cpu);
7322 get_ctx(dst_ctx);
7324 mutex_unlock(&dst_ctx->mutex);
7326 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
7328 static void sync_child_event(struct perf_event *child_event,
7329 struct task_struct *child)
7331 struct perf_event *parent_event = child_event->parent;
7332 u64 child_val;
7334 if (child_event->attr.inherit_stat)
7335 perf_event_read_event(child_event, child);
7337 child_val = perf_event_count(child_event);
7340 * Add back the child's count to the parent's count:
7342 atomic64_add(child_val, &parent_event->child_count);
7343 atomic64_add(child_event->total_time_enabled,
7344 &parent_event->child_total_time_enabled);
7345 atomic64_add(child_event->total_time_running,
7346 &parent_event->child_total_time_running);
7349 * Remove this event from the parent's list
7351 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7352 mutex_lock(&parent_event->child_mutex);
7353 list_del_init(&child_event->child_list);
7354 mutex_unlock(&parent_event->child_mutex);
7357 * Release the parent event, if this was the last
7358 * reference to it.
7360 put_event(parent_event);
7363 static void
7364 __perf_event_exit_task(struct perf_event *child_event,
7365 struct perf_event_context *child_ctx,
7366 struct task_struct *child)
7368 if (child_event->parent) {
7369 raw_spin_lock_irq(&child_ctx->lock);
7370 perf_group_detach(child_event);
7371 raw_spin_unlock_irq(&child_ctx->lock);
7374 perf_remove_from_context(child_event);
7377 * It can happen that the parent exits first, and has events
7378 * that are still around due to the child reference. These
7379 * events need to be zapped.
7381 if (child_event->parent) {
7382 sync_child_event(child_event, child);
7383 free_event(child_event);
7387 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
7389 struct perf_event *child_event, *tmp;
7390 struct perf_event_context *child_ctx;
7391 unsigned long flags;
7393 if (likely(!child->perf_event_ctxp[ctxn])) {
7394 perf_event_task(child, NULL, 0);
7395 return;
7398 local_irq_save(flags);
7400 * We can't reschedule here because interrupts are disabled,
7401 * and either child is current or it is a task that can't be
7402 * scheduled, so we are now safe from rescheduling changing
7403 * our context.
7405 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
7408 * Take the context lock here so that if find_get_context is
7409 * reading child->perf_event_ctxp, we wait until it has
7410 * incremented the context's refcount before we do put_ctx below.
7412 raw_spin_lock(&child_ctx->lock);
7413 task_ctx_sched_out(child_ctx);
7414 child->perf_event_ctxp[ctxn] = NULL;
7416 * If this context is a clone; unclone it so it can't get
7417 * swapped to another process while we're removing all
7418 * the events from it.
7420 unclone_ctx(child_ctx);
7421 update_context_time(child_ctx);
7422 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7425 * Report the task dead after unscheduling the events so that we
7426 * won't get any samples after PERF_RECORD_EXIT. We can however still
7427 * get a few PERF_RECORD_READ events.
7429 perf_event_task(child, child_ctx, 0);
7432 * We can recurse on the same lock type through:
7434 * __perf_event_exit_task()
7435 * sync_child_event()
7436 * put_event()
7437 * mutex_lock(&ctx->mutex)
7439 * But since its the parent context it won't be the same instance.
7441 mutex_lock(&child_ctx->mutex);
7443 again:
7444 list_for_each_entry_safe(child_event, tmp, &child_ctx->pinned_groups,
7445 group_entry)
7446 __perf_event_exit_task(child_event, child_ctx, child);
7448 list_for_each_entry_safe(child_event, tmp, &child_ctx->flexible_groups,
7449 group_entry)
7450 __perf_event_exit_task(child_event, child_ctx, child);
7453 * If the last event was a group event, it will have appended all
7454 * its siblings to the list, but we obtained 'tmp' before that which
7455 * will still point to the list head terminating the iteration.
7457 if (!list_empty(&child_ctx->pinned_groups) ||
7458 !list_empty(&child_ctx->flexible_groups))
7459 goto again;
7461 mutex_unlock(&child_ctx->mutex);
7463 put_ctx(child_ctx);
7467 * When a child task exits, feed back event values to parent events.
7469 void perf_event_exit_task(struct task_struct *child)
7471 struct perf_event *event, *tmp;
7472 int ctxn;
7474 mutex_lock(&child->perf_event_mutex);
7475 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
7476 owner_entry) {
7477 list_del_init(&event->owner_entry);
7480 * Ensure the list deletion is visible before we clear
7481 * the owner, closes a race against perf_release() where
7482 * we need to serialize on the owner->perf_event_mutex.
7484 smp_wmb();
7485 event->owner = NULL;
7487 mutex_unlock(&child->perf_event_mutex);
7489 for_each_task_context_nr(ctxn)
7490 perf_event_exit_task_context(child, ctxn);
7493 static void perf_free_event(struct perf_event *event,
7494 struct perf_event_context *ctx)
7496 struct perf_event *parent = event->parent;
7498 if (WARN_ON_ONCE(!parent))
7499 return;
7501 mutex_lock(&parent->child_mutex);
7502 list_del_init(&event->child_list);
7503 mutex_unlock(&parent->child_mutex);
7505 put_event(parent);
7507 perf_group_detach(event);
7508 list_del_event(event, ctx);
7509 free_event(event);
7513 * free an unexposed, unused context as created by inheritance by
7514 * perf_event_init_task below, used by fork() in case of fail.
7516 void perf_event_free_task(struct task_struct *task)
7518 struct perf_event_context *ctx;
7519 struct perf_event *event, *tmp;
7520 int ctxn;
7522 for_each_task_context_nr(ctxn) {
7523 ctx = task->perf_event_ctxp[ctxn];
7524 if (!ctx)
7525 continue;
7527 mutex_lock(&ctx->mutex);
7528 again:
7529 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
7530 group_entry)
7531 perf_free_event(event, ctx);
7533 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
7534 group_entry)
7535 perf_free_event(event, ctx);
7537 if (!list_empty(&ctx->pinned_groups) ||
7538 !list_empty(&ctx->flexible_groups))
7539 goto again;
7541 mutex_unlock(&ctx->mutex);
7543 put_ctx(ctx);
7547 void perf_event_delayed_put(struct task_struct *task)
7549 int ctxn;
7551 for_each_task_context_nr(ctxn)
7552 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
7556 * inherit a event from parent task to child task:
7558 static struct perf_event *
7559 inherit_event(struct perf_event *parent_event,
7560 struct task_struct *parent,
7561 struct perf_event_context *parent_ctx,
7562 struct task_struct *child,
7563 struct perf_event *group_leader,
7564 struct perf_event_context *child_ctx)
7566 struct perf_event *child_event;
7567 unsigned long flags;
7570 * Instead of creating recursive hierarchies of events,
7571 * we link inherited events back to the original parent,
7572 * which has a filp for sure, which we use as the reference
7573 * count:
7575 if (parent_event->parent)
7576 parent_event = parent_event->parent;
7578 child_event = perf_event_alloc(&parent_event->attr,
7579 parent_event->cpu,
7580 child,
7581 group_leader, parent_event,
7582 NULL, NULL);
7583 if (IS_ERR(child_event))
7584 return child_event;
7586 if (!atomic_long_inc_not_zero(&parent_event->refcount)) {
7587 free_event(child_event);
7588 return NULL;
7591 get_ctx(child_ctx);
7594 * Make the child state follow the state of the parent event,
7595 * not its attr.disabled bit. We hold the parent's mutex,
7596 * so we won't race with perf_event_{en, dis}able_family.
7598 if (parent_event->state >= PERF_EVENT_STATE_INACTIVE)
7599 child_event->state = PERF_EVENT_STATE_INACTIVE;
7600 else
7601 child_event->state = PERF_EVENT_STATE_OFF;
7603 if (parent_event->attr.freq) {
7604 u64 sample_period = parent_event->hw.sample_period;
7605 struct hw_perf_event *hwc = &child_event->hw;
7607 hwc->sample_period = sample_period;
7608 hwc->last_period = sample_period;
7610 local64_set(&hwc->period_left, sample_period);
7613 child_event->ctx = child_ctx;
7614 child_event->overflow_handler = parent_event->overflow_handler;
7615 child_event->overflow_handler_context
7616 = parent_event->overflow_handler_context;
7619 * Precalculate sample_data sizes
7621 perf_event__header_size(child_event);
7622 perf_event__id_header_size(child_event);
7625 * Link it up in the child's context:
7627 raw_spin_lock_irqsave(&child_ctx->lock, flags);
7628 add_event_to_ctx(child_event, child_ctx);
7629 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7632 * Link this into the parent event's child list
7634 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7635 mutex_lock(&parent_event->child_mutex);
7636 list_add_tail(&child_event->child_list, &parent_event->child_list);
7637 mutex_unlock(&parent_event->child_mutex);
7639 return child_event;
7642 static int inherit_group(struct perf_event *parent_event,
7643 struct task_struct *parent,
7644 struct perf_event_context *parent_ctx,
7645 struct task_struct *child,
7646 struct perf_event_context *child_ctx)
7648 struct perf_event *leader;
7649 struct perf_event *sub;
7650 struct perf_event *child_ctr;
7652 leader = inherit_event(parent_event, parent, parent_ctx,
7653 child, NULL, child_ctx);
7654 if (IS_ERR(leader))
7655 return PTR_ERR(leader);
7656 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
7657 child_ctr = inherit_event(sub, parent, parent_ctx,
7658 child, leader, child_ctx);
7659 if (IS_ERR(child_ctr))
7660 return PTR_ERR(child_ctr);
7662 return 0;
7665 static int
7666 inherit_task_group(struct perf_event *event, struct task_struct *parent,
7667 struct perf_event_context *parent_ctx,
7668 struct task_struct *child, int ctxn,
7669 int *inherited_all)
7671 int ret;
7672 struct perf_event_context *child_ctx;
7674 if (!event->attr.inherit) {
7675 *inherited_all = 0;
7676 return 0;
7679 child_ctx = child->perf_event_ctxp[ctxn];
7680 if (!child_ctx) {
7682 * This is executed from the parent task context, so
7683 * inherit events that have been marked for cloning.
7684 * First allocate and initialize a context for the
7685 * child.
7688 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
7689 if (!child_ctx)
7690 return -ENOMEM;
7692 child->perf_event_ctxp[ctxn] = child_ctx;
7695 ret = inherit_group(event, parent, parent_ctx,
7696 child, child_ctx);
7698 if (ret)
7699 *inherited_all = 0;
7701 return ret;
7705 * Initialize the perf_event context in task_struct
7707 int perf_event_init_context(struct task_struct *child, int ctxn)
7709 struct perf_event_context *child_ctx, *parent_ctx;
7710 struct perf_event_context *cloned_ctx;
7711 struct perf_event *event;
7712 struct task_struct *parent = current;
7713 int inherited_all = 1;
7714 unsigned long flags;
7715 int ret = 0;
7717 if (likely(!parent->perf_event_ctxp[ctxn]))
7718 return 0;
7721 * If the parent's context is a clone, pin it so it won't get
7722 * swapped under us.
7724 parent_ctx = perf_pin_task_context(parent, ctxn);
7727 * No need to check if parent_ctx != NULL here; since we saw
7728 * it non-NULL earlier, the only reason for it to become NULL
7729 * is if we exit, and since we're currently in the middle of
7730 * a fork we can't be exiting at the same time.
7734 * Lock the parent list. No need to lock the child - not PID
7735 * hashed yet and not running, so nobody can access it.
7737 mutex_lock(&parent_ctx->mutex);
7740 * We dont have to disable NMIs - we are only looking at
7741 * the list, not manipulating it:
7743 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
7744 ret = inherit_task_group(event, parent, parent_ctx,
7745 child, ctxn, &inherited_all);
7746 if (ret)
7747 break;
7751 * We can't hold ctx->lock when iterating the ->flexible_group list due
7752 * to allocations, but we need to prevent rotation because
7753 * rotate_ctx() will change the list from interrupt context.
7755 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7756 parent_ctx->rotate_disable = 1;
7757 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7759 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
7760 ret = inherit_task_group(event, parent, parent_ctx,
7761 child, ctxn, &inherited_all);
7762 if (ret)
7763 break;
7766 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7767 parent_ctx->rotate_disable = 0;
7769 child_ctx = child->perf_event_ctxp[ctxn];
7771 if (child_ctx && inherited_all) {
7773 * Mark the child context as a clone of the parent
7774 * context, or of whatever the parent is a clone of.
7776 * Note that if the parent is a clone, the holding of
7777 * parent_ctx->lock avoids it from being uncloned.
7779 cloned_ctx = parent_ctx->parent_ctx;
7780 if (cloned_ctx) {
7781 child_ctx->parent_ctx = cloned_ctx;
7782 child_ctx->parent_gen = parent_ctx->parent_gen;
7783 } else {
7784 child_ctx->parent_ctx = parent_ctx;
7785 child_ctx->parent_gen = parent_ctx->generation;
7787 get_ctx(child_ctx->parent_ctx);
7790 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7791 mutex_unlock(&parent_ctx->mutex);
7793 perf_unpin_context(parent_ctx);
7794 put_ctx(parent_ctx);
7796 return ret;
7800 * Initialize the perf_event context in task_struct
7802 int perf_event_init_task(struct task_struct *child)
7804 int ctxn, ret;
7806 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
7807 mutex_init(&child->perf_event_mutex);
7808 INIT_LIST_HEAD(&child->perf_event_list);
7810 for_each_task_context_nr(ctxn) {
7811 ret = perf_event_init_context(child, ctxn);
7812 if (ret)
7813 return ret;
7816 return 0;
7819 static void __init perf_event_init_all_cpus(void)
7821 struct swevent_htable *swhash;
7822 int cpu;
7824 for_each_possible_cpu(cpu) {
7825 swhash = &per_cpu(swevent_htable, cpu);
7826 mutex_init(&swhash->hlist_mutex);
7827 INIT_LIST_HEAD(&per_cpu(rotation_list, cpu));
7831 static void perf_event_init_cpu(int cpu)
7833 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7835 mutex_lock(&swhash->hlist_mutex);
7836 if (swhash->hlist_refcount > 0) {
7837 struct swevent_hlist *hlist;
7839 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
7840 WARN_ON(!hlist);
7841 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7843 mutex_unlock(&swhash->hlist_mutex);
7846 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC
7847 static void perf_pmu_rotate_stop(struct pmu *pmu)
7849 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7851 WARN_ON(!irqs_disabled());
7853 list_del_init(&cpuctx->rotation_list);
7856 static void __perf_event_exit_context(void *__info)
7858 struct perf_event_context *ctx = __info;
7859 struct perf_event *event, *tmp;
7861 perf_pmu_rotate_stop(ctx->pmu);
7863 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups, group_entry)
7864 __perf_remove_from_context(event);
7865 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups, group_entry)
7866 __perf_remove_from_context(event);
7869 static void perf_event_exit_cpu_context(int cpu)
7871 struct perf_event_context *ctx;
7872 struct pmu *pmu;
7873 int idx;
7875 idx = srcu_read_lock(&pmus_srcu);
7876 list_for_each_entry_rcu(pmu, &pmus, entry) {
7877 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
7879 mutex_lock(&ctx->mutex);
7880 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
7881 mutex_unlock(&ctx->mutex);
7883 srcu_read_unlock(&pmus_srcu, idx);
7886 static void perf_event_exit_cpu(int cpu)
7888 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7890 mutex_lock(&swhash->hlist_mutex);
7891 swevent_hlist_release(swhash);
7892 mutex_unlock(&swhash->hlist_mutex);
7894 perf_event_exit_cpu_context(cpu);
7896 #else
7897 static inline void perf_event_exit_cpu(int cpu) { }
7898 #endif
7900 static int
7901 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
7903 int cpu;
7905 for_each_online_cpu(cpu)
7906 perf_event_exit_cpu(cpu);
7908 return NOTIFY_OK;
7912 * Run the perf reboot notifier at the very last possible moment so that
7913 * the generic watchdog code runs as long as possible.
7915 static struct notifier_block perf_reboot_notifier = {
7916 .notifier_call = perf_reboot,
7917 .priority = INT_MIN,
7920 static int
7921 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
7923 unsigned int cpu = (long)hcpu;
7925 switch (action & ~CPU_TASKS_FROZEN) {
7927 case CPU_UP_PREPARE:
7928 case CPU_DOWN_FAILED:
7929 perf_event_init_cpu(cpu);
7930 break;
7932 case CPU_UP_CANCELED:
7933 case CPU_DOWN_PREPARE:
7934 perf_event_exit_cpu(cpu);
7935 break;
7936 default:
7937 break;
7940 return NOTIFY_OK;
7943 void __init perf_event_init(void)
7945 int ret;
7947 idr_init(&pmu_idr);
7949 perf_event_init_all_cpus();
7950 init_srcu_struct(&pmus_srcu);
7951 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
7952 perf_pmu_register(&perf_cpu_clock, NULL, -1);
7953 perf_pmu_register(&perf_task_clock, NULL, -1);
7954 perf_tp_register();
7955 perf_cpu_notifier(perf_cpu_notify);
7956 register_reboot_notifier(&perf_reboot_notifier);
7958 ret = init_hw_breakpoint();
7959 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
7961 /* do not patch jump label more than once per second */
7962 jump_label_rate_limit(&perf_sched_events, HZ);
7965 * Build time assertion that we keep the data_head at the intended
7966 * location. IOW, validation we got the __reserved[] size right.
7968 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
7969 != 1024);
7972 static int __init perf_event_sysfs_init(void)
7974 struct pmu *pmu;
7975 int ret;
7977 mutex_lock(&pmus_lock);
7979 ret = bus_register(&pmu_bus);
7980 if (ret)
7981 goto unlock;
7983 list_for_each_entry(pmu, &pmus, entry) {
7984 if (!pmu->name || pmu->type < 0)
7985 continue;
7987 ret = pmu_dev_alloc(pmu);
7988 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
7990 pmu_bus_running = 1;
7991 ret = 0;
7993 unlock:
7994 mutex_unlock(&pmus_lock);
7996 return ret;
7998 device_initcall(perf_event_sysfs_init);
8000 #ifdef CONFIG_CGROUP_PERF
8001 static struct cgroup_subsys_state *
8002 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
8004 struct perf_cgroup *jc;
8006 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
8007 if (!jc)
8008 return ERR_PTR(-ENOMEM);
8010 jc->info = alloc_percpu(struct perf_cgroup_info);
8011 if (!jc->info) {
8012 kfree(jc);
8013 return ERR_PTR(-ENOMEM);
8016 return &jc->css;
8019 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
8021 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
8023 free_percpu(jc->info);
8024 kfree(jc);
8027 static int __perf_cgroup_move(void *info)
8029 struct task_struct *task = info;
8030 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
8031 return 0;
8034 static void perf_cgroup_attach(struct cgroup_subsys_state *css,
8035 struct cgroup_taskset *tset)
8037 struct task_struct *task;
8039 cgroup_taskset_for_each(task, css, tset)
8040 task_function_call(task, __perf_cgroup_move, task);
8043 static void perf_cgroup_exit(struct cgroup_subsys_state *css,
8044 struct cgroup_subsys_state *old_css,
8045 struct task_struct *task)
8048 * cgroup_exit() is called in the copy_process() failure path.
8049 * Ignore this case since the task hasn't ran yet, this avoids
8050 * trying to poke a half freed task state from generic code.
8052 if (!(task->flags & PF_EXITING))
8053 return;
8055 task_function_call(task, __perf_cgroup_move, task);
8058 struct cgroup_subsys perf_subsys = {
8059 .name = "perf_event",
8060 .subsys_id = perf_subsys_id,
8061 .css_alloc = perf_cgroup_css_alloc,
8062 .css_free = perf_cgroup_css_free,
8063 .exit = perf_cgroup_exit,
8064 .attach = perf_cgroup_attach,
8066 #endif /* CONFIG_CGROUP_PERF */