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/sysfs.h>
22 #include <linux/dcache.h>
23 #include <linux/percpu.h>
24 #include <linux/ptrace.h>
25 #include <linux/reboot.h>
26 #include <linux/vmstat.h>
27 #include <linux/device.h>
28 #include <linux/export.h>
29 #include <linux/vmalloc.h>
30 #include <linux/hardirq.h>
31 #include <linux/rculist.h>
32 #include <linux/uaccess.h>
33 #include <linux/syscalls.h>
34 #include <linux/anon_inodes.h>
35 #include <linux/kernel_stat.h>
36 #include <linux/perf_event.h>
37 #include <linux/ftrace_event.h>
38 #include <linux/hw_breakpoint.h>
39 #include <linux/compat.h>
43 #include <asm/irq_regs.h>
45 struct remote_function_call {
46 struct task_struct *p;
47 int (*func)(void *info);
52 static void remote_function(void *data)
54 struct remote_function_call *tfc = data;
55 struct task_struct *p = tfc->p;
59 if (task_cpu(p) != smp_processor_id() || !task_curr(p))
63 tfc->ret = tfc->func(tfc->info);
67 * task_function_call - call a function on the cpu on which a task runs
68 * @p: the task to evaluate
69 * @func: the function to be called
70 * @info: the function call argument
72 * Calls the function @func when the task is currently running. This might
73 * be on the current CPU, which just calls the function directly
75 * returns: @func return value, or
76 * -ESRCH - when the process isn't running
77 * -EAGAIN - when the process moved away
80 task_function_call(struct task_struct *p, int (*func) (void *info), void *info)
82 struct remote_function_call data = {
86 .ret = -ESRCH, /* No such (running) process */
90 smp_call_function_single(task_cpu(p), remote_function, &data, 1);
96 * cpu_function_call - call a function on the cpu
97 * @func: the function to be called
98 * @info: the function call argument
100 * Calls the function @func on the remote cpu.
102 * returns: @func return value or -ENXIO when the cpu is offline
104 static int cpu_function_call(int cpu, int (*func) (void *info), void *info)
106 struct remote_function_call data = {
110 .ret = -ENXIO, /* No such CPU */
113 smp_call_function_single(cpu, remote_function, &data, 1);
118 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
119 PERF_FLAG_FD_OUTPUT |\
120 PERF_FLAG_PID_CGROUP)
123 EVENT_FLEXIBLE = 0x1,
125 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
129 * perf_sched_events : >0 events exist
130 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
132 struct jump_label_key perf_sched_events __read_mostly;
133 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
135 static atomic_t nr_mmap_events __read_mostly;
136 static atomic_t nr_comm_events __read_mostly;
137 static atomic_t nr_task_events __read_mostly;
139 static LIST_HEAD(pmus);
140 static DEFINE_MUTEX(pmus_lock);
141 static struct srcu_struct pmus_srcu;
144 * perf event paranoia level:
145 * -1 - not paranoid at all
146 * 0 - disallow raw tracepoint access for unpriv
147 * 1 - disallow cpu events for unpriv
148 * 2 - disallow kernel profiling for unpriv
150 int sysctl_perf_event_paranoid __read_mostly = 1;
152 /* Minimum for 512 kiB + 1 user control page */
153 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
156 * max perf event sample rate
158 #define DEFAULT_MAX_SAMPLE_RATE 100000
159 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
160 static int max_samples_per_tick __read_mostly =
161 DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
163 int perf_proc_update_handler(struct ctl_table *table, int write,
164 void __user *buffer, size_t *lenp,
167 int ret = proc_dointvec(table, write, buffer, lenp, ppos);
172 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
177 static atomic64_t perf_event_id;
179 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
180 enum event_type_t event_type);
182 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
183 enum event_type_t event_type,
184 struct task_struct *task);
186 static void update_context_time(struct perf_event_context *ctx);
187 static u64 perf_event_time(struct perf_event *event);
189 void __weak perf_event_print_debug(void) { }
191 extern __weak const char *perf_pmu_name(void)
196 static inline u64 perf_clock(void)
198 return local_clock();
201 static inline struct perf_cpu_context *
202 __get_cpu_context(struct perf_event_context *ctx)
204 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
207 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
208 struct perf_event_context *ctx)
210 raw_spin_lock(&cpuctx->ctx.lock);
212 raw_spin_lock(&ctx->lock);
215 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
216 struct perf_event_context *ctx)
219 raw_spin_unlock(&ctx->lock);
220 raw_spin_unlock(&cpuctx->ctx.lock);
223 #ifdef CONFIG_CGROUP_PERF
226 * Must ensure cgroup is pinned (css_get) before calling
227 * this function. In other words, we cannot call this function
228 * if there is no cgroup event for the current CPU context.
230 static inline struct perf_cgroup *
231 perf_cgroup_from_task(struct task_struct *task)
233 return container_of(task_subsys_state(task, perf_subsys_id),
234 struct perf_cgroup, css);
238 perf_cgroup_match(struct perf_event *event)
240 struct perf_event_context *ctx = event->ctx;
241 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
243 return !event->cgrp || event->cgrp == cpuctx->cgrp;
246 static inline bool perf_tryget_cgroup(struct perf_event *event)
248 return css_tryget(&event->cgrp->css);
251 static inline void perf_put_cgroup(struct perf_event *event)
253 css_put(&event->cgrp->css);
256 static inline void perf_detach_cgroup(struct perf_event *event)
258 perf_put_cgroup(event);
262 static inline int is_cgroup_event(struct perf_event *event)
264 return event->cgrp != NULL;
267 static inline u64 perf_cgroup_event_time(struct perf_event *event)
269 struct perf_cgroup_info *t;
271 t = per_cpu_ptr(event->cgrp->info, event->cpu);
275 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
277 struct perf_cgroup_info *info;
282 info = this_cpu_ptr(cgrp->info);
284 info->time += now - info->timestamp;
285 info->timestamp = now;
288 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
290 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
292 __update_cgrp_time(cgrp_out);
295 static inline void update_cgrp_time_from_event(struct perf_event *event)
297 struct perf_cgroup *cgrp;
300 * ensure we access cgroup data only when needed and
301 * when we know the cgroup is pinned (css_get)
303 if (!is_cgroup_event(event))
306 cgrp = perf_cgroup_from_task(current);
308 * Do not update time when cgroup is not active
310 if (cgrp == event->cgrp)
311 __update_cgrp_time(event->cgrp);
315 perf_cgroup_set_timestamp(struct task_struct *task,
316 struct perf_event_context *ctx)
318 struct perf_cgroup *cgrp;
319 struct perf_cgroup_info *info;
322 * ctx->lock held by caller
323 * ensure we do not access cgroup data
324 * unless we have the cgroup pinned (css_get)
326 if (!task || !ctx->nr_cgroups)
329 cgrp = perf_cgroup_from_task(task);
330 info = this_cpu_ptr(cgrp->info);
331 info->timestamp = ctx->timestamp;
334 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
335 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
338 * reschedule events based on the cgroup constraint of task.
340 * mode SWOUT : schedule out everything
341 * mode SWIN : schedule in based on cgroup for next
343 void perf_cgroup_switch(struct task_struct *task, int mode)
345 struct perf_cpu_context *cpuctx;
350 * disable interrupts to avoid geting nr_cgroup
351 * changes via __perf_event_disable(). Also
354 local_irq_save(flags);
357 * we reschedule only in the presence of cgroup
358 * constrained events.
362 list_for_each_entry_rcu(pmu, &pmus, entry) {
363 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
364 if (cpuctx->unique_pmu != pmu)
365 continue; /* ensure we process each cpuctx once */
368 * perf_cgroup_events says at least one
369 * context on this CPU has cgroup events.
371 * ctx->nr_cgroups reports the number of cgroup
372 * events for a context.
374 if (cpuctx->ctx.nr_cgroups > 0) {
375 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
376 perf_pmu_disable(cpuctx->ctx.pmu);
378 if (mode & PERF_CGROUP_SWOUT) {
379 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
381 * must not be done before ctxswout due
382 * to event_filter_match() in event_sched_out()
387 if (mode & PERF_CGROUP_SWIN) {
388 WARN_ON_ONCE(cpuctx->cgrp);
390 * set cgrp before ctxsw in to allow
391 * event_filter_match() to not have to pass
394 cpuctx->cgrp = perf_cgroup_from_task(task);
395 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
397 perf_pmu_enable(cpuctx->ctx.pmu);
398 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
404 local_irq_restore(flags);
407 static inline void perf_cgroup_sched_out(struct task_struct *task,
408 struct task_struct *next)
410 struct perf_cgroup *cgrp1;
411 struct perf_cgroup *cgrp2 = NULL;
414 * we come here when we know perf_cgroup_events > 0
416 cgrp1 = perf_cgroup_from_task(task);
419 * next is NULL when called from perf_event_enable_on_exec()
420 * that will systematically cause a cgroup_switch()
423 cgrp2 = perf_cgroup_from_task(next);
426 * only schedule out current cgroup events if we know
427 * that we are switching to a different cgroup. Otherwise,
428 * do no touch the cgroup events.
431 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
434 static inline void perf_cgroup_sched_in(struct task_struct *prev,
435 struct task_struct *task)
437 struct perf_cgroup *cgrp1;
438 struct perf_cgroup *cgrp2 = NULL;
441 * we come here when we know perf_cgroup_events > 0
443 cgrp1 = perf_cgroup_from_task(task);
445 /* prev can never be NULL */
446 cgrp2 = perf_cgroup_from_task(prev);
449 * only need to schedule in cgroup events if we are changing
450 * cgroup during ctxsw. Cgroup events were not scheduled
451 * out of ctxsw out if that was not the case.
454 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
457 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
458 struct perf_event_attr *attr,
459 struct perf_event *group_leader)
461 struct perf_cgroup *cgrp;
462 struct cgroup_subsys_state *css;
464 int ret = 0, fput_needed;
466 file = fget_light(fd, &fput_needed);
470 css = cgroup_css_from_dir(file, perf_subsys_id);
476 cgrp = container_of(css, struct perf_cgroup, css);
479 /* must be done before we fput() the file */
480 if (!perf_tryget_cgroup(event)) {
487 * all events in a group must monitor
488 * the same cgroup because a task belongs
489 * to only one perf cgroup at a time
491 if (group_leader && group_leader->cgrp != cgrp) {
492 perf_detach_cgroup(event);
496 fput_light(file, fput_needed);
501 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
503 struct perf_cgroup_info *t;
504 t = per_cpu_ptr(event->cgrp->info, event->cpu);
505 event->shadow_ctx_time = now - t->timestamp;
509 perf_cgroup_defer_enabled(struct perf_event *event)
512 * when the current task's perf cgroup does not match
513 * the event's, we need to remember to call the
514 * perf_mark_enable() function the first time a task with
515 * a matching perf cgroup is scheduled in.
517 if (is_cgroup_event(event) && !perf_cgroup_match(event))
518 event->cgrp_defer_enabled = 1;
522 perf_cgroup_mark_enabled(struct perf_event *event,
523 struct perf_event_context *ctx)
525 struct perf_event *sub;
526 u64 tstamp = perf_event_time(event);
528 if (!event->cgrp_defer_enabled)
531 event->cgrp_defer_enabled = 0;
533 event->tstamp_enabled = tstamp - event->total_time_enabled;
534 list_for_each_entry(sub, &event->sibling_list, group_entry) {
535 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
536 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
537 sub->cgrp_defer_enabled = 0;
541 #else /* !CONFIG_CGROUP_PERF */
544 perf_cgroup_match(struct perf_event *event)
549 static inline void perf_detach_cgroup(struct perf_event *event)
552 static inline int is_cgroup_event(struct perf_event *event)
557 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
562 static inline void update_cgrp_time_from_event(struct perf_event *event)
566 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
570 static inline void perf_cgroup_sched_out(struct task_struct *task,
571 struct task_struct *next)
575 static inline void perf_cgroup_sched_in(struct task_struct *prev,
576 struct task_struct *task)
580 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
581 struct perf_event_attr *attr,
582 struct perf_event *group_leader)
588 perf_cgroup_set_timestamp(struct task_struct *task,
589 struct perf_event_context *ctx)
594 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
599 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
603 static inline u64 perf_cgroup_event_time(struct perf_event *event)
609 perf_cgroup_defer_enabled(struct perf_event *event)
614 perf_cgroup_mark_enabled(struct perf_event *event,
615 struct perf_event_context *ctx)
620 void perf_pmu_disable(struct pmu *pmu)
622 int *count = this_cpu_ptr(pmu->pmu_disable_count);
624 pmu->pmu_disable(pmu);
627 void perf_pmu_enable(struct pmu *pmu)
629 int *count = this_cpu_ptr(pmu->pmu_disable_count);
631 pmu->pmu_enable(pmu);
634 static DEFINE_PER_CPU(struct list_head, rotation_list);
637 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
638 * because they're strictly cpu affine and rotate_start is called with IRQs
639 * disabled, while rotate_context is called from IRQ context.
641 static void perf_pmu_rotate_start(struct pmu *pmu)
643 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
644 struct list_head *head = &__get_cpu_var(rotation_list);
646 WARN_ON(!irqs_disabled());
648 if (list_empty(&cpuctx->rotation_list))
649 list_add(&cpuctx->rotation_list, head);
652 static void get_ctx(struct perf_event_context *ctx)
654 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
657 static void put_ctx(struct perf_event_context *ctx)
659 if (atomic_dec_and_test(&ctx->refcount)) {
661 put_ctx(ctx->parent_ctx);
663 put_task_struct(ctx->task);
664 kfree_rcu(ctx, rcu_head);
669 * Because of perf_event::ctx migration in sys_perf_event_open::move_group we
672 * Those places that change perf_event::ctx will hold both
673 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
675 * Lock ordering is by mutex address. There is one other site where
676 * perf_event_context::mutex nests and that is put_event(). But remember that
677 * that is a parent<->child context relation, and migration does not affect
678 * children, therefore these two orderings should not interact.
680 * The change in perf_event::ctx does not affect children (as claimed above)
681 * because the sys_perf_event_open() case will install a new event and break
682 * the ctx parent<->child relation.
684 * The places that change perf_event::ctx will issue:
686 * perf_remove_from_context();
688 * perf_install_in_context();
690 * to affect the change. The remove_from_context() + synchronize_rcu() should
691 * quiesce the event, after which we can install it in the new location. This
692 * means that only external vectors (perf_fops, prctl) can perturb the event
693 * while in transit. Therefore all such accessors should also acquire
694 * perf_event_context::mutex to serialize against this.
696 * However; because event->ctx can change while we're waiting to acquire
697 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
701 * task_struct::perf_event_mutex
702 * perf_event_context::mutex
703 * perf_event_context::lock
704 * perf_event::child_mutex;
705 * perf_event::mmap_mutex
708 static struct perf_event_context *perf_event_ctx_lock(struct perf_event *event)
710 struct perf_event_context *ctx;
714 ctx = ACCESS_ONCE(event->ctx);
715 if (!atomic_inc_not_zero(&ctx->refcount)) {
721 mutex_lock(&ctx->mutex);
722 if (event->ctx != ctx) {
723 mutex_unlock(&ctx->mutex);
731 static void perf_event_ctx_unlock(struct perf_event *event,
732 struct perf_event_context *ctx)
734 mutex_unlock(&ctx->mutex);
738 static void unclone_ctx(struct perf_event_context *ctx)
740 if (ctx->parent_ctx) {
741 put_ctx(ctx->parent_ctx);
742 ctx->parent_ctx = NULL;
746 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
749 * only top level events have the pid namespace they were created in
752 event = event->parent;
754 return task_tgid_nr_ns(p, event->ns);
757 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
760 * only top level events have the pid namespace they were created in
763 event = event->parent;
765 return task_pid_nr_ns(p, event->ns);
769 * If we inherit events we want to return the parent event id
772 static u64 primary_event_id(struct perf_event *event)
777 id = event->parent->id;
783 * Get the perf_event_context for a task and lock it.
784 * This has to cope with with the fact that until it is locked,
785 * the context could get moved to another task.
787 static struct perf_event_context *
788 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
790 struct perf_event_context *ctx;
794 * One of the few rules of preemptible RCU is that one cannot do
795 * rcu_read_unlock() while holding a scheduler (or nested) lock when
796 * part of the read side critical section was preemptible -- see
797 * rcu_read_unlock_special().
799 * Since ctx->lock nests under rq->lock we must ensure the entire read
800 * side critical section is non-preemptible.
804 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
807 * If this context is a clone of another, it might
808 * get swapped for another underneath us by
809 * perf_event_task_sched_out, though the
810 * rcu_read_lock() protects us from any context
811 * getting freed. Lock the context and check if it
812 * got swapped before we could get the lock, and retry
813 * if so. If we locked the right context, then it
814 * can't get swapped on us any more.
816 raw_spin_lock_irqsave(&ctx->lock, *flags);
817 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
818 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
824 if (!atomic_inc_not_zero(&ctx->refcount)) {
825 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
835 * Get the context for a task and increment its pin_count so it
836 * can't get swapped to another task. This also increments its
837 * reference count so that the context can't get freed.
839 static struct perf_event_context *
840 perf_pin_task_context(struct task_struct *task, int ctxn)
842 struct perf_event_context *ctx;
845 ctx = perf_lock_task_context(task, ctxn, &flags);
848 raw_spin_unlock_irqrestore(&ctx->lock, flags);
853 static void perf_unpin_context(struct perf_event_context *ctx)
857 raw_spin_lock_irqsave(&ctx->lock, flags);
859 raw_spin_unlock_irqrestore(&ctx->lock, flags);
863 * Update the record of the current time in a context.
865 static void update_context_time(struct perf_event_context *ctx)
867 u64 now = perf_clock();
869 ctx->time += now - ctx->timestamp;
870 ctx->timestamp = now;
873 static u64 perf_event_time(struct perf_event *event)
875 struct perf_event_context *ctx = event->ctx;
877 if (is_cgroup_event(event))
878 return perf_cgroup_event_time(event);
880 return ctx ? ctx->time : 0;
884 * Update the total_time_enabled and total_time_running fields for a event.
885 * The caller of this function needs to hold the ctx->lock.
887 static void update_event_times(struct perf_event *event)
889 struct perf_event_context *ctx = event->ctx;
892 if (event->state < PERF_EVENT_STATE_INACTIVE ||
893 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
896 * in cgroup mode, time_enabled represents
897 * the time the event was enabled AND active
898 * tasks were in the monitored cgroup. This is
899 * independent of the activity of the context as
900 * there may be a mix of cgroup and non-cgroup events.
902 * That is why we treat cgroup events differently
905 if (is_cgroup_event(event))
906 run_end = perf_event_time(event);
907 else if (ctx->is_active)
910 run_end = event->tstamp_stopped;
912 event->total_time_enabled = run_end - event->tstamp_enabled;
914 if (event->state == PERF_EVENT_STATE_INACTIVE)
915 run_end = event->tstamp_stopped;
917 run_end = perf_event_time(event);
919 event->total_time_running = run_end - event->tstamp_running;
924 * Update total_time_enabled and total_time_running for all events in a group.
926 static void update_group_times(struct perf_event *leader)
928 struct perf_event *event;
930 update_event_times(leader);
931 list_for_each_entry(event, &leader->sibling_list, group_entry)
932 update_event_times(event);
935 static struct list_head *
936 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
938 if (event->attr.pinned)
939 return &ctx->pinned_groups;
941 return &ctx->flexible_groups;
945 * Add a event from the lists for its context.
946 * Must be called with ctx->mutex and ctx->lock held.
949 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
951 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
952 event->attach_state |= PERF_ATTACH_CONTEXT;
955 * If we're a stand alone event or group leader, we go to the context
956 * list, group events are kept attached to the group so that
957 * perf_group_detach can, at all times, locate all siblings.
959 if (event->group_leader == event) {
960 struct list_head *list;
962 if (is_software_event(event))
963 event->group_flags |= PERF_GROUP_SOFTWARE;
965 list = ctx_group_list(event, ctx);
966 list_add_tail(&event->group_entry, list);
969 if (is_cgroup_event(event))
972 list_add_rcu(&event->event_entry, &ctx->event_list);
974 perf_pmu_rotate_start(ctx->pmu);
976 if (event->attr.inherit_stat)
981 * Initialize event state based on the perf_event_attr::disabled.
983 static inline void perf_event__state_init(struct perf_event *event)
985 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
986 PERF_EVENT_STATE_INACTIVE;
990 * Called at perf_event creation and when events are attached/detached from a
993 static void perf_event__read_size(struct perf_event *event)
995 int entry = sizeof(u64); /* value */
999 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1000 size += sizeof(u64);
1002 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1003 size += sizeof(u64);
1005 if (event->attr.read_format & PERF_FORMAT_ID)
1006 entry += sizeof(u64);
1008 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1009 nr += event->group_leader->nr_siblings;
1010 size += sizeof(u64);
1014 event->read_size = size;
1017 static void perf_event__header_size(struct perf_event *event)
1019 struct perf_sample_data *data;
1020 u64 sample_type = event->attr.sample_type;
1023 perf_event__read_size(event);
1025 if (sample_type & PERF_SAMPLE_IP)
1026 size += sizeof(data->ip);
1028 if (sample_type & PERF_SAMPLE_ADDR)
1029 size += sizeof(data->addr);
1031 if (sample_type & PERF_SAMPLE_PERIOD)
1032 size += sizeof(data->period);
1034 if (sample_type & PERF_SAMPLE_READ)
1035 size += event->read_size;
1037 event->header_size = size;
1040 static void perf_event__id_header_size(struct perf_event *event)
1042 struct perf_sample_data *data;
1043 u64 sample_type = event->attr.sample_type;
1046 if (sample_type & PERF_SAMPLE_TID)
1047 size += sizeof(data->tid_entry);
1049 if (sample_type & PERF_SAMPLE_TIME)
1050 size += sizeof(data->time);
1052 if (sample_type & PERF_SAMPLE_ID)
1053 size += sizeof(data->id);
1055 if (sample_type & PERF_SAMPLE_STREAM_ID)
1056 size += sizeof(data->stream_id);
1058 if (sample_type & PERF_SAMPLE_CPU)
1059 size += sizeof(data->cpu_entry);
1061 event->id_header_size = size;
1064 static void perf_group_attach(struct perf_event *event)
1066 struct perf_event *group_leader = event->group_leader, *pos;
1069 * We can have double attach due to group movement in perf_event_open.
1071 if (event->attach_state & PERF_ATTACH_GROUP)
1074 event->attach_state |= PERF_ATTACH_GROUP;
1076 if (group_leader == event)
1079 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1080 !is_software_event(event))
1081 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1083 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1084 group_leader->nr_siblings++;
1086 perf_event__header_size(group_leader);
1088 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1089 perf_event__header_size(pos);
1093 * Remove a event from the lists for its context.
1094 * Must be called with ctx->mutex and ctx->lock held.
1097 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1099 struct perf_cpu_context *cpuctx;
1101 * We can have double detach due to exit/hot-unplug + close.
1103 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1106 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1108 if (is_cgroup_event(event)) {
1110 cpuctx = __get_cpu_context(ctx);
1112 * if there are no more cgroup events
1113 * then cler cgrp to avoid stale pointer
1114 * in update_cgrp_time_from_cpuctx()
1116 if (!ctx->nr_cgroups)
1117 cpuctx->cgrp = NULL;
1121 if (event->attr.inherit_stat)
1124 list_del_rcu(&event->event_entry);
1126 if (event->group_leader == event)
1127 list_del_init(&event->group_entry);
1129 update_group_times(event);
1132 * If event was in error state, then keep it
1133 * that way, otherwise bogus counts will be
1134 * returned on read(). The only way to get out
1135 * of error state is by explicit re-enabling
1138 if (event->state > PERF_EVENT_STATE_OFF)
1139 event->state = PERF_EVENT_STATE_OFF;
1142 static void perf_group_detach(struct perf_event *event)
1144 struct perf_event *sibling, *tmp;
1145 struct list_head *list = NULL;
1148 * We can have double detach due to exit/hot-unplug + close.
1150 if (!(event->attach_state & PERF_ATTACH_GROUP))
1153 event->attach_state &= ~PERF_ATTACH_GROUP;
1156 * If this is a sibling, remove it from its group.
1158 if (event->group_leader != event) {
1159 list_del_init(&event->group_entry);
1160 event->group_leader->nr_siblings--;
1164 if (!list_empty(&event->group_entry))
1165 list = &event->group_entry;
1168 * If this was a group event with sibling events then
1169 * upgrade the siblings to singleton events by adding them
1170 * to whatever list we are on.
1172 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1174 list_move_tail(&sibling->group_entry, list);
1175 sibling->group_leader = sibling;
1177 /* Inherit group flags from the previous leader */
1178 sibling->group_flags = event->group_flags;
1182 perf_event__header_size(event->group_leader);
1184 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1185 perf_event__header_size(tmp);
1189 event_filter_match(struct perf_event *event)
1191 return (event->cpu == -1 || event->cpu == smp_processor_id())
1192 && perf_cgroup_match(event);
1196 event_sched_out(struct perf_event *event,
1197 struct perf_cpu_context *cpuctx,
1198 struct perf_event_context *ctx)
1200 u64 tstamp = perf_event_time(event);
1203 * An event which could not be activated because of
1204 * filter mismatch still needs to have its timings
1205 * maintained, otherwise bogus information is return
1206 * via read() for time_enabled, time_running:
1208 if (event->state == PERF_EVENT_STATE_INACTIVE
1209 && !event_filter_match(event)) {
1210 delta = tstamp - event->tstamp_stopped;
1211 event->tstamp_running += delta;
1212 event->tstamp_stopped = tstamp;
1215 if (event->state != PERF_EVENT_STATE_ACTIVE)
1218 event->state = PERF_EVENT_STATE_INACTIVE;
1219 if (event->pending_disable) {
1220 event->pending_disable = 0;
1221 event->state = PERF_EVENT_STATE_OFF;
1223 event->tstamp_stopped = tstamp;
1224 event->pmu->del(event, 0);
1227 if (!is_software_event(event))
1228 cpuctx->active_oncpu--;
1230 if (event->attr.exclusive || !cpuctx->active_oncpu)
1231 cpuctx->exclusive = 0;
1235 group_sched_out(struct perf_event *group_event,
1236 struct perf_cpu_context *cpuctx,
1237 struct perf_event_context *ctx)
1239 struct perf_event *event;
1240 int state = group_event->state;
1242 event_sched_out(group_event, cpuctx, ctx);
1245 * Schedule out siblings (if any):
1247 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1248 event_sched_out(event, cpuctx, ctx);
1250 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1251 cpuctx->exclusive = 0;
1254 struct remove_event {
1255 struct perf_event *event;
1260 * Cross CPU call to remove a performance event
1262 * We disable the event on the hardware level first. After that we
1263 * remove it from the context list.
1265 static int __perf_remove_from_context(void *info)
1267 struct remove_event *re = info;
1268 struct perf_event *event = re->event;
1269 struct perf_event_context *ctx = event->ctx;
1270 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1272 raw_spin_lock(&ctx->lock);
1273 event_sched_out(event, cpuctx, ctx);
1274 if (re->detach_group)
1275 perf_group_detach(event);
1276 list_del_event(event, ctx);
1277 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1279 cpuctx->task_ctx = NULL;
1281 raw_spin_unlock(&ctx->lock);
1288 * Remove the event from a task's (or a CPU's) list of events.
1290 * CPU events are removed with a smp call. For task events we only
1291 * call when the task is on a CPU.
1293 * If event->ctx is a cloned context, callers must make sure that
1294 * every task struct that event->ctx->task could possibly point to
1295 * remains valid. This is OK when called from perf_release since
1296 * that only calls us on the top-level context, which can't be a clone.
1297 * When called from perf_event_exit_task, it's OK because the
1298 * context has been detached from its task.
1300 static void perf_remove_from_context(struct perf_event *event, bool detach_group)
1302 struct perf_event_context *ctx = event->ctx;
1303 struct task_struct *task = ctx->task;
1304 struct remove_event re = {
1306 .detach_group = detach_group,
1309 lockdep_assert_held(&ctx->mutex);
1313 * Per cpu events are removed via an smp call and
1314 * the removal is always successful.
1316 cpu_function_call(event->cpu, __perf_remove_from_context, &re);
1321 if (!task_function_call(task, __perf_remove_from_context, &re))
1324 raw_spin_lock_irq(&ctx->lock);
1326 * If we failed to find a running task, but find the context active now
1327 * that we've acquired the ctx->lock, retry.
1329 if (ctx->is_active) {
1330 raw_spin_unlock_irq(&ctx->lock);
1335 * Since the task isn't running, its safe to remove the event, us
1336 * holding the ctx->lock ensures the task won't get scheduled in.
1339 perf_group_detach(event);
1340 list_del_event(event, ctx);
1341 raw_spin_unlock_irq(&ctx->lock);
1345 * Cross CPU call to disable a performance event
1347 static int __perf_event_disable(void *info)
1349 struct perf_event *event = info;
1350 struct perf_event_context *ctx = event->ctx;
1351 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1354 * If this is a per-task event, need to check whether this
1355 * event's task is the current task on this cpu.
1357 * Can trigger due to concurrent perf_event_context_sched_out()
1358 * flipping contexts around.
1360 if (ctx->task && cpuctx->task_ctx != ctx)
1363 raw_spin_lock(&ctx->lock);
1366 * If the event is on, turn it off.
1367 * If it is in error state, leave it in error state.
1369 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1370 update_context_time(ctx);
1371 update_cgrp_time_from_event(event);
1372 update_group_times(event);
1373 if (event == event->group_leader)
1374 group_sched_out(event, cpuctx, ctx);
1376 event_sched_out(event, cpuctx, ctx);
1377 event->state = PERF_EVENT_STATE_OFF;
1380 raw_spin_unlock(&ctx->lock);
1388 * If event->ctx is a cloned context, callers must make sure that
1389 * every task struct that event->ctx->task could possibly point to
1390 * remains valid. This condition is satisifed when called through
1391 * perf_event_for_each_child or perf_event_for_each because they
1392 * hold the top-level event's child_mutex, so any descendant that
1393 * goes to exit will block in sync_child_event.
1394 * When called from perf_pending_event it's OK because event->ctx
1395 * is the current context on this CPU and preemption is disabled,
1396 * hence we can't get into perf_event_task_sched_out for this context.
1398 static void _perf_event_disable(struct perf_event *event)
1400 struct perf_event_context *ctx = event->ctx;
1401 struct task_struct *task = ctx->task;
1405 * Disable the event on the cpu that it's on
1407 cpu_function_call(event->cpu, __perf_event_disable, event);
1412 if (!task_function_call(task, __perf_event_disable, event))
1415 raw_spin_lock_irq(&ctx->lock);
1417 * If the event is still active, we need to retry the cross-call.
1419 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1420 raw_spin_unlock_irq(&ctx->lock);
1422 * Reload the task pointer, it might have been changed by
1423 * a concurrent perf_event_context_sched_out().
1430 * Since we have the lock this context can't be scheduled
1431 * in, so we can change the state safely.
1433 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1434 update_group_times(event);
1435 event->state = PERF_EVENT_STATE_OFF;
1437 raw_spin_unlock_irq(&ctx->lock);
1441 * Strictly speaking kernel users cannot create groups and therefore this
1442 * interface does not need the perf_event_ctx_lock() magic.
1444 void perf_event_disable(struct perf_event *event)
1446 struct perf_event_context *ctx;
1448 ctx = perf_event_ctx_lock(event);
1449 _perf_event_disable(event);
1450 perf_event_ctx_unlock(event, ctx);
1453 static void perf_set_shadow_time(struct perf_event *event,
1454 struct perf_event_context *ctx,
1458 * use the correct time source for the time snapshot
1460 * We could get by without this by leveraging the
1461 * fact that to get to this function, the caller
1462 * has most likely already called update_context_time()
1463 * and update_cgrp_time_xx() and thus both timestamp
1464 * are identical (or very close). Given that tstamp is,
1465 * already adjusted for cgroup, we could say that:
1466 * tstamp - ctx->timestamp
1468 * tstamp - cgrp->timestamp.
1470 * Then, in perf_output_read(), the calculation would
1471 * work with no changes because:
1472 * - event is guaranteed scheduled in
1473 * - no scheduled out in between
1474 * - thus the timestamp would be the same
1476 * But this is a bit hairy.
1478 * So instead, we have an explicit cgroup call to remain
1479 * within the time time source all along. We believe it
1480 * is cleaner and simpler to understand.
1482 if (is_cgroup_event(event))
1483 perf_cgroup_set_shadow_time(event, tstamp);
1485 event->shadow_ctx_time = tstamp - ctx->timestamp;
1488 #define MAX_INTERRUPTS (~0ULL)
1490 static void perf_log_throttle(struct perf_event *event, int enable);
1493 event_sched_in(struct perf_event *event,
1494 struct perf_cpu_context *cpuctx,
1495 struct perf_event_context *ctx)
1497 u64 tstamp = perf_event_time(event);
1499 if (event->state <= PERF_EVENT_STATE_OFF)
1502 event->state = PERF_EVENT_STATE_ACTIVE;
1503 event->oncpu = smp_processor_id();
1506 * Unthrottle events, since we scheduled we might have missed several
1507 * ticks already, also for a heavily scheduling task there is little
1508 * guarantee it'll get a tick in a timely manner.
1510 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1511 perf_log_throttle(event, 1);
1512 event->hw.interrupts = 0;
1516 * The new state must be visible before we turn it on in the hardware:
1520 if (event->pmu->add(event, PERF_EF_START)) {
1521 event->state = PERF_EVENT_STATE_INACTIVE;
1526 event->tstamp_running += tstamp - event->tstamp_stopped;
1528 perf_set_shadow_time(event, ctx, tstamp);
1530 if (!is_software_event(event))
1531 cpuctx->active_oncpu++;
1534 if (event->attr.exclusive)
1535 cpuctx->exclusive = 1;
1541 group_sched_in(struct perf_event *group_event,
1542 struct perf_cpu_context *cpuctx,
1543 struct perf_event_context *ctx)
1545 struct perf_event *event, *partial_group = NULL;
1546 struct pmu *pmu = group_event->pmu;
1547 u64 now = ctx->time;
1548 bool simulate = false;
1550 if (group_event->state == PERF_EVENT_STATE_OFF)
1553 pmu->start_txn(pmu);
1555 if (event_sched_in(group_event, cpuctx, ctx)) {
1556 pmu->cancel_txn(pmu);
1561 * Schedule in siblings as one group (if any):
1563 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1564 if (event_sched_in(event, cpuctx, ctx)) {
1565 partial_group = event;
1570 if (!pmu->commit_txn(pmu))
1575 * Groups can be scheduled in as one unit only, so undo any
1576 * partial group before returning:
1577 * The events up to the failed event are scheduled out normally,
1578 * tstamp_stopped will be updated.
1580 * The failed events and the remaining siblings need to have
1581 * their timings updated as if they had gone thru event_sched_in()
1582 * and event_sched_out(). This is required to get consistent timings
1583 * across the group. This also takes care of the case where the group
1584 * could never be scheduled by ensuring tstamp_stopped is set to mark
1585 * the time the event was actually stopped, such that time delta
1586 * calculation in update_event_times() is correct.
1588 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1589 if (event == partial_group)
1593 event->tstamp_running += now - event->tstamp_stopped;
1594 event->tstamp_stopped = now;
1596 event_sched_out(event, cpuctx, ctx);
1599 event_sched_out(group_event, cpuctx, ctx);
1601 pmu->cancel_txn(pmu);
1607 * Work out whether we can put this event group on the CPU now.
1609 static int group_can_go_on(struct perf_event *event,
1610 struct perf_cpu_context *cpuctx,
1614 * Groups consisting entirely of software events can always go on.
1616 if (event->group_flags & PERF_GROUP_SOFTWARE)
1619 * If an exclusive group is already on, no other hardware
1622 if (cpuctx->exclusive)
1625 * If this group is exclusive and there are already
1626 * events on the CPU, it can't go on.
1628 if (event->attr.exclusive && cpuctx->active_oncpu)
1631 * Otherwise, try to add it if all previous groups were able
1637 static void add_event_to_ctx(struct perf_event *event,
1638 struct perf_event_context *ctx)
1640 u64 tstamp = perf_event_time(event);
1642 list_add_event(event, ctx);
1643 perf_group_attach(event);
1644 event->tstamp_enabled = tstamp;
1645 event->tstamp_running = tstamp;
1646 event->tstamp_stopped = tstamp;
1649 static void task_ctx_sched_out(struct perf_event_context *ctx);
1651 ctx_sched_in(struct perf_event_context *ctx,
1652 struct perf_cpu_context *cpuctx,
1653 enum event_type_t event_type,
1654 struct task_struct *task);
1656 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
1657 struct perf_event_context *ctx,
1658 struct task_struct *task)
1660 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
1662 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
1663 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
1665 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
1669 * Cross CPU call to install and enable a performance event
1671 * Must be called with ctx->mutex held
1673 static int __perf_install_in_context(void *info)
1675 struct perf_event *event = info;
1676 struct perf_event_context *ctx = event->ctx;
1677 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1678 struct perf_event_context *task_ctx = cpuctx->task_ctx;
1679 struct task_struct *task = current;
1681 perf_ctx_lock(cpuctx, task_ctx);
1682 perf_pmu_disable(cpuctx->ctx.pmu);
1685 * If there was an active task_ctx schedule it out.
1688 task_ctx_sched_out(task_ctx);
1691 * If the context we're installing events in is not the
1692 * active task_ctx, flip them.
1694 if (ctx->task && task_ctx != ctx) {
1696 raw_spin_unlock(&task_ctx->lock);
1697 raw_spin_lock(&ctx->lock);
1702 cpuctx->task_ctx = task_ctx;
1703 task = task_ctx->task;
1706 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
1708 update_context_time(ctx);
1710 * update cgrp time only if current cgrp
1711 * matches event->cgrp. Must be done before
1712 * calling add_event_to_ctx()
1714 update_cgrp_time_from_event(event);
1716 add_event_to_ctx(event, ctx);
1719 * Schedule everything back in
1721 perf_event_sched_in(cpuctx, task_ctx, task);
1723 perf_pmu_enable(cpuctx->ctx.pmu);
1724 perf_ctx_unlock(cpuctx, task_ctx);
1730 * Attach a performance event to a context
1732 * First we add the event to the list with the hardware enable bit
1733 * in event->hw_config cleared.
1735 * If the event is attached to a task which is on a CPU we use a smp
1736 * call to enable it in the task context. The task might have been
1737 * scheduled away, but we check this in the smp call again.
1740 perf_install_in_context(struct perf_event_context *ctx,
1741 struct perf_event *event,
1744 struct task_struct *task = ctx->task;
1746 lockdep_assert_held(&ctx->mutex);
1752 * Per cpu events are installed via an smp call and
1753 * the install is always successful.
1755 cpu_function_call(cpu, __perf_install_in_context, event);
1760 if (!task_function_call(task, __perf_install_in_context, event))
1763 raw_spin_lock_irq(&ctx->lock);
1765 * If we failed to find a running task, but find the context active now
1766 * that we've acquired the ctx->lock, retry.
1768 if (ctx->is_active) {
1769 raw_spin_unlock_irq(&ctx->lock);
1771 * Reload the task pointer, it might have been changed by
1772 * a concurrent perf_event_context_sched_out().
1776 * Reload the task pointer, it might have been changed by
1777 * a concurrent perf_event_context_sched_out().
1784 * Since the task isn't running, its safe to add the event, us holding
1785 * the ctx->lock ensures the task won't get scheduled in.
1787 add_event_to_ctx(event, ctx);
1788 raw_spin_unlock_irq(&ctx->lock);
1792 * Put a event into inactive state and update time fields.
1793 * Enabling the leader of a group effectively enables all
1794 * the group members that aren't explicitly disabled, so we
1795 * have to update their ->tstamp_enabled also.
1796 * Note: this works for group members as well as group leaders
1797 * since the non-leader members' sibling_lists will be empty.
1799 static void __perf_event_mark_enabled(struct perf_event *event,
1800 struct perf_event_context *ctx)
1802 struct perf_event *sub;
1803 u64 tstamp = perf_event_time(event);
1805 event->state = PERF_EVENT_STATE_INACTIVE;
1806 event->tstamp_enabled = tstamp - event->total_time_enabled;
1807 list_for_each_entry(sub, &event->sibling_list, group_entry) {
1808 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
1809 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
1814 * Cross CPU call to enable a performance event
1816 static int __perf_event_enable(void *info)
1818 struct perf_event *event = info;
1819 struct perf_event_context *ctx = event->ctx;
1820 struct perf_event *leader = event->group_leader;
1821 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1825 * There's a time window between 'ctx->is_active' check
1826 * in perf_event_enable function and this place having:
1828 * - ctx->lock unlocked
1830 * where the task could be killed and 'ctx' deactivated
1831 * by perf_event_exit_task.
1833 if (!ctx->is_active)
1836 raw_spin_lock(&ctx->lock);
1837 update_context_time(ctx);
1839 if (event->state >= PERF_EVENT_STATE_INACTIVE)
1843 * set current task's cgroup time reference point
1845 perf_cgroup_set_timestamp(current, ctx);
1847 __perf_event_mark_enabled(event, ctx);
1849 if (!event_filter_match(event)) {
1850 if (is_cgroup_event(event))
1851 perf_cgroup_defer_enabled(event);
1856 * If the event is in a group and isn't the group leader,
1857 * then don't put it on unless the group is on.
1859 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
1862 if (!group_can_go_on(event, cpuctx, 1)) {
1865 if (event == leader)
1866 err = group_sched_in(event, cpuctx, ctx);
1868 err = event_sched_in(event, cpuctx, ctx);
1873 * If this event can't go on and it's part of a
1874 * group, then the whole group has to come off.
1876 if (leader != event)
1877 group_sched_out(leader, cpuctx, ctx);
1878 if (leader->attr.pinned) {
1879 update_group_times(leader);
1880 leader->state = PERF_EVENT_STATE_ERROR;
1885 raw_spin_unlock(&ctx->lock);
1893 * If event->ctx is a cloned context, callers must make sure that
1894 * every task struct that event->ctx->task could possibly point to
1895 * remains valid. This condition is satisfied when called through
1896 * perf_event_for_each_child or perf_event_for_each as described
1897 * for perf_event_disable.
1899 static void _perf_event_enable(struct perf_event *event)
1901 struct perf_event_context *ctx = event->ctx;
1902 struct task_struct *task = ctx->task;
1906 * Enable the event on the cpu that it's on
1908 cpu_function_call(event->cpu, __perf_event_enable, event);
1912 raw_spin_lock_irq(&ctx->lock);
1913 if (event->state >= PERF_EVENT_STATE_INACTIVE)
1917 * If the event is in error state, clear that first.
1918 * That way, if we see the event in error state below, we
1919 * know that it has gone back into error state, as distinct
1920 * from the task having been scheduled away before the
1921 * cross-call arrived.
1923 if (event->state == PERF_EVENT_STATE_ERROR)
1924 event->state = PERF_EVENT_STATE_OFF;
1927 if (!ctx->is_active) {
1928 __perf_event_mark_enabled(event, ctx);
1932 raw_spin_unlock_irq(&ctx->lock);
1934 if (!task_function_call(task, __perf_event_enable, event))
1937 raw_spin_lock_irq(&ctx->lock);
1940 * If the context is active and the event is still off,
1941 * we need to retry the cross-call.
1943 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
1945 * task could have been flipped by a concurrent
1946 * perf_event_context_sched_out()
1953 raw_spin_unlock_irq(&ctx->lock);
1957 * See perf_event_disable();
1959 void perf_event_enable(struct perf_event *event)
1961 struct perf_event_context *ctx;
1963 ctx = perf_event_ctx_lock(event);
1964 _perf_event_enable(event);
1965 perf_event_ctx_unlock(event, ctx);
1968 static int _perf_event_refresh(struct perf_event *event, int refresh)
1971 * not supported on inherited events
1973 if (event->attr.inherit || !is_sampling_event(event))
1976 atomic_add(refresh, &event->event_limit);
1977 _perf_event_enable(event);
1983 * See perf_event_disable()
1985 int perf_event_refresh(struct perf_event *event, int refresh)
1987 struct perf_event_context *ctx;
1990 ctx = perf_event_ctx_lock(event);
1991 ret = _perf_event_refresh(event, refresh);
1992 perf_event_ctx_unlock(event, ctx);
1996 EXPORT_SYMBOL_GPL(perf_event_refresh);
1998 static void ctx_sched_out(struct perf_event_context *ctx,
1999 struct perf_cpu_context *cpuctx,
2000 enum event_type_t event_type)
2002 struct perf_event *event;
2003 int is_active = ctx->is_active;
2005 ctx->is_active &= ~event_type;
2006 if (likely(!ctx->nr_events))
2009 update_context_time(ctx);
2010 update_cgrp_time_from_cpuctx(cpuctx);
2011 if (!ctx->nr_active)
2014 perf_pmu_disable(ctx->pmu);
2015 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2016 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2017 group_sched_out(event, cpuctx, ctx);
2020 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2021 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2022 group_sched_out(event, cpuctx, ctx);
2024 perf_pmu_enable(ctx->pmu);
2028 * Test whether two contexts are equivalent, i.e. whether they
2029 * have both been cloned from the same version of the same context
2030 * and they both have the same number of enabled events.
2031 * If the number of enabled events is the same, then the set
2032 * of enabled events should be the same, because these are both
2033 * inherited contexts, therefore we can't access individual events
2034 * in them directly with an fd; we can only enable/disable all
2035 * events via prctl, or enable/disable all events in a family
2036 * via ioctl, which will have the same effect on both contexts.
2038 static int context_equiv(struct perf_event_context *ctx1,
2039 struct perf_event_context *ctx2)
2041 return ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx
2042 && ctx1->parent_gen == ctx2->parent_gen
2043 && !ctx1->pin_count && !ctx2->pin_count;
2046 static void __perf_event_sync_stat(struct perf_event *event,
2047 struct perf_event *next_event)
2051 if (!event->attr.inherit_stat)
2055 * Update the event value, we cannot use perf_event_read()
2056 * because we're in the middle of a context switch and have IRQs
2057 * disabled, which upsets smp_call_function_single(), however
2058 * we know the event must be on the current CPU, therefore we
2059 * don't need to use it.
2061 switch (event->state) {
2062 case PERF_EVENT_STATE_ACTIVE:
2063 event->pmu->read(event);
2066 case PERF_EVENT_STATE_INACTIVE:
2067 update_event_times(event);
2075 * In order to keep per-task stats reliable we need to flip the event
2076 * values when we flip the contexts.
2078 value = local64_read(&next_event->count);
2079 value = local64_xchg(&event->count, value);
2080 local64_set(&next_event->count, value);
2082 swap(event->total_time_enabled, next_event->total_time_enabled);
2083 swap(event->total_time_running, next_event->total_time_running);
2086 * Since we swizzled the values, update the user visible data too.
2088 perf_event_update_userpage(event);
2089 perf_event_update_userpage(next_event);
2092 #define list_next_entry(pos, member) \
2093 list_entry(pos->member.next, typeof(*pos), member)
2095 static void perf_event_sync_stat(struct perf_event_context *ctx,
2096 struct perf_event_context *next_ctx)
2098 struct perf_event *event, *next_event;
2103 update_context_time(ctx);
2105 event = list_first_entry(&ctx->event_list,
2106 struct perf_event, event_entry);
2108 next_event = list_first_entry(&next_ctx->event_list,
2109 struct perf_event, event_entry);
2111 while (&event->event_entry != &ctx->event_list &&
2112 &next_event->event_entry != &next_ctx->event_list) {
2114 __perf_event_sync_stat(event, next_event);
2116 event = list_next_entry(event, event_entry);
2117 next_event = list_next_entry(next_event, event_entry);
2121 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2122 struct task_struct *next)
2124 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2125 struct perf_event_context *next_ctx;
2126 struct perf_event_context *parent;
2127 struct perf_cpu_context *cpuctx;
2133 cpuctx = __get_cpu_context(ctx);
2134 if (!cpuctx->task_ctx)
2138 parent = rcu_dereference(ctx->parent_ctx);
2139 next_ctx = next->perf_event_ctxp[ctxn];
2140 if (parent && next_ctx &&
2141 rcu_dereference(next_ctx->parent_ctx) == parent) {
2143 * Looks like the two contexts are clones, so we might be
2144 * able to optimize the context switch. We lock both
2145 * contexts and check that they are clones under the
2146 * lock (including re-checking that neither has been
2147 * uncloned in the meantime). It doesn't matter which
2148 * order we take the locks because no other cpu could
2149 * be trying to lock both of these tasks.
2151 raw_spin_lock(&ctx->lock);
2152 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2153 if (context_equiv(ctx, next_ctx)) {
2155 * XXX do we need a memory barrier of sorts
2156 * wrt to rcu_dereference() of perf_event_ctxp
2158 task->perf_event_ctxp[ctxn] = next_ctx;
2159 next->perf_event_ctxp[ctxn] = ctx;
2161 next_ctx->task = task;
2164 perf_event_sync_stat(ctx, next_ctx);
2166 raw_spin_unlock(&next_ctx->lock);
2167 raw_spin_unlock(&ctx->lock);
2172 raw_spin_lock(&ctx->lock);
2173 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2174 cpuctx->task_ctx = NULL;
2175 raw_spin_unlock(&ctx->lock);
2179 #define for_each_task_context_nr(ctxn) \
2180 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2183 * Called from scheduler to remove the events of the current task,
2184 * with interrupts disabled.
2186 * We stop each event and update the event value in event->count.
2188 * This does not protect us against NMI, but disable()
2189 * sets the disabled bit in the control field of event _before_
2190 * accessing the event control register. If a NMI hits, then it will
2191 * not restart the event.
2193 void __perf_event_task_sched_out(struct task_struct *task,
2194 struct task_struct *next)
2198 for_each_task_context_nr(ctxn)
2199 perf_event_context_sched_out(task, ctxn, next);
2202 * if cgroup events exist on this CPU, then we need
2203 * to check if we have to switch out PMU state.
2204 * cgroup event are system-wide mode only
2206 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2207 perf_cgroup_sched_out(task, next);
2210 static void task_ctx_sched_out(struct perf_event_context *ctx)
2212 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2214 if (!cpuctx->task_ctx)
2217 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2220 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2221 cpuctx->task_ctx = NULL;
2225 * Called with IRQs disabled
2227 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2228 enum event_type_t event_type)
2230 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2234 ctx_pinned_sched_in(struct perf_event_context *ctx,
2235 struct perf_cpu_context *cpuctx)
2237 struct perf_event *event;
2239 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2240 if (event->state <= PERF_EVENT_STATE_OFF)
2242 if (!event_filter_match(event))
2245 /* may need to reset tstamp_enabled */
2246 if (is_cgroup_event(event))
2247 perf_cgroup_mark_enabled(event, ctx);
2249 if (group_can_go_on(event, cpuctx, 1))
2250 group_sched_in(event, cpuctx, ctx);
2253 * If this pinned group hasn't been scheduled,
2254 * put it in error state.
2256 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2257 update_group_times(event);
2258 event->state = PERF_EVENT_STATE_ERROR;
2264 ctx_flexible_sched_in(struct perf_event_context *ctx,
2265 struct perf_cpu_context *cpuctx)
2267 struct perf_event *event;
2270 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2271 /* Ignore events in OFF or ERROR state */
2272 if (event->state <= PERF_EVENT_STATE_OFF)
2275 * Listen to the 'cpu' scheduling filter constraint
2278 if (!event_filter_match(event))
2281 /* may need to reset tstamp_enabled */
2282 if (is_cgroup_event(event))
2283 perf_cgroup_mark_enabled(event, ctx);
2285 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2286 if (group_sched_in(event, cpuctx, ctx))
2293 ctx_sched_in(struct perf_event_context *ctx,
2294 struct perf_cpu_context *cpuctx,
2295 enum event_type_t event_type,
2296 struct task_struct *task)
2299 int is_active = ctx->is_active;
2301 ctx->is_active |= event_type;
2302 if (likely(!ctx->nr_events))
2306 ctx->timestamp = now;
2307 perf_cgroup_set_timestamp(task, ctx);
2309 * First go through the list and put on any pinned groups
2310 * in order to give them the best chance of going on.
2312 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2313 ctx_pinned_sched_in(ctx, cpuctx);
2315 /* Then walk through the lower prio flexible groups */
2316 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2317 ctx_flexible_sched_in(ctx, cpuctx);
2320 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2321 enum event_type_t event_type,
2322 struct task_struct *task)
2324 struct perf_event_context *ctx = &cpuctx->ctx;
2326 ctx_sched_in(ctx, cpuctx, event_type, task);
2329 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2330 struct task_struct *task)
2332 struct perf_cpu_context *cpuctx;
2334 cpuctx = __get_cpu_context(ctx);
2335 if (cpuctx->task_ctx == ctx)
2338 perf_ctx_lock(cpuctx, ctx);
2339 perf_pmu_disable(ctx->pmu);
2341 * We want to keep the following priority order:
2342 * cpu pinned (that don't need to move), task pinned,
2343 * cpu flexible, task flexible.
2345 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2348 cpuctx->task_ctx = ctx;
2350 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2352 perf_pmu_enable(ctx->pmu);
2353 perf_ctx_unlock(cpuctx, ctx);
2356 * Since these rotations are per-cpu, we need to ensure the
2357 * cpu-context we got scheduled on is actually rotating.
2359 perf_pmu_rotate_start(ctx->pmu);
2363 * Called from scheduler to add the events of the current task
2364 * with interrupts disabled.
2366 * We restore the event value and then enable it.
2368 * This does not protect us against NMI, but enable()
2369 * sets the enabled bit in the control field of event _before_
2370 * accessing the event control register. If a NMI hits, then it will
2371 * keep the event running.
2373 void __perf_event_task_sched_in(struct task_struct *prev,
2374 struct task_struct *task)
2376 struct perf_event_context *ctx;
2379 for_each_task_context_nr(ctxn) {
2380 ctx = task->perf_event_ctxp[ctxn];
2384 perf_event_context_sched_in(ctx, task);
2387 * if cgroup events exist on this CPU, then we need
2388 * to check if we have to switch in PMU state.
2389 * cgroup event are system-wide mode only
2391 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2392 perf_cgroup_sched_in(prev, task);
2395 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2397 u64 frequency = event->attr.sample_freq;
2398 u64 sec = NSEC_PER_SEC;
2399 u64 divisor, dividend;
2401 int count_fls, nsec_fls, frequency_fls, sec_fls;
2403 count_fls = fls64(count);
2404 nsec_fls = fls64(nsec);
2405 frequency_fls = fls64(frequency);
2409 * We got @count in @nsec, with a target of sample_freq HZ
2410 * the target period becomes:
2413 * period = -------------------
2414 * @nsec * sample_freq
2419 * Reduce accuracy by one bit such that @a and @b converge
2420 * to a similar magnitude.
2422 #define REDUCE_FLS(a, b) \
2424 if (a##_fls > b##_fls) { \
2434 * Reduce accuracy until either term fits in a u64, then proceed with
2435 * the other, so that finally we can do a u64/u64 division.
2437 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2438 REDUCE_FLS(nsec, frequency);
2439 REDUCE_FLS(sec, count);
2442 if (count_fls + sec_fls > 64) {
2443 divisor = nsec * frequency;
2445 while (count_fls + sec_fls > 64) {
2446 REDUCE_FLS(count, sec);
2450 dividend = count * sec;
2452 dividend = count * sec;
2454 while (nsec_fls + frequency_fls > 64) {
2455 REDUCE_FLS(nsec, frequency);
2459 divisor = nsec * frequency;
2465 return div64_u64(dividend, divisor);
2468 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count)
2470 struct hw_perf_event *hwc = &event->hw;
2471 s64 period, sample_period;
2474 period = perf_calculate_period(event, nsec, count);
2476 delta = (s64)(period - hwc->sample_period);
2477 delta = (delta + 7) / 8; /* low pass filter */
2479 sample_period = hwc->sample_period + delta;
2484 hwc->sample_period = sample_period;
2486 if (local64_read(&hwc->period_left) > 8*sample_period) {
2487 event->pmu->stop(event, PERF_EF_UPDATE);
2488 local64_set(&hwc->period_left, 0);
2489 event->pmu->start(event, PERF_EF_RELOAD);
2493 static void perf_ctx_adjust_freq(struct perf_event_context *ctx, u64 period)
2495 struct perf_event *event;
2496 struct hw_perf_event *hwc;
2497 u64 interrupts, now;
2500 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
2501 if (event->state != PERF_EVENT_STATE_ACTIVE)
2504 if (!event_filter_match(event))
2509 interrupts = hwc->interrupts;
2510 hwc->interrupts = 0;
2513 * unthrottle events on the tick
2515 if (interrupts == MAX_INTERRUPTS) {
2516 perf_log_throttle(event, 1);
2517 event->pmu->start(event, 0);
2520 if (!event->attr.freq || !event->attr.sample_freq)
2523 event->pmu->read(event);
2524 now = local64_read(&event->count);
2525 delta = now - hwc->freq_count_stamp;
2526 hwc->freq_count_stamp = now;
2529 perf_adjust_period(event, period, delta);
2534 * Round-robin a context's events:
2536 static void rotate_ctx(struct perf_event_context *ctx)
2539 * Rotate the first entry last of non-pinned groups. Rotation might be
2540 * disabled by the inheritance code.
2542 if (!ctx->rotate_disable)
2543 list_rotate_left(&ctx->flexible_groups);
2547 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
2548 * because they're strictly cpu affine and rotate_start is called with IRQs
2549 * disabled, while rotate_context is called from IRQ context.
2551 static void perf_rotate_context(struct perf_cpu_context *cpuctx)
2553 u64 interval = (u64)cpuctx->jiffies_interval * TICK_NSEC;
2554 struct perf_event_context *ctx = NULL;
2555 int rotate = 0, remove = 1;
2557 if (cpuctx->ctx.nr_events) {
2559 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
2563 ctx = cpuctx->task_ctx;
2564 if (ctx && ctx->nr_events) {
2566 if (ctx->nr_events != ctx->nr_active)
2570 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2571 perf_pmu_disable(cpuctx->ctx.pmu);
2572 perf_ctx_adjust_freq(&cpuctx->ctx, interval);
2574 perf_ctx_adjust_freq(ctx, interval);
2579 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2581 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
2583 rotate_ctx(&cpuctx->ctx);
2587 perf_event_sched_in(cpuctx, ctx, current);
2591 list_del_init(&cpuctx->rotation_list);
2593 perf_pmu_enable(cpuctx->ctx.pmu);
2594 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2597 void perf_event_task_tick(void)
2599 struct list_head *head = &__get_cpu_var(rotation_list);
2600 struct perf_cpu_context *cpuctx, *tmp;
2602 WARN_ON(!irqs_disabled());
2604 list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) {
2605 if (cpuctx->jiffies_interval == 1 ||
2606 !(jiffies % cpuctx->jiffies_interval))
2607 perf_rotate_context(cpuctx);
2611 static int event_enable_on_exec(struct perf_event *event,
2612 struct perf_event_context *ctx)
2614 if (!event->attr.enable_on_exec)
2617 event->attr.enable_on_exec = 0;
2618 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2621 __perf_event_mark_enabled(event, ctx);
2627 * Enable all of a task's events that have been marked enable-on-exec.
2628 * This expects task == current.
2630 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
2632 struct perf_event *event;
2633 unsigned long flags;
2637 local_irq_save(flags);
2638 if (!ctx || !ctx->nr_events)
2642 * We must ctxsw out cgroup events to avoid conflict
2643 * when invoking perf_task_event_sched_in() later on
2644 * in this function. Otherwise we end up trying to
2645 * ctxswin cgroup events which are already scheduled
2648 perf_cgroup_sched_out(current, NULL);
2650 raw_spin_lock(&ctx->lock);
2651 task_ctx_sched_out(ctx);
2653 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2654 ret = event_enable_on_exec(event, ctx);
2659 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2660 ret = event_enable_on_exec(event, ctx);
2666 * Unclone this context if we enabled any event.
2671 raw_spin_unlock(&ctx->lock);
2674 * Also calls ctxswin for cgroup events, if any:
2676 perf_event_context_sched_in(ctx, ctx->task);
2678 local_irq_restore(flags);
2682 * Cross CPU call to read the hardware event
2684 static void __perf_event_read(void *info)
2686 struct perf_event *event = info;
2687 struct perf_event_context *ctx = event->ctx;
2688 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2691 * If this is a task context, we need to check whether it is
2692 * the current task context of this cpu. If not it has been
2693 * scheduled out before the smp call arrived. In that case
2694 * event->count would have been updated to a recent sample
2695 * when the event was scheduled out.
2697 if (ctx->task && cpuctx->task_ctx != ctx)
2700 raw_spin_lock(&ctx->lock);
2701 if (ctx->is_active) {
2702 update_context_time(ctx);
2703 update_cgrp_time_from_event(event);
2705 update_event_times(event);
2706 if (event->state == PERF_EVENT_STATE_ACTIVE)
2707 event->pmu->read(event);
2708 raw_spin_unlock(&ctx->lock);
2711 static inline u64 perf_event_count(struct perf_event *event)
2713 return local64_read(&event->count) + atomic64_read(&event->child_count);
2716 static u64 perf_event_read(struct perf_event *event)
2719 * If event is enabled and currently active on a CPU, update the
2720 * value in the event structure:
2722 if (event->state == PERF_EVENT_STATE_ACTIVE) {
2723 smp_call_function_single(event->oncpu,
2724 __perf_event_read, event, 1);
2725 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
2726 struct perf_event_context *ctx = event->ctx;
2727 unsigned long flags;
2729 raw_spin_lock_irqsave(&ctx->lock, flags);
2731 * may read while context is not active
2732 * (e.g., thread is blocked), in that case
2733 * we cannot update context time
2735 if (ctx->is_active) {
2736 update_context_time(ctx);
2737 update_cgrp_time_from_event(event);
2739 update_event_times(event);
2740 raw_spin_unlock_irqrestore(&ctx->lock, flags);
2743 return perf_event_count(event);
2750 struct callchain_cpus_entries {
2751 struct rcu_head rcu_head;
2752 struct perf_callchain_entry *cpu_entries[0];
2755 static DEFINE_PER_CPU(int, callchain_recursion[PERF_NR_CONTEXTS]);
2756 static atomic_t nr_callchain_events;
2757 static DEFINE_MUTEX(callchain_mutex);
2758 struct callchain_cpus_entries *callchain_cpus_entries;
2761 __weak void perf_callchain_kernel(struct perf_callchain_entry *entry,
2762 struct pt_regs *regs)
2766 __weak void perf_callchain_user(struct perf_callchain_entry *entry,
2767 struct pt_regs *regs)
2771 static void release_callchain_buffers_rcu(struct rcu_head *head)
2773 struct callchain_cpus_entries *entries;
2776 entries = container_of(head, struct callchain_cpus_entries, rcu_head);
2778 for_each_possible_cpu(cpu)
2779 kfree(entries->cpu_entries[cpu]);
2784 static void release_callchain_buffers(void)
2786 struct callchain_cpus_entries *entries;
2788 entries = callchain_cpus_entries;
2789 rcu_assign_pointer(callchain_cpus_entries, NULL);
2790 call_rcu(&entries->rcu_head, release_callchain_buffers_rcu);
2793 static int alloc_callchain_buffers(void)
2797 struct callchain_cpus_entries *entries;
2800 * We can't use the percpu allocation API for data that can be
2801 * accessed from NMI. Use a temporary manual per cpu allocation
2802 * until that gets sorted out.
2804 size = offsetof(struct callchain_cpus_entries, cpu_entries[nr_cpu_ids]);
2806 entries = kzalloc(size, GFP_KERNEL);
2810 size = sizeof(struct perf_callchain_entry) * PERF_NR_CONTEXTS;
2812 for_each_possible_cpu(cpu) {
2813 entries->cpu_entries[cpu] = kmalloc_node(size, GFP_KERNEL,
2815 if (!entries->cpu_entries[cpu])
2819 rcu_assign_pointer(callchain_cpus_entries, entries);
2824 for_each_possible_cpu(cpu)
2825 kfree(entries->cpu_entries[cpu]);
2831 static int get_callchain_buffers(void)
2836 mutex_lock(&callchain_mutex);
2838 count = atomic_inc_return(&nr_callchain_events);
2839 if (WARN_ON_ONCE(count < 1)) {
2845 /* If the allocation failed, give up */
2846 if (!callchain_cpus_entries)
2851 err = alloc_callchain_buffers();
2853 release_callchain_buffers();
2855 mutex_unlock(&callchain_mutex);
2860 static void put_callchain_buffers(void)
2862 if (atomic_dec_and_mutex_lock(&nr_callchain_events, &callchain_mutex)) {
2863 release_callchain_buffers();
2864 mutex_unlock(&callchain_mutex);
2868 static int get_recursion_context(int *recursion)
2876 else if (in_softirq())
2881 if (recursion[rctx])
2890 static inline void put_recursion_context(int *recursion, int rctx)
2896 static struct perf_callchain_entry *get_callchain_entry(int *rctx)
2899 struct callchain_cpus_entries *entries;
2901 *rctx = get_recursion_context(__get_cpu_var(callchain_recursion));
2905 entries = rcu_dereference(callchain_cpus_entries);
2909 cpu = smp_processor_id();
2911 return &entries->cpu_entries[cpu][*rctx];
2915 put_callchain_entry(int rctx)
2917 put_recursion_context(__get_cpu_var(callchain_recursion), rctx);
2920 static struct perf_callchain_entry *perf_callchain(struct pt_regs *regs)
2923 struct perf_callchain_entry *entry;
2926 entry = get_callchain_entry(&rctx);
2935 if (!user_mode(regs)) {
2936 perf_callchain_store(entry, PERF_CONTEXT_KERNEL);
2937 perf_callchain_kernel(entry, regs);
2939 regs = task_pt_regs(current);
2945 perf_callchain_store(entry, PERF_CONTEXT_USER);
2946 perf_callchain_user(entry, regs);
2950 put_callchain_entry(rctx);
2956 * Initialize the perf_event context in a task_struct:
2958 static void __perf_event_init_context(struct perf_event_context *ctx)
2960 raw_spin_lock_init(&ctx->lock);
2961 mutex_init(&ctx->mutex);
2962 INIT_LIST_HEAD(&ctx->pinned_groups);
2963 INIT_LIST_HEAD(&ctx->flexible_groups);
2964 INIT_LIST_HEAD(&ctx->event_list);
2965 atomic_set(&ctx->refcount, 1);
2968 static struct perf_event_context *
2969 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
2971 struct perf_event_context *ctx;
2973 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
2977 __perf_event_init_context(ctx);
2980 get_task_struct(task);
2987 static struct task_struct *
2988 find_lively_task_by_vpid(pid_t vpid)
2990 struct task_struct *task;
2997 task = find_task_by_vpid(vpid);
2999 get_task_struct(task);
3003 return ERR_PTR(-ESRCH);
3005 /* Reuse ptrace permission checks for now. */
3007 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
3012 put_task_struct(task);
3013 return ERR_PTR(err);
3018 * Returns a matching context with refcount and pincount.
3020 static struct perf_event_context *
3021 find_get_context(struct pmu *pmu, struct task_struct *task, int cpu)
3023 struct perf_event_context *ctx;
3024 struct perf_cpu_context *cpuctx;
3025 unsigned long flags;
3029 /* Must be root to operate on a CPU event: */
3030 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3031 return ERR_PTR(-EACCES);
3034 * We could be clever and allow to attach a event to an
3035 * offline CPU and activate it when the CPU comes up, but
3038 if (!cpu_online(cpu))
3039 return ERR_PTR(-ENODEV);
3041 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3050 ctxn = pmu->task_ctx_nr;
3055 ctx = perf_lock_task_context(task, ctxn, &flags);
3059 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3061 ctx = alloc_perf_context(pmu, task);
3067 mutex_lock(&task->perf_event_mutex);
3069 * If it has already passed perf_event_exit_task().
3070 * we must see PF_EXITING, it takes this mutex too.
3072 if (task->flags & PF_EXITING)
3074 else if (task->perf_event_ctxp[ctxn])
3079 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3081 mutex_unlock(&task->perf_event_mutex);
3083 if (unlikely(err)) {
3095 return ERR_PTR(err);
3098 static void perf_event_free_filter(struct perf_event *event);
3100 static void free_event_rcu(struct rcu_head *head)
3102 struct perf_event *event;
3104 event = container_of(head, struct perf_event, rcu_head);
3106 put_pid_ns(event->ns);
3107 perf_event_free_filter(event);
3111 static void ring_buffer_put(struct ring_buffer *rb);
3112 static void ring_buffer_detach(struct perf_event *event, struct ring_buffer *rb);
3114 static void free_event(struct perf_event *event)
3116 irq_work_sync(&event->pending);
3118 if (!event->parent) {
3119 if (event->attach_state & PERF_ATTACH_TASK)
3120 jump_label_dec(&perf_sched_events);
3121 if (event->attr.mmap || event->attr.mmap_data)
3122 atomic_dec(&nr_mmap_events);
3123 if (event->attr.comm)
3124 atomic_dec(&nr_comm_events);
3125 if (event->attr.task)
3126 atomic_dec(&nr_task_events);
3127 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3128 put_callchain_buffers();
3129 if (is_cgroup_event(event)) {
3130 atomic_dec(&per_cpu(perf_cgroup_events, event->cpu));
3131 jump_label_dec(&perf_sched_events);
3136 struct ring_buffer *rb;
3139 * Can happen when we close an event with re-directed output.
3141 * Since we have a 0 refcount, perf_mmap_close() will skip
3142 * over us; possibly making our ring_buffer_put() the last.
3144 mutex_lock(&event->mmap_mutex);
3147 rcu_assign_pointer(event->rb, NULL);
3148 ring_buffer_detach(event, rb);
3149 ring_buffer_put(rb); /* could be last */
3151 mutex_unlock(&event->mmap_mutex);
3154 if (is_cgroup_event(event))
3155 perf_detach_cgroup(event);
3158 event->destroy(event);
3161 put_ctx(event->ctx);
3163 call_rcu(&event->rcu_head, free_event_rcu);
3166 int perf_event_release_kernel(struct perf_event *event)
3168 struct perf_event_context *ctx = event->ctx;
3170 WARN_ON_ONCE(ctx->parent_ctx);
3172 * There are two ways this annotation is useful:
3174 * 1) there is a lock recursion from perf_event_exit_task
3175 * see the comment there.
3177 * 2) there is a lock-inversion with mmap_sem through
3178 * perf_event_read_group(), which takes faults while
3179 * holding ctx->mutex, however this is called after
3180 * the last filedesc died, so there is no possibility
3181 * to trigger the AB-BA case.
3183 mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
3184 perf_remove_from_context(event, true);
3185 mutex_unlock(&ctx->mutex);
3191 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3194 * Called when the last reference to the file is gone.
3196 static void put_event(struct perf_event *event)
3198 struct task_struct *owner;
3200 if (!atomic_long_dec_and_test(&event->refcount))
3204 owner = ACCESS_ONCE(event->owner);
3206 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3207 * !owner it means the list deletion is complete and we can indeed
3208 * free this event, otherwise we need to serialize on
3209 * owner->perf_event_mutex.
3211 smp_read_barrier_depends();
3214 * Since delayed_put_task_struct() also drops the last
3215 * task reference we can safely take a new reference
3216 * while holding the rcu_read_lock().
3218 get_task_struct(owner);
3224 * If we're here through perf_event_exit_task() we're already
3225 * holding ctx->mutex which would be an inversion wrt. the
3226 * normal lock order.
3228 * However we can safely take this lock because its the child
3231 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
3234 * We have to re-check the event->owner field, if it is cleared
3235 * we raced with perf_event_exit_task(), acquiring the mutex
3236 * ensured they're done, and we can proceed with freeing the
3240 list_del_init(&event->owner_entry);
3241 mutex_unlock(&owner->perf_event_mutex);
3242 put_task_struct(owner);
3245 perf_event_release_kernel(event);
3248 static int perf_release(struct inode *inode, struct file *file)
3250 put_event(file->private_data);
3254 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3256 struct perf_event *child;
3262 mutex_lock(&event->child_mutex);
3263 total += perf_event_read(event);
3264 *enabled += event->total_time_enabled +
3265 atomic64_read(&event->child_total_time_enabled);
3266 *running += event->total_time_running +
3267 atomic64_read(&event->child_total_time_running);
3269 list_for_each_entry(child, &event->child_list, child_list) {
3270 total += perf_event_read(child);
3271 *enabled += child->total_time_enabled;
3272 *running += child->total_time_running;
3274 mutex_unlock(&event->child_mutex);
3278 EXPORT_SYMBOL_GPL(perf_event_read_value);
3280 static void __perf_read_group_add(struct perf_event *leader,
3281 u64 read_format, u64 *values)
3283 struct perf_event_context *ctx = leader->ctx;
3284 struct perf_event *sub;
3285 unsigned long flags;
3286 int n = 1; /* skip @nr */
3287 u64 count, enabled, running;
3289 count = perf_event_read_value(leader, &enabled, &running);
3292 * Since we co-schedule groups, {enabled,running} times of siblings
3293 * will be identical to those of the leader, so we only publish one
3296 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3297 values[n++] = enabled;
3298 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3299 values[n++] = running;
3302 * Write {count,id} tuples for every sibling.
3304 values[n++] += count;
3305 if (read_format & PERF_FORMAT_ID)
3306 values[n++] = primary_event_id(leader);
3308 raw_spin_lock_irqsave(&ctx->lock, flags);
3310 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3311 values[n++] = perf_event_read_value(sub, &enabled, &running);
3312 if (read_format & PERF_FORMAT_ID)
3313 values[n++] = primary_event_id(sub);
3316 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3319 static int perf_event_read_group(struct perf_event *event,
3320 u64 read_format, char __user *buf)
3322 struct perf_event *leader = event->group_leader, *child;
3323 struct perf_event_context *ctx = leader->ctx;
3324 int ret = event->read_size;
3327 lockdep_assert_held(&ctx->mutex);
3329 values = kzalloc(event->read_size, GFP_KERNEL);
3333 values[0] = 1 + leader->nr_siblings;
3336 * By locking the child_mutex of the leader we effectively
3337 * lock the child list of all siblings.. XXX explain how.
3339 mutex_lock(&leader->child_mutex);
3341 __perf_read_group_add(leader, read_format, values);
3342 list_for_each_entry(child, &leader->child_list, child_list)
3343 __perf_read_group_add(child, read_format, values);
3345 mutex_unlock(&leader->child_mutex);
3347 if (copy_to_user(buf, values, event->read_size))
3355 static int perf_event_read_one(struct perf_event *event,
3356 u64 read_format, char __user *buf)
3358 u64 enabled, running;
3362 values[n++] = perf_event_read_value(event, &enabled, &running);
3363 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3364 values[n++] = enabled;
3365 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3366 values[n++] = running;
3367 if (read_format & PERF_FORMAT_ID)
3368 values[n++] = primary_event_id(event);
3370 if (copy_to_user(buf, values, n * sizeof(u64)))
3373 return n * sizeof(u64);
3377 * Read the performance event - simple non blocking version for now
3380 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
3382 u64 read_format = event->attr.read_format;
3386 * Return end-of-file for a read on a event that is in
3387 * error state (i.e. because it was pinned but it couldn't be
3388 * scheduled on to the CPU at some point).
3390 if (event->state == PERF_EVENT_STATE_ERROR)
3393 if (count < event->read_size)
3396 WARN_ON_ONCE(event->ctx->parent_ctx);
3397 if (read_format & PERF_FORMAT_GROUP)
3398 ret = perf_event_read_group(event, read_format, buf);
3400 ret = perf_event_read_one(event, read_format, buf);
3406 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
3408 struct perf_event *event = file->private_data;
3409 struct perf_event_context *ctx;
3412 ctx = perf_event_ctx_lock(event);
3413 ret = perf_read_hw(event, buf, count);
3414 perf_event_ctx_unlock(event, ctx);
3419 static unsigned int perf_poll(struct file *file, poll_table *wait)
3421 struct perf_event *event = file->private_data;
3422 struct ring_buffer *rb;
3423 unsigned int events = POLL_HUP;
3426 * Pin the event->rb by taking event->mmap_mutex; otherwise
3427 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
3429 mutex_lock(&event->mmap_mutex);
3432 events = atomic_xchg(&rb->poll, 0);
3433 mutex_unlock(&event->mmap_mutex);
3435 poll_wait(file, &event->waitq, wait);
3440 static void _perf_event_reset(struct perf_event *event)
3442 (void)perf_event_read(event);
3443 local64_set(&event->count, 0);
3444 perf_event_update_userpage(event);
3448 * Holding the top-level event's child_mutex means that any
3449 * descendant process that has inherited this event will block
3450 * in sync_child_event if it goes to exit, thus satisfying the
3451 * task existence requirements of perf_event_enable/disable.
3453 static void perf_event_for_each_child(struct perf_event *event,
3454 void (*func)(struct perf_event *))
3456 struct perf_event *child;
3458 WARN_ON_ONCE(event->ctx->parent_ctx);
3460 mutex_lock(&event->child_mutex);
3462 list_for_each_entry(child, &event->child_list, child_list)
3464 mutex_unlock(&event->child_mutex);
3467 static void perf_event_for_each(struct perf_event *event,
3468 void (*func)(struct perf_event *))
3470 struct perf_event_context *ctx = event->ctx;
3471 struct perf_event *sibling;
3473 lockdep_assert_held(&ctx->mutex);
3475 event = event->group_leader;
3477 perf_event_for_each_child(event, func);
3479 list_for_each_entry(sibling, &event->sibling_list, group_entry)
3480 perf_event_for_each_child(sibling, func);
3483 static int perf_event_period(struct perf_event *event, u64 __user *arg)
3485 struct perf_event_context *ctx = event->ctx;
3489 if (!is_sampling_event(event))
3492 if (copy_from_user(&value, arg, sizeof(value)))
3498 raw_spin_lock_irq(&ctx->lock);
3499 if (event->attr.freq) {
3500 if (value > sysctl_perf_event_sample_rate) {
3505 event->attr.sample_freq = value;
3507 event->attr.sample_period = value;
3508 event->hw.sample_period = value;
3511 raw_spin_unlock_irq(&ctx->lock);
3516 static const struct file_operations perf_fops;
3518 static struct file *perf_fget_light(int fd, int *fput_needed)
3522 file = fget_light(fd, fput_needed);
3524 return ERR_PTR(-EBADF);
3526 if (file->f_op != &perf_fops) {
3527 fput_light(file, *fput_needed);
3529 return ERR_PTR(-EBADF);
3535 static int perf_event_set_output(struct perf_event *event,
3536 struct perf_event *output_event);
3537 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
3539 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
3541 void (*func)(struct perf_event *);
3545 case PERF_EVENT_IOC_ENABLE:
3546 func = _perf_event_enable;
3548 case PERF_EVENT_IOC_DISABLE:
3549 func = _perf_event_disable;
3551 case PERF_EVENT_IOC_RESET:
3552 func = _perf_event_reset;
3555 case PERF_EVENT_IOC_REFRESH:
3556 return _perf_event_refresh(event, arg);
3558 case PERF_EVENT_IOC_PERIOD:
3559 return perf_event_period(event, (u64 __user *)arg);
3561 case PERF_EVENT_IOC_SET_OUTPUT:
3563 struct file *output_file = NULL;
3564 struct perf_event *output_event = NULL;
3565 int fput_needed = 0;
3569 output_file = perf_fget_light(arg, &fput_needed);
3570 if (IS_ERR(output_file))
3571 return PTR_ERR(output_file);
3572 output_event = output_file->private_data;
3575 ret = perf_event_set_output(event, output_event);
3577 fput_light(output_file, fput_needed);
3582 case PERF_EVENT_IOC_SET_FILTER:
3583 return perf_event_set_filter(event, (void __user *)arg);
3589 if (flags & PERF_IOC_FLAG_GROUP)
3590 perf_event_for_each(event, func);
3592 perf_event_for_each_child(event, func);
3597 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
3599 struct perf_event *event = file->private_data;
3600 struct perf_event_context *ctx;
3603 ctx = perf_event_ctx_lock(event);
3604 ret = _perf_ioctl(event, cmd, arg);
3605 perf_event_ctx_unlock(event, ctx);
3610 #ifdef CONFIG_COMPAT
3611 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
3614 switch (_IOC_NR(cmd)) {
3615 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
3616 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
3617 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
3618 cmd &= ~IOCSIZE_MASK;
3619 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
3623 return perf_ioctl(file, cmd, arg);
3626 # define perf_compat_ioctl NULL
3629 int perf_event_task_enable(void)
3631 struct perf_event_context *ctx;
3632 struct perf_event *event;
3634 mutex_lock(¤t->perf_event_mutex);
3635 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
3636 ctx = perf_event_ctx_lock(event);
3637 perf_event_for_each_child(event, _perf_event_enable);
3638 perf_event_ctx_unlock(event, ctx);
3640 mutex_unlock(¤t->perf_event_mutex);
3645 int perf_event_task_disable(void)
3647 struct perf_event_context *ctx;
3648 struct perf_event *event;
3650 mutex_lock(¤t->perf_event_mutex);
3651 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
3652 ctx = perf_event_ctx_lock(event);
3653 perf_event_for_each_child(event, _perf_event_disable);
3654 perf_event_ctx_unlock(event, ctx);
3656 mutex_unlock(¤t->perf_event_mutex);
3661 #ifndef PERF_EVENT_INDEX_OFFSET
3662 # define PERF_EVENT_INDEX_OFFSET 0
3665 static int perf_event_index(struct perf_event *event)
3667 if (event->hw.state & PERF_HES_STOPPED)
3670 if (event->state != PERF_EVENT_STATE_ACTIVE)
3673 return event->hw.idx + 1 - PERF_EVENT_INDEX_OFFSET;
3676 static void calc_timer_values(struct perf_event *event,
3683 ctx_time = event->shadow_ctx_time + now;
3684 *enabled = ctx_time - event->tstamp_enabled;
3685 *running = ctx_time - event->tstamp_running;
3689 * Callers need to ensure there can be no nesting of this function, otherwise
3690 * the seqlock logic goes bad. We can not serialize this because the arch
3691 * code calls this from NMI context.
3693 void perf_event_update_userpage(struct perf_event *event)
3695 struct perf_event_mmap_page *userpg;
3696 struct ring_buffer *rb;
3697 u64 enabled, running;
3701 * compute total_time_enabled, total_time_running
3702 * based on snapshot values taken when the event
3703 * was last scheduled in.
3705 * we cannot simply called update_context_time()
3706 * because of locking issue as we can be called in
3709 calc_timer_values(event, &enabled, &running);
3710 rb = rcu_dereference(event->rb);
3714 userpg = rb->user_page;
3717 * Disable preemption so as to not let the corresponding user-space
3718 * spin too long if we get preempted.
3723 userpg->index = perf_event_index(event);
3724 userpg->offset = perf_event_count(event);
3725 if (event->state == PERF_EVENT_STATE_ACTIVE)
3726 userpg->offset -= local64_read(&event->hw.prev_count);
3728 userpg->time_enabled = enabled +
3729 atomic64_read(&event->child_total_time_enabled);
3731 userpg->time_running = running +
3732 atomic64_read(&event->child_total_time_running);
3741 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
3743 struct perf_event *event = vma->vm_file->private_data;
3744 struct ring_buffer *rb;
3745 int ret = VM_FAULT_SIGBUS;
3747 if (vmf->flags & FAULT_FLAG_MKWRITE) {
3748 if (vmf->pgoff == 0)
3754 rb = rcu_dereference(event->rb);
3758 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
3761 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
3765 get_page(vmf->page);
3766 vmf->page->mapping = vma->vm_file->f_mapping;
3767 vmf->page->index = vmf->pgoff;
3776 static void ring_buffer_attach(struct perf_event *event,
3777 struct ring_buffer *rb)
3779 unsigned long flags;
3781 if (!list_empty(&event->rb_entry))
3784 spin_lock_irqsave(&rb->event_lock, flags);
3785 if (list_empty(&event->rb_entry))
3786 list_add(&event->rb_entry, &rb->event_list);
3787 spin_unlock_irqrestore(&rb->event_lock, flags);
3790 static void ring_buffer_detach(struct perf_event *event, struct ring_buffer *rb)
3792 unsigned long flags;
3794 if (list_empty(&event->rb_entry))
3797 spin_lock_irqsave(&rb->event_lock, flags);
3798 list_del_init(&event->rb_entry);
3799 wake_up_all(&event->waitq);
3800 spin_unlock_irqrestore(&rb->event_lock, flags);
3803 static void ring_buffer_wakeup(struct perf_event *event)
3805 struct ring_buffer *rb;
3808 rb = rcu_dereference(event->rb);
3810 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
3811 wake_up_all(&event->waitq);
3816 static void rb_free_rcu(struct rcu_head *rcu_head)
3818 struct ring_buffer *rb;
3820 rb = container_of(rcu_head, struct ring_buffer, rcu_head);
3824 static struct ring_buffer *ring_buffer_get(struct perf_event *event)
3826 struct ring_buffer *rb;
3829 rb = rcu_dereference(event->rb);
3831 if (!atomic_inc_not_zero(&rb->refcount))
3839 static void ring_buffer_put(struct ring_buffer *rb)
3841 if (!atomic_dec_and_test(&rb->refcount))
3844 WARN_ON_ONCE(!list_empty(&rb->event_list));
3846 call_rcu(&rb->rcu_head, rb_free_rcu);
3849 static void perf_mmap_open(struct vm_area_struct *vma)
3851 struct perf_event *event = vma->vm_file->private_data;
3853 atomic_inc(&event->mmap_count);
3854 atomic_inc(&event->rb->mmap_count);
3858 * A buffer can be mmap()ed multiple times; either directly through the same
3859 * event, or through other events by use of perf_event_set_output().
3861 * In order to undo the VM accounting done by perf_mmap() we need to destroy
3862 * the buffer here, where we still have a VM context. This means we need
3863 * to detach all events redirecting to us.
3865 static void perf_mmap_close(struct vm_area_struct *vma)
3867 struct perf_event *event = vma->vm_file->private_data;
3869 struct ring_buffer *rb = event->rb;
3870 struct user_struct *mmap_user = rb->mmap_user;
3871 int mmap_locked = rb->mmap_locked;
3872 unsigned long size = perf_data_size(rb);
3874 atomic_dec(&rb->mmap_count);
3876 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
3879 /* Detach current event from the buffer. */
3880 rcu_assign_pointer(event->rb, NULL);
3881 ring_buffer_detach(event, rb);
3882 mutex_unlock(&event->mmap_mutex);
3884 /* If there's still other mmap()s of this buffer, we're done. */
3885 if (atomic_read(&rb->mmap_count)) {
3886 ring_buffer_put(rb); /* can't be last */
3891 * No other mmap()s, detach from all other events that might redirect
3892 * into the now unreachable buffer. Somewhat complicated by the
3893 * fact that rb::event_lock otherwise nests inside mmap_mutex.
3897 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
3898 if (!atomic_long_inc_not_zero(&event->refcount)) {
3900 * This event is en-route to free_event() which will
3901 * detach it and remove it from the list.
3907 mutex_lock(&event->mmap_mutex);
3909 * Check we didn't race with perf_event_set_output() which can
3910 * swizzle the rb from under us while we were waiting to
3911 * acquire mmap_mutex.
3913 * If we find a different rb; ignore this event, a next
3914 * iteration will no longer find it on the list. We have to
3915 * still restart the iteration to make sure we're not now
3916 * iterating the wrong list.
3918 if (event->rb == rb) {
3919 rcu_assign_pointer(event->rb, NULL);
3920 ring_buffer_detach(event, rb);
3921 ring_buffer_put(rb); /* can't be last, we still have one */
3923 mutex_unlock(&event->mmap_mutex);
3927 * Restart the iteration; either we're on the wrong list or
3928 * destroyed its integrity by doing a deletion.
3935 * It could be there's still a few 0-ref events on the list; they'll
3936 * get cleaned up by free_event() -- they'll also still have their
3937 * ref on the rb and will free it whenever they are done with it.
3939 * Aside from that, this buffer is 'fully' detached and unmapped,
3940 * undo the VM accounting.
3943 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
3944 vma->vm_mm->pinned_vm -= mmap_locked;
3945 free_uid(mmap_user);
3947 ring_buffer_put(rb); /* could be last */
3950 static const struct vm_operations_struct perf_mmap_vmops = {
3951 .open = perf_mmap_open,
3952 .close = perf_mmap_close,
3953 .fault = perf_mmap_fault,
3954 .page_mkwrite = perf_mmap_fault,
3957 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
3959 struct perf_event *event = file->private_data;
3960 unsigned long user_locked, user_lock_limit;
3961 struct user_struct *user = current_user();
3962 unsigned long locked, lock_limit;
3963 struct ring_buffer *rb;
3964 unsigned long vma_size;
3965 unsigned long nr_pages;
3966 long user_extra, extra;
3967 int ret = 0, flags = 0;
3970 * Don't allow mmap() of inherited per-task counters. This would
3971 * create a performance issue due to all children writing to the
3974 if (event->cpu == -1 && event->attr.inherit)
3977 if (!(vma->vm_flags & VM_SHARED))
3980 vma_size = vma->vm_end - vma->vm_start;
3981 nr_pages = (vma_size / PAGE_SIZE) - 1;
3984 * If we have rb pages ensure they're a power-of-two number, so we
3985 * can do bitmasks instead of modulo.
3987 if (nr_pages != 0 && !is_power_of_2(nr_pages))
3990 if (vma_size != PAGE_SIZE * (1 + nr_pages))
3993 if (vma->vm_pgoff != 0)
3996 WARN_ON_ONCE(event->ctx->parent_ctx);
3998 mutex_lock(&event->mmap_mutex);
4000 if (event->rb->nr_pages != nr_pages) {
4005 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4007 * Raced against perf_mmap_close() through
4008 * perf_event_set_output(). Try again, hope for better
4011 mutex_unlock(&event->mmap_mutex);
4018 user_extra = nr_pages + 1;
4019 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
4022 * Increase the limit linearly with more CPUs:
4024 user_lock_limit *= num_online_cpus();
4026 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
4029 if (user_locked > user_lock_limit)
4030 extra = user_locked - user_lock_limit;
4032 lock_limit = rlimit(RLIMIT_MEMLOCK);
4033 lock_limit >>= PAGE_SHIFT;
4034 locked = vma->vm_mm->pinned_vm + extra;
4036 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
4037 !capable(CAP_IPC_LOCK)) {
4044 if (vma->vm_flags & VM_WRITE)
4045 flags |= RING_BUFFER_WRITABLE;
4047 rb = rb_alloc(nr_pages,
4048 event->attr.watermark ? event->attr.wakeup_watermark : 0,
4056 atomic_set(&rb->mmap_count, 1);
4057 rb->mmap_locked = extra;
4058 rb->mmap_user = get_current_user();
4060 atomic_long_add(user_extra, &user->locked_vm);
4061 vma->vm_mm->pinned_vm += extra;
4063 ring_buffer_attach(event, rb);
4064 rcu_assign_pointer(event->rb, rb);
4068 atomic_inc(&event->mmap_count);
4069 mutex_unlock(&event->mmap_mutex);
4072 * Since pinned accounting is per vm we cannot allow fork() to copy our
4075 vma->vm_flags |= VM_DONTCOPY | VM_RESERVED;
4076 vma->vm_ops = &perf_mmap_vmops;
4081 static int perf_fasync(int fd, struct file *filp, int on)
4083 struct inode *inode = filp->f_path.dentry->d_inode;
4084 struct perf_event *event = filp->private_data;
4087 mutex_lock(&inode->i_mutex);
4088 retval = fasync_helper(fd, filp, on, &event->fasync);
4089 mutex_unlock(&inode->i_mutex);
4097 static const struct file_operations perf_fops = {
4098 .llseek = no_llseek,
4099 .release = perf_release,
4102 .unlocked_ioctl = perf_ioctl,
4103 .compat_ioctl = perf_compat_ioctl,
4105 .fasync = perf_fasync,
4111 * If there's data, ensure we set the poll() state and publish everything
4112 * to user-space before waking everybody up.
4115 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
4117 /* only the parent has fasync state */
4119 event = event->parent;
4120 return &event->fasync;
4123 void perf_event_wakeup(struct perf_event *event)
4125 ring_buffer_wakeup(event);
4127 if (event->pending_kill) {
4128 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
4129 event->pending_kill = 0;
4133 static void perf_pending_event(struct irq_work *entry)
4135 struct perf_event *event = container_of(entry,
4136 struct perf_event, pending);
4139 rctx = perf_swevent_get_recursion_context();
4141 * If we 'fail' here, that's OK, it means recursion is already disabled
4142 * and we won't recurse 'further'.
4145 if (event->pending_disable) {
4146 event->pending_disable = 0;
4147 __perf_event_disable(event);
4150 if (event->pending_wakeup) {
4151 event->pending_wakeup = 0;
4152 perf_event_wakeup(event);
4156 perf_swevent_put_recursion_context(rctx);
4160 * We assume there is only KVM supporting the callbacks.
4161 * Later on, we might change it to a list if there is
4162 * another virtualization implementation supporting the callbacks.
4164 struct perf_guest_info_callbacks *perf_guest_cbs;
4166 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4168 perf_guest_cbs = cbs;
4171 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
4173 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4175 perf_guest_cbs = NULL;
4178 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
4180 static void __perf_event_header__init_id(struct perf_event_header *header,
4181 struct perf_sample_data *data,
4182 struct perf_event *event)
4184 u64 sample_type = event->attr.sample_type;
4186 data->type = sample_type;
4187 header->size += event->id_header_size;
4189 if (sample_type & PERF_SAMPLE_TID) {
4190 /* namespace issues */
4191 data->tid_entry.pid = perf_event_pid(event, current);
4192 data->tid_entry.tid = perf_event_tid(event, current);
4195 if (sample_type & PERF_SAMPLE_TIME)
4196 data->time = perf_clock();
4198 if (sample_type & PERF_SAMPLE_ID)
4199 data->id = primary_event_id(event);
4201 if (sample_type & PERF_SAMPLE_STREAM_ID)
4202 data->stream_id = event->id;
4204 if (sample_type & PERF_SAMPLE_CPU) {
4205 data->cpu_entry.cpu = raw_smp_processor_id();
4206 data->cpu_entry.reserved = 0;
4210 void perf_event_header__init_id(struct perf_event_header *header,
4211 struct perf_sample_data *data,
4212 struct perf_event *event)
4214 if (event->attr.sample_id_all)
4215 __perf_event_header__init_id(header, data, event);
4218 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
4219 struct perf_sample_data *data)
4221 u64 sample_type = data->type;
4223 if (sample_type & PERF_SAMPLE_TID)
4224 perf_output_put(handle, data->tid_entry);
4226 if (sample_type & PERF_SAMPLE_TIME)
4227 perf_output_put(handle, data->time);
4229 if (sample_type & PERF_SAMPLE_ID)
4230 perf_output_put(handle, data->id);
4232 if (sample_type & PERF_SAMPLE_STREAM_ID)
4233 perf_output_put(handle, data->stream_id);
4235 if (sample_type & PERF_SAMPLE_CPU)
4236 perf_output_put(handle, data->cpu_entry);
4239 void perf_event__output_id_sample(struct perf_event *event,
4240 struct perf_output_handle *handle,
4241 struct perf_sample_data *sample)
4243 if (event->attr.sample_id_all)
4244 __perf_event__output_id_sample(handle, sample);
4247 static void perf_output_read_one(struct perf_output_handle *handle,
4248 struct perf_event *event,
4249 u64 enabled, u64 running)
4251 u64 read_format = event->attr.read_format;
4255 values[n++] = perf_event_count(event);
4256 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4257 values[n++] = enabled +
4258 atomic64_read(&event->child_total_time_enabled);
4260 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4261 values[n++] = running +
4262 atomic64_read(&event->child_total_time_running);
4264 if (read_format & PERF_FORMAT_ID)
4265 values[n++] = primary_event_id(event);
4267 __output_copy(handle, values, n * sizeof(u64));
4270 static void perf_output_read_group(struct perf_output_handle *handle,
4271 struct perf_event *event,
4272 u64 enabled, u64 running)
4274 struct perf_event *leader = event->group_leader, *sub;
4275 u64 read_format = event->attr.read_format;
4279 values[n++] = 1 + leader->nr_siblings;
4281 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4282 values[n++] = enabled;
4284 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4285 values[n++] = running;
4287 if (leader != event)
4288 leader->pmu->read(leader);
4290 values[n++] = perf_event_count(leader);
4291 if (read_format & PERF_FORMAT_ID)
4292 values[n++] = primary_event_id(leader);
4294 __output_copy(handle, values, n * sizeof(u64));
4296 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4300 sub->pmu->read(sub);
4302 values[n++] = perf_event_count(sub);
4303 if (read_format & PERF_FORMAT_ID)
4304 values[n++] = primary_event_id(sub);
4306 __output_copy(handle, values, n * sizeof(u64));
4310 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
4311 PERF_FORMAT_TOTAL_TIME_RUNNING)
4314 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
4316 * The problem is that its both hard and excessively expensive to iterate the
4317 * child list, not to mention that its impossible to IPI the children running
4318 * on another CPU, from interrupt/NMI context.
4320 static void perf_output_read(struct perf_output_handle *handle,
4321 struct perf_event *event)
4323 u64 enabled = 0, running = 0;
4324 u64 read_format = event->attr.read_format;
4327 * compute total_time_enabled, total_time_running
4328 * based on snapshot values taken when the event
4329 * was last scheduled in.
4331 * we cannot simply called update_context_time()
4332 * because of locking issue as we are called in
4335 if (read_format & PERF_FORMAT_TOTAL_TIMES)
4336 calc_timer_values(event, &enabled, &running);
4338 if (event->attr.read_format & PERF_FORMAT_GROUP)
4339 perf_output_read_group(handle, event, enabled, running);
4341 perf_output_read_one(handle, event, enabled, running);
4344 void perf_output_sample(struct perf_output_handle *handle,
4345 struct perf_event_header *header,
4346 struct perf_sample_data *data,
4347 struct perf_event *event)
4349 u64 sample_type = data->type;
4351 perf_output_put(handle, *header);
4353 if (sample_type & PERF_SAMPLE_IP)
4354 perf_output_put(handle, data->ip);
4356 if (sample_type & PERF_SAMPLE_TID)
4357 perf_output_put(handle, data->tid_entry);
4359 if (sample_type & PERF_SAMPLE_TIME)
4360 perf_output_put(handle, data->time);
4362 if (sample_type & PERF_SAMPLE_ADDR)
4363 perf_output_put(handle, data->addr);
4365 if (sample_type & PERF_SAMPLE_ID)
4366 perf_output_put(handle, data->id);
4368 if (sample_type & PERF_SAMPLE_STREAM_ID)
4369 perf_output_put(handle, data->stream_id);
4371 if (sample_type & PERF_SAMPLE_CPU)
4372 perf_output_put(handle, data->cpu_entry);
4374 if (sample_type & PERF_SAMPLE_PERIOD)
4375 perf_output_put(handle, data->period);
4377 if (sample_type & PERF_SAMPLE_READ)
4378 perf_output_read(handle, event);
4380 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4381 if (data->callchain) {
4384 if (data->callchain)
4385 size += data->callchain->nr;
4387 size *= sizeof(u64);
4389 __output_copy(handle, data->callchain, size);
4392 perf_output_put(handle, nr);
4396 if (sample_type & PERF_SAMPLE_RAW) {
4398 perf_output_put(handle, data->raw->size);
4399 __output_copy(handle, data->raw->data,
4406 .size = sizeof(u32),
4409 perf_output_put(handle, raw);
4413 if (!event->attr.watermark) {
4414 int wakeup_events = event->attr.wakeup_events;
4416 if (wakeup_events) {
4417 struct ring_buffer *rb = handle->rb;
4418 int events = local_inc_return(&rb->events);
4420 if (events >= wakeup_events) {
4421 local_sub(wakeup_events, &rb->events);
4422 local_inc(&rb->wakeup);
4428 void perf_prepare_sample(struct perf_event_header *header,
4429 struct perf_sample_data *data,
4430 struct perf_event *event,
4431 struct pt_regs *regs)
4433 u64 sample_type = event->attr.sample_type;
4435 header->type = PERF_RECORD_SAMPLE;
4436 header->size = sizeof(*header) + event->header_size;
4439 header->misc |= perf_misc_flags(regs);
4441 __perf_event_header__init_id(header, data, event);
4443 if (sample_type & PERF_SAMPLE_IP)
4444 data->ip = perf_instruction_pointer(regs);
4446 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4449 data->callchain = perf_callchain(regs);
4451 if (data->callchain)
4452 size += data->callchain->nr;
4454 header->size += size * sizeof(u64);
4457 if (sample_type & PERF_SAMPLE_RAW) {
4458 int size = sizeof(u32);
4461 size += data->raw->size;
4463 size += sizeof(u32);
4465 WARN_ON_ONCE(size & (sizeof(u64)-1));
4466 header->size += size;
4470 static void perf_event_output(struct perf_event *event,
4471 struct perf_sample_data *data,
4472 struct pt_regs *regs)
4474 struct perf_output_handle handle;
4475 struct perf_event_header header;
4477 /* protect the callchain buffers */
4480 perf_prepare_sample(&header, data, event, regs);
4482 if (perf_output_begin(&handle, event, header.size))
4485 perf_output_sample(&handle, &header, data, event);
4487 perf_output_end(&handle);
4497 struct perf_read_event {
4498 struct perf_event_header header;
4505 perf_event_read_event(struct perf_event *event,
4506 struct task_struct *task)
4508 struct perf_output_handle handle;
4509 struct perf_sample_data sample;
4510 struct perf_read_event read_event = {
4512 .type = PERF_RECORD_READ,
4514 .size = sizeof(read_event) + event->read_size,
4516 .pid = perf_event_pid(event, task),
4517 .tid = perf_event_tid(event, task),
4521 perf_event_header__init_id(&read_event.header, &sample, event);
4522 ret = perf_output_begin(&handle, event, read_event.header.size);
4526 perf_output_put(&handle, read_event);
4527 perf_output_read(&handle, event);
4528 perf_event__output_id_sample(event, &handle, &sample);
4530 perf_output_end(&handle);
4534 * task tracking -- fork/exit
4536 * enabled by: attr.comm | attr.mmap | attr.mmap_data | attr.task
4539 struct perf_task_event {
4540 struct task_struct *task;
4541 struct perf_event_context *task_ctx;
4544 struct perf_event_header header;
4554 static void perf_event_task_output(struct perf_event *event,
4555 struct perf_task_event *task_event)
4557 struct perf_output_handle handle;
4558 struct perf_sample_data sample;
4559 struct task_struct *task = task_event->task;
4560 int ret, size = task_event->event_id.header.size;
4562 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
4564 ret = perf_output_begin(&handle, event,
4565 task_event->event_id.header.size);
4569 task_event->event_id.pid = perf_event_pid(event, task);
4570 task_event->event_id.ppid = perf_event_pid(event, current);
4572 task_event->event_id.tid = perf_event_tid(event, task);
4573 task_event->event_id.ptid = perf_event_tid(event, current);
4575 perf_output_put(&handle, task_event->event_id);
4577 perf_event__output_id_sample(event, &handle, &sample);
4579 perf_output_end(&handle);
4581 task_event->event_id.header.size = size;
4584 static int perf_event_task_match(struct perf_event *event)
4586 if (event->state < PERF_EVENT_STATE_INACTIVE)
4589 if (!event_filter_match(event))
4592 if (event->attr.comm || event->attr.mmap ||
4593 event->attr.mmap_data || event->attr.task)
4599 static void perf_event_task_ctx(struct perf_event_context *ctx,
4600 struct perf_task_event *task_event)
4602 struct perf_event *event;
4604 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4605 if (perf_event_task_match(event))
4606 perf_event_task_output(event, task_event);
4610 static void perf_event_task_event(struct perf_task_event *task_event)
4612 struct perf_cpu_context *cpuctx;
4613 struct perf_event_context *ctx;
4618 list_for_each_entry_rcu(pmu, &pmus, entry) {
4619 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4620 if (cpuctx->unique_pmu != pmu)
4622 perf_event_task_ctx(&cpuctx->ctx, task_event);
4624 ctx = task_event->task_ctx;
4626 ctxn = pmu->task_ctx_nr;
4629 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4632 perf_event_task_ctx(ctx, task_event);
4634 put_cpu_ptr(pmu->pmu_cpu_context);
4639 static void perf_event_task(struct task_struct *task,
4640 struct perf_event_context *task_ctx,
4643 struct perf_task_event task_event;
4645 if (!atomic_read(&nr_comm_events) &&
4646 !atomic_read(&nr_mmap_events) &&
4647 !atomic_read(&nr_task_events))
4650 task_event = (struct perf_task_event){
4652 .task_ctx = task_ctx,
4655 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
4657 .size = sizeof(task_event.event_id),
4663 .time = perf_clock(),
4667 perf_event_task_event(&task_event);
4670 void perf_event_fork(struct task_struct *task)
4672 perf_event_task(task, NULL, 1);
4679 struct perf_comm_event {
4680 struct task_struct *task;
4685 struct perf_event_header header;
4692 static void perf_event_comm_output(struct perf_event *event,
4693 struct perf_comm_event *comm_event)
4695 struct perf_output_handle handle;
4696 struct perf_sample_data sample;
4697 int size = comm_event->event_id.header.size;
4700 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
4701 ret = perf_output_begin(&handle, event,
4702 comm_event->event_id.header.size);
4707 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
4708 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
4710 perf_output_put(&handle, comm_event->event_id);
4711 __output_copy(&handle, comm_event->comm,
4712 comm_event->comm_size);
4714 perf_event__output_id_sample(event, &handle, &sample);
4716 perf_output_end(&handle);
4718 comm_event->event_id.header.size = size;
4721 static int perf_event_comm_match(struct perf_event *event)
4723 if (event->state < PERF_EVENT_STATE_INACTIVE)
4726 if (!event_filter_match(event))
4729 if (event->attr.comm)
4735 static void perf_event_comm_ctx(struct perf_event_context *ctx,
4736 struct perf_comm_event *comm_event)
4738 struct perf_event *event;
4740 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4741 if (perf_event_comm_match(event))
4742 perf_event_comm_output(event, comm_event);
4746 static void perf_event_comm_event(struct perf_comm_event *comm_event)
4748 struct perf_cpu_context *cpuctx;
4749 struct perf_event_context *ctx;
4750 char comm[TASK_COMM_LEN];
4755 memset(comm, 0, sizeof(comm));
4756 strlcpy(comm, comm_event->task->comm, sizeof(comm));
4757 size = ALIGN(strlen(comm)+1, sizeof(u64));
4759 comm_event->comm = comm;
4760 comm_event->comm_size = size;
4762 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
4764 list_for_each_entry_rcu(pmu, &pmus, entry) {
4765 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4766 if (cpuctx->unique_pmu != pmu)
4768 perf_event_comm_ctx(&cpuctx->ctx, comm_event);
4770 ctxn = pmu->task_ctx_nr;
4774 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4776 perf_event_comm_ctx(ctx, comm_event);
4778 put_cpu_ptr(pmu->pmu_cpu_context);
4783 void perf_event_comm(struct task_struct *task)
4785 struct perf_comm_event comm_event;
4786 struct perf_event_context *ctx;
4789 for_each_task_context_nr(ctxn) {
4790 ctx = task->perf_event_ctxp[ctxn];
4794 perf_event_enable_on_exec(ctx);
4797 if (!atomic_read(&nr_comm_events))
4800 comm_event = (struct perf_comm_event){
4806 .type = PERF_RECORD_COMM,
4815 perf_event_comm_event(&comm_event);
4822 struct perf_mmap_event {
4823 struct vm_area_struct *vma;
4825 const char *file_name;
4829 struct perf_event_header header;
4839 static void perf_event_mmap_output(struct perf_event *event,
4840 struct perf_mmap_event *mmap_event)
4842 struct perf_output_handle handle;
4843 struct perf_sample_data sample;
4844 int size = mmap_event->event_id.header.size;
4847 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
4848 ret = perf_output_begin(&handle, event,
4849 mmap_event->event_id.header.size);
4853 mmap_event->event_id.pid = perf_event_pid(event, current);
4854 mmap_event->event_id.tid = perf_event_tid(event, current);
4856 perf_output_put(&handle, mmap_event->event_id);
4857 __output_copy(&handle, mmap_event->file_name,
4858 mmap_event->file_size);
4860 perf_event__output_id_sample(event, &handle, &sample);
4862 perf_output_end(&handle);
4864 mmap_event->event_id.header.size = size;
4867 static int perf_event_mmap_match(struct perf_event *event,
4868 struct perf_mmap_event *mmap_event,
4871 if (event->state < PERF_EVENT_STATE_INACTIVE)
4874 if (!event_filter_match(event))
4877 if ((!executable && event->attr.mmap_data) ||
4878 (executable && event->attr.mmap))
4884 static void perf_event_mmap_ctx(struct perf_event_context *ctx,
4885 struct perf_mmap_event *mmap_event,
4888 struct perf_event *event;
4890 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4891 if (perf_event_mmap_match(event, mmap_event, executable))
4892 perf_event_mmap_output(event, mmap_event);
4896 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
4898 struct perf_cpu_context *cpuctx;
4899 struct perf_event_context *ctx;
4900 struct vm_area_struct *vma = mmap_event->vma;
4901 struct file *file = vma->vm_file;
4909 memset(tmp, 0, sizeof(tmp));
4913 * d_path works from the end of the rb backwards, so we
4914 * need to add enough zero bytes after the string to handle
4915 * the 64bit alignment we do later.
4917 buf = kzalloc(PATH_MAX + sizeof(u64), GFP_KERNEL);
4919 name = strncpy(tmp, "//enomem", sizeof(tmp));
4922 name = d_path(&file->f_path, buf, PATH_MAX);
4924 name = strncpy(tmp, "//toolong", sizeof(tmp));
4928 if (arch_vma_name(mmap_event->vma)) {
4929 name = strncpy(tmp, arch_vma_name(mmap_event->vma),
4935 name = strncpy(tmp, "[vdso]", sizeof(tmp));
4937 } else if (vma->vm_start <= vma->vm_mm->start_brk &&
4938 vma->vm_end >= vma->vm_mm->brk) {
4939 name = strncpy(tmp, "[heap]", sizeof(tmp));
4941 } else if (vma->vm_start <= vma->vm_mm->start_stack &&
4942 vma->vm_end >= vma->vm_mm->start_stack) {
4943 name = strncpy(tmp, "[stack]", sizeof(tmp));
4947 name = strncpy(tmp, "//anon", sizeof(tmp));
4952 size = ALIGN(strlen(name)+1, sizeof(u64));
4954 mmap_event->file_name = name;
4955 mmap_event->file_size = size;
4957 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
4960 list_for_each_entry_rcu(pmu, &pmus, entry) {
4961 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4962 if (cpuctx->unique_pmu != pmu)
4964 perf_event_mmap_ctx(&cpuctx->ctx, mmap_event,
4965 vma->vm_flags & VM_EXEC);
4967 ctxn = pmu->task_ctx_nr;
4971 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4973 perf_event_mmap_ctx(ctx, mmap_event,
4974 vma->vm_flags & VM_EXEC);
4977 put_cpu_ptr(pmu->pmu_cpu_context);
4984 void perf_event_mmap(struct vm_area_struct *vma)
4986 struct perf_mmap_event mmap_event;
4988 if (!atomic_read(&nr_mmap_events))
4991 mmap_event = (struct perf_mmap_event){
4997 .type = PERF_RECORD_MMAP,
4998 .misc = PERF_RECORD_MISC_USER,
5003 .start = vma->vm_start,
5004 .len = vma->vm_end - vma->vm_start,
5005 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
5009 perf_event_mmap_event(&mmap_event);
5013 * IRQ throttle logging
5016 static void perf_log_throttle(struct perf_event *event, int enable)
5018 struct perf_output_handle handle;
5019 struct perf_sample_data sample;
5023 struct perf_event_header header;
5027 } throttle_event = {
5029 .type = PERF_RECORD_THROTTLE,
5031 .size = sizeof(throttle_event),
5033 .time = perf_clock(),
5034 .id = primary_event_id(event),
5035 .stream_id = event->id,
5039 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
5041 perf_event_header__init_id(&throttle_event.header, &sample, event);
5043 ret = perf_output_begin(&handle, event,
5044 throttle_event.header.size);
5048 perf_output_put(&handle, throttle_event);
5049 perf_event__output_id_sample(event, &handle, &sample);
5050 perf_output_end(&handle);
5054 * Generic event overflow handling, sampling.
5057 static int __perf_event_overflow(struct perf_event *event,
5058 int throttle, struct perf_sample_data *data,
5059 struct pt_regs *regs)
5061 int events = atomic_read(&event->event_limit);
5062 struct hw_perf_event *hwc = &event->hw;
5066 * Non-sampling counters might still use the PMI to fold short
5067 * hardware counters, ignore those.
5069 if (unlikely(!is_sampling_event(event)))
5072 if (unlikely(hwc->interrupts >= max_samples_per_tick)) {
5074 hwc->interrupts = MAX_INTERRUPTS;
5075 perf_log_throttle(event, 0);
5081 if (event->attr.freq) {
5082 u64 now = perf_clock();
5083 s64 delta = now - hwc->freq_time_stamp;
5085 hwc->freq_time_stamp = now;
5087 if (delta > 0 && delta < 2*TICK_NSEC)
5088 perf_adjust_period(event, delta, hwc->last_period);
5092 * XXX event_limit might not quite work as expected on inherited
5096 event->pending_kill = POLL_IN;
5097 if (events && atomic_dec_and_test(&event->event_limit)) {
5099 event->pending_kill = POLL_HUP;
5100 event->pending_disable = 1;
5101 irq_work_queue(&event->pending);
5104 if (event->overflow_handler)
5105 event->overflow_handler(event, data, regs);
5107 perf_event_output(event, data, regs);
5109 if (*perf_event_fasync(event) && event->pending_kill) {
5110 event->pending_wakeup = 1;
5111 irq_work_queue(&event->pending);
5117 int perf_event_overflow(struct perf_event *event,
5118 struct perf_sample_data *data,
5119 struct pt_regs *regs)
5121 return __perf_event_overflow(event, 1, data, regs);
5125 * Generic software event infrastructure
5128 struct swevent_htable {
5129 struct swevent_hlist *swevent_hlist;
5130 struct mutex hlist_mutex;
5133 /* Recursion avoidance in each contexts */
5134 int recursion[PERF_NR_CONTEXTS];
5137 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
5140 * We directly increment event->count and keep a second value in
5141 * event->hw.period_left to count intervals. This period event
5142 * is kept in the range [-sample_period, 0] so that we can use the
5146 static u64 perf_swevent_set_period(struct perf_event *event)
5148 struct hw_perf_event *hwc = &event->hw;
5149 u64 period = hwc->last_period;
5153 hwc->last_period = hwc->sample_period;
5156 old = val = local64_read(&hwc->period_left);
5160 nr = div64_u64(period + val, period);
5161 offset = nr * period;
5163 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
5169 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
5170 struct perf_sample_data *data,
5171 struct pt_regs *regs)
5173 struct hw_perf_event *hwc = &event->hw;
5176 data->period = event->hw.last_period;
5178 overflow = perf_swevent_set_period(event);
5180 if (hwc->interrupts == MAX_INTERRUPTS)
5183 for (; overflow; overflow--) {
5184 if (__perf_event_overflow(event, throttle,
5187 * We inhibit the overflow from happening when
5188 * hwc->interrupts == MAX_INTERRUPTS.
5196 static void perf_swevent_event(struct perf_event *event, u64 nr,
5197 struct perf_sample_data *data,
5198 struct pt_regs *regs)
5200 struct hw_perf_event *hwc = &event->hw;
5202 local64_add(nr, &event->count);
5207 if (!is_sampling_event(event))
5210 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
5211 return perf_swevent_overflow(event, 1, data, regs);
5213 if (local64_add_negative(nr, &hwc->period_left))
5216 perf_swevent_overflow(event, 0, data, regs);
5219 static int perf_exclude_event(struct perf_event *event,
5220 struct pt_regs *regs)
5222 if (event->hw.state & PERF_HES_STOPPED)
5226 if (event->attr.exclude_user && user_mode(regs))
5229 if (event->attr.exclude_kernel && !user_mode(regs))
5236 static int perf_swevent_match(struct perf_event *event,
5237 enum perf_type_id type,
5239 struct perf_sample_data *data,
5240 struct pt_regs *regs)
5242 if (event->attr.type != type)
5245 if (event->attr.config != event_id)
5248 if (perf_exclude_event(event, regs))
5254 static inline u64 swevent_hash(u64 type, u32 event_id)
5256 u64 val = event_id | (type << 32);
5258 return hash_64(val, SWEVENT_HLIST_BITS);
5261 static inline struct hlist_head *
5262 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
5264 u64 hash = swevent_hash(type, event_id);
5266 return &hlist->heads[hash];
5269 /* For the read side: events when they trigger */
5270 static inline struct hlist_head *
5271 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
5273 struct swevent_hlist *hlist;
5275 hlist = rcu_dereference(swhash->swevent_hlist);
5279 return __find_swevent_head(hlist, type, event_id);
5282 /* For the event head insertion and removal in the hlist */
5283 static inline struct hlist_head *
5284 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
5286 struct swevent_hlist *hlist;
5287 u32 event_id = event->attr.config;
5288 u64 type = event->attr.type;
5291 * Event scheduling is always serialized against hlist allocation
5292 * and release. Which makes the protected version suitable here.
5293 * The context lock guarantees that.
5295 hlist = rcu_dereference_protected(swhash->swevent_hlist,
5296 lockdep_is_held(&event->ctx->lock));
5300 return __find_swevent_head(hlist, type, event_id);
5303 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
5305 struct perf_sample_data *data,
5306 struct pt_regs *regs)
5308 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5309 struct perf_event *event;
5310 struct hlist_node *node;
5311 struct hlist_head *head;
5314 head = find_swevent_head_rcu(swhash, type, event_id);
5318 hlist_for_each_entry_rcu(event, node, head, hlist_entry) {
5319 if (perf_swevent_match(event, type, event_id, data, regs))
5320 perf_swevent_event(event, nr, data, regs);
5326 int perf_swevent_get_recursion_context(void)
5328 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5330 return get_recursion_context(swhash->recursion);
5332 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
5334 inline void perf_swevent_put_recursion_context(int rctx)
5336 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5338 put_recursion_context(swhash->recursion, rctx);
5341 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
5343 struct perf_sample_data data;
5346 preempt_disable_notrace();
5347 rctx = perf_swevent_get_recursion_context();
5351 perf_sample_data_init(&data, addr);
5353 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
5355 perf_swevent_put_recursion_context(rctx);
5356 preempt_enable_notrace();
5359 static void perf_swevent_read(struct perf_event *event)
5363 static int perf_swevent_add(struct perf_event *event, int flags)
5365 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5366 struct hw_perf_event *hwc = &event->hw;
5367 struct hlist_head *head;
5369 if (is_sampling_event(event)) {
5370 hwc->last_period = hwc->sample_period;
5371 perf_swevent_set_period(event);
5374 hwc->state = !(flags & PERF_EF_START);
5376 head = find_swevent_head(swhash, event);
5377 if (WARN_ON_ONCE(!head))
5380 hlist_add_head_rcu(&event->hlist_entry, head);
5385 static void perf_swevent_del(struct perf_event *event, int flags)
5387 hlist_del_rcu(&event->hlist_entry);
5390 static void perf_swevent_start(struct perf_event *event, int flags)
5392 event->hw.state = 0;
5395 static void perf_swevent_stop(struct perf_event *event, int flags)
5397 event->hw.state = PERF_HES_STOPPED;
5400 /* Deref the hlist from the update side */
5401 static inline struct swevent_hlist *
5402 swevent_hlist_deref(struct swevent_htable *swhash)
5404 return rcu_dereference_protected(swhash->swevent_hlist,
5405 lockdep_is_held(&swhash->hlist_mutex));
5408 static void swevent_hlist_release(struct swevent_htable *swhash)
5410 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
5415 rcu_assign_pointer(swhash->swevent_hlist, NULL);
5416 kfree_rcu(hlist, rcu_head);
5419 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
5421 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5423 mutex_lock(&swhash->hlist_mutex);
5425 if (!--swhash->hlist_refcount)
5426 swevent_hlist_release(swhash);
5428 mutex_unlock(&swhash->hlist_mutex);
5431 static void swevent_hlist_put(struct perf_event *event)
5435 if (event->cpu != -1) {
5436 swevent_hlist_put_cpu(event, event->cpu);
5440 for_each_possible_cpu(cpu)
5441 swevent_hlist_put_cpu(event, cpu);
5444 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
5446 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5449 mutex_lock(&swhash->hlist_mutex);
5450 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
5451 struct swevent_hlist *hlist;
5453 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
5458 rcu_assign_pointer(swhash->swevent_hlist, hlist);
5460 swhash->hlist_refcount++;
5462 mutex_unlock(&swhash->hlist_mutex);
5467 static int swevent_hlist_get(struct perf_event *event)
5470 int cpu, failed_cpu;
5472 if (event->cpu != -1)
5473 return swevent_hlist_get_cpu(event, event->cpu);
5476 for_each_possible_cpu(cpu) {
5477 err = swevent_hlist_get_cpu(event, cpu);
5487 for_each_possible_cpu(cpu) {
5488 if (cpu == failed_cpu)
5490 swevent_hlist_put_cpu(event, cpu);
5497 struct jump_label_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
5499 static void sw_perf_event_destroy(struct perf_event *event)
5501 u64 event_id = event->attr.config;
5503 WARN_ON(event->parent);
5505 jump_label_dec(&perf_swevent_enabled[event_id]);
5506 swevent_hlist_put(event);
5509 static int perf_swevent_init(struct perf_event *event)
5511 u64 event_id = event->attr.config;
5513 if (event->attr.type != PERF_TYPE_SOFTWARE)
5517 case PERF_COUNT_SW_CPU_CLOCK:
5518 case PERF_COUNT_SW_TASK_CLOCK:
5525 if (event_id >= PERF_COUNT_SW_MAX)
5528 if (!event->parent) {
5531 err = swevent_hlist_get(event);
5535 jump_label_inc(&perf_swevent_enabled[event_id]);
5536 event->destroy = sw_perf_event_destroy;
5542 static struct pmu perf_swevent = {
5543 .task_ctx_nr = perf_sw_context,
5545 .event_init = perf_swevent_init,
5546 .add = perf_swevent_add,
5547 .del = perf_swevent_del,
5548 .start = perf_swevent_start,
5549 .stop = perf_swevent_stop,
5550 .read = perf_swevent_read,
5553 #ifdef CONFIG_EVENT_TRACING
5555 static int perf_tp_filter_match(struct perf_event *event,
5556 struct perf_sample_data *data)
5558 void *record = data->raw->data;
5560 /* only top level events have filters set */
5562 event = event->parent;
5564 if (likely(!event->filter) || filter_match_preds(event->filter, record))
5569 static int perf_tp_event_match(struct perf_event *event,
5570 struct perf_sample_data *data,
5571 struct pt_regs *regs)
5573 if (event->hw.state & PERF_HES_STOPPED)
5576 * All tracepoints are from kernel-space.
5578 if (event->attr.exclude_kernel)
5581 if (!perf_tp_filter_match(event, data))
5587 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
5588 struct pt_regs *regs, struct hlist_head *head, int rctx)
5590 struct perf_sample_data data;
5591 struct perf_event *event;
5592 struct hlist_node *node;
5594 struct perf_raw_record raw = {
5599 perf_sample_data_init(&data, addr);
5602 hlist_for_each_entry_rcu(event, node, head, hlist_entry) {
5603 if (perf_tp_event_match(event, &data, regs))
5604 perf_swevent_event(event, count, &data, regs);
5607 perf_swevent_put_recursion_context(rctx);
5609 EXPORT_SYMBOL_GPL(perf_tp_event);
5611 static void tp_perf_event_destroy(struct perf_event *event)
5613 perf_trace_destroy(event);
5616 static int perf_tp_event_init(struct perf_event *event)
5620 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5623 err = perf_trace_init(event);
5627 event->destroy = tp_perf_event_destroy;
5632 static struct pmu perf_tracepoint = {
5633 .task_ctx_nr = perf_sw_context,
5635 .event_init = perf_tp_event_init,
5636 .add = perf_trace_add,
5637 .del = perf_trace_del,
5638 .start = perf_swevent_start,
5639 .stop = perf_swevent_stop,
5640 .read = perf_swevent_read,
5643 static inline void perf_tp_register(void)
5645 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
5648 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
5653 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5656 filter_str = strndup_user(arg, PAGE_SIZE);
5657 if (IS_ERR(filter_str))
5658 return PTR_ERR(filter_str);
5660 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
5666 static void perf_event_free_filter(struct perf_event *event)
5668 ftrace_profile_free_filter(event);
5673 static inline void perf_tp_register(void)
5677 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
5682 static void perf_event_free_filter(struct perf_event *event)
5686 #endif /* CONFIG_EVENT_TRACING */
5688 #ifdef CONFIG_HAVE_HW_BREAKPOINT
5689 void perf_bp_event(struct perf_event *bp, void *data)
5691 struct perf_sample_data sample;
5692 struct pt_regs *regs = data;
5694 perf_sample_data_init(&sample, bp->attr.bp_addr);
5696 if (!bp->hw.state && !perf_exclude_event(bp, regs))
5697 perf_swevent_event(bp, 1, &sample, regs);
5702 * hrtimer based swevent callback
5705 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
5707 enum hrtimer_restart ret = HRTIMER_RESTART;
5708 struct perf_sample_data data;
5709 struct pt_regs *regs;
5710 struct perf_event *event;
5713 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
5715 if (event->state != PERF_EVENT_STATE_ACTIVE)
5716 return HRTIMER_NORESTART;
5718 event->pmu->read(event);
5720 perf_sample_data_init(&data, 0);
5721 data.period = event->hw.last_period;
5722 regs = get_irq_regs();
5724 if (regs && !perf_exclude_event(event, regs)) {
5725 if (!(event->attr.exclude_idle && current->pid == 0))
5726 if (perf_event_overflow(event, &data, regs))
5727 ret = HRTIMER_NORESTART;
5730 period = max_t(u64, 10000, event->hw.sample_period);
5731 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
5736 static void perf_swevent_start_hrtimer(struct perf_event *event)
5738 struct hw_perf_event *hwc = &event->hw;
5741 if (!is_sampling_event(event))
5744 period = local64_read(&hwc->period_left);
5749 local64_set(&hwc->period_left, 0);
5751 period = max_t(u64, 10000, hwc->sample_period);
5753 __hrtimer_start_range_ns(&hwc->hrtimer,
5754 ns_to_ktime(period), 0,
5755 HRTIMER_MODE_REL_PINNED, 0);
5758 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
5760 struct hw_perf_event *hwc = &event->hw;
5762 if (is_sampling_event(event)) {
5763 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
5764 local64_set(&hwc->period_left, ktime_to_ns(remaining));
5766 hrtimer_cancel(&hwc->hrtimer);
5770 static void perf_swevent_init_hrtimer(struct perf_event *event)
5772 struct hw_perf_event *hwc = &event->hw;
5774 if (!is_sampling_event(event))
5777 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
5778 hwc->hrtimer.function = perf_swevent_hrtimer;
5781 * Since hrtimers have a fixed rate, we can do a static freq->period
5782 * mapping and avoid the whole period adjust feedback stuff.
5784 if (event->attr.freq) {
5785 long freq = event->attr.sample_freq;
5787 event->attr.sample_period = NSEC_PER_SEC / freq;
5788 hwc->sample_period = event->attr.sample_period;
5789 local64_set(&hwc->period_left, hwc->sample_period);
5790 event->attr.freq = 0;
5795 * Software event: cpu wall time clock
5798 static void cpu_clock_event_update(struct perf_event *event)
5803 now = local_clock();
5804 prev = local64_xchg(&event->hw.prev_count, now);
5805 local64_add(now - prev, &event->count);
5808 static void cpu_clock_event_start(struct perf_event *event, int flags)
5810 local64_set(&event->hw.prev_count, local_clock());
5811 perf_swevent_start_hrtimer(event);
5814 static void cpu_clock_event_stop(struct perf_event *event, int flags)
5816 perf_swevent_cancel_hrtimer(event);
5817 cpu_clock_event_update(event);
5820 static int cpu_clock_event_add(struct perf_event *event, int flags)
5822 if (flags & PERF_EF_START)
5823 cpu_clock_event_start(event, flags);
5828 static void cpu_clock_event_del(struct perf_event *event, int flags)
5830 cpu_clock_event_stop(event, flags);
5833 static void cpu_clock_event_read(struct perf_event *event)
5835 cpu_clock_event_update(event);
5838 static int cpu_clock_event_init(struct perf_event *event)
5840 if (event->attr.type != PERF_TYPE_SOFTWARE)
5843 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
5846 perf_swevent_init_hrtimer(event);
5851 static struct pmu perf_cpu_clock = {
5852 .task_ctx_nr = perf_sw_context,
5854 .event_init = cpu_clock_event_init,
5855 .add = cpu_clock_event_add,
5856 .del = cpu_clock_event_del,
5857 .start = cpu_clock_event_start,
5858 .stop = cpu_clock_event_stop,
5859 .read = cpu_clock_event_read,
5863 * Software event: task time clock
5866 static void task_clock_event_update(struct perf_event *event, u64 now)
5871 prev = local64_xchg(&event->hw.prev_count, now);
5873 local64_add(delta, &event->count);
5876 static void task_clock_event_start(struct perf_event *event, int flags)
5878 local64_set(&event->hw.prev_count, event->ctx->time);
5879 perf_swevent_start_hrtimer(event);
5882 static void task_clock_event_stop(struct perf_event *event, int flags)
5884 perf_swevent_cancel_hrtimer(event);
5885 task_clock_event_update(event, event->ctx->time);
5888 static int task_clock_event_add(struct perf_event *event, int flags)
5890 if (flags & PERF_EF_START)
5891 task_clock_event_start(event, flags);
5896 static void task_clock_event_del(struct perf_event *event, int flags)
5898 task_clock_event_stop(event, PERF_EF_UPDATE);
5901 static void task_clock_event_read(struct perf_event *event)
5903 u64 now = perf_clock();
5904 u64 delta = now - event->ctx->timestamp;
5905 u64 time = event->ctx->time + delta;
5907 task_clock_event_update(event, time);
5910 static int task_clock_event_init(struct perf_event *event)
5912 if (event->attr.type != PERF_TYPE_SOFTWARE)
5915 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
5918 perf_swevent_init_hrtimer(event);
5923 static struct pmu perf_task_clock = {
5924 .task_ctx_nr = perf_sw_context,
5926 .event_init = task_clock_event_init,
5927 .add = task_clock_event_add,
5928 .del = task_clock_event_del,
5929 .start = task_clock_event_start,
5930 .stop = task_clock_event_stop,
5931 .read = task_clock_event_read,
5934 static void perf_pmu_nop_void(struct pmu *pmu)
5938 static int perf_pmu_nop_int(struct pmu *pmu)
5943 static void perf_pmu_start_txn(struct pmu *pmu)
5945 perf_pmu_disable(pmu);
5948 static int perf_pmu_commit_txn(struct pmu *pmu)
5950 perf_pmu_enable(pmu);
5954 static void perf_pmu_cancel_txn(struct pmu *pmu)
5956 perf_pmu_enable(pmu);
5960 * Ensures all contexts with the same task_ctx_nr have the same
5961 * pmu_cpu_context too.
5963 static void *find_pmu_context(int ctxn)
5970 list_for_each_entry(pmu, &pmus, entry) {
5971 if (pmu->task_ctx_nr == ctxn)
5972 return pmu->pmu_cpu_context;
5978 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
5982 for_each_possible_cpu(cpu) {
5983 struct perf_cpu_context *cpuctx;
5985 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
5987 if (cpuctx->unique_pmu == old_pmu)
5988 cpuctx->unique_pmu = pmu;
5992 static void free_pmu_context(struct pmu *pmu)
5996 mutex_lock(&pmus_lock);
5998 * Like a real lame refcount.
6000 list_for_each_entry(i, &pmus, entry) {
6001 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
6002 update_pmu_context(i, pmu);
6007 free_percpu(pmu->pmu_cpu_context);
6009 mutex_unlock(&pmus_lock);
6011 static struct idr pmu_idr;
6014 type_show(struct device *dev, struct device_attribute *attr, char *page)
6016 struct pmu *pmu = dev_get_drvdata(dev);
6018 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
6021 static struct device_attribute pmu_dev_attrs[] = {
6026 static int pmu_bus_running;
6027 static struct bus_type pmu_bus = {
6028 .name = "event_source",
6029 .dev_attrs = pmu_dev_attrs,
6032 static void pmu_dev_release(struct device *dev)
6037 static int pmu_dev_alloc(struct pmu *pmu)
6041 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
6045 device_initialize(pmu->dev);
6046 ret = dev_set_name(pmu->dev, "%s", pmu->name);
6050 dev_set_drvdata(pmu->dev, pmu);
6051 pmu->dev->bus = &pmu_bus;
6052 pmu->dev->release = pmu_dev_release;
6053 ret = device_add(pmu->dev);
6061 put_device(pmu->dev);
6065 static struct lock_class_key cpuctx_mutex;
6066 static struct lock_class_key cpuctx_lock;
6068 int perf_pmu_register(struct pmu *pmu, char *name, int type)
6072 mutex_lock(&pmus_lock);
6074 pmu->pmu_disable_count = alloc_percpu(int);
6075 if (!pmu->pmu_disable_count)
6084 int err = idr_pre_get(&pmu_idr, GFP_KERNEL);
6088 err = idr_get_new_above(&pmu_idr, pmu, PERF_TYPE_MAX, &type);
6096 if (pmu_bus_running) {
6097 ret = pmu_dev_alloc(pmu);
6103 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
6104 if (pmu->pmu_cpu_context)
6105 goto got_cpu_context;
6108 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
6109 if (!pmu->pmu_cpu_context)
6112 for_each_possible_cpu(cpu) {
6113 struct perf_cpu_context *cpuctx;
6115 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6116 __perf_event_init_context(&cpuctx->ctx);
6117 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
6118 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
6119 cpuctx->ctx.pmu = pmu;
6120 cpuctx->jiffies_interval = 1;
6121 INIT_LIST_HEAD(&cpuctx->rotation_list);
6122 cpuctx->unique_pmu = pmu;
6126 if (!pmu->start_txn) {
6127 if (pmu->pmu_enable) {
6129 * If we have pmu_enable/pmu_disable calls, install
6130 * transaction stubs that use that to try and batch
6131 * hardware accesses.
6133 pmu->start_txn = perf_pmu_start_txn;
6134 pmu->commit_txn = perf_pmu_commit_txn;
6135 pmu->cancel_txn = perf_pmu_cancel_txn;
6137 pmu->start_txn = perf_pmu_nop_void;
6138 pmu->commit_txn = perf_pmu_nop_int;
6139 pmu->cancel_txn = perf_pmu_nop_void;
6143 if (!pmu->pmu_enable) {
6144 pmu->pmu_enable = perf_pmu_nop_void;
6145 pmu->pmu_disable = perf_pmu_nop_void;
6148 list_add_rcu(&pmu->entry, &pmus);
6151 mutex_unlock(&pmus_lock);
6156 device_del(pmu->dev);
6157 put_device(pmu->dev);
6160 if (pmu->type >= PERF_TYPE_MAX)
6161 idr_remove(&pmu_idr, pmu->type);
6164 free_percpu(pmu->pmu_disable_count);
6168 void perf_pmu_unregister(struct pmu *pmu)
6170 mutex_lock(&pmus_lock);
6171 list_del_rcu(&pmu->entry);
6172 mutex_unlock(&pmus_lock);
6175 * We dereference the pmu list under both SRCU and regular RCU, so
6176 * synchronize against both of those.
6178 synchronize_srcu(&pmus_srcu);
6181 free_percpu(pmu->pmu_disable_count);
6182 if (pmu->type >= PERF_TYPE_MAX)
6183 idr_remove(&pmu_idr, pmu->type);
6184 device_del(pmu->dev);
6185 put_device(pmu->dev);
6186 free_pmu_context(pmu);
6189 struct pmu *perf_init_event(struct perf_event *event)
6191 struct pmu *pmu = NULL;
6195 idx = srcu_read_lock(&pmus_srcu);
6198 pmu = idr_find(&pmu_idr, event->attr.type);
6202 ret = pmu->event_init(event);
6208 list_for_each_entry_rcu(pmu, &pmus, entry) {
6210 ret = pmu->event_init(event);
6214 if (ret != -ENOENT) {
6219 pmu = ERR_PTR(-ENOENT);
6221 srcu_read_unlock(&pmus_srcu, idx);
6227 * Allocate and initialize a event structure
6229 static struct perf_event *
6230 perf_event_alloc(struct perf_event_attr *attr, int cpu,
6231 struct task_struct *task,
6232 struct perf_event *group_leader,
6233 struct perf_event *parent_event,
6234 perf_overflow_handler_t overflow_handler,
6238 struct perf_event *event;
6239 struct hw_perf_event *hwc;
6242 if ((unsigned)cpu >= nr_cpu_ids) {
6243 if (!task || cpu != -1)
6244 return ERR_PTR(-EINVAL);
6247 event = kzalloc(sizeof(*event), GFP_KERNEL);
6249 return ERR_PTR(-ENOMEM);
6252 * Single events are their own group leaders, with an
6253 * empty sibling list:
6256 group_leader = event;
6258 mutex_init(&event->child_mutex);
6259 INIT_LIST_HEAD(&event->child_list);
6261 INIT_LIST_HEAD(&event->group_entry);
6262 INIT_LIST_HEAD(&event->event_entry);
6263 INIT_LIST_HEAD(&event->sibling_list);
6264 INIT_LIST_HEAD(&event->rb_entry);
6266 init_waitqueue_head(&event->waitq);
6267 init_irq_work(&event->pending, perf_pending_event);
6269 mutex_init(&event->mmap_mutex);
6271 atomic_long_set(&event->refcount, 1);
6273 event->attr = *attr;
6274 event->group_leader = group_leader;
6278 event->parent = parent_event;
6280 event->ns = get_pid_ns(current->nsproxy->pid_ns);
6281 event->id = atomic64_inc_return(&perf_event_id);
6283 event->state = PERF_EVENT_STATE_INACTIVE;
6286 event->attach_state = PERF_ATTACH_TASK;
6287 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6289 * hw_breakpoint is a bit difficult here..
6291 if (attr->type == PERF_TYPE_BREAKPOINT)
6292 event->hw.bp_target = task;
6296 if (!overflow_handler && parent_event) {
6297 overflow_handler = parent_event->overflow_handler;
6298 context = parent_event->overflow_handler_context;
6301 event->overflow_handler = overflow_handler;
6302 event->overflow_handler_context = context;
6304 perf_event__state_init(event);
6309 hwc->sample_period = attr->sample_period;
6310 if (attr->freq && attr->sample_freq)
6311 hwc->sample_period = 1;
6312 hwc->last_period = hwc->sample_period;
6314 local64_set(&hwc->period_left, hwc->sample_period);
6317 * We currently do not support PERF_SAMPLE_READ on inherited events.
6318 * See perf_output_read().
6320 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
6323 pmu = perf_init_event(event);
6329 else if (IS_ERR(pmu))
6334 put_pid_ns(event->ns);
6336 return ERR_PTR(err);
6339 if (!event->parent) {
6340 if (event->attach_state & PERF_ATTACH_TASK)
6341 jump_label_inc(&perf_sched_events);
6342 if (event->attr.mmap || event->attr.mmap_data)
6343 atomic_inc(&nr_mmap_events);
6344 if (event->attr.comm)
6345 atomic_inc(&nr_comm_events);
6346 if (event->attr.task)
6347 atomic_inc(&nr_task_events);
6348 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
6349 err = get_callchain_buffers();
6352 return ERR_PTR(err);
6360 static int perf_copy_attr(struct perf_event_attr __user *uattr,
6361 struct perf_event_attr *attr)
6366 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
6370 * zero the full structure, so that a short copy will be nice.
6372 memset(attr, 0, sizeof(*attr));
6374 ret = get_user(size, &uattr->size);
6378 if (size > PAGE_SIZE) /* silly large */
6381 if (!size) /* abi compat */
6382 size = PERF_ATTR_SIZE_VER0;
6384 if (size < PERF_ATTR_SIZE_VER0)
6388 * If we're handed a bigger struct than we know of,
6389 * ensure all the unknown bits are 0 - i.e. new
6390 * user-space does not rely on any kernel feature
6391 * extensions we dont know about yet.
6393 if (size > sizeof(*attr)) {
6394 unsigned char __user *addr;
6395 unsigned char __user *end;
6398 addr = (void __user *)uattr + sizeof(*attr);
6399 end = (void __user *)uattr + size;
6401 for (; addr < end; addr++) {
6402 ret = get_user(val, addr);
6408 size = sizeof(*attr);
6411 ret = copy_from_user(attr, uattr, size);
6415 if (attr->__reserved_1)
6418 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
6421 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
6428 put_user(sizeof(*attr), &uattr->size);
6434 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
6436 struct ring_buffer *rb = NULL, *old_rb = NULL;
6442 /* don't allow circular references */
6443 if (event == output_event)
6447 * Don't allow cross-cpu buffers
6449 if (output_event->cpu != event->cpu)
6453 * If its not a per-cpu rb, it must be the same task.
6455 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
6459 mutex_lock(&event->mmap_mutex);
6460 /* Can't redirect output if we've got an active mmap() */
6461 if (atomic_read(&event->mmap_count))
6467 /* get the rb we want to redirect to */
6468 rb = ring_buffer_get(output_event);
6474 ring_buffer_detach(event, old_rb);
6477 ring_buffer_attach(event, rb);
6479 rcu_assign_pointer(event->rb, rb);
6482 ring_buffer_put(old_rb);
6484 * Since we detached before setting the new rb, so that we
6485 * could attach the new rb, we could have missed a wakeup.
6488 wake_up_all(&event->waitq);
6493 mutex_unlock(&event->mmap_mutex);
6499 static void mutex_lock_double(struct mutex *a, struct mutex *b)
6505 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
6509 * Variation on perf_event_ctx_lock_nested(), except we take two context
6512 static struct perf_event_context *
6513 __perf_event_ctx_lock_double(struct perf_event *group_leader,
6514 struct perf_event_context *ctx)
6516 struct perf_event_context *gctx;
6520 gctx = ACCESS_ONCE(group_leader->ctx);
6521 if (!atomic_inc_not_zero(&gctx->refcount)) {
6527 mutex_lock_double(&gctx->mutex, &ctx->mutex);
6529 if (group_leader->ctx != gctx) {
6530 mutex_unlock(&ctx->mutex);
6531 mutex_unlock(&gctx->mutex);
6540 * sys_perf_event_open - open a performance event, associate it to a task/cpu
6542 * @attr_uptr: event_id type attributes for monitoring/sampling
6545 * @group_fd: group leader event fd
6547 SYSCALL_DEFINE5(perf_event_open,
6548 struct perf_event_attr __user *, attr_uptr,
6549 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
6551 struct perf_event *group_leader = NULL, *output_event = NULL;
6552 struct perf_event *event, *sibling;
6553 struct perf_event_attr attr;
6554 struct perf_event_context *ctx, *uninitialized_var(gctx);
6555 struct file *event_file = NULL;
6556 struct file *group_file = NULL;
6557 struct task_struct *task = NULL;
6561 int fput_needed = 0;
6564 /* for future expandability... */
6565 if (flags & ~PERF_FLAG_ALL)
6568 err = perf_copy_attr(attr_uptr, &attr);
6572 if (!attr.exclude_kernel) {
6573 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
6578 if (attr.sample_freq > sysctl_perf_event_sample_rate)
6581 if (attr.sample_period & (1ULL << 63))
6586 * In cgroup mode, the pid argument is used to pass the fd
6587 * opened to the cgroup directory in cgroupfs. The cpu argument
6588 * designates the cpu on which to monitor threads from that
6591 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
6594 event_fd = get_unused_fd_flags(O_RDWR);
6598 if (group_fd != -1) {
6599 group_file = perf_fget_light(group_fd, &fput_needed);
6600 if (IS_ERR(group_file)) {
6601 err = PTR_ERR(group_file);
6604 group_leader = group_file->private_data;
6605 if (flags & PERF_FLAG_FD_OUTPUT)
6606 output_event = group_leader;
6607 if (flags & PERF_FLAG_FD_NO_GROUP)
6608 group_leader = NULL;
6611 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
6612 task = find_lively_task_by_vpid(pid);
6614 err = PTR_ERR(task);
6619 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
6621 if (IS_ERR(event)) {
6622 err = PTR_ERR(event);
6626 if (flags & PERF_FLAG_PID_CGROUP) {
6627 err = perf_cgroup_connect(pid, event, &attr, group_leader);
6632 * - that has cgroup constraint on event->cpu
6633 * - that may need work on context switch
6635 atomic_inc(&per_cpu(perf_cgroup_events, event->cpu));
6636 jump_label_inc(&perf_sched_events);
6640 * Special case software events and allow them to be part of
6641 * any hardware group.
6646 (is_software_event(event) != is_software_event(group_leader))) {
6647 if (is_software_event(event)) {
6649 * If event and group_leader are not both a software
6650 * event, and event is, then group leader is not.
6652 * Allow the addition of software events to !software
6653 * groups, this is safe because software events never
6656 pmu = group_leader->pmu;
6657 } else if (is_software_event(group_leader) &&
6658 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
6660 * In case the group is a pure software group, and we
6661 * try to add a hardware event, move the whole group to
6662 * the hardware context.
6669 * Get the target context (task or percpu):
6671 ctx = find_get_context(pmu, task, cpu);
6678 put_task_struct(task);
6683 * Look up the group leader (we will attach this event to it):
6689 * Do not allow a recursive hierarchy (this new sibling
6690 * becoming part of another group-sibling):
6692 if (group_leader->group_leader != group_leader)
6695 * Make sure we're both events for the same CPU;
6696 * grouping events for different CPUs is broken; since
6697 * you can never concurrently schedule them anyhow.
6699 if (group_leader->cpu != event->cpu)
6703 * Make sure we're both on the same task, or both
6706 if (group_leader->ctx->task != ctx->task)
6710 * Do not allow to attach to a group in a different task
6711 * or CPU context. If we're moving SW events, we'll fix
6712 * this up later, so allow that.
6714 if (!move_group && group_leader->ctx != ctx)
6718 * Only a group leader can be exclusive or pinned
6720 if (attr.exclusive || attr.pinned)
6725 err = perf_event_set_output(event, output_event);
6730 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, O_RDWR);
6731 if (IS_ERR(event_file)) {
6732 err = PTR_ERR(event_file);
6737 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
6740 * Check if we raced against another sys_perf_event_open() call
6741 * moving the software group underneath us.
6743 if (!(group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
6745 * If someone moved the group out from under us, check
6746 * if this new event wound up on the same ctx, if so
6747 * its the regular !move_group case, otherwise fail.
6753 perf_event_ctx_unlock(group_leader, gctx);
6759 * See perf_event_ctx_lock() for comments on the details
6760 * of swizzling perf_event::ctx.
6762 perf_remove_from_context(group_leader, false);
6765 * Removing from the context ends up with disabled
6766 * event. What we want here is event in the initial
6767 * startup state, ready to be add into new context.
6769 perf_event__state_init(group_leader);
6770 list_for_each_entry(sibling, &group_leader->sibling_list,
6772 perf_remove_from_context(sibling, false);
6773 perf_event__state_init(sibling);
6777 mutex_lock(&ctx->mutex);
6780 WARN_ON_ONCE(ctx->parent_ctx);
6784 * Wait for everybody to stop referencing the events through
6785 * the old lists, before installing it on new lists.
6789 perf_install_in_context(ctx, group_leader, cpu);
6791 list_for_each_entry(sibling, &group_leader->sibling_list,
6793 perf_install_in_context(ctx, sibling, cpu);
6798 perf_install_in_context(ctx, event, cpu);
6800 perf_unpin_context(ctx);
6803 perf_event_ctx_unlock(group_leader, gctx);
6806 mutex_unlock(&ctx->mutex);
6808 event->owner = current;
6810 mutex_lock(¤t->perf_event_mutex);
6811 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
6812 mutex_unlock(¤t->perf_event_mutex);
6815 * Precalculate sample_data sizes
6817 perf_event__header_size(event);
6818 perf_event__id_header_size(event);
6821 * Drop the reference on the group_event after placing the
6822 * new event on the sibling_list. This ensures destruction
6823 * of the group leader will find the pointer to itself in
6824 * perf_group_detach().
6826 fput_light(group_file, fput_needed);
6827 fd_install(event_fd, event_file);
6832 perf_event_ctx_unlock(group_leader, gctx);
6833 mutex_unlock(&ctx->mutex);
6836 perf_unpin_context(ctx);
6840 * If event_file is set, the fput() above will have called ->release()
6841 * and that will take care of freeing the event.
6847 put_task_struct(task);
6849 fput_light(group_file, fput_needed);
6851 put_unused_fd(event_fd);
6856 * perf_event_create_kernel_counter
6858 * @attr: attributes of the counter to create
6859 * @cpu: cpu in which the counter is bound
6860 * @task: task to profile (NULL for percpu)
6863 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
6864 struct task_struct *task,
6865 perf_overflow_handler_t overflow_handler,
6868 struct perf_event_context *ctx;
6869 struct perf_event *event;
6873 * Get the target context (task or percpu):
6876 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
6877 overflow_handler, context);
6878 if (IS_ERR(event)) {
6879 err = PTR_ERR(event);
6883 ctx = find_get_context(event->pmu, task, cpu);
6889 WARN_ON_ONCE(ctx->parent_ctx);
6890 mutex_lock(&ctx->mutex);
6891 perf_install_in_context(ctx, event, cpu);
6893 perf_unpin_context(ctx);
6894 mutex_unlock(&ctx->mutex);
6901 return ERR_PTR(err);
6903 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
6905 static void sync_child_event(struct perf_event *child_event,
6906 struct task_struct *child)
6908 struct perf_event *parent_event = child_event->parent;
6911 if (child_event->attr.inherit_stat)
6912 perf_event_read_event(child_event, child);
6914 child_val = perf_event_count(child_event);
6917 * Add back the child's count to the parent's count:
6919 atomic64_add(child_val, &parent_event->child_count);
6920 atomic64_add(child_event->total_time_enabled,
6921 &parent_event->child_total_time_enabled);
6922 atomic64_add(child_event->total_time_running,
6923 &parent_event->child_total_time_running);
6926 * Remove this event from the parent's list
6928 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
6929 mutex_lock(&parent_event->child_mutex);
6930 list_del_init(&child_event->child_list);
6931 mutex_unlock(&parent_event->child_mutex);
6934 * Release the parent event, if this was the last
6937 put_event(parent_event);
6941 __perf_event_exit_task(struct perf_event *child_event,
6942 struct perf_event_context *child_ctx,
6943 struct task_struct *child)
6945 perf_remove_from_context(child_event, !!child_event->parent);
6948 * It can happen that the parent exits first, and has events
6949 * that are still around due to the child reference. These
6950 * events need to be zapped.
6952 if (child_event->parent) {
6953 sync_child_event(child_event, child);
6954 free_event(child_event);
6958 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
6960 struct perf_event *child_event, *tmp;
6961 struct perf_event_context *child_ctx;
6962 unsigned long flags;
6964 if (likely(!child->perf_event_ctxp[ctxn])) {
6965 perf_event_task(child, NULL, 0);
6969 local_irq_save(flags);
6971 * We can't reschedule here because interrupts are disabled,
6972 * and either child is current or it is a task that can't be
6973 * scheduled, so we are now safe from rescheduling changing
6976 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
6979 * Take the context lock here so that if find_get_context is
6980 * reading child->perf_event_ctxp, we wait until it has
6981 * incremented the context's refcount before we do put_ctx below.
6983 raw_spin_lock(&child_ctx->lock);
6984 task_ctx_sched_out(child_ctx);
6985 child->perf_event_ctxp[ctxn] = NULL;
6987 * If this context is a clone; unclone it so it can't get
6988 * swapped to another process while we're removing all
6989 * the events from it.
6991 unclone_ctx(child_ctx);
6992 update_context_time(child_ctx);
6993 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
6996 * Report the task dead after unscheduling the events so that we
6997 * won't get any samples after PERF_RECORD_EXIT. We can however still
6998 * get a few PERF_RECORD_READ events.
7000 perf_event_task(child, child_ctx, 0);
7003 * We can recurse on the same lock type through:
7005 * __perf_event_exit_task()
7006 * sync_child_event()
7008 * mutex_lock(&ctx->mutex)
7010 * But since its the parent context it won't be the same instance.
7012 mutex_lock(&child_ctx->mutex);
7015 list_for_each_entry_safe(child_event, tmp, &child_ctx->pinned_groups,
7017 __perf_event_exit_task(child_event, child_ctx, child);
7019 list_for_each_entry_safe(child_event, tmp, &child_ctx->flexible_groups,
7021 __perf_event_exit_task(child_event, child_ctx, child);
7024 * If the last event was a group event, it will have appended all
7025 * its siblings to the list, but we obtained 'tmp' before that which
7026 * will still point to the list head terminating the iteration.
7028 if (!list_empty(&child_ctx->pinned_groups) ||
7029 !list_empty(&child_ctx->flexible_groups))
7032 mutex_unlock(&child_ctx->mutex);
7038 * When a child task exits, feed back event values to parent events.
7040 void perf_event_exit_task(struct task_struct *child)
7042 struct perf_event *event, *tmp;
7045 mutex_lock(&child->perf_event_mutex);
7046 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
7048 list_del_init(&event->owner_entry);
7051 * Ensure the list deletion is visible before we clear
7052 * the owner, closes a race against perf_release() where
7053 * we need to serialize on the owner->perf_event_mutex.
7056 event->owner = NULL;
7058 mutex_unlock(&child->perf_event_mutex);
7060 for_each_task_context_nr(ctxn)
7061 perf_event_exit_task_context(child, ctxn);
7064 static void perf_free_event(struct perf_event *event,
7065 struct perf_event_context *ctx)
7067 struct perf_event *parent = event->parent;
7069 if (WARN_ON_ONCE(!parent))
7072 mutex_lock(&parent->child_mutex);
7073 list_del_init(&event->child_list);
7074 mutex_unlock(&parent->child_mutex);
7078 perf_group_detach(event);
7079 list_del_event(event, ctx);
7084 * free an unexposed, unused context as created by inheritance by
7085 * perf_event_init_task below, used by fork() in case of fail.
7087 void perf_event_free_task(struct task_struct *task)
7089 struct perf_event_context *ctx;
7090 struct perf_event *event, *tmp;
7093 for_each_task_context_nr(ctxn) {
7094 ctx = task->perf_event_ctxp[ctxn];
7098 mutex_lock(&ctx->mutex);
7100 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
7102 perf_free_event(event, ctx);
7104 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
7106 perf_free_event(event, ctx);
7108 if (!list_empty(&ctx->pinned_groups) ||
7109 !list_empty(&ctx->flexible_groups))
7112 mutex_unlock(&ctx->mutex);
7118 void perf_event_delayed_put(struct task_struct *task)
7122 for_each_task_context_nr(ctxn)
7123 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
7127 * inherit a event from parent task to child task:
7129 static struct perf_event *
7130 inherit_event(struct perf_event *parent_event,
7131 struct task_struct *parent,
7132 struct perf_event_context *parent_ctx,
7133 struct task_struct *child,
7134 struct perf_event *group_leader,
7135 struct perf_event_context *child_ctx)
7137 struct perf_event *child_event;
7138 unsigned long flags;
7141 * Instead of creating recursive hierarchies of events,
7142 * we link inherited events back to the original parent,
7143 * which has a filp for sure, which we use as the reference
7146 if (parent_event->parent)
7147 parent_event = parent_event->parent;
7149 child_event = perf_event_alloc(&parent_event->attr,
7152 group_leader, parent_event,
7154 if (IS_ERR(child_event))
7157 if (!atomic_long_inc_not_zero(&parent_event->refcount)) {
7158 free_event(child_event);
7165 * Make the child state follow the state of the parent event,
7166 * not its attr.disabled bit. We hold the parent's mutex,
7167 * so we won't race with perf_event_{en, dis}able_family.
7169 if (parent_event->state >= PERF_EVENT_STATE_INACTIVE)
7170 child_event->state = PERF_EVENT_STATE_INACTIVE;
7172 child_event->state = PERF_EVENT_STATE_OFF;
7174 if (parent_event->attr.freq) {
7175 u64 sample_period = parent_event->hw.sample_period;
7176 struct hw_perf_event *hwc = &child_event->hw;
7178 hwc->sample_period = sample_period;
7179 hwc->last_period = sample_period;
7181 local64_set(&hwc->period_left, sample_period);
7184 child_event->ctx = child_ctx;
7185 child_event->overflow_handler = parent_event->overflow_handler;
7186 child_event->overflow_handler_context
7187 = parent_event->overflow_handler_context;
7190 * Precalculate sample_data sizes
7192 perf_event__header_size(child_event);
7193 perf_event__id_header_size(child_event);
7196 * Link it up in the child's context:
7198 raw_spin_lock_irqsave(&child_ctx->lock, flags);
7199 add_event_to_ctx(child_event, child_ctx);
7200 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7203 * Link this into the parent event's child list
7205 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7206 mutex_lock(&parent_event->child_mutex);
7207 list_add_tail(&child_event->child_list, &parent_event->child_list);
7208 mutex_unlock(&parent_event->child_mutex);
7213 static int inherit_group(struct perf_event *parent_event,
7214 struct task_struct *parent,
7215 struct perf_event_context *parent_ctx,
7216 struct task_struct *child,
7217 struct perf_event_context *child_ctx)
7219 struct perf_event *leader;
7220 struct perf_event *sub;
7221 struct perf_event *child_ctr;
7223 leader = inherit_event(parent_event, parent, parent_ctx,
7224 child, NULL, child_ctx);
7226 return PTR_ERR(leader);
7227 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
7228 child_ctr = inherit_event(sub, parent, parent_ctx,
7229 child, leader, child_ctx);
7230 if (IS_ERR(child_ctr))
7231 return PTR_ERR(child_ctr);
7237 inherit_task_group(struct perf_event *event, struct task_struct *parent,
7238 struct perf_event_context *parent_ctx,
7239 struct task_struct *child, int ctxn,
7243 struct perf_event_context *child_ctx;
7245 if (!event->attr.inherit) {
7250 child_ctx = child->perf_event_ctxp[ctxn];
7253 * This is executed from the parent task context, so
7254 * inherit events that have been marked for cloning.
7255 * First allocate and initialize a context for the
7259 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
7263 child->perf_event_ctxp[ctxn] = child_ctx;
7266 ret = inherit_group(event, parent, parent_ctx,
7276 * Initialize the perf_event context in task_struct
7278 int perf_event_init_context(struct task_struct *child, int ctxn)
7280 struct perf_event_context *child_ctx, *parent_ctx;
7281 struct perf_event_context *cloned_ctx;
7282 struct perf_event *event;
7283 struct task_struct *parent = current;
7284 int inherited_all = 1;
7285 unsigned long flags;
7288 if (likely(!parent->perf_event_ctxp[ctxn]))
7292 * If the parent's context is a clone, pin it so it won't get
7295 parent_ctx = perf_pin_task_context(parent, ctxn);
7298 * No need to check if parent_ctx != NULL here; since we saw
7299 * it non-NULL earlier, the only reason for it to become NULL
7300 * is if we exit, and since we're currently in the middle of
7301 * a fork we can't be exiting at the same time.
7305 * Lock the parent list. No need to lock the child - not PID
7306 * hashed yet and not running, so nobody can access it.
7308 mutex_lock(&parent_ctx->mutex);
7311 * We dont have to disable NMIs - we are only looking at
7312 * the list, not manipulating it:
7314 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
7315 ret = inherit_task_group(event, parent, parent_ctx,
7316 child, ctxn, &inherited_all);
7322 * We can't hold ctx->lock when iterating the ->flexible_group list due
7323 * to allocations, but we need to prevent rotation because
7324 * rotate_ctx() will change the list from interrupt context.
7326 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7327 parent_ctx->rotate_disable = 1;
7328 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7330 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
7331 ret = inherit_task_group(event, parent, parent_ctx,
7332 child, ctxn, &inherited_all);
7337 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7338 parent_ctx->rotate_disable = 0;
7340 child_ctx = child->perf_event_ctxp[ctxn];
7342 if (child_ctx && inherited_all) {
7344 * Mark the child context as a clone of the parent
7345 * context, or of whatever the parent is a clone of.
7347 * Note that if the parent is a clone, the holding of
7348 * parent_ctx->lock avoids it from being uncloned.
7350 cloned_ctx = parent_ctx->parent_ctx;
7352 child_ctx->parent_ctx = cloned_ctx;
7353 child_ctx->parent_gen = parent_ctx->parent_gen;
7355 child_ctx->parent_ctx = parent_ctx;
7356 child_ctx->parent_gen = parent_ctx->generation;
7358 get_ctx(child_ctx->parent_ctx);
7361 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7363 mutex_unlock(&parent_ctx->mutex);
7365 perf_unpin_context(parent_ctx);
7366 put_ctx(parent_ctx);
7372 * Initialize the perf_event context in task_struct
7374 int perf_event_init_task(struct task_struct *child)
7378 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
7379 mutex_init(&child->perf_event_mutex);
7380 INIT_LIST_HEAD(&child->perf_event_list);
7382 for_each_task_context_nr(ctxn) {
7383 ret = perf_event_init_context(child, ctxn);
7385 perf_event_free_task(child);
7393 static void __init perf_event_init_all_cpus(void)
7395 struct swevent_htable *swhash;
7398 for_each_possible_cpu(cpu) {
7399 swhash = &per_cpu(swevent_htable, cpu);
7400 mutex_init(&swhash->hlist_mutex);
7401 INIT_LIST_HEAD(&per_cpu(rotation_list, cpu));
7405 static void __cpuinit perf_event_init_cpu(int cpu)
7407 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7409 mutex_lock(&swhash->hlist_mutex);
7410 if (swhash->hlist_refcount > 0) {
7411 struct swevent_hlist *hlist;
7413 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
7415 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7417 mutex_unlock(&swhash->hlist_mutex);
7420 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC
7421 static void perf_pmu_rotate_stop(struct pmu *pmu)
7423 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7425 WARN_ON(!irqs_disabled());
7427 list_del_init(&cpuctx->rotation_list);
7430 static void __perf_event_exit_context(void *__info)
7432 struct remove_event re = { .detach_group = false };
7433 struct perf_event_context *ctx = __info;
7435 perf_pmu_rotate_stop(ctx->pmu);
7438 list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
7439 __perf_remove_from_context(&re);
7443 static void perf_event_exit_cpu_context(int cpu)
7445 struct perf_event_context *ctx;
7449 idx = srcu_read_lock(&pmus_srcu);
7450 list_for_each_entry_rcu(pmu, &pmus, entry) {
7451 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
7453 mutex_lock(&ctx->mutex);
7454 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
7455 mutex_unlock(&ctx->mutex);
7457 srcu_read_unlock(&pmus_srcu, idx);
7460 static void perf_event_exit_cpu(int cpu)
7462 perf_event_exit_cpu_context(cpu);
7465 static inline void perf_event_exit_cpu(int cpu) { }
7469 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
7473 for_each_online_cpu(cpu)
7474 perf_event_exit_cpu(cpu);
7480 * Run the perf reboot notifier at the very last possible moment so that
7481 * the generic watchdog code runs as long as possible.
7483 static struct notifier_block perf_reboot_notifier = {
7484 .notifier_call = perf_reboot,
7485 .priority = INT_MIN,
7488 static int __cpuinit
7489 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
7491 unsigned int cpu = (long)hcpu;
7493 switch (action & ~CPU_TASKS_FROZEN) {
7495 case CPU_UP_PREPARE:
7496 case CPU_DOWN_FAILED:
7497 perf_event_init_cpu(cpu);
7500 case CPU_UP_CANCELED:
7501 case CPU_DOWN_PREPARE:
7502 perf_event_exit_cpu(cpu);
7512 void __init perf_event_init(void)
7518 perf_event_init_all_cpus();
7519 init_srcu_struct(&pmus_srcu);
7520 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
7521 perf_pmu_register(&perf_cpu_clock, NULL, -1);
7522 perf_pmu_register(&perf_task_clock, NULL, -1);
7524 perf_cpu_notifier(perf_cpu_notify);
7525 register_reboot_notifier(&perf_reboot_notifier);
7527 ret = init_hw_breakpoint();
7528 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
7531 static int __init perf_event_sysfs_init(void)
7536 mutex_lock(&pmus_lock);
7538 ret = bus_register(&pmu_bus);
7542 list_for_each_entry(pmu, &pmus, entry) {
7543 if (!pmu->name || pmu->type < 0)
7546 ret = pmu_dev_alloc(pmu);
7547 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
7549 pmu_bus_running = 1;
7553 mutex_unlock(&pmus_lock);
7557 device_initcall(perf_event_sysfs_init);
7559 #ifdef CONFIG_CGROUP_PERF
7560 static struct cgroup_subsys_state *perf_cgroup_create(
7561 struct cgroup_subsys *ss, struct cgroup *cont)
7563 struct perf_cgroup *jc;
7565 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
7567 return ERR_PTR(-ENOMEM);
7569 jc->info = alloc_percpu(struct perf_cgroup_info);
7572 return ERR_PTR(-ENOMEM);
7578 static void perf_cgroup_destroy(struct cgroup_subsys *ss,
7579 struct cgroup *cont)
7581 struct perf_cgroup *jc;
7582 jc = container_of(cgroup_subsys_state(cont, perf_subsys_id),
7583 struct perf_cgroup, css);
7584 free_percpu(jc->info);
7588 static int __perf_cgroup_move(void *info)
7590 struct task_struct *task = info;
7591 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
7596 perf_cgroup_attach_task(struct cgroup *cgrp, struct task_struct *task)
7598 task_function_call(task, __perf_cgroup_move, task);
7601 static void perf_cgroup_exit(struct cgroup_subsys *ss, struct cgroup *cgrp,
7602 struct cgroup *old_cgrp, struct task_struct *task)
7605 * cgroup_exit() is called in the copy_process() failure path.
7606 * Ignore this case since the task hasn't ran yet, this avoids
7607 * trying to poke a half freed task state from generic code.
7609 if (!(task->flags & PF_EXITING))
7612 perf_cgroup_attach_task(cgrp, task);
7615 struct cgroup_subsys perf_subsys = {
7616 .name = "perf_event",
7617 .subsys_id = perf_subsys_id,
7618 .create = perf_cgroup_create,
7619 .destroy = perf_cgroup_destroy,
7620 .exit = perf_cgroup_exit,
7621 .attach_task = perf_cgroup_attach_task,
7623 #endif /* CONFIG_CGROUP_PERF */