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
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>
45 #include <asm/irq_regs.h>
47 struct remote_function_call {
48 struct task_struct *p;
49 int (*func)(void *info);
54 static void remote_function(void *data)
56 struct remote_function_call *tfc = data;
57 struct task_struct *p = tfc->p;
61 if (task_cpu(p) != smp_processor_id() || !task_curr(p))
65 tfc->ret = tfc->func(tfc->info);
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
82 task_function_call(struct task_struct *p, int (*func) (void *info), void *info)
84 struct remote_function_call data = {
88 .ret = -ESRCH, /* No such (running) process */
92 smp_call_function_single(task_cpu(p), remote_function, &data, 1);
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 = {
112 .ret = -ENXIO, /* No such CPU */
115 smp_call_function_single(cpu, remote_function, &data, 1);
120 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
121 PERF_FLAG_FD_OUTPUT |\
122 PERF_FLAG_PID_CGROUP)
125 * branch priv levels that need permission checks
127 #define PERF_SAMPLE_BRANCH_PERM_PLM \
128 (PERF_SAMPLE_BRANCH_KERNEL |\
129 PERF_SAMPLE_BRANCH_HV)
132 EVENT_FLEXIBLE = 0x1,
134 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
138 * perf_sched_events : >0 events exist
139 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
141 struct static_key_deferred perf_sched_events __read_mostly;
142 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
143 static DEFINE_PER_CPU(atomic_t, perf_branch_stack_events);
145 static atomic_t nr_mmap_events __read_mostly;
146 static atomic_t nr_comm_events __read_mostly;
147 static atomic_t nr_task_events __read_mostly;
149 static LIST_HEAD(pmus);
150 static DEFINE_MUTEX(pmus_lock);
151 static struct srcu_struct pmus_srcu;
154 * perf event paranoia level:
155 * -1 - not paranoid at all
156 * 0 - disallow raw tracepoint access for unpriv
157 * 1 - disallow cpu events for unpriv
158 * 2 - disallow kernel profiling for unpriv
160 int sysctl_perf_event_paranoid __read_mostly = 1;
162 /* Minimum for 512 kiB + 1 user control page */
163 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
166 * max perf event sample rate
168 #define DEFAULT_MAX_SAMPLE_RATE 100000
169 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
170 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
172 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
174 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
175 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
177 static atomic_t perf_sample_allowed_ns __read_mostly =
178 ATOMIC_INIT( DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100);
180 void update_perf_cpu_limits(void)
182 u64 tmp = perf_sample_period_ns;
184 tmp *= sysctl_perf_cpu_time_max_percent;
186 atomic_set(&perf_sample_allowed_ns, tmp);
189 int perf_proc_update_handler(struct ctl_table *table, int write,
190 void __user *buffer, size_t *lenp,
193 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
198 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
199 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
200 update_perf_cpu_limits();
205 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
207 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
208 void __user *buffer, size_t *lenp,
211 int ret = proc_dointvec(table, write, buffer, lenp, ppos);
216 update_perf_cpu_limits();
222 * perf samples are done in some very critical code paths (NMIs).
223 * If they take too much CPU time, the system can lock up and not
224 * get any real work done. This will drop the sample rate when
225 * we detect that events are taking too long.
227 #define NR_ACCUMULATED_SAMPLES 128
228 DEFINE_PER_CPU(u64, running_sample_length);
230 void perf_sample_event_took(u64 sample_len_ns)
232 u64 avg_local_sample_len;
233 u64 local_samples_len;
235 if (atomic_read(&perf_sample_allowed_ns) == 0)
238 /* decay the counter by 1 average sample */
239 local_samples_len = __get_cpu_var(running_sample_length);
240 local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES;
241 local_samples_len += sample_len_ns;
242 __get_cpu_var(running_sample_length) = local_samples_len;
245 * note: this will be biased artifically low until we have
246 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
247 * from having to maintain a count.
249 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
251 if (avg_local_sample_len <= atomic_read(&perf_sample_allowed_ns))
254 if (max_samples_per_tick <= 1)
257 max_samples_per_tick = DIV_ROUND_UP(max_samples_per_tick, 2);
258 sysctl_perf_event_sample_rate = max_samples_per_tick * HZ;
259 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
261 printk_ratelimited(KERN_WARNING
262 "perf samples too long (%lld > %d), lowering "
263 "kernel.perf_event_max_sample_rate to %d\n",
264 avg_local_sample_len,
265 atomic_read(&perf_sample_allowed_ns),
266 sysctl_perf_event_sample_rate);
268 update_perf_cpu_limits();
271 static atomic64_t perf_event_id;
273 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
274 enum event_type_t event_type);
276 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
277 enum event_type_t event_type,
278 struct task_struct *task);
280 static void update_context_time(struct perf_event_context *ctx);
281 static u64 perf_event_time(struct perf_event *event);
283 void __weak perf_event_print_debug(void) { }
285 extern __weak const char *perf_pmu_name(void)
290 static inline u64 perf_clock(void)
292 return local_clock();
295 static inline struct perf_cpu_context *
296 __get_cpu_context(struct perf_event_context *ctx)
298 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
301 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
302 struct perf_event_context *ctx)
304 raw_spin_lock(&cpuctx->ctx.lock);
306 raw_spin_lock(&ctx->lock);
309 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
310 struct perf_event_context *ctx)
313 raw_spin_unlock(&ctx->lock);
314 raw_spin_unlock(&cpuctx->ctx.lock);
317 #ifdef CONFIG_CGROUP_PERF
320 * perf_cgroup_info keeps track of time_enabled for a cgroup.
321 * This is a per-cpu dynamically allocated data structure.
323 struct perf_cgroup_info {
329 struct cgroup_subsys_state css;
330 struct perf_cgroup_info __percpu *info;
334 * Must ensure cgroup is pinned (css_get) before calling
335 * this function. In other words, we cannot call this function
336 * if there is no cgroup event for the current CPU context.
338 static inline struct perf_cgroup *
339 perf_cgroup_from_task(struct task_struct *task)
341 return container_of(task_subsys_state(task, perf_subsys_id),
342 struct perf_cgroup, css);
346 perf_cgroup_match(struct perf_event *event)
348 struct perf_event_context *ctx = event->ctx;
349 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
351 /* @event doesn't care about cgroup */
355 /* wants specific cgroup scope but @cpuctx isn't associated with any */
360 * Cgroup scoping is recursive. An event enabled for a cgroup is
361 * also enabled for all its descendant cgroups. If @cpuctx's
362 * cgroup is a descendant of @event's (the test covers identity
363 * case), it's a match.
365 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
366 event->cgrp->css.cgroup);
369 static inline bool perf_tryget_cgroup(struct perf_event *event)
371 return css_tryget(&event->cgrp->css);
374 static inline void perf_put_cgroup(struct perf_event *event)
376 css_put(&event->cgrp->css);
379 static inline void perf_detach_cgroup(struct perf_event *event)
381 perf_put_cgroup(event);
385 static inline int is_cgroup_event(struct perf_event *event)
387 return event->cgrp != NULL;
390 static inline u64 perf_cgroup_event_time(struct perf_event *event)
392 struct perf_cgroup_info *t;
394 t = per_cpu_ptr(event->cgrp->info, event->cpu);
398 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
400 struct perf_cgroup_info *info;
405 info = this_cpu_ptr(cgrp->info);
407 info->time += now - info->timestamp;
408 info->timestamp = now;
411 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
413 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
415 __update_cgrp_time(cgrp_out);
418 static inline void update_cgrp_time_from_event(struct perf_event *event)
420 struct perf_cgroup *cgrp;
423 * ensure we access cgroup data only when needed and
424 * when we know the cgroup is pinned (css_get)
426 if (!is_cgroup_event(event))
429 cgrp = perf_cgroup_from_task(current);
431 * Do not update time when cgroup is not active
433 if (cgrp == event->cgrp)
434 __update_cgrp_time(event->cgrp);
438 perf_cgroup_set_timestamp(struct task_struct *task,
439 struct perf_event_context *ctx)
441 struct perf_cgroup *cgrp;
442 struct perf_cgroup_info *info;
445 * ctx->lock held by caller
446 * ensure we do not access cgroup data
447 * unless we have the cgroup pinned (css_get)
449 if (!task || !ctx->nr_cgroups)
452 cgrp = perf_cgroup_from_task(task);
453 info = this_cpu_ptr(cgrp->info);
454 info->timestamp = ctx->timestamp;
457 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
458 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
461 * reschedule events based on the cgroup constraint of task.
463 * mode SWOUT : schedule out everything
464 * mode SWIN : schedule in based on cgroup for next
466 void perf_cgroup_switch(struct task_struct *task, int mode)
468 struct perf_cpu_context *cpuctx;
473 * disable interrupts to avoid geting nr_cgroup
474 * changes via __perf_event_disable(). Also
477 local_irq_save(flags);
480 * we reschedule only in the presence of cgroup
481 * constrained events.
485 list_for_each_entry_rcu(pmu, &pmus, entry) {
486 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
487 if (cpuctx->unique_pmu != pmu)
488 continue; /* ensure we process each cpuctx once */
491 * perf_cgroup_events says at least one
492 * context on this CPU has cgroup events.
494 * ctx->nr_cgroups reports the number of cgroup
495 * events for a context.
497 if (cpuctx->ctx.nr_cgroups > 0) {
498 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
499 perf_pmu_disable(cpuctx->ctx.pmu);
501 if (mode & PERF_CGROUP_SWOUT) {
502 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
504 * must not be done before ctxswout due
505 * to event_filter_match() in event_sched_out()
510 if (mode & PERF_CGROUP_SWIN) {
511 WARN_ON_ONCE(cpuctx->cgrp);
513 * set cgrp before ctxsw in to allow
514 * event_filter_match() to not have to pass
517 cpuctx->cgrp = perf_cgroup_from_task(task);
518 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
520 perf_pmu_enable(cpuctx->ctx.pmu);
521 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
527 local_irq_restore(flags);
530 static inline void perf_cgroup_sched_out(struct task_struct *task,
531 struct task_struct *next)
533 struct perf_cgroup *cgrp1;
534 struct perf_cgroup *cgrp2 = NULL;
537 * we come here when we know perf_cgroup_events > 0
539 cgrp1 = perf_cgroup_from_task(task);
542 * next is NULL when called from perf_event_enable_on_exec()
543 * that will systematically cause a cgroup_switch()
546 cgrp2 = perf_cgroup_from_task(next);
549 * only schedule out current cgroup events if we know
550 * that we are switching to a different cgroup. Otherwise,
551 * do no touch the cgroup events.
554 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
557 static inline void perf_cgroup_sched_in(struct task_struct *prev,
558 struct task_struct *task)
560 struct perf_cgroup *cgrp1;
561 struct perf_cgroup *cgrp2 = NULL;
564 * we come here when we know perf_cgroup_events > 0
566 cgrp1 = perf_cgroup_from_task(task);
568 /* prev can never be NULL */
569 cgrp2 = perf_cgroup_from_task(prev);
572 * only need to schedule in cgroup events if we are changing
573 * cgroup during ctxsw. Cgroup events were not scheduled
574 * out of ctxsw out if that was not the case.
577 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
580 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
581 struct perf_event_attr *attr,
582 struct perf_event *group_leader)
584 struct perf_cgroup *cgrp;
585 struct cgroup_subsys_state *css;
586 struct fd f = fdget(fd);
592 css = cgroup_css_from_dir(f.file, perf_subsys_id);
598 cgrp = container_of(css, struct perf_cgroup, css);
601 /* must be done before we fput() the file */
602 if (!perf_tryget_cgroup(event)) {
609 * all events in a group must monitor
610 * the same cgroup because a task belongs
611 * to only one perf cgroup at a time
613 if (group_leader && group_leader->cgrp != cgrp) {
614 perf_detach_cgroup(event);
623 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
625 struct perf_cgroup_info *t;
626 t = per_cpu_ptr(event->cgrp->info, event->cpu);
627 event->shadow_ctx_time = now - t->timestamp;
631 perf_cgroup_defer_enabled(struct perf_event *event)
634 * when the current task's perf cgroup does not match
635 * the event's, we need to remember to call the
636 * perf_mark_enable() function the first time a task with
637 * a matching perf cgroup is scheduled in.
639 if (is_cgroup_event(event) && !perf_cgroup_match(event))
640 event->cgrp_defer_enabled = 1;
644 perf_cgroup_mark_enabled(struct perf_event *event,
645 struct perf_event_context *ctx)
647 struct perf_event *sub;
648 u64 tstamp = perf_event_time(event);
650 if (!event->cgrp_defer_enabled)
653 event->cgrp_defer_enabled = 0;
655 event->tstamp_enabled = tstamp - event->total_time_enabled;
656 list_for_each_entry(sub, &event->sibling_list, group_entry) {
657 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
658 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
659 sub->cgrp_defer_enabled = 0;
663 #else /* !CONFIG_CGROUP_PERF */
666 perf_cgroup_match(struct perf_event *event)
671 static inline void perf_detach_cgroup(struct perf_event *event)
674 static inline int is_cgroup_event(struct perf_event *event)
679 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
684 static inline void update_cgrp_time_from_event(struct perf_event *event)
688 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
692 static inline void perf_cgroup_sched_out(struct task_struct *task,
693 struct task_struct *next)
697 static inline void perf_cgroup_sched_in(struct task_struct *prev,
698 struct task_struct *task)
702 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
703 struct perf_event_attr *attr,
704 struct perf_event *group_leader)
710 perf_cgroup_set_timestamp(struct task_struct *task,
711 struct perf_event_context *ctx)
716 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
721 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
725 static inline u64 perf_cgroup_event_time(struct perf_event *event)
731 perf_cgroup_defer_enabled(struct perf_event *event)
736 perf_cgroup_mark_enabled(struct perf_event *event,
737 struct perf_event_context *ctx)
742 void perf_pmu_disable(struct pmu *pmu)
744 int *count = this_cpu_ptr(pmu->pmu_disable_count);
746 pmu->pmu_disable(pmu);
749 void perf_pmu_enable(struct pmu *pmu)
751 int *count = this_cpu_ptr(pmu->pmu_disable_count);
753 pmu->pmu_enable(pmu);
756 static DEFINE_PER_CPU(struct list_head, rotation_list);
759 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
760 * because they're strictly cpu affine and rotate_start is called with IRQs
761 * disabled, while rotate_context is called from IRQ context.
763 static void perf_pmu_rotate_start(struct pmu *pmu)
765 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
766 struct list_head *head = &__get_cpu_var(rotation_list);
768 WARN_ON(!irqs_disabled());
770 if (list_empty(&cpuctx->rotation_list)) {
771 int was_empty = list_empty(head);
772 list_add(&cpuctx->rotation_list, head);
774 tick_nohz_full_kick();
778 static void get_ctx(struct perf_event_context *ctx)
780 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
783 static void put_ctx(struct perf_event_context *ctx)
785 if (atomic_dec_and_test(&ctx->refcount)) {
787 put_ctx(ctx->parent_ctx);
789 put_task_struct(ctx->task);
790 kfree_rcu(ctx, rcu_head);
794 static void unclone_ctx(struct perf_event_context *ctx)
796 if (ctx->parent_ctx) {
797 put_ctx(ctx->parent_ctx);
798 ctx->parent_ctx = NULL;
802 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
805 * only top level events have the pid namespace they were created in
808 event = event->parent;
810 return task_tgid_nr_ns(p, event->ns);
813 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
816 * only top level events have the pid namespace they were created in
819 event = event->parent;
821 return task_pid_nr_ns(p, event->ns);
825 * If we inherit events we want to return the parent event id
828 static u64 primary_event_id(struct perf_event *event)
833 id = event->parent->id;
839 * Get the perf_event_context for a task and lock it.
840 * This has to cope with with the fact that until it is locked,
841 * the context could get moved to another task.
843 static struct perf_event_context *
844 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
846 struct perf_event_context *ctx;
850 * One of the few rules of preemptible RCU is that one cannot do
851 * rcu_read_unlock() while holding a scheduler (or nested) lock when
852 * part of the read side critical section was preemptible -- see
853 * rcu_read_unlock_special().
855 * Since ctx->lock nests under rq->lock we must ensure the entire read
856 * side critical section is non-preemptible.
860 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
863 * If this context is a clone of another, it might
864 * get swapped for another underneath us by
865 * perf_event_task_sched_out, though the
866 * rcu_read_lock() protects us from any context
867 * getting freed. Lock the context and check if it
868 * got swapped before we could get the lock, and retry
869 * if so. If we locked the right context, then it
870 * can't get swapped on us any more.
872 raw_spin_lock_irqsave(&ctx->lock, *flags);
873 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
874 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
880 if (!atomic_inc_not_zero(&ctx->refcount)) {
881 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
891 * Get the context for a task and increment its pin_count so it
892 * can't get swapped to another task. This also increments its
893 * reference count so that the context can't get freed.
895 static struct perf_event_context *
896 perf_pin_task_context(struct task_struct *task, int ctxn)
898 struct perf_event_context *ctx;
901 ctx = perf_lock_task_context(task, ctxn, &flags);
904 raw_spin_unlock_irqrestore(&ctx->lock, flags);
909 static void perf_unpin_context(struct perf_event_context *ctx)
913 raw_spin_lock_irqsave(&ctx->lock, flags);
915 raw_spin_unlock_irqrestore(&ctx->lock, flags);
919 * Update the record of the current time in a context.
921 static void update_context_time(struct perf_event_context *ctx)
923 u64 now = perf_clock();
925 ctx->time += now - ctx->timestamp;
926 ctx->timestamp = now;
929 static u64 perf_event_time(struct perf_event *event)
931 struct perf_event_context *ctx = event->ctx;
933 if (is_cgroup_event(event))
934 return perf_cgroup_event_time(event);
936 return ctx ? ctx->time : 0;
940 * Update the total_time_enabled and total_time_running fields for a event.
941 * The caller of this function needs to hold the ctx->lock.
943 static void update_event_times(struct perf_event *event)
945 struct perf_event_context *ctx = event->ctx;
948 if (event->state < PERF_EVENT_STATE_INACTIVE ||
949 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
952 * in cgroup mode, time_enabled represents
953 * the time the event was enabled AND active
954 * tasks were in the monitored cgroup. This is
955 * independent of the activity of the context as
956 * there may be a mix of cgroup and non-cgroup events.
958 * That is why we treat cgroup events differently
961 if (is_cgroup_event(event))
962 run_end = perf_cgroup_event_time(event);
963 else if (ctx->is_active)
966 run_end = event->tstamp_stopped;
968 event->total_time_enabled = run_end - event->tstamp_enabled;
970 if (event->state == PERF_EVENT_STATE_INACTIVE)
971 run_end = event->tstamp_stopped;
973 run_end = perf_event_time(event);
975 event->total_time_running = run_end - event->tstamp_running;
980 * Update total_time_enabled and total_time_running for all events in a group.
982 static void update_group_times(struct perf_event *leader)
984 struct perf_event *event;
986 update_event_times(leader);
987 list_for_each_entry(event, &leader->sibling_list, group_entry)
988 update_event_times(event);
991 static struct list_head *
992 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
994 if (event->attr.pinned)
995 return &ctx->pinned_groups;
997 return &ctx->flexible_groups;
1001 * Add a event from the lists for its context.
1002 * Must be called with ctx->mutex and ctx->lock held.
1005 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1007 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1008 event->attach_state |= PERF_ATTACH_CONTEXT;
1011 * If we're a stand alone event or group leader, we go to the context
1012 * list, group events are kept attached to the group so that
1013 * perf_group_detach can, at all times, locate all siblings.
1015 if (event->group_leader == event) {
1016 struct list_head *list;
1018 if (is_software_event(event))
1019 event->group_flags |= PERF_GROUP_SOFTWARE;
1021 list = ctx_group_list(event, ctx);
1022 list_add_tail(&event->group_entry, list);
1025 if (is_cgroup_event(event))
1028 if (has_branch_stack(event))
1029 ctx->nr_branch_stack++;
1031 list_add_rcu(&event->event_entry, &ctx->event_list);
1032 if (!ctx->nr_events)
1033 perf_pmu_rotate_start(ctx->pmu);
1035 if (event->attr.inherit_stat)
1040 * Initialize event state based on the perf_event_attr::disabled.
1042 static inline void perf_event__state_init(struct perf_event *event)
1044 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1045 PERF_EVENT_STATE_INACTIVE;
1049 * Called at perf_event creation and when events are attached/detached from a
1052 static void perf_event__read_size(struct perf_event *event)
1054 int entry = sizeof(u64); /* value */
1058 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1059 size += sizeof(u64);
1061 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1062 size += sizeof(u64);
1064 if (event->attr.read_format & PERF_FORMAT_ID)
1065 entry += sizeof(u64);
1067 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1068 nr += event->group_leader->nr_siblings;
1069 size += sizeof(u64);
1073 event->read_size = size;
1076 static void perf_event__header_size(struct perf_event *event)
1078 struct perf_sample_data *data;
1079 u64 sample_type = event->attr.sample_type;
1082 perf_event__read_size(event);
1084 if (sample_type & PERF_SAMPLE_IP)
1085 size += sizeof(data->ip);
1087 if (sample_type & PERF_SAMPLE_ADDR)
1088 size += sizeof(data->addr);
1090 if (sample_type & PERF_SAMPLE_PERIOD)
1091 size += sizeof(data->period);
1093 if (sample_type & PERF_SAMPLE_WEIGHT)
1094 size += sizeof(data->weight);
1096 if (sample_type & PERF_SAMPLE_READ)
1097 size += event->read_size;
1099 if (sample_type & PERF_SAMPLE_DATA_SRC)
1100 size += sizeof(data->data_src.val);
1102 event->header_size = size;
1105 static void perf_event__id_header_size(struct perf_event *event)
1107 struct perf_sample_data *data;
1108 u64 sample_type = event->attr.sample_type;
1111 if (sample_type & PERF_SAMPLE_TID)
1112 size += sizeof(data->tid_entry);
1114 if (sample_type & PERF_SAMPLE_TIME)
1115 size += sizeof(data->time);
1117 if (sample_type & PERF_SAMPLE_ID)
1118 size += sizeof(data->id);
1120 if (sample_type & PERF_SAMPLE_STREAM_ID)
1121 size += sizeof(data->stream_id);
1123 if (sample_type & PERF_SAMPLE_CPU)
1124 size += sizeof(data->cpu_entry);
1126 event->id_header_size = size;
1129 static void perf_group_attach(struct perf_event *event)
1131 struct perf_event *group_leader = event->group_leader, *pos;
1134 * We can have double attach due to group movement in perf_event_open.
1136 if (event->attach_state & PERF_ATTACH_GROUP)
1139 event->attach_state |= PERF_ATTACH_GROUP;
1141 if (group_leader == event)
1144 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1145 !is_software_event(event))
1146 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1148 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1149 group_leader->nr_siblings++;
1151 perf_event__header_size(group_leader);
1153 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1154 perf_event__header_size(pos);
1158 * Remove a event from the lists for its context.
1159 * Must be called with ctx->mutex and ctx->lock held.
1162 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1164 struct perf_cpu_context *cpuctx;
1166 * We can have double detach due to exit/hot-unplug + close.
1168 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1171 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1173 if (is_cgroup_event(event)) {
1175 cpuctx = __get_cpu_context(ctx);
1177 * if there are no more cgroup events
1178 * then cler cgrp to avoid stale pointer
1179 * in update_cgrp_time_from_cpuctx()
1181 if (!ctx->nr_cgroups)
1182 cpuctx->cgrp = NULL;
1185 if (has_branch_stack(event))
1186 ctx->nr_branch_stack--;
1189 if (event->attr.inherit_stat)
1192 list_del_rcu(&event->event_entry);
1194 if (event->group_leader == event)
1195 list_del_init(&event->group_entry);
1197 update_group_times(event);
1200 * If event was in error state, then keep it
1201 * that way, otherwise bogus counts will be
1202 * returned on read(). The only way to get out
1203 * of error state is by explicit re-enabling
1206 if (event->state > PERF_EVENT_STATE_OFF)
1207 event->state = PERF_EVENT_STATE_OFF;
1210 static void perf_group_detach(struct perf_event *event)
1212 struct perf_event *sibling, *tmp;
1213 struct list_head *list = NULL;
1216 * We can have double detach due to exit/hot-unplug + close.
1218 if (!(event->attach_state & PERF_ATTACH_GROUP))
1221 event->attach_state &= ~PERF_ATTACH_GROUP;
1224 * If this is a sibling, remove it from its group.
1226 if (event->group_leader != event) {
1227 list_del_init(&event->group_entry);
1228 event->group_leader->nr_siblings--;
1232 if (!list_empty(&event->group_entry))
1233 list = &event->group_entry;
1236 * If this was a group event with sibling events then
1237 * upgrade the siblings to singleton events by adding them
1238 * to whatever list we are on.
1240 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1242 list_move_tail(&sibling->group_entry, list);
1243 sibling->group_leader = sibling;
1245 /* Inherit group flags from the previous leader */
1246 sibling->group_flags = event->group_flags;
1250 perf_event__header_size(event->group_leader);
1252 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1253 perf_event__header_size(tmp);
1257 event_filter_match(struct perf_event *event)
1259 return (event->cpu == -1 || event->cpu == smp_processor_id())
1260 && perf_cgroup_match(event);
1264 event_sched_out(struct perf_event *event,
1265 struct perf_cpu_context *cpuctx,
1266 struct perf_event_context *ctx)
1268 u64 tstamp = perf_event_time(event);
1271 * An event which could not be activated because of
1272 * filter mismatch still needs to have its timings
1273 * maintained, otherwise bogus information is return
1274 * via read() for time_enabled, time_running:
1276 if (event->state == PERF_EVENT_STATE_INACTIVE
1277 && !event_filter_match(event)) {
1278 delta = tstamp - event->tstamp_stopped;
1279 event->tstamp_running += delta;
1280 event->tstamp_stopped = tstamp;
1283 if (event->state != PERF_EVENT_STATE_ACTIVE)
1286 event->state = PERF_EVENT_STATE_INACTIVE;
1287 if (event->pending_disable) {
1288 event->pending_disable = 0;
1289 event->state = PERF_EVENT_STATE_OFF;
1291 event->tstamp_stopped = tstamp;
1292 event->pmu->del(event, 0);
1295 if (!is_software_event(event))
1296 cpuctx->active_oncpu--;
1298 if (event->attr.freq && event->attr.sample_freq)
1300 if (event->attr.exclusive || !cpuctx->active_oncpu)
1301 cpuctx->exclusive = 0;
1305 group_sched_out(struct perf_event *group_event,
1306 struct perf_cpu_context *cpuctx,
1307 struct perf_event_context *ctx)
1309 struct perf_event *event;
1310 int state = group_event->state;
1312 event_sched_out(group_event, cpuctx, ctx);
1315 * Schedule out siblings (if any):
1317 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1318 event_sched_out(event, cpuctx, ctx);
1320 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1321 cpuctx->exclusive = 0;
1324 struct remove_event {
1325 struct perf_event *event;
1330 * Cross CPU call to remove a performance event
1332 * We disable the event on the hardware level first. After that we
1333 * remove it from the context list.
1335 static int __perf_remove_from_context(void *info)
1337 struct remove_event *re = info;
1338 struct perf_event *event = re->event;
1339 struct perf_event_context *ctx = event->ctx;
1340 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1342 raw_spin_lock(&ctx->lock);
1343 event_sched_out(event, cpuctx, ctx);
1344 if (re->detach_group)
1345 perf_group_detach(event);
1346 list_del_event(event, ctx);
1347 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1349 cpuctx->task_ctx = NULL;
1351 raw_spin_unlock(&ctx->lock);
1358 * Remove the event from a task's (or a CPU's) list of events.
1360 * CPU events are removed with a smp call. For task events we only
1361 * call when the task is on a CPU.
1363 * If event->ctx is a cloned context, callers must make sure that
1364 * every task struct that event->ctx->task could possibly point to
1365 * remains valid. This is OK when called from perf_release since
1366 * that only calls us on the top-level context, which can't be a clone.
1367 * When called from perf_event_exit_task, it's OK because the
1368 * context has been detached from its task.
1370 static void perf_remove_from_context(struct perf_event *event, bool detach_group)
1372 struct perf_event_context *ctx = event->ctx;
1373 struct task_struct *task = ctx->task;
1374 struct remove_event re = {
1376 .detach_group = detach_group,
1379 lockdep_assert_held(&ctx->mutex);
1383 * Per cpu events are removed via an smp call and
1384 * the removal is always successful.
1386 cpu_function_call(event->cpu, __perf_remove_from_context, &re);
1391 if (!task_function_call(task, __perf_remove_from_context, &re))
1394 raw_spin_lock_irq(&ctx->lock);
1396 * If we failed to find a running task, but find the context active now
1397 * that we've acquired the ctx->lock, retry.
1399 if (ctx->is_active) {
1400 raw_spin_unlock_irq(&ctx->lock);
1402 * Reload the task pointer, it might have been changed by
1403 * a concurrent perf_event_context_sched_out().
1410 * Since the task isn't running, its safe to remove the event, us
1411 * holding the ctx->lock ensures the task won't get scheduled in.
1414 perf_group_detach(event);
1415 list_del_event(event, ctx);
1416 raw_spin_unlock_irq(&ctx->lock);
1420 * Cross CPU call to disable a performance event
1422 int __perf_event_disable(void *info)
1424 struct perf_event *event = info;
1425 struct perf_event_context *ctx = event->ctx;
1426 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1429 * If this is a per-task event, need to check whether this
1430 * event's task is the current task on this cpu.
1432 * Can trigger due to concurrent perf_event_context_sched_out()
1433 * flipping contexts around.
1435 if (ctx->task && cpuctx->task_ctx != ctx)
1438 raw_spin_lock(&ctx->lock);
1441 * If the event is on, turn it off.
1442 * If it is in error state, leave it in error state.
1444 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1445 update_context_time(ctx);
1446 update_cgrp_time_from_event(event);
1447 update_group_times(event);
1448 if (event == event->group_leader)
1449 group_sched_out(event, cpuctx, ctx);
1451 event_sched_out(event, cpuctx, ctx);
1452 event->state = PERF_EVENT_STATE_OFF;
1455 raw_spin_unlock(&ctx->lock);
1463 * If event->ctx is a cloned context, callers must make sure that
1464 * every task struct that event->ctx->task could possibly point to
1465 * remains valid. This condition is satisifed when called through
1466 * perf_event_for_each_child or perf_event_for_each because they
1467 * hold the top-level event's child_mutex, so any descendant that
1468 * goes to exit will block in sync_child_event.
1469 * When called from perf_pending_event it's OK because event->ctx
1470 * is the current context on this CPU and preemption is disabled,
1471 * hence we can't get into perf_event_task_sched_out for this context.
1473 void perf_event_disable(struct perf_event *event)
1475 struct perf_event_context *ctx = event->ctx;
1476 struct task_struct *task = ctx->task;
1480 * Disable the event on the cpu that it's on
1482 cpu_function_call(event->cpu, __perf_event_disable, event);
1487 if (!task_function_call(task, __perf_event_disable, event))
1490 raw_spin_lock_irq(&ctx->lock);
1492 * If the event is still active, we need to retry the cross-call.
1494 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1495 raw_spin_unlock_irq(&ctx->lock);
1497 * Reload the task pointer, it might have been changed by
1498 * a concurrent perf_event_context_sched_out().
1505 * Since we have the lock this context can't be scheduled
1506 * in, so we can change the state safely.
1508 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1509 update_group_times(event);
1510 event->state = PERF_EVENT_STATE_OFF;
1512 raw_spin_unlock_irq(&ctx->lock);
1514 EXPORT_SYMBOL_GPL(perf_event_disable);
1516 static void perf_set_shadow_time(struct perf_event *event,
1517 struct perf_event_context *ctx,
1521 * use the correct time source for the time snapshot
1523 * We could get by without this by leveraging the
1524 * fact that to get to this function, the caller
1525 * has most likely already called update_context_time()
1526 * and update_cgrp_time_xx() and thus both timestamp
1527 * are identical (or very close). Given that tstamp is,
1528 * already adjusted for cgroup, we could say that:
1529 * tstamp - ctx->timestamp
1531 * tstamp - cgrp->timestamp.
1533 * Then, in perf_output_read(), the calculation would
1534 * work with no changes because:
1535 * - event is guaranteed scheduled in
1536 * - no scheduled out in between
1537 * - thus the timestamp would be the same
1539 * But this is a bit hairy.
1541 * So instead, we have an explicit cgroup call to remain
1542 * within the time time source all along. We believe it
1543 * is cleaner and simpler to understand.
1545 if (is_cgroup_event(event))
1546 perf_cgroup_set_shadow_time(event, tstamp);
1548 event->shadow_ctx_time = tstamp - ctx->timestamp;
1551 #define MAX_INTERRUPTS (~0ULL)
1553 static void perf_log_throttle(struct perf_event *event, int enable);
1556 event_sched_in(struct perf_event *event,
1557 struct perf_cpu_context *cpuctx,
1558 struct perf_event_context *ctx)
1560 u64 tstamp = perf_event_time(event);
1562 if (event->state <= PERF_EVENT_STATE_OFF)
1565 event->state = PERF_EVENT_STATE_ACTIVE;
1566 event->oncpu = smp_processor_id();
1569 * Unthrottle events, since we scheduled we might have missed several
1570 * ticks already, also for a heavily scheduling task there is little
1571 * guarantee it'll get a tick in a timely manner.
1573 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1574 perf_log_throttle(event, 1);
1575 event->hw.interrupts = 0;
1579 * The new state must be visible before we turn it on in the hardware:
1583 if (event->pmu->add(event, PERF_EF_START)) {
1584 event->state = PERF_EVENT_STATE_INACTIVE;
1589 event->tstamp_running += tstamp - event->tstamp_stopped;
1591 perf_set_shadow_time(event, ctx, tstamp);
1593 if (!is_software_event(event))
1594 cpuctx->active_oncpu++;
1596 if (event->attr.freq && event->attr.sample_freq)
1599 if (event->attr.exclusive)
1600 cpuctx->exclusive = 1;
1606 group_sched_in(struct perf_event *group_event,
1607 struct perf_cpu_context *cpuctx,
1608 struct perf_event_context *ctx)
1610 struct perf_event *event, *partial_group = NULL;
1611 struct pmu *pmu = group_event->pmu;
1612 u64 now = ctx->time;
1613 bool simulate = false;
1615 if (group_event->state == PERF_EVENT_STATE_OFF)
1618 pmu->start_txn(pmu);
1620 if (event_sched_in(group_event, cpuctx, ctx)) {
1621 pmu->cancel_txn(pmu);
1626 * Schedule in siblings as one group (if any):
1628 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1629 if (event_sched_in(event, cpuctx, ctx)) {
1630 partial_group = event;
1635 if (!pmu->commit_txn(pmu))
1640 * Groups can be scheduled in as one unit only, so undo any
1641 * partial group before returning:
1642 * The events up to the failed event are scheduled out normally,
1643 * tstamp_stopped will be updated.
1645 * The failed events and the remaining siblings need to have
1646 * their timings updated as if they had gone thru event_sched_in()
1647 * and event_sched_out(). This is required to get consistent timings
1648 * across the group. This also takes care of the case where the group
1649 * could never be scheduled by ensuring tstamp_stopped is set to mark
1650 * the time the event was actually stopped, such that time delta
1651 * calculation in update_event_times() is correct.
1653 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1654 if (event == partial_group)
1658 event->tstamp_running += now - event->tstamp_stopped;
1659 event->tstamp_stopped = now;
1661 event_sched_out(event, cpuctx, ctx);
1664 event_sched_out(group_event, cpuctx, ctx);
1666 pmu->cancel_txn(pmu);
1672 * Work out whether we can put this event group on the CPU now.
1674 static int group_can_go_on(struct perf_event *event,
1675 struct perf_cpu_context *cpuctx,
1679 * Groups consisting entirely of software events can always go on.
1681 if (event->group_flags & PERF_GROUP_SOFTWARE)
1684 * If an exclusive group is already on, no other hardware
1687 if (cpuctx->exclusive)
1690 * If this group is exclusive and there are already
1691 * events on the CPU, it can't go on.
1693 if (event->attr.exclusive && cpuctx->active_oncpu)
1696 * Otherwise, try to add it if all previous groups were able
1702 static void add_event_to_ctx(struct perf_event *event,
1703 struct perf_event_context *ctx)
1705 u64 tstamp = perf_event_time(event);
1707 list_add_event(event, ctx);
1708 perf_group_attach(event);
1709 event->tstamp_enabled = tstamp;
1710 event->tstamp_running = tstamp;
1711 event->tstamp_stopped = tstamp;
1714 static void task_ctx_sched_out(struct perf_event_context *ctx);
1716 ctx_sched_in(struct perf_event_context *ctx,
1717 struct perf_cpu_context *cpuctx,
1718 enum event_type_t event_type,
1719 struct task_struct *task);
1721 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
1722 struct perf_event_context *ctx,
1723 struct task_struct *task)
1725 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
1727 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
1728 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
1730 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
1734 * Cross CPU call to install and enable a performance event
1736 * Must be called with ctx->mutex held
1738 static int __perf_install_in_context(void *info)
1740 struct perf_event *event = info;
1741 struct perf_event_context *ctx = event->ctx;
1742 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1743 struct perf_event_context *task_ctx = cpuctx->task_ctx;
1744 struct task_struct *task = current;
1746 perf_ctx_lock(cpuctx, task_ctx);
1747 perf_pmu_disable(cpuctx->ctx.pmu);
1750 * If there was an active task_ctx schedule it out.
1753 task_ctx_sched_out(task_ctx);
1756 * If the context we're installing events in is not the
1757 * active task_ctx, flip them.
1759 if (ctx->task && task_ctx != ctx) {
1761 raw_spin_unlock(&task_ctx->lock);
1762 raw_spin_lock(&ctx->lock);
1767 cpuctx->task_ctx = task_ctx;
1768 task = task_ctx->task;
1771 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
1773 update_context_time(ctx);
1775 * update cgrp time only if current cgrp
1776 * matches event->cgrp. Must be done before
1777 * calling add_event_to_ctx()
1779 update_cgrp_time_from_event(event);
1781 add_event_to_ctx(event, ctx);
1784 * Schedule everything back in
1786 perf_event_sched_in(cpuctx, task_ctx, task);
1788 perf_pmu_enable(cpuctx->ctx.pmu);
1789 perf_ctx_unlock(cpuctx, task_ctx);
1795 * Attach a performance event to a context
1797 * First we add the event to the list with the hardware enable bit
1798 * in event->hw_config cleared.
1800 * If the event is attached to a task which is on a CPU we use a smp
1801 * call to enable it in the task context. The task might have been
1802 * scheduled away, but we check this in the smp call again.
1805 perf_install_in_context(struct perf_event_context *ctx,
1806 struct perf_event *event,
1809 struct task_struct *task = ctx->task;
1811 lockdep_assert_held(&ctx->mutex);
1814 if (event->cpu != -1)
1819 * Per cpu events are installed via an smp call and
1820 * the install is always successful.
1822 cpu_function_call(cpu, __perf_install_in_context, event);
1827 if (!task_function_call(task, __perf_install_in_context, event))
1830 raw_spin_lock_irq(&ctx->lock);
1832 * If we failed to find a running task, but find the context active now
1833 * that we've acquired the ctx->lock, retry.
1835 if (ctx->is_active) {
1836 raw_spin_unlock_irq(&ctx->lock);
1838 * Reload the task pointer, it might have been changed by
1839 * a concurrent perf_event_context_sched_out().
1846 * Since the task isn't running, its safe to add the event, us holding
1847 * the ctx->lock ensures the task won't get scheduled in.
1849 add_event_to_ctx(event, ctx);
1850 raw_spin_unlock_irq(&ctx->lock);
1854 * Put a event into inactive state and update time fields.
1855 * Enabling the leader of a group effectively enables all
1856 * the group members that aren't explicitly disabled, so we
1857 * have to update their ->tstamp_enabled also.
1858 * Note: this works for group members as well as group leaders
1859 * since the non-leader members' sibling_lists will be empty.
1861 static void __perf_event_mark_enabled(struct perf_event *event)
1863 struct perf_event *sub;
1864 u64 tstamp = perf_event_time(event);
1866 event->state = PERF_EVENT_STATE_INACTIVE;
1867 event->tstamp_enabled = tstamp - event->total_time_enabled;
1868 list_for_each_entry(sub, &event->sibling_list, group_entry) {
1869 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
1870 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
1875 * Cross CPU call to enable a performance event
1877 static int __perf_event_enable(void *info)
1879 struct perf_event *event = info;
1880 struct perf_event_context *ctx = event->ctx;
1881 struct perf_event *leader = event->group_leader;
1882 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1886 * There's a time window between 'ctx->is_active' check
1887 * in perf_event_enable function and this place having:
1889 * - ctx->lock unlocked
1891 * where the task could be killed and 'ctx' deactivated
1892 * by perf_event_exit_task.
1894 if (!ctx->is_active)
1897 raw_spin_lock(&ctx->lock);
1898 update_context_time(ctx);
1900 if (event->state >= PERF_EVENT_STATE_INACTIVE)
1904 * set current task's cgroup time reference point
1906 perf_cgroup_set_timestamp(current, ctx);
1908 __perf_event_mark_enabled(event);
1910 if (!event_filter_match(event)) {
1911 if (is_cgroup_event(event))
1912 perf_cgroup_defer_enabled(event);
1917 * If the event is in a group and isn't the group leader,
1918 * then don't put it on unless the group is on.
1920 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
1923 if (!group_can_go_on(event, cpuctx, 1)) {
1926 if (event == leader)
1927 err = group_sched_in(event, cpuctx, ctx);
1929 err = event_sched_in(event, cpuctx, ctx);
1934 * If this event can't go on and it's part of a
1935 * group, then the whole group has to come off.
1937 if (leader != event)
1938 group_sched_out(leader, cpuctx, ctx);
1939 if (leader->attr.pinned) {
1940 update_group_times(leader);
1941 leader->state = PERF_EVENT_STATE_ERROR;
1946 raw_spin_unlock(&ctx->lock);
1954 * If event->ctx is a cloned context, callers must make sure that
1955 * every task struct that event->ctx->task could possibly point to
1956 * remains valid. This condition is satisfied when called through
1957 * perf_event_for_each_child or perf_event_for_each as described
1958 * for perf_event_disable.
1960 void perf_event_enable(struct perf_event *event)
1962 struct perf_event_context *ctx = event->ctx;
1963 struct task_struct *task = ctx->task;
1967 * Enable the event on the cpu that it's on
1969 cpu_function_call(event->cpu, __perf_event_enable, event);
1973 raw_spin_lock_irq(&ctx->lock);
1974 if (event->state >= PERF_EVENT_STATE_INACTIVE)
1978 * If the event is in error state, clear that first.
1979 * That way, if we see the event in error state below, we
1980 * know that it has gone back into error state, as distinct
1981 * from the task having been scheduled away before the
1982 * cross-call arrived.
1984 if (event->state == PERF_EVENT_STATE_ERROR)
1985 event->state = PERF_EVENT_STATE_OFF;
1988 if (!ctx->is_active) {
1989 __perf_event_mark_enabled(event);
1993 raw_spin_unlock_irq(&ctx->lock);
1995 if (!task_function_call(task, __perf_event_enable, event))
1998 raw_spin_lock_irq(&ctx->lock);
2001 * If the context is active and the event is still off,
2002 * we need to retry the cross-call.
2004 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
2006 * task could have been flipped by a concurrent
2007 * perf_event_context_sched_out()
2014 raw_spin_unlock_irq(&ctx->lock);
2016 EXPORT_SYMBOL_GPL(perf_event_enable);
2018 int perf_event_refresh(struct perf_event *event, int refresh)
2021 * not supported on inherited events
2023 if (event->attr.inherit || !is_sampling_event(event))
2026 atomic_add(refresh, &event->event_limit);
2027 perf_event_enable(event);
2031 EXPORT_SYMBOL_GPL(perf_event_refresh);
2033 static void ctx_sched_out(struct perf_event_context *ctx,
2034 struct perf_cpu_context *cpuctx,
2035 enum event_type_t event_type)
2037 struct perf_event *event;
2038 int is_active = ctx->is_active;
2040 ctx->is_active &= ~event_type;
2041 if (likely(!ctx->nr_events))
2044 update_context_time(ctx);
2045 update_cgrp_time_from_cpuctx(cpuctx);
2046 if (!ctx->nr_active)
2049 perf_pmu_disable(ctx->pmu);
2050 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2051 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2052 group_sched_out(event, cpuctx, ctx);
2055 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2056 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2057 group_sched_out(event, cpuctx, ctx);
2059 perf_pmu_enable(ctx->pmu);
2063 * Test whether two contexts are equivalent, i.e. whether they
2064 * have both been cloned from the same version of the same context
2065 * and they both have the same number of enabled events.
2066 * If the number of enabled events is the same, then the set
2067 * of enabled events should be the same, because these are both
2068 * inherited contexts, therefore we can't access individual events
2069 * in them directly with an fd; we can only enable/disable all
2070 * events via prctl, or enable/disable all events in a family
2071 * via ioctl, which will have the same effect on both contexts.
2073 static int context_equiv(struct perf_event_context *ctx1,
2074 struct perf_event_context *ctx2)
2076 return ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx
2077 && ctx1->parent_gen == ctx2->parent_gen
2078 && !ctx1->pin_count && !ctx2->pin_count;
2081 static void __perf_event_sync_stat(struct perf_event *event,
2082 struct perf_event *next_event)
2086 if (!event->attr.inherit_stat)
2090 * Update the event value, we cannot use perf_event_read()
2091 * because we're in the middle of a context switch and have IRQs
2092 * disabled, which upsets smp_call_function_single(), however
2093 * we know the event must be on the current CPU, therefore we
2094 * don't need to use it.
2096 switch (event->state) {
2097 case PERF_EVENT_STATE_ACTIVE:
2098 event->pmu->read(event);
2101 case PERF_EVENT_STATE_INACTIVE:
2102 update_event_times(event);
2110 * In order to keep per-task stats reliable we need to flip the event
2111 * values when we flip the contexts.
2113 value = local64_read(&next_event->count);
2114 value = local64_xchg(&event->count, value);
2115 local64_set(&next_event->count, value);
2117 swap(event->total_time_enabled, next_event->total_time_enabled);
2118 swap(event->total_time_running, next_event->total_time_running);
2121 * Since we swizzled the values, update the user visible data too.
2123 perf_event_update_userpage(event);
2124 perf_event_update_userpage(next_event);
2127 static void perf_event_sync_stat(struct perf_event_context *ctx,
2128 struct perf_event_context *next_ctx)
2130 struct perf_event *event, *next_event;
2135 update_context_time(ctx);
2137 event = list_first_entry(&ctx->event_list,
2138 struct perf_event, event_entry);
2140 next_event = list_first_entry(&next_ctx->event_list,
2141 struct perf_event, event_entry);
2143 while (&event->event_entry != &ctx->event_list &&
2144 &next_event->event_entry != &next_ctx->event_list) {
2146 __perf_event_sync_stat(event, next_event);
2148 event = list_next_entry(event, event_entry);
2149 next_event = list_next_entry(next_event, event_entry);
2153 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2154 struct task_struct *next)
2156 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2157 struct perf_event_context *next_ctx;
2158 struct perf_event_context *parent;
2159 struct perf_cpu_context *cpuctx;
2165 cpuctx = __get_cpu_context(ctx);
2166 if (!cpuctx->task_ctx)
2170 parent = rcu_dereference(ctx->parent_ctx);
2171 next_ctx = next->perf_event_ctxp[ctxn];
2172 if (parent && next_ctx &&
2173 rcu_dereference(next_ctx->parent_ctx) == parent) {
2175 * Looks like the two contexts are clones, so we might be
2176 * able to optimize the context switch. We lock both
2177 * contexts and check that they are clones under the
2178 * lock (including re-checking that neither has been
2179 * uncloned in the meantime). It doesn't matter which
2180 * order we take the locks because no other cpu could
2181 * be trying to lock both of these tasks.
2183 raw_spin_lock(&ctx->lock);
2184 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2185 if (context_equiv(ctx, next_ctx)) {
2187 * XXX do we need a memory barrier of sorts
2188 * wrt to rcu_dereference() of perf_event_ctxp
2190 task->perf_event_ctxp[ctxn] = next_ctx;
2191 next->perf_event_ctxp[ctxn] = ctx;
2193 next_ctx->task = task;
2196 perf_event_sync_stat(ctx, next_ctx);
2198 raw_spin_unlock(&next_ctx->lock);
2199 raw_spin_unlock(&ctx->lock);
2204 raw_spin_lock(&ctx->lock);
2205 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2206 cpuctx->task_ctx = NULL;
2207 raw_spin_unlock(&ctx->lock);
2211 #define for_each_task_context_nr(ctxn) \
2212 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2215 * Called from scheduler to remove the events of the current task,
2216 * with interrupts disabled.
2218 * We stop each event and update the event value in event->count.
2220 * This does not protect us against NMI, but disable()
2221 * sets the disabled bit in the control field of event _before_
2222 * accessing the event control register. If a NMI hits, then it will
2223 * not restart the event.
2225 void __perf_event_task_sched_out(struct task_struct *task,
2226 struct task_struct *next)
2230 for_each_task_context_nr(ctxn)
2231 perf_event_context_sched_out(task, ctxn, next);
2234 * if cgroup events exist on this CPU, then we need
2235 * to check if we have to switch out PMU state.
2236 * cgroup event are system-wide mode only
2238 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2239 perf_cgroup_sched_out(task, next);
2242 static void task_ctx_sched_out(struct perf_event_context *ctx)
2244 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2246 if (!cpuctx->task_ctx)
2249 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2252 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2253 cpuctx->task_ctx = NULL;
2257 * Called with IRQs disabled
2259 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2260 enum event_type_t event_type)
2262 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2266 ctx_pinned_sched_in(struct perf_event_context *ctx,
2267 struct perf_cpu_context *cpuctx)
2269 struct perf_event *event;
2271 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2272 if (event->state <= PERF_EVENT_STATE_OFF)
2274 if (!event_filter_match(event))
2277 /* may need to reset tstamp_enabled */
2278 if (is_cgroup_event(event))
2279 perf_cgroup_mark_enabled(event, ctx);
2281 if (group_can_go_on(event, cpuctx, 1))
2282 group_sched_in(event, cpuctx, ctx);
2285 * If this pinned group hasn't been scheduled,
2286 * put it in error state.
2288 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2289 update_group_times(event);
2290 event->state = PERF_EVENT_STATE_ERROR;
2296 ctx_flexible_sched_in(struct perf_event_context *ctx,
2297 struct perf_cpu_context *cpuctx)
2299 struct perf_event *event;
2302 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2303 /* Ignore events in OFF or ERROR state */
2304 if (event->state <= PERF_EVENT_STATE_OFF)
2307 * Listen to the 'cpu' scheduling filter constraint
2310 if (!event_filter_match(event))
2313 /* may need to reset tstamp_enabled */
2314 if (is_cgroup_event(event))
2315 perf_cgroup_mark_enabled(event, ctx);
2317 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2318 if (group_sched_in(event, cpuctx, ctx))
2325 ctx_sched_in(struct perf_event_context *ctx,
2326 struct perf_cpu_context *cpuctx,
2327 enum event_type_t event_type,
2328 struct task_struct *task)
2331 int is_active = ctx->is_active;
2333 ctx->is_active |= event_type;
2334 if (likely(!ctx->nr_events))
2338 ctx->timestamp = now;
2339 perf_cgroup_set_timestamp(task, ctx);
2341 * First go through the list and put on any pinned groups
2342 * in order to give them the best chance of going on.
2344 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2345 ctx_pinned_sched_in(ctx, cpuctx);
2347 /* Then walk through the lower prio flexible groups */
2348 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2349 ctx_flexible_sched_in(ctx, cpuctx);
2352 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2353 enum event_type_t event_type,
2354 struct task_struct *task)
2356 struct perf_event_context *ctx = &cpuctx->ctx;
2358 ctx_sched_in(ctx, cpuctx, event_type, task);
2361 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2362 struct task_struct *task)
2364 struct perf_cpu_context *cpuctx;
2366 cpuctx = __get_cpu_context(ctx);
2367 if (cpuctx->task_ctx == ctx)
2370 perf_ctx_lock(cpuctx, ctx);
2371 perf_pmu_disable(ctx->pmu);
2373 * We want to keep the following priority order:
2374 * cpu pinned (that don't need to move), task pinned,
2375 * cpu flexible, task flexible.
2377 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2380 cpuctx->task_ctx = ctx;
2382 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2384 perf_pmu_enable(ctx->pmu);
2385 perf_ctx_unlock(cpuctx, ctx);
2388 * Since these rotations are per-cpu, we need to ensure the
2389 * cpu-context we got scheduled on is actually rotating.
2391 perf_pmu_rotate_start(ctx->pmu);
2395 * When sampling the branck stack in system-wide, it may be necessary
2396 * to flush the stack on context switch. This happens when the branch
2397 * stack does not tag its entries with the pid of the current task.
2398 * Otherwise it becomes impossible to associate a branch entry with a
2399 * task. This ambiguity is more likely to appear when the branch stack
2400 * supports priv level filtering and the user sets it to monitor only
2401 * at the user level (which could be a useful measurement in system-wide
2402 * mode). In that case, the risk is high of having a branch stack with
2403 * branch from multiple tasks. Flushing may mean dropping the existing
2404 * entries or stashing them somewhere in the PMU specific code layer.
2406 * This function provides the context switch callback to the lower code
2407 * layer. It is invoked ONLY when there is at least one system-wide context
2408 * with at least one active event using taken branch sampling.
2410 static void perf_branch_stack_sched_in(struct task_struct *prev,
2411 struct task_struct *task)
2413 struct perf_cpu_context *cpuctx;
2415 unsigned long flags;
2417 /* no need to flush branch stack if not changing task */
2421 local_irq_save(flags);
2425 list_for_each_entry_rcu(pmu, &pmus, entry) {
2426 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2429 * check if the context has at least one
2430 * event using PERF_SAMPLE_BRANCH_STACK
2432 if (cpuctx->ctx.nr_branch_stack > 0
2433 && pmu->flush_branch_stack) {
2435 pmu = cpuctx->ctx.pmu;
2437 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2439 perf_pmu_disable(pmu);
2441 pmu->flush_branch_stack();
2443 perf_pmu_enable(pmu);
2445 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2451 local_irq_restore(flags);
2455 * Called from scheduler to add the events of the current task
2456 * with interrupts disabled.
2458 * We restore the event value and then enable it.
2460 * This does not protect us against NMI, but enable()
2461 * sets the enabled bit in the control field of event _before_
2462 * accessing the event control register. If a NMI hits, then it will
2463 * keep the event running.
2465 void __perf_event_task_sched_in(struct task_struct *prev,
2466 struct task_struct *task)
2468 struct perf_event_context *ctx;
2471 for_each_task_context_nr(ctxn) {
2472 ctx = task->perf_event_ctxp[ctxn];
2476 perf_event_context_sched_in(ctx, task);
2479 * if cgroup events exist on this CPU, then we need
2480 * to check if we have to switch in PMU state.
2481 * cgroup event are system-wide mode only
2483 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2484 perf_cgroup_sched_in(prev, task);
2486 /* check for system-wide branch_stack events */
2487 if (atomic_read(&__get_cpu_var(perf_branch_stack_events)))
2488 perf_branch_stack_sched_in(prev, task);
2491 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2493 u64 frequency = event->attr.sample_freq;
2494 u64 sec = NSEC_PER_SEC;
2495 u64 divisor, dividend;
2497 int count_fls, nsec_fls, frequency_fls, sec_fls;
2499 count_fls = fls64(count);
2500 nsec_fls = fls64(nsec);
2501 frequency_fls = fls64(frequency);
2505 * We got @count in @nsec, with a target of sample_freq HZ
2506 * the target period becomes:
2509 * period = -------------------
2510 * @nsec * sample_freq
2515 * Reduce accuracy by one bit such that @a and @b converge
2516 * to a similar magnitude.
2518 #define REDUCE_FLS(a, b) \
2520 if (a##_fls > b##_fls) { \
2530 * Reduce accuracy until either term fits in a u64, then proceed with
2531 * the other, so that finally we can do a u64/u64 division.
2533 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2534 REDUCE_FLS(nsec, frequency);
2535 REDUCE_FLS(sec, count);
2538 if (count_fls + sec_fls > 64) {
2539 divisor = nsec * frequency;
2541 while (count_fls + sec_fls > 64) {
2542 REDUCE_FLS(count, sec);
2546 dividend = count * sec;
2548 dividend = count * sec;
2550 while (nsec_fls + frequency_fls > 64) {
2551 REDUCE_FLS(nsec, frequency);
2555 divisor = nsec * frequency;
2561 return div64_u64(dividend, divisor);
2564 static DEFINE_PER_CPU(int, perf_throttled_count);
2565 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2567 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2569 struct hw_perf_event *hwc = &event->hw;
2570 s64 period, sample_period;
2573 period = perf_calculate_period(event, nsec, count);
2575 delta = (s64)(period - hwc->sample_period);
2576 delta = (delta + 7) / 8; /* low pass filter */
2578 sample_period = hwc->sample_period + delta;
2583 hwc->sample_period = sample_period;
2585 if (local64_read(&hwc->period_left) > 8*sample_period) {
2587 event->pmu->stop(event, PERF_EF_UPDATE);
2589 local64_set(&hwc->period_left, 0);
2592 event->pmu->start(event, PERF_EF_RELOAD);
2597 * combine freq adjustment with unthrottling to avoid two passes over the
2598 * events. At the same time, make sure, having freq events does not change
2599 * the rate of unthrottling as that would introduce bias.
2601 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
2604 struct perf_event *event;
2605 struct hw_perf_event *hwc;
2606 u64 now, period = TICK_NSEC;
2610 * only need to iterate over all events iff:
2611 * - context have events in frequency mode (needs freq adjust)
2612 * - there are events to unthrottle on this cpu
2614 if (!(ctx->nr_freq || needs_unthr))
2617 raw_spin_lock(&ctx->lock);
2618 perf_pmu_disable(ctx->pmu);
2620 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
2621 if (event->state != PERF_EVENT_STATE_ACTIVE)
2624 if (!event_filter_match(event))
2629 if (needs_unthr && hwc->interrupts == MAX_INTERRUPTS) {
2630 hwc->interrupts = 0;
2631 perf_log_throttle(event, 1);
2632 event->pmu->start(event, 0);
2635 if (!event->attr.freq || !event->attr.sample_freq)
2639 * stop the event and update event->count
2641 event->pmu->stop(event, PERF_EF_UPDATE);
2643 now = local64_read(&event->count);
2644 delta = now - hwc->freq_count_stamp;
2645 hwc->freq_count_stamp = now;
2649 * reload only if value has changed
2650 * we have stopped the event so tell that
2651 * to perf_adjust_period() to avoid stopping it
2655 perf_adjust_period(event, period, delta, false);
2657 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
2660 perf_pmu_enable(ctx->pmu);
2661 raw_spin_unlock(&ctx->lock);
2665 * Round-robin a context's events:
2667 static void rotate_ctx(struct perf_event_context *ctx)
2670 * Rotate the first entry last of non-pinned groups. Rotation might be
2671 * disabled by the inheritance code.
2673 if (!ctx->rotate_disable)
2674 list_rotate_left(&ctx->flexible_groups);
2678 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
2679 * because they're strictly cpu affine and rotate_start is called with IRQs
2680 * disabled, while rotate_context is called from IRQ context.
2682 static void perf_rotate_context(struct perf_cpu_context *cpuctx)
2684 struct perf_event_context *ctx = NULL;
2685 int rotate = 0, remove = 1;
2687 if (cpuctx->ctx.nr_events) {
2689 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
2693 ctx = cpuctx->task_ctx;
2694 if (ctx && ctx->nr_events) {
2696 if (ctx->nr_events != ctx->nr_active)
2703 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2704 perf_pmu_disable(cpuctx->ctx.pmu);
2706 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2708 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
2710 rotate_ctx(&cpuctx->ctx);
2714 perf_event_sched_in(cpuctx, ctx, current);
2716 perf_pmu_enable(cpuctx->ctx.pmu);
2717 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2720 list_del_init(&cpuctx->rotation_list);
2723 #ifdef CONFIG_NO_HZ_FULL
2724 bool perf_event_can_stop_tick(void)
2726 if (list_empty(&__get_cpu_var(rotation_list)))
2733 void perf_event_task_tick(void)
2735 struct list_head *head = &__get_cpu_var(rotation_list);
2736 struct perf_cpu_context *cpuctx, *tmp;
2737 struct perf_event_context *ctx;
2740 WARN_ON(!irqs_disabled());
2742 __this_cpu_inc(perf_throttled_seq);
2743 throttled = __this_cpu_xchg(perf_throttled_count, 0);
2745 list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) {
2747 perf_adjust_freq_unthr_context(ctx, throttled);
2749 ctx = cpuctx->task_ctx;
2751 perf_adjust_freq_unthr_context(ctx, throttled);
2753 if (cpuctx->jiffies_interval == 1 ||
2754 !(jiffies % cpuctx->jiffies_interval))
2755 perf_rotate_context(cpuctx);
2759 static int event_enable_on_exec(struct perf_event *event,
2760 struct perf_event_context *ctx)
2762 if (!event->attr.enable_on_exec)
2765 event->attr.enable_on_exec = 0;
2766 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2769 __perf_event_mark_enabled(event);
2775 * Enable all of a task's events that have been marked enable-on-exec.
2776 * This expects task == current.
2778 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
2780 struct perf_event *event;
2781 unsigned long flags;
2785 local_irq_save(flags);
2786 if (!ctx || !ctx->nr_events)
2790 * We must ctxsw out cgroup events to avoid conflict
2791 * when invoking perf_task_event_sched_in() later on
2792 * in this function. Otherwise we end up trying to
2793 * ctxswin cgroup events which are already scheduled
2796 perf_cgroup_sched_out(current, NULL);
2798 raw_spin_lock(&ctx->lock);
2799 task_ctx_sched_out(ctx);
2801 list_for_each_entry(event, &ctx->event_list, event_entry) {
2802 ret = event_enable_on_exec(event, ctx);
2808 * Unclone this context if we enabled any event.
2813 raw_spin_unlock(&ctx->lock);
2816 * Also calls ctxswin for cgroup events, if any:
2818 perf_event_context_sched_in(ctx, ctx->task);
2820 local_irq_restore(flags);
2824 * Cross CPU call to read the hardware event
2826 static void __perf_event_read(void *info)
2828 struct perf_event *event = info;
2829 struct perf_event_context *ctx = event->ctx;
2830 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2833 * If this is a task context, we need to check whether it is
2834 * the current task context of this cpu. If not it has been
2835 * scheduled out before the smp call arrived. In that case
2836 * event->count would have been updated to a recent sample
2837 * when the event was scheduled out.
2839 if (ctx->task && cpuctx->task_ctx != ctx)
2842 raw_spin_lock(&ctx->lock);
2843 if (ctx->is_active) {
2844 update_context_time(ctx);
2845 update_cgrp_time_from_event(event);
2847 update_event_times(event);
2848 if (event->state == PERF_EVENT_STATE_ACTIVE)
2849 event->pmu->read(event);
2850 raw_spin_unlock(&ctx->lock);
2853 static inline u64 perf_event_count(struct perf_event *event)
2855 return local64_read(&event->count) + atomic64_read(&event->child_count);
2858 static u64 perf_event_read(struct perf_event *event)
2861 * If event is enabled and currently active on a CPU, update the
2862 * value in the event structure:
2864 if (event->state == PERF_EVENT_STATE_ACTIVE) {
2865 smp_call_function_single(event->oncpu,
2866 __perf_event_read, event, 1);
2867 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
2868 struct perf_event_context *ctx = event->ctx;
2869 unsigned long flags;
2871 raw_spin_lock_irqsave(&ctx->lock, flags);
2873 * may read while context is not active
2874 * (e.g., thread is blocked), in that case
2875 * we cannot update context time
2877 if (ctx->is_active) {
2878 update_context_time(ctx);
2879 update_cgrp_time_from_event(event);
2881 update_event_times(event);
2882 raw_spin_unlock_irqrestore(&ctx->lock, flags);
2885 return perf_event_count(event);
2889 * Initialize the perf_event context in a task_struct:
2891 static void __perf_event_init_context(struct perf_event_context *ctx)
2893 raw_spin_lock_init(&ctx->lock);
2894 mutex_init(&ctx->mutex);
2895 INIT_LIST_HEAD(&ctx->pinned_groups);
2896 INIT_LIST_HEAD(&ctx->flexible_groups);
2897 INIT_LIST_HEAD(&ctx->event_list);
2898 atomic_set(&ctx->refcount, 1);
2901 static struct perf_event_context *
2902 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
2904 struct perf_event_context *ctx;
2906 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
2910 __perf_event_init_context(ctx);
2913 get_task_struct(task);
2920 static struct task_struct *
2921 find_lively_task_by_vpid(pid_t vpid)
2923 struct task_struct *task;
2930 task = find_task_by_vpid(vpid);
2932 get_task_struct(task);
2936 return ERR_PTR(-ESRCH);
2938 /* Reuse ptrace permission checks for now. */
2940 if (!ptrace_may_access(task, PTRACE_MODE_READ))
2945 put_task_struct(task);
2946 return ERR_PTR(err);
2951 * Returns a matching context with refcount and pincount.
2953 static struct perf_event_context *
2954 find_get_context(struct pmu *pmu, struct task_struct *task, int cpu)
2956 struct perf_event_context *ctx;
2957 struct perf_cpu_context *cpuctx;
2958 unsigned long flags;
2962 /* Must be root to operate on a CPU event: */
2963 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
2964 return ERR_PTR(-EACCES);
2967 * We could be clever and allow to attach a event to an
2968 * offline CPU and activate it when the CPU comes up, but
2971 if (!cpu_online(cpu))
2972 return ERR_PTR(-ENODEV);
2974 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
2983 ctxn = pmu->task_ctx_nr;
2988 ctx = perf_lock_task_context(task, ctxn, &flags);
2992 raw_spin_unlock_irqrestore(&ctx->lock, flags);
2994 ctx = alloc_perf_context(pmu, task);
3000 mutex_lock(&task->perf_event_mutex);
3002 * If it has already passed perf_event_exit_task().
3003 * we must see PF_EXITING, it takes this mutex too.
3005 if (task->flags & PF_EXITING)
3007 else if (task->perf_event_ctxp[ctxn])
3012 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3014 mutex_unlock(&task->perf_event_mutex);
3016 if (unlikely(err)) {
3028 return ERR_PTR(err);
3031 static void perf_event_free_filter(struct perf_event *event);
3033 static void free_event_rcu(struct rcu_head *head)
3035 struct perf_event *event;
3037 event = container_of(head, struct perf_event, rcu_head);
3039 put_pid_ns(event->ns);
3040 perf_event_free_filter(event);
3044 static void ring_buffer_put(struct ring_buffer *rb);
3045 static void ring_buffer_detach(struct perf_event *event, struct ring_buffer *rb);
3047 static void free_event(struct perf_event *event)
3049 irq_work_sync(&event->pending);
3051 if (!event->parent) {
3052 if (event->attach_state & PERF_ATTACH_TASK)
3053 static_key_slow_dec_deferred(&perf_sched_events);
3054 if (event->attr.mmap || event->attr.mmap_data)
3055 atomic_dec(&nr_mmap_events);
3056 if (event->attr.comm)
3057 atomic_dec(&nr_comm_events);
3058 if (event->attr.task)
3059 atomic_dec(&nr_task_events);
3060 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3061 put_callchain_buffers();
3062 if (is_cgroup_event(event)) {
3063 atomic_dec(&per_cpu(perf_cgroup_events, event->cpu));
3064 static_key_slow_dec_deferred(&perf_sched_events);
3067 if (has_branch_stack(event)) {
3068 static_key_slow_dec_deferred(&perf_sched_events);
3069 /* is system-wide event */
3070 if (!(event->attach_state & PERF_ATTACH_TASK)) {
3071 atomic_dec(&per_cpu(perf_branch_stack_events,
3078 struct ring_buffer *rb;
3081 * Can happen when we close an event with re-directed output.
3083 * Since we have a 0 refcount, perf_mmap_close() will skip
3084 * over us; possibly making our ring_buffer_put() the last.
3086 mutex_lock(&event->mmap_mutex);
3089 rcu_assign_pointer(event->rb, NULL);
3090 ring_buffer_detach(event, rb);
3091 ring_buffer_put(rb); /* could be last */
3093 mutex_unlock(&event->mmap_mutex);
3096 if (is_cgroup_event(event))
3097 perf_detach_cgroup(event);
3100 event->destroy(event);
3103 put_ctx(event->ctx);
3105 call_rcu(&event->rcu_head, free_event_rcu);
3108 int perf_event_release_kernel(struct perf_event *event)
3110 struct perf_event_context *ctx = event->ctx;
3112 WARN_ON_ONCE(ctx->parent_ctx);
3114 * There are two ways this annotation is useful:
3116 * 1) there is a lock recursion from perf_event_exit_task
3117 * see the comment there.
3119 * 2) there is a lock-inversion with mmap_sem through
3120 * perf_event_read_group(), which takes faults while
3121 * holding ctx->mutex, however this is called after
3122 * the last filedesc died, so there is no possibility
3123 * to trigger the AB-BA case.
3125 mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
3126 perf_remove_from_context(event, true);
3127 mutex_unlock(&ctx->mutex);
3133 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3136 * Called when the last reference to the file is gone.
3138 static void put_event(struct perf_event *event)
3140 struct task_struct *owner;
3142 if (!atomic_long_dec_and_test(&event->refcount))
3146 owner = ACCESS_ONCE(event->owner);
3148 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3149 * !owner it means the list deletion is complete and we can indeed
3150 * free this event, otherwise we need to serialize on
3151 * owner->perf_event_mutex.
3153 smp_read_barrier_depends();
3156 * Since delayed_put_task_struct() also drops the last
3157 * task reference we can safely take a new reference
3158 * while holding the rcu_read_lock().
3160 get_task_struct(owner);
3165 mutex_lock(&owner->perf_event_mutex);
3167 * We have to re-check the event->owner field, if it is cleared
3168 * we raced with perf_event_exit_task(), acquiring the mutex
3169 * ensured they're done, and we can proceed with freeing the
3173 list_del_init(&event->owner_entry);
3174 mutex_unlock(&owner->perf_event_mutex);
3175 put_task_struct(owner);
3178 perf_event_release_kernel(event);
3181 static int perf_release(struct inode *inode, struct file *file)
3183 put_event(file->private_data);
3187 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3189 struct perf_event *child;
3195 mutex_lock(&event->child_mutex);
3196 total += perf_event_read(event);
3197 *enabled += event->total_time_enabled +
3198 atomic64_read(&event->child_total_time_enabled);
3199 *running += event->total_time_running +
3200 atomic64_read(&event->child_total_time_running);
3202 list_for_each_entry(child, &event->child_list, child_list) {
3203 total += perf_event_read(child);
3204 *enabled += child->total_time_enabled;
3205 *running += child->total_time_running;
3207 mutex_unlock(&event->child_mutex);
3211 EXPORT_SYMBOL_GPL(perf_event_read_value);
3213 static int perf_event_read_group(struct perf_event *event,
3214 u64 read_format, char __user *buf)
3216 struct perf_event *leader = event->group_leader, *sub;
3217 int n = 0, size = 0, ret = -EFAULT;
3218 struct perf_event_context *ctx = leader->ctx;
3220 u64 count, enabled, running;
3222 mutex_lock(&ctx->mutex);
3223 count = perf_event_read_value(leader, &enabled, &running);
3225 values[n++] = 1 + leader->nr_siblings;
3226 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3227 values[n++] = enabled;
3228 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3229 values[n++] = running;
3230 values[n++] = count;
3231 if (read_format & PERF_FORMAT_ID)
3232 values[n++] = primary_event_id(leader);
3234 size = n * sizeof(u64);
3236 if (copy_to_user(buf, values, size))
3241 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3244 values[n++] = perf_event_read_value(sub, &enabled, &running);
3245 if (read_format & PERF_FORMAT_ID)
3246 values[n++] = primary_event_id(sub);
3248 size = n * sizeof(u64);
3250 if (copy_to_user(buf + ret, values, size)) {
3258 mutex_unlock(&ctx->mutex);
3263 static int perf_event_read_one(struct perf_event *event,
3264 u64 read_format, char __user *buf)
3266 u64 enabled, running;
3270 values[n++] = perf_event_read_value(event, &enabled, &running);
3271 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3272 values[n++] = enabled;
3273 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3274 values[n++] = running;
3275 if (read_format & PERF_FORMAT_ID)
3276 values[n++] = primary_event_id(event);
3278 if (copy_to_user(buf, values, n * sizeof(u64)))
3281 return n * sizeof(u64);
3285 * Read the performance event - simple non blocking version for now
3288 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
3290 u64 read_format = event->attr.read_format;
3294 * Return end-of-file for a read on a event that is in
3295 * error state (i.e. because it was pinned but it couldn't be
3296 * scheduled on to the CPU at some point).
3298 if (event->state == PERF_EVENT_STATE_ERROR)
3301 if (count < event->read_size)
3304 WARN_ON_ONCE(event->ctx->parent_ctx);
3305 if (read_format & PERF_FORMAT_GROUP)
3306 ret = perf_event_read_group(event, read_format, buf);
3308 ret = perf_event_read_one(event, read_format, buf);
3314 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
3316 struct perf_event *event = file->private_data;
3318 return perf_read_hw(event, buf, count);
3321 static unsigned int perf_poll(struct file *file, poll_table *wait)
3323 struct perf_event *event = file->private_data;
3324 struct ring_buffer *rb;
3325 unsigned int events = POLL_HUP;
3328 * Pin the event->rb by taking event->mmap_mutex; otherwise
3329 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
3331 mutex_lock(&event->mmap_mutex);
3334 events = atomic_xchg(&rb->poll, 0);
3335 mutex_unlock(&event->mmap_mutex);
3337 poll_wait(file, &event->waitq, wait);
3342 static void perf_event_reset(struct perf_event *event)
3344 (void)perf_event_read(event);
3345 local64_set(&event->count, 0);
3346 perf_event_update_userpage(event);
3350 * Holding the top-level event's child_mutex means that any
3351 * descendant process that has inherited this event will block
3352 * in sync_child_event if it goes to exit, thus satisfying the
3353 * task existence requirements of perf_event_enable/disable.
3355 static void perf_event_for_each_child(struct perf_event *event,
3356 void (*func)(struct perf_event *))
3358 struct perf_event *child;
3360 WARN_ON_ONCE(event->ctx->parent_ctx);
3361 mutex_lock(&event->child_mutex);
3363 list_for_each_entry(child, &event->child_list, child_list)
3365 mutex_unlock(&event->child_mutex);
3368 static void perf_event_for_each(struct perf_event *event,
3369 void (*func)(struct perf_event *))
3371 struct perf_event_context *ctx = event->ctx;
3372 struct perf_event *sibling;
3374 WARN_ON_ONCE(ctx->parent_ctx);
3375 mutex_lock(&ctx->mutex);
3376 event = event->group_leader;
3378 perf_event_for_each_child(event, func);
3379 list_for_each_entry(sibling, &event->sibling_list, group_entry)
3380 perf_event_for_each_child(sibling, func);
3381 mutex_unlock(&ctx->mutex);
3384 static int perf_event_period(struct perf_event *event, u64 __user *arg)
3386 struct perf_event_context *ctx = event->ctx;
3390 if (!is_sampling_event(event))
3393 if (copy_from_user(&value, arg, sizeof(value)))
3399 raw_spin_lock_irq(&ctx->lock);
3400 if (event->attr.freq) {
3401 if (value > sysctl_perf_event_sample_rate) {
3406 event->attr.sample_freq = value;
3408 event->attr.sample_period = value;
3409 event->hw.sample_period = value;
3412 raw_spin_unlock_irq(&ctx->lock);
3417 static const struct file_operations perf_fops;
3419 static inline int perf_fget_light(int fd, struct fd *p)
3421 struct fd f = fdget(fd);
3425 if (f.file->f_op != &perf_fops) {
3433 static int perf_event_set_output(struct perf_event *event,
3434 struct perf_event *output_event);
3435 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
3437 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
3439 struct perf_event *event = file->private_data;
3440 void (*func)(struct perf_event *);
3444 case PERF_EVENT_IOC_ENABLE:
3445 func = perf_event_enable;
3447 case PERF_EVENT_IOC_DISABLE:
3448 func = perf_event_disable;
3450 case PERF_EVENT_IOC_RESET:
3451 func = perf_event_reset;
3454 case PERF_EVENT_IOC_REFRESH:
3455 return perf_event_refresh(event, arg);
3457 case PERF_EVENT_IOC_PERIOD:
3458 return perf_event_period(event, (u64 __user *)arg);
3460 case PERF_EVENT_IOC_SET_OUTPUT:
3464 struct perf_event *output_event;
3466 ret = perf_fget_light(arg, &output);
3469 output_event = output.file->private_data;
3470 ret = perf_event_set_output(event, output_event);
3473 ret = perf_event_set_output(event, NULL);
3478 case PERF_EVENT_IOC_SET_FILTER:
3479 return perf_event_set_filter(event, (void __user *)arg);
3485 if (flags & PERF_IOC_FLAG_GROUP)
3486 perf_event_for_each(event, func);
3488 perf_event_for_each_child(event, func);
3493 int perf_event_task_enable(void)
3495 struct perf_event *event;
3497 mutex_lock(¤t->perf_event_mutex);
3498 list_for_each_entry(event, ¤t->perf_event_list, owner_entry)
3499 perf_event_for_each_child(event, perf_event_enable);
3500 mutex_unlock(¤t->perf_event_mutex);
3505 int perf_event_task_disable(void)
3507 struct perf_event *event;
3509 mutex_lock(¤t->perf_event_mutex);
3510 list_for_each_entry(event, ¤t->perf_event_list, owner_entry)
3511 perf_event_for_each_child(event, perf_event_disable);
3512 mutex_unlock(¤t->perf_event_mutex);
3517 static int perf_event_index(struct perf_event *event)
3519 if (event->hw.state & PERF_HES_STOPPED)
3522 if (event->state != PERF_EVENT_STATE_ACTIVE)
3525 return event->pmu->event_idx(event);
3528 static void calc_timer_values(struct perf_event *event,
3535 *now = perf_clock();
3536 ctx_time = event->shadow_ctx_time + *now;
3537 *enabled = ctx_time - event->tstamp_enabled;
3538 *running = ctx_time - event->tstamp_running;
3541 void __weak arch_perf_update_userpage(struct perf_event_mmap_page *userpg, u64 now)
3546 * Callers need to ensure there can be no nesting of this function, otherwise
3547 * the seqlock logic goes bad. We can not serialize this because the arch
3548 * code calls this from NMI context.
3550 void perf_event_update_userpage(struct perf_event *event)
3552 struct perf_event_mmap_page *userpg;
3553 struct ring_buffer *rb;
3554 u64 enabled, running, now;
3558 * compute total_time_enabled, total_time_running
3559 * based on snapshot values taken when the event
3560 * was last scheduled in.
3562 * we cannot simply called update_context_time()
3563 * because of locking issue as we can be called in
3566 calc_timer_values(event, &now, &enabled, &running);
3567 rb = rcu_dereference(event->rb);
3571 userpg = rb->user_page;
3574 * Disable preemption so as to not let the corresponding user-space
3575 * spin too long if we get preempted.
3580 userpg->index = perf_event_index(event);
3581 userpg->offset = perf_event_count(event);
3583 userpg->offset -= local64_read(&event->hw.prev_count);
3585 userpg->time_enabled = enabled +
3586 atomic64_read(&event->child_total_time_enabled);
3588 userpg->time_running = running +
3589 atomic64_read(&event->child_total_time_running);
3591 arch_perf_update_userpage(userpg, now);
3600 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
3602 struct perf_event *event = vma->vm_file->private_data;
3603 struct ring_buffer *rb;
3604 int ret = VM_FAULT_SIGBUS;
3606 if (vmf->flags & FAULT_FLAG_MKWRITE) {
3607 if (vmf->pgoff == 0)
3613 rb = rcu_dereference(event->rb);
3617 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
3620 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
3624 get_page(vmf->page);
3625 vmf->page->mapping = vma->vm_file->f_mapping;
3626 vmf->page->index = vmf->pgoff;
3635 static void ring_buffer_attach(struct perf_event *event,
3636 struct ring_buffer *rb)
3638 unsigned long flags;
3640 if (!list_empty(&event->rb_entry))
3643 spin_lock_irqsave(&rb->event_lock, flags);
3644 if (list_empty(&event->rb_entry))
3645 list_add(&event->rb_entry, &rb->event_list);
3646 spin_unlock_irqrestore(&rb->event_lock, flags);
3649 static void ring_buffer_detach(struct perf_event *event, struct ring_buffer *rb)
3651 unsigned long flags;
3653 if (list_empty(&event->rb_entry))
3656 spin_lock_irqsave(&rb->event_lock, flags);
3657 list_del_init(&event->rb_entry);
3658 wake_up_all(&event->waitq);
3659 spin_unlock_irqrestore(&rb->event_lock, flags);
3662 static void ring_buffer_wakeup(struct perf_event *event)
3664 struct ring_buffer *rb;
3667 rb = rcu_dereference(event->rb);
3669 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
3670 wake_up_all(&event->waitq);
3675 static void rb_free_rcu(struct rcu_head *rcu_head)
3677 struct ring_buffer *rb;
3679 rb = container_of(rcu_head, struct ring_buffer, rcu_head);
3683 static struct ring_buffer *ring_buffer_get(struct perf_event *event)
3685 struct ring_buffer *rb;
3688 rb = rcu_dereference(event->rb);
3690 if (!atomic_inc_not_zero(&rb->refcount))
3698 static void ring_buffer_put(struct ring_buffer *rb)
3700 if (!atomic_dec_and_test(&rb->refcount))
3703 WARN_ON_ONCE(!list_empty(&rb->event_list));
3705 call_rcu(&rb->rcu_head, rb_free_rcu);
3708 static void perf_mmap_open(struct vm_area_struct *vma)
3710 struct perf_event *event = vma->vm_file->private_data;
3712 atomic_inc(&event->mmap_count);
3713 atomic_inc(&event->rb->mmap_count);
3717 * A buffer can be mmap()ed multiple times; either directly through the same
3718 * event, or through other events by use of perf_event_set_output().
3720 * In order to undo the VM accounting done by perf_mmap() we need to destroy
3721 * the buffer here, where we still have a VM context. This means we need
3722 * to detach all events redirecting to us.
3724 static void perf_mmap_close(struct vm_area_struct *vma)
3726 struct perf_event *event = vma->vm_file->private_data;
3728 struct ring_buffer *rb = event->rb;
3729 struct user_struct *mmap_user = rb->mmap_user;
3730 int mmap_locked = rb->mmap_locked;
3731 unsigned long size = perf_data_size(rb);
3733 atomic_dec(&rb->mmap_count);
3735 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
3738 /* Detach current event from the buffer. */
3739 rcu_assign_pointer(event->rb, NULL);
3740 ring_buffer_detach(event, rb);
3741 mutex_unlock(&event->mmap_mutex);
3743 /* If there's still other mmap()s of this buffer, we're done. */
3744 if (atomic_read(&rb->mmap_count)) {
3745 ring_buffer_put(rb); /* can't be last */
3750 * No other mmap()s, detach from all other events that might redirect
3751 * into the now unreachable buffer. Somewhat complicated by the
3752 * fact that rb::event_lock otherwise nests inside mmap_mutex.
3756 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
3757 if (!atomic_long_inc_not_zero(&event->refcount)) {
3759 * This event is en-route to free_event() which will
3760 * detach it and remove it from the list.
3766 mutex_lock(&event->mmap_mutex);
3768 * Check we didn't race with perf_event_set_output() which can
3769 * swizzle the rb from under us while we were waiting to
3770 * acquire mmap_mutex.
3772 * If we find a different rb; ignore this event, a next
3773 * iteration will no longer find it on the list. We have to
3774 * still restart the iteration to make sure we're not now
3775 * iterating the wrong list.
3777 if (event->rb == rb) {
3778 rcu_assign_pointer(event->rb, NULL);
3779 ring_buffer_detach(event, rb);
3780 ring_buffer_put(rb); /* can't be last, we still have one */
3782 mutex_unlock(&event->mmap_mutex);
3786 * Restart the iteration; either we're on the wrong list or
3787 * destroyed its integrity by doing a deletion.
3794 * It could be there's still a few 0-ref events on the list; they'll
3795 * get cleaned up by free_event() -- they'll also still have their
3796 * ref on the rb and will free it whenever they are done with it.
3798 * Aside from that, this buffer is 'fully' detached and unmapped,
3799 * undo the VM accounting.
3802 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
3803 vma->vm_mm->pinned_vm -= mmap_locked;
3804 free_uid(mmap_user);
3806 ring_buffer_put(rb); /* could be last */
3809 static const struct vm_operations_struct perf_mmap_vmops = {
3810 .open = perf_mmap_open,
3811 .close = perf_mmap_close,
3812 .fault = perf_mmap_fault,
3813 .page_mkwrite = perf_mmap_fault,
3816 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
3818 struct perf_event *event = file->private_data;
3819 unsigned long user_locked, user_lock_limit;
3820 struct user_struct *user = current_user();
3821 unsigned long locked, lock_limit;
3822 struct ring_buffer *rb;
3823 unsigned long vma_size;
3824 unsigned long nr_pages;
3825 long user_extra, extra;
3826 int ret = 0, flags = 0;
3829 * Don't allow mmap() of inherited per-task counters. This would
3830 * create a performance issue due to all children writing to the
3833 if (event->cpu == -1 && event->attr.inherit)
3836 if (!(vma->vm_flags & VM_SHARED))
3839 vma_size = vma->vm_end - vma->vm_start;
3840 nr_pages = (vma_size / PAGE_SIZE) - 1;
3843 * If we have rb pages ensure they're a power-of-two number, so we
3844 * can do bitmasks instead of modulo.
3846 if (nr_pages != 0 && !is_power_of_2(nr_pages))
3849 if (vma_size != PAGE_SIZE * (1 + nr_pages))
3852 if (vma->vm_pgoff != 0)
3855 WARN_ON_ONCE(event->ctx->parent_ctx);
3857 mutex_lock(&event->mmap_mutex);
3859 if (event->rb->nr_pages != nr_pages) {
3864 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
3866 * Raced against perf_mmap_close() through
3867 * perf_event_set_output(). Try again, hope for better
3870 mutex_unlock(&event->mmap_mutex);
3877 user_extra = nr_pages + 1;
3878 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
3881 * Increase the limit linearly with more CPUs:
3883 user_lock_limit *= num_online_cpus();
3885 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
3888 if (user_locked > user_lock_limit)
3889 extra = user_locked - user_lock_limit;
3891 lock_limit = rlimit(RLIMIT_MEMLOCK);
3892 lock_limit >>= PAGE_SHIFT;
3893 locked = vma->vm_mm->pinned_vm + extra;
3895 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
3896 !capable(CAP_IPC_LOCK)) {
3903 if (vma->vm_flags & VM_WRITE)
3904 flags |= RING_BUFFER_WRITABLE;
3906 rb = rb_alloc(nr_pages,
3907 event->attr.watermark ? event->attr.wakeup_watermark : 0,
3915 atomic_set(&rb->mmap_count, 1);
3916 rb->mmap_locked = extra;
3917 rb->mmap_user = get_current_user();
3919 atomic_long_add(user_extra, &user->locked_vm);
3920 vma->vm_mm->pinned_vm += extra;
3922 ring_buffer_attach(event, rb);
3923 rcu_assign_pointer(event->rb, rb);
3925 perf_event_update_userpage(event);
3929 atomic_inc(&event->mmap_count);
3930 mutex_unlock(&event->mmap_mutex);
3933 * Since pinned accounting is per vm we cannot allow fork() to copy our
3936 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
3937 vma->vm_ops = &perf_mmap_vmops;
3942 static int perf_fasync(int fd, struct file *filp, int on)
3944 struct inode *inode = file_inode(filp);
3945 struct perf_event *event = filp->private_data;
3948 mutex_lock(&inode->i_mutex);
3949 retval = fasync_helper(fd, filp, on, &event->fasync);
3950 mutex_unlock(&inode->i_mutex);
3958 static const struct file_operations perf_fops = {
3959 .llseek = no_llseek,
3960 .release = perf_release,
3963 .unlocked_ioctl = perf_ioctl,
3964 .compat_ioctl = perf_ioctl,
3966 .fasync = perf_fasync,
3972 * If there's data, ensure we set the poll() state and publish everything
3973 * to user-space before waking everybody up.
3976 void perf_event_wakeup(struct perf_event *event)
3978 ring_buffer_wakeup(event);
3980 if (event->pending_kill) {
3981 kill_fasync(&event->fasync, SIGIO, event->pending_kill);
3982 event->pending_kill = 0;
3986 static void perf_pending_event(struct irq_work *entry)
3988 struct perf_event *event = container_of(entry,
3989 struct perf_event, pending);
3991 if (event->pending_disable) {
3992 event->pending_disable = 0;
3993 __perf_event_disable(event);
3996 if (event->pending_wakeup) {
3997 event->pending_wakeup = 0;
3998 perf_event_wakeup(event);
4003 * We assume there is only KVM supporting the callbacks.
4004 * Later on, we might change it to a list if there is
4005 * another virtualization implementation supporting the callbacks.
4007 struct perf_guest_info_callbacks *perf_guest_cbs;
4009 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4011 perf_guest_cbs = cbs;
4014 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
4016 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4018 perf_guest_cbs = NULL;
4021 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
4024 perf_output_sample_regs(struct perf_output_handle *handle,
4025 struct pt_regs *regs, u64 mask)
4029 for_each_set_bit(bit, (const unsigned long *) &mask,
4030 sizeof(mask) * BITS_PER_BYTE) {
4033 val = perf_reg_value(regs, bit);
4034 perf_output_put(handle, val);
4038 static void perf_sample_regs_user(struct perf_regs_user *regs_user,
4039 struct pt_regs *regs)
4041 if (!user_mode(regs)) {
4043 regs = task_pt_regs(current);
4049 regs_user->regs = regs;
4050 regs_user->abi = perf_reg_abi(current);
4055 * Get remaining task size from user stack pointer.
4057 * It'd be better to take stack vma map and limit this more
4058 * precisly, but there's no way to get it safely under interrupt,
4059 * so using TASK_SIZE as limit.
4061 static u64 perf_ustack_task_size(struct pt_regs *regs)
4063 unsigned long addr = perf_user_stack_pointer(regs);
4065 if (!addr || addr >= TASK_SIZE)
4068 return TASK_SIZE - addr;
4072 perf_sample_ustack_size(u16 stack_size, u16 header_size,
4073 struct pt_regs *regs)
4077 /* No regs, no stack pointer, no dump. */
4082 * Check if we fit in with the requested stack size into the:
4084 * If we don't, we limit the size to the TASK_SIZE.
4086 * - remaining sample size
4087 * If we don't, we customize the stack size to
4088 * fit in to the remaining sample size.
4091 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
4092 stack_size = min(stack_size, (u16) task_size);
4094 /* Current header size plus static size and dynamic size. */
4095 header_size += 2 * sizeof(u64);
4097 /* Do we fit in with the current stack dump size? */
4098 if ((u16) (header_size + stack_size) < header_size) {
4100 * If we overflow the maximum size for the sample,
4101 * we customize the stack dump size to fit in.
4103 stack_size = USHRT_MAX - header_size - sizeof(u64);
4104 stack_size = round_up(stack_size, sizeof(u64));
4111 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
4112 struct pt_regs *regs)
4114 /* Case of a kernel thread, nothing to dump */
4117 perf_output_put(handle, size);
4126 * - the size requested by user or the best one we can fit
4127 * in to the sample max size
4129 * - user stack dump data
4131 * - the actual dumped size
4135 perf_output_put(handle, dump_size);
4138 sp = perf_user_stack_pointer(regs);
4139 rem = __output_copy_user(handle, (void *) sp, dump_size);
4140 dyn_size = dump_size - rem;
4142 perf_output_skip(handle, rem);
4145 perf_output_put(handle, dyn_size);
4149 static void __perf_event_header__init_id(struct perf_event_header *header,
4150 struct perf_sample_data *data,
4151 struct perf_event *event)
4153 u64 sample_type = event->attr.sample_type;
4155 data->type = sample_type;
4156 header->size += event->id_header_size;
4158 if (sample_type & PERF_SAMPLE_TID) {
4159 /* namespace issues */
4160 data->tid_entry.pid = perf_event_pid(event, current);
4161 data->tid_entry.tid = perf_event_tid(event, current);
4164 if (sample_type & PERF_SAMPLE_TIME)
4165 data->time = perf_clock();
4167 if (sample_type & PERF_SAMPLE_ID)
4168 data->id = primary_event_id(event);
4170 if (sample_type & PERF_SAMPLE_STREAM_ID)
4171 data->stream_id = event->id;
4173 if (sample_type & PERF_SAMPLE_CPU) {
4174 data->cpu_entry.cpu = raw_smp_processor_id();
4175 data->cpu_entry.reserved = 0;
4179 void perf_event_header__init_id(struct perf_event_header *header,
4180 struct perf_sample_data *data,
4181 struct perf_event *event)
4183 if (event->attr.sample_id_all)
4184 __perf_event_header__init_id(header, data, event);
4187 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
4188 struct perf_sample_data *data)
4190 u64 sample_type = data->type;
4192 if (sample_type & PERF_SAMPLE_TID)
4193 perf_output_put(handle, data->tid_entry);
4195 if (sample_type & PERF_SAMPLE_TIME)
4196 perf_output_put(handle, data->time);
4198 if (sample_type & PERF_SAMPLE_ID)
4199 perf_output_put(handle, data->id);
4201 if (sample_type & PERF_SAMPLE_STREAM_ID)
4202 perf_output_put(handle, data->stream_id);
4204 if (sample_type & PERF_SAMPLE_CPU)
4205 perf_output_put(handle, data->cpu_entry);
4208 void perf_event__output_id_sample(struct perf_event *event,
4209 struct perf_output_handle *handle,
4210 struct perf_sample_data *sample)
4212 if (event->attr.sample_id_all)
4213 __perf_event__output_id_sample(handle, sample);
4216 static void perf_output_read_one(struct perf_output_handle *handle,
4217 struct perf_event *event,
4218 u64 enabled, u64 running)
4220 u64 read_format = event->attr.read_format;
4224 values[n++] = perf_event_count(event);
4225 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4226 values[n++] = enabled +
4227 atomic64_read(&event->child_total_time_enabled);
4229 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4230 values[n++] = running +
4231 atomic64_read(&event->child_total_time_running);
4233 if (read_format & PERF_FORMAT_ID)
4234 values[n++] = primary_event_id(event);
4236 __output_copy(handle, values, n * sizeof(u64));
4240 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
4242 static void perf_output_read_group(struct perf_output_handle *handle,
4243 struct perf_event *event,
4244 u64 enabled, u64 running)
4246 struct perf_event *leader = event->group_leader, *sub;
4247 u64 read_format = event->attr.read_format;
4251 values[n++] = 1 + leader->nr_siblings;
4253 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4254 values[n++] = enabled;
4256 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4257 values[n++] = running;
4259 if (leader != event)
4260 leader->pmu->read(leader);
4262 values[n++] = perf_event_count(leader);
4263 if (read_format & PERF_FORMAT_ID)
4264 values[n++] = primary_event_id(leader);
4266 __output_copy(handle, values, n * sizeof(u64));
4268 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4272 sub->pmu->read(sub);
4274 values[n++] = perf_event_count(sub);
4275 if (read_format & PERF_FORMAT_ID)
4276 values[n++] = primary_event_id(sub);
4278 __output_copy(handle, values, n * sizeof(u64));
4282 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
4283 PERF_FORMAT_TOTAL_TIME_RUNNING)
4285 static void perf_output_read(struct perf_output_handle *handle,
4286 struct perf_event *event)
4288 u64 enabled = 0, running = 0, now;
4289 u64 read_format = event->attr.read_format;
4292 * compute total_time_enabled, total_time_running
4293 * based on snapshot values taken when the event
4294 * was last scheduled in.
4296 * we cannot simply called update_context_time()
4297 * because of locking issue as we are called in
4300 if (read_format & PERF_FORMAT_TOTAL_TIMES)
4301 calc_timer_values(event, &now, &enabled, &running);
4303 if (event->attr.read_format & PERF_FORMAT_GROUP)
4304 perf_output_read_group(handle, event, enabled, running);
4306 perf_output_read_one(handle, event, enabled, running);
4309 void perf_output_sample(struct perf_output_handle *handle,
4310 struct perf_event_header *header,
4311 struct perf_sample_data *data,
4312 struct perf_event *event)
4314 u64 sample_type = data->type;
4316 perf_output_put(handle, *header);
4318 if (sample_type & PERF_SAMPLE_IP)
4319 perf_output_put(handle, data->ip);
4321 if (sample_type & PERF_SAMPLE_TID)
4322 perf_output_put(handle, data->tid_entry);
4324 if (sample_type & PERF_SAMPLE_TIME)
4325 perf_output_put(handle, data->time);
4327 if (sample_type & PERF_SAMPLE_ADDR)
4328 perf_output_put(handle, data->addr);
4330 if (sample_type & PERF_SAMPLE_ID)
4331 perf_output_put(handle, data->id);
4333 if (sample_type & PERF_SAMPLE_STREAM_ID)
4334 perf_output_put(handle, data->stream_id);
4336 if (sample_type & PERF_SAMPLE_CPU)
4337 perf_output_put(handle, data->cpu_entry);
4339 if (sample_type & PERF_SAMPLE_PERIOD)
4340 perf_output_put(handle, data->period);
4342 if (sample_type & PERF_SAMPLE_READ)
4343 perf_output_read(handle, event);
4345 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4346 if (data->callchain) {
4349 if (data->callchain)
4350 size += data->callchain->nr;
4352 size *= sizeof(u64);
4354 __output_copy(handle, data->callchain, size);
4357 perf_output_put(handle, nr);
4361 if (sample_type & PERF_SAMPLE_RAW) {
4363 perf_output_put(handle, data->raw->size);
4364 __output_copy(handle, data->raw->data,
4371 .size = sizeof(u32),
4374 perf_output_put(handle, raw);
4378 if (!event->attr.watermark) {
4379 int wakeup_events = event->attr.wakeup_events;
4381 if (wakeup_events) {
4382 struct ring_buffer *rb = handle->rb;
4383 int events = local_inc_return(&rb->events);
4385 if (events >= wakeup_events) {
4386 local_sub(wakeup_events, &rb->events);
4387 local_inc(&rb->wakeup);
4392 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4393 if (data->br_stack) {
4396 size = data->br_stack->nr
4397 * sizeof(struct perf_branch_entry);
4399 perf_output_put(handle, data->br_stack->nr);
4400 perf_output_copy(handle, data->br_stack->entries, size);
4403 * we always store at least the value of nr
4406 perf_output_put(handle, nr);
4410 if (sample_type & PERF_SAMPLE_REGS_USER) {
4411 u64 abi = data->regs_user.abi;
4414 * If there are no regs to dump, notice it through
4415 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
4417 perf_output_put(handle, abi);
4420 u64 mask = event->attr.sample_regs_user;
4421 perf_output_sample_regs(handle,
4422 data->regs_user.regs,
4427 if (sample_type & PERF_SAMPLE_STACK_USER)
4428 perf_output_sample_ustack(handle,
4429 data->stack_user_size,
4430 data->regs_user.regs);
4432 if (sample_type & PERF_SAMPLE_WEIGHT)
4433 perf_output_put(handle, data->weight);
4435 if (sample_type & PERF_SAMPLE_DATA_SRC)
4436 perf_output_put(handle, data->data_src.val);
4439 void perf_prepare_sample(struct perf_event_header *header,
4440 struct perf_sample_data *data,
4441 struct perf_event *event,
4442 struct pt_regs *regs)
4444 u64 sample_type = event->attr.sample_type;
4446 header->type = PERF_RECORD_SAMPLE;
4447 header->size = sizeof(*header) + event->header_size;
4450 header->misc |= perf_misc_flags(regs);
4452 __perf_event_header__init_id(header, data, event);
4454 if (sample_type & PERF_SAMPLE_IP)
4455 data->ip = perf_instruction_pointer(regs);
4457 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4460 data->callchain = perf_callchain(event, regs);
4462 if (data->callchain)
4463 size += data->callchain->nr;
4465 header->size += size * sizeof(u64);
4468 if (sample_type & PERF_SAMPLE_RAW) {
4469 int size = sizeof(u32);
4472 size += data->raw->size;
4474 size += sizeof(u32);
4476 WARN_ON_ONCE(size & (sizeof(u64)-1));
4477 header->size += size;
4480 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4481 int size = sizeof(u64); /* nr */
4482 if (data->br_stack) {
4483 size += data->br_stack->nr
4484 * sizeof(struct perf_branch_entry);
4486 header->size += size;
4489 if (sample_type & PERF_SAMPLE_REGS_USER) {
4490 /* regs dump ABI info */
4491 int size = sizeof(u64);
4493 perf_sample_regs_user(&data->regs_user, regs);
4495 if (data->regs_user.regs) {
4496 u64 mask = event->attr.sample_regs_user;
4497 size += hweight64(mask) * sizeof(u64);
4500 header->size += size;
4503 if (sample_type & PERF_SAMPLE_STACK_USER) {
4505 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
4506 * processed as the last one or have additional check added
4507 * in case new sample type is added, because we could eat
4508 * up the rest of the sample size.
4510 struct perf_regs_user *uregs = &data->regs_user;
4511 u16 stack_size = event->attr.sample_stack_user;
4512 u16 size = sizeof(u64);
4515 perf_sample_regs_user(uregs, regs);
4517 stack_size = perf_sample_ustack_size(stack_size, header->size,
4521 * If there is something to dump, add space for the dump
4522 * itself and for the field that tells the dynamic size,
4523 * which is how many have been actually dumped.
4526 size += sizeof(u64) + stack_size;
4528 data->stack_user_size = stack_size;
4529 header->size += size;
4533 static void perf_event_output(struct perf_event *event,
4534 struct perf_sample_data *data,
4535 struct pt_regs *regs)
4537 struct perf_output_handle handle;
4538 struct perf_event_header header;
4540 /* protect the callchain buffers */
4543 perf_prepare_sample(&header, data, event, regs);
4545 if (perf_output_begin(&handle, event, header.size))
4548 perf_output_sample(&handle, &header, data, event);
4550 perf_output_end(&handle);
4560 struct perf_read_event {
4561 struct perf_event_header header;
4568 perf_event_read_event(struct perf_event *event,
4569 struct task_struct *task)
4571 struct perf_output_handle handle;
4572 struct perf_sample_data sample;
4573 struct perf_read_event read_event = {
4575 .type = PERF_RECORD_READ,
4577 .size = sizeof(read_event) + event->read_size,
4579 .pid = perf_event_pid(event, task),
4580 .tid = perf_event_tid(event, task),
4584 perf_event_header__init_id(&read_event.header, &sample, event);
4585 ret = perf_output_begin(&handle, event, read_event.header.size);
4589 perf_output_put(&handle, read_event);
4590 perf_output_read(&handle, event);
4591 perf_event__output_id_sample(event, &handle, &sample);
4593 perf_output_end(&handle);
4596 typedef int (perf_event_aux_match_cb)(struct perf_event *event, void *data);
4597 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
4600 perf_event_aux_ctx(struct perf_event_context *ctx,
4601 perf_event_aux_match_cb match,
4602 perf_event_aux_output_cb output,
4605 struct perf_event *event;
4607 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4608 if (event->state < PERF_EVENT_STATE_INACTIVE)
4610 if (!event_filter_match(event))
4612 if (match(event, data))
4613 output(event, data);
4618 perf_event_aux(perf_event_aux_match_cb match,
4619 perf_event_aux_output_cb output,
4621 struct perf_event_context *task_ctx)
4623 struct perf_cpu_context *cpuctx;
4624 struct perf_event_context *ctx;
4629 list_for_each_entry_rcu(pmu, &pmus, entry) {
4630 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4631 if (cpuctx->unique_pmu != pmu)
4633 perf_event_aux_ctx(&cpuctx->ctx, match, output, data);
4636 ctxn = pmu->task_ctx_nr;
4639 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4641 perf_event_aux_ctx(ctx, match, output, data);
4643 put_cpu_ptr(pmu->pmu_cpu_context);
4648 perf_event_aux_ctx(task_ctx, match, output, data);
4655 * task tracking -- fork/exit
4657 * enabled by: attr.comm | attr.mmap | attr.mmap_data | attr.task
4660 struct perf_task_event {
4661 struct task_struct *task;
4662 struct perf_event_context *task_ctx;
4665 struct perf_event_header header;
4675 static void perf_event_task_output(struct perf_event *event,
4678 struct perf_task_event *task_event = data;
4679 struct perf_output_handle handle;
4680 struct perf_sample_data sample;
4681 struct task_struct *task = task_event->task;
4682 int ret, size = task_event->event_id.header.size;
4684 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
4686 ret = perf_output_begin(&handle, event,
4687 task_event->event_id.header.size);
4691 task_event->event_id.pid = perf_event_pid(event, task);
4692 task_event->event_id.ppid = perf_event_pid(event, current);
4694 task_event->event_id.tid = perf_event_tid(event, task);
4695 task_event->event_id.ptid = perf_event_tid(event, current);
4697 perf_output_put(&handle, task_event->event_id);
4699 perf_event__output_id_sample(event, &handle, &sample);
4701 perf_output_end(&handle);
4703 task_event->event_id.header.size = size;
4706 static int perf_event_task_match(struct perf_event *event,
4707 void *data __maybe_unused)
4709 return event->attr.comm || event->attr.mmap ||
4710 event->attr.mmap_data || event->attr.task;
4713 static void perf_event_task(struct task_struct *task,
4714 struct perf_event_context *task_ctx,
4717 struct perf_task_event task_event;
4719 if (!atomic_read(&nr_comm_events) &&
4720 !atomic_read(&nr_mmap_events) &&
4721 !atomic_read(&nr_task_events))
4724 task_event = (struct perf_task_event){
4726 .task_ctx = task_ctx,
4729 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
4731 .size = sizeof(task_event.event_id),
4737 .time = perf_clock(),
4741 perf_event_aux(perf_event_task_match,
4742 perf_event_task_output,
4747 void perf_event_fork(struct task_struct *task)
4749 perf_event_task(task, NULL, 1);
4756 struct perf_comm_event {
4757 struct task_struct *task;
4762 struct perf_event_header header;
4769 static void perf_event_comm_output(struct perf_event *event,
4772 struct perf_comm_event *comm_event = data;
4773 struct perf_output_handle handle;
4774 struct perf_sample_data sample;
4775 int size = comm_event->event_id.header.size;
4778 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
4779 ret = perf_output_begin(&handle, event,
4780 comm_event->event_id.header.size);
4785 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
4786 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
4788 perf_output_put(&handle, comm_event->event_id);
4789 __output_copy(&handle, comm_event->comm,
4790 comm_event->comm_size);
4792 perf_event__output_id_sample(event, &handle, &sample);
4794 perf_output_end(&handle);
4796 comm_event->event_id.header.size = size;
4799 static int perf_event_comm_match(struct perf_event *event,
4800 void *data __maybe_unused)
4802 return event->attr.comm;
4805 static void perf_event_comm_event(struct perf_comm_event *comm_event)
4807 char comm[TASK_COMM_LEN];
4810 memset(comm, 0, sizeof(comm));
4811 strlcpy(comm, comm_event->task->comm, sizeof(comm));
4812 size = ALIGN(strlen(comm)+1, sizeof(u64));
4814 comm_event->comm = comm;
4815 comm_event->comm_size = size;
4817 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
4819 perf_event_aux(perf_event_comm_match,
4820 perf_event_comm_output,
4825 void perf_event_comm(struct task_struct *task)
4827 struct perf_comm_event comm_event;
4828 struct perf_event_context *ctx;
4832 for_each_task_context_nr(ctxn) {
4833 ctx = task->perf_event_ctxp[ctxn];
4837 perf_event_enable_on_exec(ctx);
4841 if (!atomic_read(&nr_comm_events))
4844 comm_event = (struct perf_comm_event){
4850 .type = PERF_RECORD_COMM,
4859 perf_event_comm_event(&comm_event);
4866 struct perf_mmap_event {
4867 struct vm_area_struct *vma;
4869 const char *file_name;
4873 struct perf_event_header header;
4883 static void perf_event_mmap_output(struct perf_event *event,
4886 struct perf_mmap_event *mmap_event = data;
4887 struct perf_output_handle handle;
4888 struct perf_sample_data sample;
4889 int size = mmap_event->event_id.header.size;
4892 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
4893 ret = perf_output_begin(&handle, event,
4894 mmap_event->event_id.header.size);
4898 mmap_event->event_id.pid = perf_event_pid(event, current);
4899 mmap_event->event_id.tid = perf_event_tid(event, current);
4901 perf_output_put(&handle, mmap_event->event_id);
4902 __output_copy(&handle, mmap_event->file_name,
4903 mmap_event->file_size);
4905 perf_event__output_id_sample(event, &handle, &sample);
4907 perf_output_end(&handle);
4909 mmap_event->event_id.header.size = size;
4912 static int perf_event_mmap_match(struct perf_event *event,
4915 struct perf_mmap_event *mmap_event = data;
4916 struct vm_area_struct *vma = mmap_event->vma;
4917 int executable = vma->vm_flags & VM_EXEC;
4919 return (!executable && event->attr.mmap_data) ||
4920 (executable && event->attr.mmap);
4923 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
4925 struct vm_area_struct *vma = mmap_event->vma;
4926 struct file *file = vma->vm_file;
4932 memset(tmp, 0, sizeof(tmp));
4936 * d_path works from the end of the rb backwards, so we
4937 * need to add enough zero bytes after the string to handle
4938 * the 64bit alignment we do later.
4940 buf = kzalloc(PATH_MAX + sizeof(u64), GFP_KERNEL);
4942 name = strncpy(tmp, "//enomem", sizeof(tmp));
4945 name = d_path(&file->f_path, buf, PATH_MAX);
4947 name = strncpy(tmp, "//toolong", sizeof(tmp));
4951 if (arch_vma_name(mmap_event->vma)) {
4952 name = strncpy(tmp, arch_vma_name(mmap_event->vma),
4954 tmp[sizeof(tmp) - 1] = '\0';
4959 name = strncpy(tmp, "[vdso]", sizeof(tmp));
4961 } else if (vma->vm_start <= vma->vm_mm->start_brk &&
4962 vma->vm_end >= vma->vm_mm->brk) {
4963 name = strncpy(tmp, "[heap]", sizeof(tmp));
4965 } else if (vma->vm_start <= vma->vm_mm->start_stack &&
4966 vma->vm_end >= vma->vm_mm->start_stack) {
4967 name = strncpy(tmp, "[stack]", sizeof(tmp));
4971 name = strncpy(tmp, "//anon", sizeof(tmp));
4976 size = ALIGN(strlen(name)+1, sizeof(u64));
4978 mmap_event->file_name = name;
4979 mmap_event->file_size = size;
4981 if (!(vma->vm_flags & VM_EXEC))
4982 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
4984 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
4986 perf_event_aux(perf_event_mmap_match,
4987 perf_event_mmap_output,
4994 void perf_event_mmap(struct vm_area_struct *vma)
4996 struct perf_mmap_event mmap_event;
4998 if (!atomic_read(&nr_mmap_events))
5001 mmap_event = (struct perf_mmap_event){
5007 .type = PERF_RECORD_MMAP,
5008 .misc = PERF_RECORD_MISC_USER,
5013 .start = vma->vm_start,
5014 .len = vma->vm_end - vma->vm_start,
5015 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
5019 perf_event_mmap_event(&mmap_event);
5023 * IRQ throttle logging
5026 static void perf_log_throttle(struct perf_event *event, int enable)
5028 struct perf_output_handle handle;
5029 struct perf_sample_data sample;
5033 struct perf_event_header header;
5037 } throttle_event = {
5039 .type = PERF_RECORD_THROTTLE,
5041 .size = sizeof(throttle_event),
5043 .time = perf_clock(),
5044 .id = primary_event_id(event),
5045 .stream_id = event->id,
5049 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
5051 perf_event_header__init_id(&throttle_event.header, &sample, event);
5053 ret = perf_output_begin(&handle, event,
5054 throttle_event.header.size);
5058 perf_output_put(&handle, throttle_event);
5059 perf_event__output_id_sample(event, &handle, &sample);
5060 perf_output_end(&handle);
5064 * Generic event overflow handling, sampling.
5067 static int __perf_event_overflow(struct perf_event *event,
5068 int throttle, struct perf_sample_data *data,
5069 struct pt_regs *regs)
5071 int events = atomic_read(&event->event_limit);
5072 struct hw_perf_event *hwc = &event->hw;
5077 * Non-sampling counters might still use the PMI to fold short
5078 * hardware counters, ignore those.
5080 if (unlikely(!is_sampling_event(event)))
5083 seq = __this_cpu_read(perf_throttled_seq);
5084 if (seq != hwc->interrupts_seq) {
5085 hwc->interrupts_seq = seq;
5086 hwc->interrupts = 1;
5089 if (unlikely(throttle
5090 && hwc->interrupts >= max_samples_per_tick)) {
5091 __this_cpu_inc(perf_throttled_count);
5092 hwc->interrupts = MAX_INTERRUPTS;
5093 perf_log_throttle(event, 0);
5098 if (event->attr.freq) {
5099 u64 now = perf_clock();
5100 s64 delta = now - hwc->freq_time_stamp;
5102 hwc->freq_time_stamp = now;
5104 if (delta > 0 && delta < 2*TICK_NSEC)
5105 perf_adjust_period(event, delta, hwc->last_period, true);
5109 * XXX event_limit might not quite work as expected on inherited
5113 event->pending_kill = POLL_IN;
5114 if (events && atomic_dec_and_test(&event->event_limit)) {
5116 event->pending_kill = POLL_HUP;
5117 event->pending_disable = 1;
5118 irq_work_queue(&event->pending);
5121 if (event->overflow_handler)
5122 event->overflow_handler(event, data, regs);
5124 perf_event_output(event, data, regs);
5126 if (event->fasync && event->pending_kill) {
5127 event->pending_wakeup = 1;
5128 irq_work_queue(&event->pending);
5134 int perf_event_overflow(struct perf_event *event,
5135 struct perf_sample_data *data,
5136 struct pt_regs *regs)
5138 return __perf_event_overflow(event, 1, data, regs);
5142 * Generic software event infrastructure
5145 struct swevent_htable {
5146 struct swevent_hlist *swevent_hlist;
5147 struct mutex hlist_mutex;
5150 /* Recursion avoidance in each contexts */
5151 int recursion[PERF_NR_CONTEXTS];
5153 /* Keeps track of cpu being initialized/exited */
5157 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
5160 * We directly increment event->count and keep a second value in
5161 * event->hw.period_left to count intervals. This period event
5162 * is kept in the range [-sample_period, 0] so that we can use the
5166 static u64 perf_swevent_set_period(struct perf_event *event)
5168 struct hw_perf_event *hwc = &event->hw;
5169 u64 period = hwc->last_period;
5173 hwc->last_period = hwc->sample_period;
5176 old = val = local64_read(&hwc->period_left);
5180 nr = div64_u64(period + val, period);
5181 offset = nr * period;
5183 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
5189 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
5190 struct perf_sample_data *data,
5191 struct pt_regs *regs)
5193 struct hw_perf_event *hwc = &event->hw;
5197 overflow = perf_swevent_set_period(event);
5199 if (hwc->interrupts == MAX_INTERRUPTS)
5202 for (; overflow; overflow--) {
5203 if (__perf_event_overflow(event, throttle,
5206 * We inhibit the overflow from happening when
5207 * hwc->interrupts == MAX_INTERRUPTS.
5215 static void perf_swevent_event(struct perf_event *event, u64 nr,
5216 struct perf_sample_data *data,
5217 struct pt_regs *regs)
5219 struct hw_perf_event *hwc = &event->hw;
5221 local64_add(nr, &event->count);
5226 if (!is_sampling_event(event))
5229 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
5231 return perf_swevent_overflow(event, 1, data, regs);
5233 data->period = event->hw.last_period;
5235 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
5236 return perf_swevent_overflow(event, 1, data, regs);
5238 if (local64_add_negative(nr, &hwc->period_left))
5241 perf_swevent_overflow(event, 0, data, regs);
5244 static int perf_exclude_event(struct perf_event *event,
5245 struct pt_regs *regs)
5247 if (event->hw.state & PERF_HES_STOPPED)
5251 if (event->attr.exclude_user && user_mode(regs))
5254 if (event->attr.exclude_kernel && !user_mode(regs))
5261 static int perf_swevent_match(struct perf_event *event,
5262 enum perf_type_id type,
5264 struct perf_sample_data *data,
5265 struct pt_regs *regs)
5267 if (event->attr.type != type)
5270 if (event->attr.config != event_id)
5273 if (perf_exclude_event(event, regs))
5279 static inline u64 swevent_hash(u64 type, u32 event_id)
5281 u64 val = event_id | (type << 32);
5283 return hash_64(val, SWEVENT_HLIST_BITS);
5286 static inline struct hlist_head *
5287 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
5289 u64 hash = swevent_hash(type, event_id);
5291 return &hlist->heads[hash];
5294 /* For the read side: events when they trigger */
5295 static inline struct hlist_head *
5296 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
5298 struct swevent_hlist *hlist;
5300 hlist = rcu_dereference(swhash->swevent_hlist);
5304 return __find_swevent_head(hlist, type, event_id);
5307 /* For the event head insertion and removal in the hlist */
5308 static inline struct hlist_head *
5309 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
5311 struct swevent_hlist *hlist;
5312 u32 event_id = event->attr.config;
5313 u64 type = event->attr.type;
5316 * Event scheduling is always serialized against hlist allocation
5317 * and release. Which makes the protected version suitable here.
5318 * The context lock guarantees that.
5320 hlist = rcu_dereference_protected(swhash->swevent_hlist,
5321 lockdep_is_held(&event->ctx->lock));
5325 return __find_swevent_head(hlist, type, event_id);
5328 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
5330 struct perf_sample_data *data,
5331 struct pt_regs *regs)
5333 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5334 struct perf_event *event;
5335 struct hlist_head *head;
5338 head = find_swevent_head_rcu(swhash, type, event_id);
5342 hlist_for_each_entry_rcu(event, head, hlist_entry) {
5343 if (perf_swevent_match(event, type, event_id, data, regs))
5344 perf_swevent_event(event, nr, data, regs);
5350 int perf_swevent_get_recursion_context(void)
5352 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5354 return get_recursion_context(swhash->recursion);
5356 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
5358 inline void perf_swevent_put_recursion_context(int rctx)
5360 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5362 put_recursion_context(swhash->recursion, rctx);
5365 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
5367 struct perf_sample_data data;
5370 preempt_disable_notrace();
5371 rctx = perf_swevent_get_recursion_context();
5375 perf_sample_data_init(&data, addr, 0);
5377 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
5379 perf_swevent_put_recursion_context(rctx);
5380 preempt_enable_notrace();
5383 static void perf_swevent_read(struct perf_event *event)
5387 static int perf_swevent_add(struct perf_event *event, int flags)
5389 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5390 struct hw_perf_event *hwc = &event->hw;
5391 struct hlist_head *head;
5393 if (is_sampling_event(event)) {
5394 hwc->last_period = hwc->sample_period;
5395 perf_swevent_set_period(event);
5398 hwc->state = !(flags & PERF_EF_START);
5400 head = find_swevent_head(swhash, event);
5403 * We can race with cpu hotplug code. Do not
5404 * WARN if the cpu just got unplugged.
5406 WARN_ON_ONCE(swhash->online);
5410 hlist_add_head_rcu(&event->hlist_entry, head);
5415 static void perf_swevent_del(struct perf_event *event, int flags)
5417 hlist_del_rcu(&event->hlist_entry);
5420 static void perf_swevent_start(struct perf_event *event, int flags)
5422 event->hw.state = 0;
5425 static void perf_swevent_stop(struct perf_event *event, int flags)
5427 event->hw.state = PERF_HES_STOPPED;
5430 /* Deref the hlist from the update side */
5431 static inline struct swevent_hlist *
5432 swevent_hlist_deref(struct swevent_htable *swhash)
5434 return rcu_dereference_protected(swhash->swevent_hlist,
5435 lockdep_is_held(&swhash->hlist_mutex));
5438 static void swevent_hlist_release(struct swevent_htable *swhash)
5440 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
5445 rcu_assign_pointer(swhash->swevent_hlist, NULL);
5446 kfree_rcu(hlist, rcu_head);
5449 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
5451 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5453 mutex_lock(&swhash->hlist_mutex);
5455 if (!--swhash->hlist_refcount)
5456 swevent_hlist_release(swhash);
5458 mutex_unlock(&swhash->hlist_mutex);
5461 static void swevent_hlist_put(struct perf_event *event)
5465 if (event->cpu != -1) {
5466 swevent_hlist_put_cpu(event, event->cpu);
5470 for_each_possible_cpu(cpu)
5471 swevent_hlist_put_cpu(event, cpu);
5474 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
5476 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5479 mutex_lock(&swhash->hlist_mutex);
5481 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
5482 struct swevent_hlist *hlist;
5484 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
5489 rcu_assign_pointer(swhash->swevent_hlist, hlist);
5491 swhash->hlist_refcount++;
5493 mutex_unlock(&swhash->hlist_mutex);
5498 static int swevent_hlist_get(struct perf_event *event)
5501 int cpu, failed_cpu;
5503 if (event->cpu != -1)
5504 return swevent_hlist_get_cpu(event, event->cpu);
5507 for_each_possible_cpu(cpu) {
5508 err = swevent_hlist_get_cpu(event, cpu);
5518 for_each_possible_cpu(cpu) {
5519 if (cpu == failed_cpu)
5521 swevent_hlist_put_cpu(event, cpu);
5528 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
5530 static void sw_perf_event_destroy(struct perf_event *event)
5532 u64 event_id = event->attr.config;
5534 WARN_ON(event->parent);
5536 static_key_slow_dec(&perf_swevent_enabled[event_id]);
5537 swevent_hlist_put(event);
5540 static int perf_swevent_init(struct perf_event *event)
5542 u64 event_id = event->attr.config;
5544 if (event->attr.type != PERF_TYPE_SOFTWARE)
5548 * no branch sampling for software events
5550 if (has_branch_stack(event))
5554 case PERF_COUNT_SW_CPU_CLOCK:
5555 case PERF_COUNT_SW_TASK_CLOCK:
5562 if (event_id >= PERF_COUNT_SW_MAX)
5565 if (!event->parent) {
5568 err = swevent_hlist_get(event);
5572 static_key_slow_inc(&perf_swevent_enabled[event_id]);
5573 event->destroy = sw_perf_event_destroy;
5579 static int perf_swevent_event_idx(struct perf_event *event)
5584 static struct pmu perf_swevent = {
5585 .task_ctx_nr = perf_sw_context,
5587 .event_init = perf_swevent_init,
5588 .add = perf_swevent_add,
5589 .del = perf_swevent_del,
5590 .start = perf_swevent_start,
5591 .stop = perf_swevent_stop,
5592 .read = perf_swevent_read,
5594 .event_idx = perf_swevent_event_idx,
5597 #ifdef CONFIG_EVENT_TRACING
5599 static int perf_tp_filter_match(struct perf_event *event,
5600 struct perf_sample_data *data)
5602 void *record = data->raw->data;
5604 if (likely(!event->filter) || filter_match_preds(event->filter, record))
5609 static int perf_tp_event_match(struct perf_event *event,
5610 struct perf_sample_data *data,
5611 struct pt_regs *regs)
5613 if (event->hw.state & PERF_HES_STOPPED)
5616 * All tracepoints are from kernel-space.
5618 if (event->attr.exclude_kernel)
5621 if (!perf_tp_filter_match(event, data))
5627 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
5628 struct pt_regs *regs, struct hlist_head *head, int rctx,
5629 struct task_struct *task)
5631 struct perf_sample_data data;
5632 struct perf_event *event;
5634 struct perf_raw_record raw = {
5639 perf_sample_data_init(&data, addr, 0);
5642 hlist_for_each_entry_rcu(event, head, hlist_entry) {
5643 if (perf_tp_event_match(event, &data, regs))
5644 perf_swevent_event(event, count, &data, regs);
5648 * If we got specified a target task, also iterate its context and
5649 * deliver this event there too.
5651 if (task && task != current) {
5652 struct perf_event_context *ctx;
5653 struct trace_entry *entry = record;
5656 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
5660 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5661 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5663 if (event->attr.config != entry->type)
5665 if (perf_tp_event_match(event, &data, regs))
5666 perf_swevent_event(event, count, &data, regs);
5672 perf_swevent_put_recursion_context(rctx);
5674 EXPORT_SYMBOL_GPL(perf_tp_event);
5676 static void tp_perf_event_destroy(struct perf_event *event)
5678 perf_trace_destroy(event);
5681 static int perf_tp_event_init(struct perf_event *event)
5685 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5689 * no branch sampling for tracepoint events
5691 if (has_branch_stack(event))
5694 err = perf_trace_init(event);
5698 event->destroy = tp_perf_event_destroy;
5703 static struct pmu perf_tracepoint = {
5704 .task_ctx_nr = perf_sw_context,
5706 .event_init = perf_tp_event_init,
5707 .add = perf_trace_add,
5708 .del = perf_trace_del,
5709 .start = perf_swevent_start,
5710 .stop = perf_swevent_stop,
5711 .read = perf_swevent_read,
5713 .event_idx = perf_swevent_event_idx,
5716 static inline void perf_tp_register(void)
5718 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
5721 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
5726 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5729 filter_str = strndup_user(arg, PAGE_SIZE);
5730 if (IS_ERR(filter_str))
5731 return PTR_ERR(filter_str);
5733 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
5739 static void perf_event_free_filter(struct perf_event *event)
5741 ftrace_profile_free_filter(event);
5746 static inline void perf_tp_register(void)
5750 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
5755 static void perf_event_free_filter(struct perf_event *event)
5759 #endif /* CONFIG_EVENT_TRACING */
5761 #ifdef CONFIG_HAVE_HW_BREAKPOINT
5762 void perf_bp_event(struct perf_event *bp, void *data)
5764 struct perf_sample_data sample;
5765 struct pt_regs *regs = data;
5767 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
5769 if (!bp->hw.state && !perf_exclude_event(bp, regs))
5770 perf_swevent_event(bp, 1, &sample, regs);
5775 * hrtimer based swevent callback
5778 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
5780 enum hrtimer_restart ret = HRTIMER_RESTART;
5781 struct perf_sample_data data;
5782 struct pt_regs *regs;
5783 struct perf_event *event;
5786 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
5788 if (event->state != PERF_EVENT_STATE_ACTIVE)
5789 return HRTIMER_NORESTART;
5791 event->pmu->read(event);
5793 perf_sample_data_init(&data, 0, event->hw.last_period);
5794 regs = get_irq_regs();
5796 if (regs && !perf_exclude_event(event, regs)) {
5797 if (!(event->attr.exclude_idle && is_idle_task(current)))
5798 if (__perf_event_overflow(event, 1, &data, regs))
5799 ret = HRTIMER_NORESTART;
5802 period = max_t(u64, 10000, event->hw.sample_period);
5803 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
5808 static void perf_swevent_start_hrtimer(struct perf_event *event)
5810 struct hw_perf_event *hwc = &event->hw;
5813 if (!is_sampling_event(event))
5816 period = local64_read(&hwc->period_left);
5821 local64_set(&hwc->period_left, 0);
5823 period = max_t(u64, 10000, hwc->sample_period);
5825 __hrtimer_start_range_ns(&hwc->hrtimer,
5826 ns_to_ktime(period), 0,
5827 HRTIMER_MODE_REL_PINNED, 0);
5830 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
5832 struct hw_perf_event *hwc = &event->hw;
5834 if (is_sampling_event(event)) {
5835 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
5836 local64_set(&hwc->period_left, ktime_to_ns(remaining));
5838 hrtimer_cancel(&hwc->hrtimer);
5842 static void perf_swevent_init_hrtimer(struct perf_event *event)
5844 struct hw_perf_event *hwc = &event->hw;
5846 if (!is_sampling_event(event))
5849 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
5850 hwc->hrtimer.function = perf_swevent_hrtimer;
5853 * Since hrtimers have a fixed rate, we can do a static freq->period
5854 * mapping and avoid the whole period adjust feedback stuff.
5856 if (event->attr.freq) {
5857 long freq = event->attr.sample_freq;
5859 event->attr.sample_period = NSEC_PER_SEC / freq;
5860 hwc->sample_period = event->attr.sample_period;
5861 local64_set(&hwc->period_left, hwc->sample_period);
5862 hwc->last_period = hwc->sample_period;
5863 event->attr.freq = 0;
5868 * Software event: cpu wall time clock
5871 static void cpu_clock_event_update(struct perf_event *event)
5876 now = local_clock();
5877 prev = local64_xchg(&event->hw.prev_count, now);
5878 local64_add(now - prev, &event->count);
5881 static void cpu_clock_event_start(struct perf_event *event, int flags)
5883 local64_set(&event->hw.prev_count, local_clock());
5884 perf_swevent_start_hrtimer(event);
5887 static void cpu_clock_event_stop(struct perf_event *event, int flags)
5889 perf_swevent_cancel_hrtimer(event);
5890 cpu_clock_event_update(event);
5893 static int cpu_clock_event_add(struct perf_event *event, int flags)
5895 if (flags & PERF_EF_START)
5896 cpu_clock_event_start(event, flags);
5901 static void cpu_clock_event_del(struct perf_event *event, int flags)
5903 cpu_clock_event_stop(event, flags);
5906 static void cpu_clock_event_read(struct perf_event *event)
5908 cpu_clock_event_update(event);
5911 static int cpu_clock_event_init(struct perf_event *event)
5913 if (event->attr.type != PERF_TYPE_SOFTWARE)
5916 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
5920 * no branch sampling for software events
5922 if (has_branch_stack(event))
5925 perf_swevent_init_hrtimer(event);
5930 static struct pmu perf_cpu_clock = {
5931 .task_ctx_nr = perf_sw_context,
5933 .event_init = cpu_clock_event_init,
5934 .add = cpu_clock_event_add,
5935 .del = cpu_clock_event_del,
5936 .start = cpu_clock_event_start,
5937 .stop = cpu_clock_event_stop,
5938 .read = cpu_clock_event_read,
5940 .event_idx = perf_swevent_event_idx,
5944 * Software event: task time clock
5947 static void task_clock_event_update(struct perf_event *event, u64 now)
5952 prev = local64_xchg(&event->hw.prev_count, now);
5954 local64_add(delta, &event->count);
5957 static void task_clock_event_start(struct perf_event *event, int flags)
5959 local64_set(&event->hw.prev_count, event->ctx->time);
5960 perf_swevent_start_hrtimer(event);
5963 static void task_clock_event_stop(struct perf_event *event, int flags)
5965 perf_swevent_cancel_hrtimer(event);
5966 task_clock_event_update(event, event->ctx->time);
5969 static int task_clock_event_add(struct perf_event *event, int flags)
5971 if (flags & PERF_EF_START)
5972 task_clock_event_start(event, flags);
5977 static void task_clock_event_del(struct perf_event *event, int flags)
5979 task_clock_event_stop(event, PERF_EF_UPDATE);
5982 static void task_clock_event_read(struct perf_event *event)
5984 u64 now = perf_clock();
5985 u64 delta = now - event->ctx->timestamp;
5986 u64 time = event->ctx->time + delta;
5988 task_clock_event_update(event, time);
5991 static int task_clock_event_init(struct perf_event *event)
5993 if (event->attr.type != PERF_TYPE_SOFTWARE)
5996 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
6000 * no branch sampling for software events
6002 if (has_branch_stack(event))
6005 perf_swevent_init_hrtimer(event);
6010 static struct pmu perf_task_clock = {
6011 .task_ctx_nr = perf_sw_context,
6013 .event_init = task_clock_event_init,
6014 .add = task_clock_event_add,
6015 .del = task_clock_event_del,
6016 .start = task_clock_event_start,
6017 .stop = task_clock_event_stop,
6018 .read = task_clock_event_read,
6020 .event_idx = perf_swevent_event_idx,
6023 static void perf_pmu_nop_void(struct pmu *pmu)
6027 static int perf_pmu_nop_int(struct pmu *pmu)
6032 static void perf_pmu_start_txn(struct pmu *pmu)
6034 perf_pmu_disable(pmu);
6037 static int perf_pmu_commit_txn(struct pmu *pmu)
6039 perf_pmu_enable(pmu);
6043 static void perf_pmu_cancel_txn(struct pmu *pmu)
6045 perf_pmu_enable(pmu);
6048 static int perf_event_idx_default(struct perf_event *event)
6050 return event->hw.idx + 1;
6054 * Ensures all contexts with the same task_ctx_nr have the same
6055 * pmu_cpu_context too.
6057 static void *find_pmu_context(int ctxn)
6064 list_for_each_entry(pmu, &pmus, entry) {
6065 if (pmu->task_ctx_nr == ctxn)
6066 return pmu->pmu_cpu_context;
6072 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
6076 for_each_possible_cpu(cpu) {
6077 struct perf_cpu_context *cpuctx;
6079 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6081 if (cpuctx->unique_pmu == old_pmu)
6082 cpuctx->unique_pmu = pmu;
6086 static void free_pmu_context(struct pmu *pmu)
6090 mutex_lock(&pmus_lock);
6092 * Like a real lame refcount.
6094 list_for_each_entry(i, &pmus, entry) {
6095 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
6096 update_pmu_context(i, pmu);
6101 free_percpu(pmu->pmu_cpu_context);
6103 mutex_unlock(&pmus_lock);
6105 static struct idr pmu_idr;
6108 type_show(struct device *dev, struct device_attribute *attr, char *page)
6110 struct pmu *pmu = dev_get_drvdata(dev);
6112 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
6115 static struct device_attribute pmu_dev_attrs[] = {
6120 static int pmu_bus_running;
6121 static struct bus_type pmu_bus = {
6122 .name = "event_source",
6123 .dev_attrs = pmu_dev_attrs,
6126 static void pmu_dev_release(struct device *dev)
6131 static int pmu_dev_alloc(struct pmu *pmu)
6135 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
6139 pmu->dev->groups = pmu->attr_groups;
6140 device_initialize(pmu->dev);
6141 ret = dev_set_name(pmu->dev, "%s", pmu->name);
6145 dev_set_drvdata(pmu->dev, pmu);
6146 pmu->dev->bus = &pmu_bus;
6147 pmu->dev->release = pmu_dev_release;
6148 ret = device_add(pmu->dev);
6156 put_device(pmu->dev);
6160 static struct lock_class_key cpuctx_mutex;
6161 static struct lock_class_key cpuctx_lock;
6163 int perf_pmu_register(struct pmu *pmu, char *name, int type)
6167 mutex_lock(&pmus_lock);
6169 pmu->pmu_disable_count = alloc_percpu(int);
6170 if (!pmu->pmu_disable_count)
6179 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
6187 if (pmu_bus_running) {
6188 ret = pmu_dev_alloc(pmu);
6194 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
6195 if (pmu->pmu_cpu_context)
6196 goto got_cpu_context;
6199 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
6200 if (!pmu->pmu_cpu_context)
6203 for_each_possible_cpu(cpu) {
6204 struct perf_cpu_context *cpuctx;
6206 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6207 __perf_event_init_context(&cpuctx->ctx);
6208 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
6209 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
6210 cpuctx->ctx.type = cpu_context;
6211 cpuctx->ctx.pmu = pmu;
6212 cpuctx->jiffies_interval = 1;
6213 INIT_LIST_HEAD(&cpuctx->rotation_list);
6214 cpuctx->unique_pmu = pmu;
6218 if (!pmu->start_txn) {
6219 if (pmu->pmu_enable) {
6221 * If we have pmu_enable/pmu_disable calls, install
6222 * transaction stubs that use that to try and batch
6223 * hardware accesses.
6225 pmu->start_txn = perf_pmu_start_txn;
6226 pmu->commit_txn = perf_pmu_commit_txn;
6227 pmu->cancel_txn = perf_pmu_cancel_txn;
6229 pmu->start_txn = perf_pmu_nop_void;
6230 pmu->commit_txn = perf_pmu_nop_int;
6231 pmu->cancel_txn = perf_pmu_nop_void;
6235 if (!pmu->pmu_enable) {
6236 pmu->pmu_enable = perf_pmu_nop_void;
6237 pmu->pmu_disable = perf_pmu_nop_void;
6240 if (!pmu->event_idx)
6241 pmu->event_idx = perf_event_idx_default;
6243 list_add_rcu(&pmu->entry, &pmus);
6246 mutex_unlock(&pmus_lock);
6251 device_del(pmu->dev);
6252 put_device(pmu->dev);
6255 if (pmu->type >= PERF_TYPE_MAX)
6256 idr_remove(&pmu_idr, pmu->type);
6259 free_percpu(pmu->pmu_disable_count);
6263 void perf_pmu_unregister(struct pmu *pmu)
6265 mutex_lock(&pmus_lock);
6266 list_del_rcu(&pmu->entry);
6267 mutex_unlock(&pmus_lock);
6270 * We dereference the pmu list under both SRCU and regular RCU, so
6271 * synchronize against both of those.
6273 synchronize_srcu(&pmus_srcu);
6276 free_percpu(pmu->pmu_disable_count);
6277 if (pmu->type >= PERF_TYPE_MAX)
6278 idr_remove(&pmu_idr, pmu->type);
6279 device_del(pmu->dev);
6280 put_device(pmu->dev);
6281 free_pmu_context(pmu);
6284 struct pmu *perf_init_event(struct perf_event *event)
6286 struct pmu *pmu = NULL;
6290 idx = srcu_read_lock(&pmus_srcu);
6293 pmu = idr_find(&pmu_idr, event->attr.type);
6297 ret = pmu->event_init(event);
6303 list_for_each_entry_rcu(pmu, &pmus, entry) {
6305 ret = pmu->event_init(event);
6309 if (ret != -ENOENT) {
6314 pmu = ERR_PTR(-ENOENT);
6316 srcu_read_unlock(&pmus_srcu, idx);
6322 * Allocate and initialize a event structure
6324 static struct perf_event *
6325 perf_event_alloc(struct perf_event_attr *attr, int cpu,
6326 struct task_struct *task,
6327 struct perf_event *group_leader,
6328 struct perf_event *parent_event,
6329 perf_overflow_handler_t overflow_handler,
6333 struct perf_event *event;
6334 struct hw_perf_event *hwc;
6337 if ((unsigned)cpu >= nr_cpu_ids) {
6338 if (!task || cpu != -1)
6339 return ERR_PTR(-EINVAL);
6342 event = kzalloc(sizeof(*event), GFP_KERNEL);
6344 return ERR_PTR(-ENOMEM);
6347 * Single events are their own group leaders, with an
6348 * empty sibling list:
6351 group_leader = event;
6353 mutex_init(&event->child_mutex);
6354 INIT_LIST_HEAD(&event->child_list);
6356 INIT_LIST_HEAD(&event->group_entry);
6357 INIT_LIST_HEAD(&event->event_entry);
6358 INIT_LIST_HEAD(&event->sibling_list);
6359 INIT_LIST_HEAD(&event->rb_entry);
6361 init_waitqueue_head(&event->waitq);
6362 init_irq_work(&event->pending, perf_pending_event);
6364 mutex_init(&event->mmap_mutex);
6366 atomic_long_set(&event->refcount, 1);
6368 event->attr = *attr;
6369 event->group_leader = group_leader;
6373 event->parent = parent_event;
6375 event->ns = get_pid_ns(task_active_pid_ns(current));
6376 event->id = atomic64_inc_return(&perf_event_id);
6378 event->state = PERF_EVENT_STATE_INACTIVE;
6381 event->attach_state = PERF_ATTACH_TASK;
6383 if (attr->type == PERF_TYPE_TRACEPOINT)
6384 event->hw.tp_target = task;
6385 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6387 * hw_breakpoint is a bit difficult here..
6389 else if (attr->type == PERF_TYPE_BREAKPOINT)
6390 event->hw.bp_target = task;
6394 if (!overflow_handler && parent_event) {
6395 overflow_handler = parent_event->overflow_handler;
6396 context = parent_event->overflow_handler_context;
6399 event->overflow_handler = overflow_handler;
6400 event->overflow_handler_context = context;
6402 perf_event__state_init(event);
6407 hwc->sample_period = attr->sample_period;
6408 if (attr->freq && attr->sample_freq)
6409 hwc->sample_period = 1;
6410 hwc->last_period = hwc->sample_period;
6412 local64_set(&hwc->period_left, hwc->sample_period);
6415 * we currently do not support PERF_FORMAT_GROUP on inherited events
6417 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
6420 pmu = perf_init_event(event);
6426 else if (IS_ERR(pmu))
6431 put_pid_ns(event->ns);
6433 return ERR_PTR(err);
6436 if (!event->parent) {
6437 if (event->attach_state & PERF_ATTACH_TASK)
6438 static_key_slow_inc(&perf_sched_events.key);
6439 if (event->attr.mmap || event->attr.mmap_data)
6440 atomic_inc(&nr_mmap_events);
6441 if (event->attr.comm)
6442 atomic_inc(&nr_comm_events);
6443 if (event->attr.task)
6444 atomic_inc(&nr_task_events);
6445 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
6446 err = get_callchain_buffers();
6449 return ERR_PTR(err);
6452 if (has_branch_stack(event)) {
6453 static_key_slow_inc(&perf_sched_events.key);
6454 if (!(event->attach_state & PERF_ATTACH_TASK))
6455 atomic_inc(&per_cpu(perf_branch_stack_events,
6463 static int perf_copy_attr(struct perf_event_attr __user *uattr,
6464 struct perf_event_attr *attr)
6469 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
6473 * zero the full structure, so that a short copy will be nice.
6475 memset(attr, 0, sizeof(*attr));
6477 ret = get_user(size, &uattr->size);
6481 if (size > PAGE_SIZE) /* silly large */
6484 if (!size) /* abi compat */
6485 size = PERF_ATTR_SIZE_VER0;
6487 if (size < PERF_ATTR_SIZE_VER0)
6491 * If we're handed a bigger struct than we know of,
6492 * ensure all the unknown bits are 0 - i.e. new
6493 * user-space does not rely on any kernel feature
6494 * extensions we dont know about yet.
6496 if (size > sizeof(*attr)) {
6497 unsigned char __user *addr;
6498 unsigned char __user *end;
6501 addr = (void __user *)uattr + sizeof(*attr);
6502 end = (void __user *)uattr + size;
6504 for (; addr < end; addr++) {
6505 ret = get_user(val, addr);
6511 size = sizeof(*attr);
6514 ret = copy_from_user(attr, uattr, size);
6518 if (attr->__reserved_1)
6521 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
6524 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
6527 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
6528 u64 mask = attr->branch_sample_type;
6530 /* only using defined bits */
6531 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
6534 /* at least one branch bit must be set */
6535 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
6538 /* kernel level capture: check permissions */
6539 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
6540 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
6543 /* propagate priv level, when not set for branch */
6544 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
6546 /* exclude_kernel checked on syscall entry */
6547 if (!attr->exclude_kernel)
6548 mask |= PERF_SAMPLE_BRANCH_KERNEL;
6550 if (!attr->exclude_user)
6551 mask |= PERF_SAMPLE_BRANCH_USER;
6553 if (!attr->exclude_hv)
6554 mask |= PERF_SAMPLE_BRANCH_HV;
6556 * adjust user setting (for HW filter setup)
6558 attr->branch_sample_type = mask;
6562 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
6563 ret = perf_reg_validate(attr->sample_regs_user);
6568 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
6569 if (!arch_perf_have_user_stack_dump())
6573 * We have __u32 type for the size, but so far
6574 * we can only use __u16 as maximum due to the
6575 * __u16 sample size limit.
6577 if (attr->sample_stack_user >= USHRT_MAX)
6579 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
6587 put_user(sizeof(*attr), &uattr->size);
6593 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
6595 struct ring_buffer *rb = NULL, *old_rb = NULL;
6601 /* don't allow circular references */
6602 if (event == output_event)
6606 * Don't allow cross-cpu buffers
6608 if (output_event->cpu != event->cpu)
6612 * If its not a per-cpu rb, it must be the same task.
6614 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
6618 mutex_lock(&event->mmap_mutex);
6619 /* Can't redirect output if we've got an active mmap() */
6620 if (atomic_read(&event->mmap_count))
6626 /* get the rb we want to redirect to */
6627 rb = ring_buffer_get(output_event);
6633 ring_buffer_detach(event, old_rb);
6636 ring_buffer_attach(event, rb);
6638 rcu_assign_pointer(event->rb, rb);
6641 ring_buffer_put(old_rb);
6643 * Since we detached before setting the new rb, so that we
6644 * could attach the new rb, we could have missed a wakeup.
6647 wake_up_all(&event->waitq);
6652 mutex_unlock(&event->mmap_mutex);
6659 * sys_perf_event_open - open a performance event, associate it to a task/cpu
6661 * @attr_uptr: event_id type attributes for monitoring/sampling
6664 * @group_fd: group leader event fd
6666 SYSCALL_DEFINE5(perf_event_open,
6667 struct perf_event_attr __user *, attr_uptr,
6668 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
6670 struct perf_event *group_leader = NULL, *output_event = NULL;
6671 struct perf_event *event, *sibling;
6672 struct perf_event_attr attr;
6673 struct perf_event_context *ctx;
6674 struct file *event_file = NULL;
6675 struct fd group = {NULL, 0};
6676 struct task_struct *task = NULL;
6682 /* for future expandability... */
6683 if (flags & ~PERF_FLAG_ALL)
6686 err = perf_copy_attr(attr_uptr, &attr);
6690 if (!attr.exclude_kernel) {
6691 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
6696 if (attr.sample_freq > sysctl_perf_event_sample_rate)
6699 if (attr.sample_period & (1ULL << 63))
6704 * In cgroup mode, the pid argument is used to pass the fd
6705 * opened to the cgroup directory in cgroupfs. The cpu argument
6706 * designates the cpu on which to monitor threads from that
6709 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
6712 event_fd = get_unused_fd();
6716 if (group_fd != -1) {
6717 err = perf_fget_light(group_fd, &group);
6720 group_leader = group.file->private_data;
6721 if (flags & PERF_FLAG_FD_OUTPUT)
6722 output_event = group_leader;
6723 if (flags & PERF_FLAG_FD_NO_GROUP)
6724 group_leader = NULL;
6727 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
6728 task = find_lively_task_by_vpid(pid);
6730 err = PTR_ERR(task);
6737 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
6739 if (IS_ERR(event)) {
6740 err = PTR_ERR(event);
6744 if (flags & PERF_FLAG_PID_CGROUP) {
6745 err = perf_cgroup_connect(pid, event, &attr, group_leader);
6750 * - that has cgroup constraint on event->cpu
6751 * - that may need work on context switch
6753 atomic_inc(&per_cpu(perf_cgroup_events, event->cpu));
6754 static_key_slow_inc(&perf_sched_events.key);
6758 * Special case software events and allow them to be part of
6759 * any hardware group.
6764 (is_software_event(event) != is_software_event(group_leader))) {
6765 if (is_software_event(event)) {
6767 * If event and group_leader are not both a software
6768 * event, and event is, then group leader is not.
6770 * Allow the addition of software events to !software
6771 * groups, this is safe because software events never
6774 pmu = group_leader->pmu;
6775 } else if (is_software_event(group_leader) &&
6776 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
6778 * In case the group is a pure software group, and we
6779 * try to add a hardware event, move the whole group to
6780 * the hardware context.
6787 * Get the target context (task or percpu):
6789 ctx = find_get_context(pmu, task, event->cpu);
6796 put_task_struct(task);
6801 * Look up the group leader (we will attach this event to it):
6807 * Do not allow a recursive hierarchy (this new sibling
6808 * becoming part of another group-sibling):
6810 if (group_leader->group_leader != group_leader)
6813 * Do not allow to attach to a group in a different
6814 * task or CPU context:
6817 if (group_leader->ctx->type != ctx->type)
6820 if (group_leader->ctx != ctx)
6825 * Only a group leader can be exclusive or pinned
6827 if (attr.exclusive || attr.pinned)
6832 err = perf_event_set_output(event, output_event);
6837 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, O_RDWR);
6838 if (IS_ERR(event_file)) {
6839 err = PTR_ERR(event_file);
6844 struct perf_event_context *gctx = group_leader->ctx;
6846 mutex_lock(&gctx->mutex);
6847 perf_remove_from_context(group_leader, false);
6850 * Removing from the context ends up with disabled
6851 * event. What we want here is event in the initial
6852 * startup state, ready to be add into new context.
6854 perf_event__state_init(group_leader);
6855 list_for_each_entry(sibling, &group_leader->sibling_list,
6857 perf_remove_from_context(sibling, false);
6858 perf_event__state_init(sibling);
6861 mutex_unlock(&gctx->mutex);
6865 WARN_ON_ONCE(ctx->parent_ctx);
6866 mutex_lock(&ctx->mutex);
6870 perf_install_in_context(ctx, group_leader, event->cpu);
6872 list_for_each_entry(sibling, &group_leader->sibling_list,
6874 perf_install_in_context(ctx, sibling, event->cpu);
6879 perf_install_in_context(ctx, event, event->cpu);
6881 perf_unpin_context(ctx);
6882 mutex_unlock(&ctx->mutex);
6886 event->owner = current;
6888 mutex_lock(¤t->perf_event_mutex);
6889 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
6890 mutex_unlock(¤t->perf_event_mutex);
6893 * Precalculate sample_data sizes
6895 perf_event__header_size(event);
6896 perf_event__id_header_size(event);
6899 * Drop the reference on the group_event after placing the
6900 * new event on the sibling_list. This ensures destruction
6901 * of the group leader will find the pointer to itself in
6902 * perf_group_detach().
6905 fd_install(event_fd, event_file);
6909 perf_unpin_context(ctx);
6916 put_task_struct(task);
6920 put_unused_fd(event_fd);
6925 * perf_event_create_kernel_counter
6927 * @attr: attributes of the counter to create
6928 * @cpu: cpu in which the counter is bound
6929 * @task: task to profile (NULL for percpu)
6932 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
6933 struct task_struct *task,
6934 perf_overflow_handler_t overflow_handler,
6937 struct perf_event_context *ctx;
6938 struct perf_event *event;
6942 * Get the target context (task or percpu):
6945 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
6946 overflow_handler, context);
6947 if (IS_ERR(event)) {
6948 err = PTR_ERR(event);
6952 ctx = find_get_context(event->pmu, task, cpu);
6958 WARN_ON_ONCE(ctx->parent_ctx);
6959 mutex_lock(&ctx->mutex);
6960 perf_install_in_context(ctx, event, cpu);
6962 perf_unpin_context(ctx);
6963 mutex_unlock(&ctx->mutex);
6970 return ERR_PTR(err);
6972 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
6974 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
6976 struct perf_event_context *src_ctx;
6977 struct perf_event_context *dst_ctx;
6978 struct perf_event *event, *tmp;
6981 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
6982 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
6984 mutex_lock(&src_ctx->mutex);
6985 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
6987 perf_remove_from_context(event, false);
6989 list_add(&event->event_entry, &events);
6991 mutex_unlock(&src_ctx->mutex);
6995 mutex_lock(&dst_ctx->mutex);
6996 list_for_each_entry_safe(event, tmp, &events, event_entry) {
6997 list_del(&event->event_entry);
6998 if (event->state >= PERF_EVENT_STATE_OFF)
6999 event->state = PERF_EVENT_STATE_INACTIVE;
7000 perf_install_in_context(dst_ctx, event, dst_cpu);
7003 mutex_unlock(&dst_ctx->mutex);
7005 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
7007 static void sync_child_event(struct perf_event *child_event,
7008 struct task_struct *child)
7010 struct perf_event *parent_event = child_event->parent;
7013 if (child_event->attr.inherit_stat)
7014 perf_event_read_event(child_event, child);
7016 child_val = perf_event_count(child_event);
7019 * Add back the child's count to the parent's count:
7021 atomic64_add(child_val, &parent_event->child_count);
7022 atomic64_add(child_event->total_time_enabled,
7023 &parent_event->child_total_time_enabled);
7024 atomic64_add(child_event->total_time_running,
7025 &parent_event->child_total_time_running);
7028 * Remove this event from the parent's list
7030 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7031 mutex_lock(&parent_event->child_mutex);
7032 list_del_init(&child_event->child_list);
7033 mutex_unlock(&parent_event->child_mutex);
7036 * Release the parent event, if this was the last
7039 put_event(parent_event);
7043 __perf_event_exit_task(struct perf_event *child_event,
7044 struct perf_event_context *child_ctx,
7045 struct task_struct *child)
7047 perf_remove_from_context(child_event, !!child_event->parent);
7050 * It can happen that the parent exits first, and has events
7051 * that are still around due to the child reference. These
7052 * events need to be zapped.
7054 if (child_event->parent) {
7055 sync_child_event(child_event, child);
7056 free_event(child_event);
7060 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
7062 struct perf_event *child_event, *tmp;
7063 struct perf_event_context *child_ctx;
7064 unsigned long flags;
7066 if (likely(!child->perf_event_ctxp[ctxn])) {
7067 perf_event_task(child, NULL, 0);
7071 local_irq_save(flags);
7073 * We can't reschedule here because interrupts are disabled,
7074 * and either child is current or it is a task that can't be
7075 * scheduled, so we are now safe from rescheduling changing
7078 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
7081 * Take the context lock here so that if find_get_context is
7082 * reading child->perf_event_ctxp, we wait until it has
7083 * incremented the context's refcount before we do put_ctx below.
7085 raw_spin_lock(&child_ctx->lock);
7086 task_ctx_sched_out(child_ctx);
7087 child->perf_event_ctxp[ctxn] = NULL;
7089 * If this context is a clone; unclone it so it can't get
7090 * swapped to another process while we're removing all
7091 * the events from it.
7093 unclone_ctx(child_ctx);
7094 update_context_time(child_ctx);
7095 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7098 * Report the task dead after unscheduling the events so that we
7099 * won't get any samples after PERF_RECORD_EXIT. We can however still
7100 * get a few PERF_RECORD_READ events.
7102 perf_event_task(child, child_ctx, 0);
7105 * We can recurse on the same lock type through:
7107 * __perf_event_exit_task()
7108 * sync_child_event()
7110 * mutex_lock(&ctx->mutex)
7112 * But since its the parent context it won't be the same instance.
7114 mutex_lock(&child_ctx->mutex);
7117 list_for_each_entry_safe(child_event, tmp, &child_ctx->pinned_groups,
7119 __perf_event_exit_task(child_event, child_ctx, child);
7121 list_for_each_entry_safe(child_event, tmp, &child_ctx->flexible_groups,
7123 __perf_event_exit_task(child_event, child_ctx, child);
7126 * If the last event was a group event, it will have appended all
7127 * its siblings to the list, but we obtained 'tmp' before that which
7128 * will still point to the list head terminating the iteration.
7130 if (!list_empty(&child_ctx->pinned_groups) ||
7131 !list_empty(&child_ctx->flexible_groups))
7134 mutex_unlock(&child_ctx->mutex);
7140 * When a child task exits, feed back event values to parent events.
7142 void perf_event_exit_task(struct task_struct *child)
7144 struct perf_event *event, *tmp;
7147 mutex_lock(&child->perf_event_mutex);
7148 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
7150 list_del_init(&event->owner_entry);
7153 * Ensure the list deletion is visible before we clear
7154 * the owner, closes a race against perf_release() where
7155 * we need to serialize on the owner->perf_event_mutex.
7158 event->owner = NULL;
7160 mutex_unlock(&child->perf_event_mutex);
7162 for_each_task_context_nr(ctxn)
7163 perf_event_exit_task_context(child, ctxn);
7166 static void perf_free_event(struct perf_event *event,
7167 struct perf_event_context *ctx)
7169 struct perf_event *parent = event->parent;
7171 if (WARN_ON_ONCE(!parent))
7174 mutex_lock(&parent->child_mutex);
7175 list_del_init(&event->child_list);
7176 mutex_unlock(&parent->child_mutex);
7180 perf_group_detach(event);
7181 list_del_event(event, ctx);
7186 * free an unexposed, unused context as created by inheritance by
7187 * perf_event_init_task below, used by fork() in case of fail.
7189 void perf_event_free_task(struct task_struct *task)
7191 struct perf_event_context *ctx;
7192 struct perf_event *event, *tmp;
7195 for_each_task_context_nr(ctxn) {
7196 ctx = task->perf_event_ctxp[ctxn];
7200 mutex_lock(&ctx->mutex);
7202 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
7204 perf_free_event(event, ctx);
7206 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
7208 perf_free_event(event, ctx);
7210 if (!list_empty(&ctx->pinned_groups) ||
7211 !list_empty(&ctx->flexible_groups))
7214 mutex_unlock(&ctx->mutex);
7220 void perf_event_delayed_put(struct task_struct *task)
7224 for_each_task_context_nr(ctxn)
7225 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
7229 * inherit a event from parent task to child task:
7231 static struct perf_event *
7232 inherit_event(struct perf_event *parent_event,
7233 struct task_struct *parent,
7234 struct perf_event_context *parent_ctx,
7235 struct task_struct *child,
7236 struct perf_event *group_leader,
7237 struct perf_event_context *child_ctx)
7239 struct perf_event *child_event;
7240 unsigned long flags;
7243 * Instead of creating recursive hierarchies of events,
7244 * we link inherited events back to the original parent,
7245 * which has a filp for sure, which we use as the reference
7248 if (parent_event->parent)
7249 parent_event = parent_event->parent;
7251 child_event = perf_event_alloc(&parent_event->attr,
7254 group_leader, parent_event,
7256 if (IS_ERR(child_event))
7259 if (!atomic_long_inc_not_zero(&parent_event->refcount)) {
7260 free_event(child_event);
7267 * Make the child state follow the state of the parent event,
7268 * not its attr.disabled bit. We hold the parent's mutex,
7269 * so we won't race with perf_event_{en, dis}able_family.
7271 if (parent_event->state >= PERF_EVENT_STATE_INACTIVE)
7272 child_event->state = PERF_EVENT_STATE_INACTIVE;
7274 child_event->state = PERF_EVENT_STATE_OFF;
7276 if (parent_event->attr.freq) {
7277 u64 sample_period = parent_event->hw.sample_period;
7278 struct hw_perf_event *hwc = &child_event->hw;
7280 hwc->sample_period = sample_period;
7281 hwc->last_period = sample_period;
7283 local64_set(&hwc->period_left, sample_period);
7286 child_event->ctx = child_ctx;
7287 child_event->overflow_handler = parent_event->overflow_handler;
7288 child_event->overflow_handler_context
7289 = parent_event->overflow_handler_context;
7292 * Precalculate sample_data sizes
7294 perf_event__header_size(child_event);
7295 perf_event__id_header_size(child_event);
7298 * Link it up in the child's context:
7300 raw_spin_lock_irqsave(&child_ctx->lock, flags);
7301 add_event_to_ctx(child_event, child_ctx);
7302 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7305 * Link this into the parent event's child list
7307 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7308 mutex_lock(&parent_event->child_mutex);
7309 list_add_tail(&child_event->child_list, &parent_event->child_list);
7310 mutex_unlock(&parent_event->child_mutex);
7315 static int inherit_group(struct perf_event *parent_event,
7316 struct task_struct *parent,
7317 struct perf_event_context *parent_ctx,
7318 struct task_struct *child,
7319 struct perf_event_context *child_ctx)
7321 struct perf_event *leader;
7322 struct perf_event *sub;
7323 struct perf_event *child_ctr;
7325 leader = inherit_event(parent_event, parent, parent_ctx,
7326 child, NULL, child_ctx);
7328 return PTR_ERR(leader);
7329 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
7330 child_ctr = inherit_event(sub, parent, parent_ctx,
7331 child, leader, child_ctx);
7332 if (IS_ERR(child_ctr))
7333 return PTR_ERR(child_ctr);
7339 inherit_task_group(struct perf_event *event, struct task_struct *parent,
7340 struct perf_event_context *parent_ctx,
7341 struct task_struct *child, int ctxn,
7345 struct perf_event_context *child_ctx;
7347 if (!event->attr.inherit) {
7352 child_ctx = child->perf_event_ctxp[ctxn];
7355 * This is executed from the parent task context, so
7356 * inherit events that have been marked for cloning.
7357 * First allocate and initialize a context for the
7361 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
7365 child->perf_event_ctxp[ctxn] = child_ctx;
7368 ret = inherit_group(event, parent, parent_ctx,
7378 * Initialize the perf_event context in task_struct
7380 int perf_event_init_context(struct task_struct *child, int ctxn)
7382 struct perf_event_context *child_ctx, *parent_ctx;
7383 struct perf_event_context *cloned_ctx;
7384 struct perf_event *event;
7385 struct task_struct *parent = current;
7386 int inherited_all = 1;
7387 unsigned long flags;
7390 if (likely(!parent->perf_event_ctxp[ctxn]))
7394 * If the parent's context is a clone, pin it so it won't get
7397 parent_ctx = perf_pin_task_context(parent, ctxn);
7400 * No need to check if parent_ctx != NULL here; since we saw
7401 * it non-NULL earlier, the only reason for it to become NULL
7402 * is if we exit, and since we're currently in the middle of
7403 * a fork we can't be exiting at the same time.
7407 * Lock the parent list. No need to lock the child - not PID
7408 * hashed yet and not running, so nobody can access it.
7410 mutex_lock(&parent_ctx->mutex);
7413 * We dont have to disable NMIs - we are only looking at
7414 * the list, not manipulating it:
7416 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
7417 ret = inherit_task_group(event, parent, parent_ctx,
7418 child, ctxn, &inherited_all);
7424 * We can't hold ctx->lock when iterating the ->flexible_group list due
7425 * to allocations, but we need to prevent rotation because
7426 * rotate_ctx() will change the list from interrupt context.
7428 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7429 parent_ctx->rotate_disable = 1;
7430 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7432 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
7433 ret = inherit_task_group(event, parent, parent_ctx,
7434 child, ctxn, &inherited_all);
7439 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7440 parent_ctx->rotate_disable = 0;
7442 child_ctx = child->perf_event_ctxp[ctxn];
7444 if (child_ctx && inherited_all) {
7446 * Mark the child context as a clone of the parent
7447 * context, or of whatever the parent is a clone of.
7449 * Note that if the parent is a clone, the holding of
7450 * parent_ctx->lock avoids it from being uncloned.
7452 cloned_ctx = parent_ctx->parent_ctx;
7454 child_ctx->parent_ctx = cloned_ctx;
7455 child_ctx->parent_gen = parent_ctx->parent_gen;
7457 child_ctx->parent_ctx = parent_ctx;
7458 child_ctx->parent_gen = parent_ctx->generation;
7460 get_ctx(child_ctx->parent_ctx);
7463 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7464 mutex_unlock(&parent_ctx->mutex);
7466 perf_unpin_context(parent_ctx);
7467 put_ctx(parent_ctx);
7473 * Initialize the perf_event context in task_struct
7475 int perf_event_init_task(struct task_struct *child)
7479 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
7480 mutex_init(&child->perf_event_mutex);
7481 INIT_LIST_HEAD(&child->perf_event_list);
7483 for_each_task_context_nr(ctxn) {
7484 ret = perf_event_init_context(child, ctxn);
7486 perf_event_free_task(child);
7494 static void __init perf_event_init_all_cpus(void)
7496 struct swevent_htable *swhash;
7499 for_each_possible_cpu(cpu) {
7500 swhash = &per_cpu(swevent_htable, cpu);
7501 mutex_init(&swhash->hlist_mutex);
7502 INIT_LIST_HEAD(&per_cpu(rotation_list, cpu));
7506 static void __cpuinit perf_event_init_cpu(int cpu)
7508 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7510 mutex_lock(&swhash->hlist_mutex);
7511 swhash->online = true;
7512 if (swhash->hlist_refcount > 0) {
7513 struct swevent_hlist *hlist;
7515 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
7517 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7519 mutex_unlock(&swhash->hlist_mutex);
7522 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC
7523 static void perf_pmu_rotate_stop(struct pmu *pmu)
7525 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7527 WARN_ON(!irqs_disabled());
7529 list_del_init(&cpuctx->rotation_list);
7532 static void __perf_event_exit_context(void *__info)
7534 struct remove_event re = { .detach_group = false };
7535 struct perf_event_context *ctx = __info;
7537 perf_pmu_rotate_stop(ctx->pmu);
7540 list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
7541 __perf_remove_from_context(&re);
7545 static void perf_event_exit_cpu_context(int cpu)
7547 struct perf_event_context *ctx;
7551 idx = srcu_read_lock(&pmus_srcu);
7552 list_for_each_entry_rcu(pmu, &pmus, entry) {
7553 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
7555 mutex_lock(&ctx->mutex);
7556 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
7557 mutex_unlock(&ctx->mutex);
7559 srcu_read_unlock(&pmus_srcu, idx);
7562 static void perf_event_exit_cpu(int cpu)
7564 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7566 perf_event_exit_cpu_context(cpu);
7568 mutex_lock(&swhash->hlist_mutex);
7569 swhash->online = false;
7570 swevent_hlist_release(swhash);
7571 mutex_unlock(&swhash->hlist_mutex);
7574 static inline void perf_event_exit_cpu(int cpu) { }
7578 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
7582 for_each_online_cpu(cpu)
7583 perf_event_exit_cpu(cpu);
7589 * Run the perf reboot notifier at the very last possible moment so that
7590 * the generic watchdog code runs as long as possible.
7592 static struct notifier_block perf_reboot_notifier = {
7593 .notifier_call = perf_reboot,
7594 .priority = INT_MIN,
7597 static int __cpuinit
7598 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
7600 unsigned int cpu = (long)hcpu;
7602 switch (action & ~CPU_TASKS_FROZEN) {
7604 case CPU_UP_PREPARE:
7605 case CPU_DOWN_FAILED:
7606 perf_event_init_cpu(cpu);
7609 case CPU_UP_CANCELED:
7610 case CPU_DOWN_PREPARE:
7611 perf_event_exit_cpu(cpu);
7621 void __init perf_event_init(void)
7627 perf_event_init_all_cpus();
7628 init_srcu_struct(&pmus_srcu);
7629 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
7630 perf_pmu_register(&perf_cpu_clock, NULL, -1);
7631 perf_pmu_register(&perf_task_clock, NULL, -1);
7633 perf_cpu_notifier(perf_cpu_notify);
7634 register_reboot_notifier(&perf_reboot_notifier);
7636 ret = init_hw_breakpoint();
7637 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
7639 /* do not patch jump label more than once per second */
7640 jump_label_rate_limit(&perf_sched_events, HZ);
7643 * Build time assertion that we keep the data_head at the intended
7644 * location. IOW, validation we got the __reserved[] size right.
7646 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
7650 static int __init perf_event_sysfs_init(void)
7655 mutex_lock(&pmus_lock);
7657 ret = bus_register(&pmu_bus);
7661 list_for_each_entry(pmu, &pmus, entry) {
7662 if (!pmu->name || pmu->type < 0)
7665 ret = pmu_dev_alloc(pmu);
7666 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
7668 pmu_bus_running = 1;
7672 mutex_unlock(&pmus_lock);
7676 device_initcall(perf_event_sysfs_init);
7678 #ifdef CONFIG_CGROUP_PERF
7679 static struct cgroup_subsys_state *perf_cgroup_css_alloc(struct cgroup *cont)
7681 struct perf_cgroup *jc;
7683 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
7685 return ERR_PTR(-ENOMEM);
7687 jc->info = alloc_percpu(struct perf_cgroup_info);
7690 return ERR_PTR(-ENOMEM);
7696 static void perf_cgroup_css_free(struct cgroup *cont)
7698 struct perf_cgroup *jc;
7699 jc = container_of(cgroup_subsys_state(cont, perf_subsys_id),
7700 struct perf_cgroup, css);
7701 free_percpu(jc->info);
7705 static int __perf_cgroup_move(void *info)
7707 struct task_struct *task = info;
7708 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
7712 static void perf_cgroup_attach(struct cgroup *cgrp, struct cgroup_taskset *tset)
7714 struct task_struct *task;
7716 cgroup_taskset_for_each(task, cgrp, tset)
7717 task_function_call(task, __perf_cgroup_move, task);
7720 static void perf_cgroup_exit(struct cgroup *cgrp, struct cgroup *old_cgrp,
7721 struct task_struct *task)
7724 * cgroup_exit() is called in the copy_process() failure path.
7725 * Ignore this case since the task hasn't ran yet, this avoids
7726 * trying to poke a half freed task state from generic code.
7728 if (!(task->flags & PF_EXITING))
7731 task_function_call(task, __perf_cgroup_move, task);
7734 struct cgroup_subsys perf_subsys = {
7735 .name = "perf_event",
7736 .subsys_id = perf_subsys_id,
7737 .css_alloc = perf_cgroup_css_alloc,
7738 .css_free = perf_cgroup_css_free,
7739 .exit = perf_cgroup_exit,
7740 .attach = perf_cgroup_attach,
7742 #endif /* CONFIG_CGROUP_PERF */