2 * Performance events core code:
4 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
5 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
6 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
7 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
9 * For licensing details see kernel-base/COPYING
14 #include <linux/cpu.h>
15 #include <linux/smp.h>
16 #include <linux/idr.h>
17 #include <linux/file.h>
18 #include <linux/poll.h>
19 #include <linux/slab.h>
20 #include <linux/hash.h>
21 #include <linux/tick.h>
22 #include <linux/sysfs.h>
23 #include <linux/dcache.h>
24 #include <linux/percpu.h>
25 #include <linux/ptrace.h>
26 #include <linux/reboot.h>
27 #include <linux/vmstat.h>
28 #include <linux/device.h>
29 #include <linux/export.h>
30 #include <linux/vmalloc.h>
31 #include <linux/hardirq.h>
32 #include <linux/rculist.h>
33 #include <linux/uaccess.h>
34 #include <linux/syscalls.h>
35 #include <linux/anon_inodes.h>
36 #include <linux/kernel_stat.h>
37 #include <linux/perf_event.h>
38 #include <linux/ftrace_event.h>
39 #include <linux/hw_breakpoint.h>
40 #include <linux/mm_types.h>
41 #include <linux/cgroup.h>
45 #include <asm/irq_regs.h>
47 struct remote_function_call {
48 struct task_struct *p;
49 int (*func)(void *info);
54 static void remote_function(void *data)
56 struct remote_function_call *tfc = data;
57 struct task_struct *p = tfc->p;
61 if (task_cpu(p) != smp_processor_id() || !task_curr(p))
65 tfc->ret = tfc->func(tfc->info);
69 * task_function_call - call a function on the cpu on which a task runs
70 * @p: the task to evaluate
71 * @func: the function to be called
72 * @info: the function call argument
74 * Calls the function @func when the task is currently running. This might
75 * be on the current CPU, which just calls the function directly
77 * returns: @func return value, or
78 * -ESRCH - when the process isn't running
79 * -EAGAIN - when the process moved away
82 task_function_call(struct task_struct *p, int (*func) (void *info), void *info)
84 struct remote_function_call data = {
88 .ret = -ESRCH, /* No such (running) process */
92 smp_call_function_single(task_cpu(p), remote_function, &data, 1);
98 * cpu_function_call - call a function on the cpu
99 * @func: the function to be called
100 * @info: the function call argument
102 * Calls the function @func on the remote cpu.
104 * returns: @func return value or -ENXIO when the cpu is offline
106 static int cpu_function_call(int cpu, int (*func) (void *info), void *info)
108 struct remote_function_call data = {
112 .ret = -ENXIO, /* No such CPU */
115 smp_call_function_single(cpu, remote_function, &data, 1);
120 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
121 PERF_FLAG_FD_OUTPUT |\
122 PERF_FLAG_PID_CGROUP)
125 * branch priv levels that need permission checks
127 #define PERF_SAMPLE_BRANCH_PERM_PLM \
128 (PERF_SAMPLE_BRANCH_KERNEL |\
129 PERF_SAMPLE_BRANCH_HV)
132 EVENT_FLEXIBLE = 0x1,
134 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
138 * perf_sched_events : >0 events exist
139 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
141 struct static_key_deferred perf_sched_events __read_mostly;
142 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
143 static DEFINE_PER_CPU(atomic_t, perf_branch_stack_events);
145 static atomic_t nr_mmap_events __read_mostly;
146 static atomic_t nr_comm_events __read_mostly;
147 static atomic_t nr_task_events __read_mostly;
149 static LIST_HEAD(pmus);
150 static DEFINE_MUTEX(pmus_lock);
151 static struct srcu_struct pmus_srcu;
154 * perf event paranoia level:
155 * -1 - not paranoid at all
156 * 0 - disallow raw tracepoint access for unpriv
157 * 1 - disallow cpu events for unpriv
158 * 2 - disallow kernel profiling for unpriv
160 int sysctl_perf_event_paranoid __read_mostly = 1;
162 /* Minimum for 512 kiB + 1 user control page */
163 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
166 * max perf event sample rate
168 #define DEFAULT_MAX_SAMPLE_RATE 100000
169 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
170 static int max_samples_per_tick __read_mostly =
171 DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
173 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
175 int perf_proc_update_handler(struct ctl_table *table, int write,
176 void __user *buffer, size_t *lenp,
179 int ret = proc_dointvec(table, write, buffer, lenp, ppos);
184 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
189 static atomic64_t perf_event_id;
191 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
192 enum event_type_t event_type);
194 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
195 enum event_type_t event_type,
196 struct task_struct *task);
198 static void update_context_time(struct perf_event_context *ctx);
199 static u64 perf_event_time(struct perf_event *event);
201 void __weak perf_event_print_debug(void) { }
203 extern __weak const char *perf_pmu_name(void)
208 static inline u64 perf_clock(void)
210 return local_clock();
213 static inline struct perf_cpu_context *
214 __get_cpu_context(struct perf_event_context *ctx)
216 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
219 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
220 struct perf_event_context *ctx)
222 raw_spin_lock(&cpuctx->ctx.lock);
224 raw_spin_lock(&ctx->lock);
227 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
228 struct perf_event_context *ctx)
231 raw_spin_unlock(&ctx->lock);
232 raw_spin_unlock(&cpuctx->ctx.lock);
235 #ifdef CONFIG_CGROUP_PERF
238 * perf_cgroup_info keeps track of time_enabled for a cgroup.
239 * This is a per-cpu dynamically allocated data structure.
241 struct perf_cgroup_info {
247 struct cgroup_subsys_state css;
248 struct perf_cgroup_info __percpu *info;
252 * Must ensure cgroup is pinned (css_get) before calling
253 * this function. In other words, we cannot call this function
254 * if there is no cgroup event for the current CPU context.
256 static inline struct perf_cgroup *
257 perf_cgroup_from_task(struct task_struct *task)
259 return container_of(task_subsys_state(task, perf_subsys_id),
260 struct perf_cgroup, css);
264 perf_cgroup_match(struct perf_event *event)
266 struct perf_event_context *ctx = event->ctx;
267 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
269 /* @event doesn't care about cgroup */
273 /* wants specific cgroup scope but @cpuctx isn't associated with any */
278 * Cgroup scoping is recursive. An event enabled for a cgroup is
279 * also enabled for all its descendant cgroups. If @cpuctx's
280 * cgroup is a descendant of @event's (the test covers identity
281 * case), it's a match.
283 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
284 event->cgrp->css.cgroup);
287 static inline bool perf_tryget_cgroup(struct perf_event *event)
289 return css_tryget(&event->cgrp->css);
292 static inline void perf_put_cgroup(struct perf_event *event)
294 css_put(&event->cgrp->css);
297 static inline void perf_detach_cgroup(struct perf_event *event)
299 perf_put_cgroup(event);
303 static inline int is_cgroup_event(struct perf_event *event)
305 return event->cgrp != NULL;
308 static inline u64 perf_cgroup_event_time(struct perf_event *event)
310 struct perf_cgroup_info *t;
312 t = per_cpu_ptr(event->cgrp->info, event->cpu);
316 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
318 struct perf_cgroup_info *info;
323 info = this_cpu_ptr(cgrp->info);
325 info->time += now - info->timestamp;
326 info->timestamp = now;
329 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
331 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
333 __update_cgrp_time(cgrp_out);
336 static inline void update_cgrp_time_from_event(struct perf_event *event)
338 struct perf_cgroup *cgrp;
341 * ensure we access cgroup data only when needed and
342 * when we know the cgroup is pinned (css_get)
344 if (!is_cgroup_event(event))
347 cgrp = perf_cgroup_from_task(current);
349 * Do not update time when cgroup is not active
351 if (cgrp == event->cgrp)
352 __update_cgrp_time(event->cgrp);
356 perf_cgroup_set_timestamp(struct task_struct *task,
357 struct perf_event_context *ctx)
359 struct perf_cgroup *cgrp;
360 struct perf_cgroup_info *info;
363 * ctx->lock held by caller
364 * ensure we do not access cgroup data
365 * unless we have the cgroup pinned (css_get)
367 if (!task || !ctx->nr_cgroups)
370 cgrp = perf_cgroup_from_task(task);
371 info = this_cpu_ptr(cgrp->info);
372 info->timestamp = ctx->timestamp;
375 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
376 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
379 * reschedule events based on the cgroup constraint of task.
381 * mode SWOUT : schedule out everything
382 * mode SWIN : schedule in based on cgroup for next
384 void perf_cgroup_switch(struct task_struct *task, int mode)
386 struct perf_cpu_context *cpuctx;
391 * disable interrupts to avoid geting nr_cgroup
392 * changes via __perf_event_disable(). Also
395 local_irq_save(flags);
398 * we reschedule only in the presence of cgroup
399 * constrained events.
403 list_for_each_entry_rcu(pmu, &pmus, entry) {
404 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
405 if (cpuctx->unique_pmu != pmu)
406 continue; /* ensure we process each cpuctx once */
409 * perf_cgroup_events says at least one
410 * context on this CPU has cgroup events.
412 * ctx->nr_cgroups reports the number of cgroup
413 * events for a context.
415 if (cpuctx->ctx.nr_cgroups > 0) {
416 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
417 perf_pmu_disable(cpuctx->ctx.pmu);
419 if (mode & PERF_CGROUP_SWOUT) {
420 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
422 * must not be done before ctxswout due
423 * to event_filter_match() in event_sched_out()
428 if (mode & PERF_CGROUP_SWIN) {
429 WARN_ON_ONCE(cpuctx->cgrp);
431 * set cgrp before ctxsw in to allow
432 * event_filter_match() to not have to pass
435 cpuctx->cgrp = perf_cgroup_from_task(task);
436 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
438 perf_pmu_enable(cpuctx->ctx.pmu);
439 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
445 local_irq_restore(flags);
448 static inline void perf_cgroup_sched_out(struct task_struct *task,
449 struct task_struct *next)
451 struct perf_cgroup *cgrp1;
452 struct perf_cgroup *cgrp2 = NULL;
455 * we come here when we know perf_cgroup_events > 0
457 cgrp1 = perf_cgroup_from_task(task);
460 * next is NULL when called from perf_event_enable_on_exec()
461 * that will systematically cause a cgroup_switch()
464 cgrp2 = perf_cgroup_from_task(next);
467 * only schedule out current cgroup events if we know
468 * that we are switching to a different cgroup. Otherwise,
469 * do no touch the cgroup events.
472 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
475 static inline void perf_cgroup_sched_in(struct task_struct *prev,
476 struct task_struct *task)
478 struct perf_cgroup *cgrp1;
479 struct perf_cgroup *cgrp2 = NULL;
482 * we come here when we know perf_cgroup_events > 0
484 cgrp1 = perf_cgroup_from_task(task);
486 /* prev can never be NULL */
487 cgrp2 = perf_cgroup_from_task(prev);
490 * only need to schedule in cgroup events if we are changing
491 * cgroup during ctxsw. Cgroup events were not scheduled
492 * out of ctxsw out if that was not the case.
495 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
498 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
499 struct perf_event_attr *attr,
500 struct perf_event *group_leader)
502 struct perf_cgroup *cgrp;
503 struct cgroup_subsys_state *css;
504 struct fd f = fdget(fd);
510 css = cgroup_css_from_dir(f.file, perf_subsys_id);
516 cgrp = container_of(css, struct perf_cgroup, css);
519 /* must be done before we fput() the file */
520 if (!perf_tryget_cgroup(event)) {
527 * all events in a group must monitor
528 * the same cgroup because a task belongs
529 * to only one perf cgroup at a time
531 if (group_leader && group_leader->cgrp != cgrp) {
532 perf_detach_cgroup(event);
541 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
543 struct perf_cgroup_info *t;
544 t = per_cpu_ptr(event->cgrp->info, event->cpu);
545 event->shadow_ctx_time = now - t->timestamp;
549 perf_cgroup_defer_enabled(struct perf_event *event)
552 * when the current task's perf cgroup does not match
553 * the event's, we need to remember to call the
554 * perf_mark_enable() function the first time a task with
555 * a matching perf cgroup is scheduled in.
557 if (is_cgroup_event(event) && !perf_cgroup_match(event))
558 event->cgrp_defer_enabled = 1;
562 perf_cgroup_mark_enabled(struct perf_event *event,
563 struct perf_event_context *ctx)
565 struct perf_event *sub;
566 u64 tstamp = perf_event_time(event);
568 if (!event->cgrp_defer_enabled)
571 event->cgrp_defer_enabled = 0;
573 event->tstamp_enabled = tstamp - event->total_time_enabled;
574 list_for_each_entry(sub, &event->sibling_list, group_entry) {
575 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
576 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
577 sub->cgrp_defer_enabled = 0;
581 #else /* !CONFIG_CGROUP_PERF */
584 perf_cgroup_match(struct perf_event *event)
589 static inline void perf_detach_cgroup(struct perf_event *event)
592 static inline int is_cgroup_event(struct perf_event *event)
597 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
602 static inline void update_cgrp_time_from_event(struct perf_event *event)
606 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
610 static inline void perf_cgroup_sched_out(struct task_struct *task,
611 struct task_struct *next)
615 static inline void perf_cgroup_sched_in(struct task_struct *prev,
616 struct task_struct *task)
620 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
621 struct perf_event_attr *attr,
622 struct perf_event *group_leader)
628 perf_cgroup_set_timestamp(struct task_struct *task,
629 struct perf_event_context *ctx)
634 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
639 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
643 static inline u64 perf_cgroup_event_time(struct perf_event *event)
649 perf_cgroup_defer_enabled(struct perf_event *event)
654 perf_cgroup_mark_enabled(struct perf_event *event,
655 struct perf_event_context *ctx)
661 * set default to be dependent on timer tick just
664 #define PERF_CPU_HRTIMER (1000 / HZ)
666 * function must be called with interrupts disbled
668 static enum hrtimer_restart perf_cpu_hrtimer_handler(struct hrtimer *hr)
670 struct perf_cpu_context *cpuctx;
671 enum hrtimer_restart ret = HRTIMER_NORESTART;
674 WARN_ON(!irqs_disabled());
676 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
678 rotations = perf_rotate_context(cpuctx);
681 * arm timer if needed
684 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
685 ret = HRTIMER_RESTART;
691 /* CPU is going down */
692 void perf_cpu_hrtimer_cancel(int cpu)
694 struct perf_cpu_context *cpuctx;
698 if (WARN_ON(cpu != smp_processor_id()))
701 local_irq_save(flags);
705 list_for_each_entry_rcu(pmu, &pmus, entry) {
706 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
708 if (pmu->task_ctx_nr == perf_sw_context)
711 hrtimer_cancel(&cpuctx->hrtimer);
716 local_irq_restore(flags);
719 static void __perf_cpu_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
721 struct hrtimer *hr = &cpuctx->hrtimer;
722 struct pmu *pmu = cpuctx->ctx.pmu;
725 /* no multiplexing needed for SW PMU */
726 if (pmu->task_ctx_nr == perf_sw_context)
730 * check default is sane, if not set then force to
731 * default interval (1/tick)
733 timer = pmu->hrtimer_interval_ms;
735 timer = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
737 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
739 hrtimer_init(hr, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
740 hr->function = perf_cpu_hrtimer_handler;
743 static void perf_cpu_hrtimer_restart(struct perf_cpu_context *cpuctx)
745 struct hrtimer *hr = &cpuctx->hrtimer;
746 struct pmu *pmu = cpuctx->ctx.pmu;
749 if (pmu->task_ctx_nr == perf_sw_context)
752 if (hrtimer_active(hr))
755 if (!hrtimer_callback_running(hr))
756 __hrtimer_start_range_ns(hr, cpuctx->hrtimer_interval,
757 0, HRTIMER_MODE_REL_PINNED, 0);
760 void perf_pmu_disable(struct pmu *pmu)
762 int *count = this_cpu_ptr(pmu->pmu_disable_count);
764 pmu->pmu_disable(pmu);
767 void perf_pmu_enable(struct pmu *pmu)
769 int *count = this_cpu_ptr(pmu->pmu_disable_count);
771 pmu->pmu_enable(pmu);
774 static DEFINE_PER_CPU(struct list_head, rotation_list);
777 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
778 * because they're strictly cpu affine and rotate_start is called with IRQs
779 * disabled, while rotate_context is called from IRQ context.
781 static void perf_pmu_rotate_start(struct pmu *pmu)
783 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
784 struct list_head *head = &__get_cpu_var(rotation_list);
786 WARN_ON(!irqs_disabled());
788 if (list_empty(&cpuctx->rotation_list)) {
789 int was_empty = list_empty(head);
790 list_add(&cpuctx->rotation_list, head);
792 tick_nohz_full_kick();
796 static void get_ctx(struct perf_event_context *ctx)
798 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
801 static void put_ctx(struct perf_event_context *ctx)
803 if (atomic_dec_and_test(&ctx->refcount)) {
805 put_ctx(ctx->parent_ctx);
807 put_task_struct(ctx->task);
808 kfree_rcu(ctx, rcu_head);
812 static void unclone_ctx(struct perf_event_context *ctx)
814 if (ctx->parent_ctx) {
815 put_ctx(ctx->parent_ctx);
816 ctx->parent_ctx = NULL;
820 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
823 * only top level events have the pid namespace they were created in
826 event = event->parent;
828 return task_tgid_nr_ns(p, event->ns);
831 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
834 * only top level events have the pid namespace they were created in
837 event = event->parent;
839 return task_pid_nr_ns(p, event->ns);
843 * If we inherit events we want to return the parent event id
846 static u64 primary_event_id(struct perf_event *event)
851 id = event->parent->id;
857 * Get the perf_event_context for a task and lock it.
858 * This has to cope with with the fact that until it is locked,
859 * the context could get moved to another task.
861 static struct perf_event_context *
862 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
864 struct perf_event_context *ctx;
868 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
871 * If this context is a clone of another, it might
872 * get swapped for another underneath us by
873 * perf_event_task_sched_out, though the
874 * rcu_read_lock() protects us from any context
875 * getting freed. Lock the context and check if it
876 * got swapped before we could get the lock, and retry
877 * if so. If we locked the right context, then it
878 * can't get swapped on us any more.
880 raw_spin_lock_irqsave(&ctx->lock, *flags);
881 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
882 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
886 if (!atomic_inc_not_zero(&ctx->refcount)) {
887 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
896 * Get the context for a task and increment its pin_count so it
897 * can't get swapped to another task. This also increments its
898 * reference count so that the context can't get freed.
900 static struct perf_event_context *
901 perf_pin_task_context(struct task_struct *task, int ctxn)
903 struct perf_event_context *ctx;
906 ctx = perf_lock_task_context(task, ctxn, &flags);
909 raw_spin_unlock_irqrestore(&ctx->lock, flags);
914 static void perf_unpin_context(struct perf_event_context *ctx)
918 raw_spin_lock_irqsave(&ctx->lock, flags);
920 raw_spin_unlock_irqrestore(&ctx->lock, flags);
924 * Update the record of the current time in a context.
926 static void update_context_time(struct perf_event_context *ctx)
928 u64 now = perf_clock();
930 ctx->time += now - ctx->timestamp;
931 ctx->timestamp = now;
934 static u64 perf_event_time(struct perf_event *event)
936 struct perf_event_context *ctx = event->ctx;
938 if (is_cgroup_event(event))
939 return perf_cgroup_event_time(event);
941 return ctx ? ctx->time : 0;
945 * Update the total_time_enabled and total_time_running fields for a event.
946 * The caller of this function needs to hold the ctx->lock.
948 static void update_event_times(struct perf_event *event)
950 struct perf_event_context *ctx = event->ctx;
953 if (event->state < PERF_EVENT_STATE_INACTIVE ||
954 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
957 * in cgroup mode, time_enabled represents
958 * the time the event was enabled AND active
959 * tasks were in the monitored cgroup. This is
960 * independent of the activity of the context as
961 * there may be a mix of cgroup and non-cgroup events.
963 * That is why we treat cgroup events differently
966 if (is_cgroup_event(event))
967 run_end = perf_cgroup_event_time(event);
968 else if (ctx->is_active)
971 run_end = event->tstamp_stopped;
973 event->total_time_enabled = run_end - event->tstamp_enabled;
975 if (event->state == PERF_EVENT_STATE_INACTIVE)
976 run_end = event->tstamp_stopped;
978 run_end = perf_event_time(event);
980 event->total_time_running = run_end - event->tstamp_running;
985 * Update total_time_enabled and total_time_running for all events in a group.
987 static void update_group_times(struct perf_event *leader)
989 struct perf_event *event;
991 update_event_times(leader);
992 list_for_each_entry(event, &leader->sibling_list, group_entry)
993 update_event_times(event);
996 static struct list_head *
997 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
999 if (event->attr.pinned)
1000 return &ctx->pinned_groups;
1002 return &ctx->flexible_groups;
1006 * Add a event from the lists for its context.
1007 * Must be called with ctx->mutex and ctx->lock held.
1010 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1012 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1013 event->attach_state |= PERF_ATTACH_CONTEXT;
1016 * If we're a stand alone event or group leader, we go to the context
1017 * list, group events are kept attached to the group so that
1018 * perf_group_detach can, at all times, locate all siblings.
1020 if (event->group_leader == event) {
1021 struct list_head *list;
1023 if (is_software_event(event))
1024 event->group_flags |= PERF_GROUP_SOFTWARE;
1026 list = ctx_group_list(event, ctx);
1027 list_add_tail(&event->group_entry, list);
1030 if (is_cgroup_event(event))
1033 if (has_branch_stack(event))
1034 ctx->nr_branch_stack++;
1036 list_add_rcu(&event->event_entry, &ctx->event_list);
1037 if (!ctx->nr_events)
1038 perf_pmu_rotate_start(ctx->pmu);
1040 if (event->attr.inherit_stat)
1045 * Initialize event state based on the perf_event_attr::disabled.
1047 static inline void perf_event__state_init(struct perf_event *event)
1049 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1050 PERF_EVENT_STATE_INACTIVE;
1054 * Called at perf_event creation and when events are attached/detached from a
1057 static void perf_event__read_size(struct perf_event *event)
1059 int entry = sizeof(u64); /* value */
1063 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1064 size += sizeof(u64);
1066 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1067 size += sizeof(u64);
1069 if (event->attr.read_format & PERF_FORMAT_ID)
1070 entry += sizeof(u64);
1072 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1073 nr += event->group_leader->nr_siblings;
1074 size += sizeof(u64);
1078 event->read_size = size;
1081 static void perf_event__header_size(struct perf_event *event)
1083 struct perf_sample_data *data;
1084 u64 sample_type = event->attr.sample_type;
1087 perf_event__read_size(event);
1089 if (sample_type & PERF_SAMPLE_IP)
1090 size += sizeof(data->ip);
1092 if (sample_type & PERF_SAMPLE_ADDR)
1093 size += sizeof(data->addr);
1095 if (sample_type & PERF_SAMPLE_PERIOD)
1096 size += sizeof(data->period);
1098 if (sample_type & PERF_SAMPLE_WEIGHT)
1099 size += sizeof(data->weight);
1101 if (sample_type & PERF_SAMPLE_READ)
1102 size += event->read_size;
1104 if (sample_type & PERF_SAMPLE_DATA_SRC)
1105 size += sizeof(data->data_src.val);
1107 event->header_size = size;
1110 static void perf_event__id_header_size(struct perf_event *event)
1112 struct perf_sample_data *data;
1113 u64 sample_type = event->attr.sample_type;
1116 if (sample_type & PERF_SAMPLE_TID)
1117 size += sizeof(data->tid_entry);
1119 if (sample_type & PERF_SAMPLE_TIME)
1120 size += sizeof(data->time);
1122 if (sample_type & PERF_SAMPLE_ID)
1123 size += sizeof(data->id);
1125 if (sample_type & PERF_SAMPLE_STREAM_ID)
1126 size += sizeof(data->stream_id);
1128 if (sample_type & PERF_SAMPLE_CPU)
1129 size += sizeof(data->cpu_entry);
1131 event->id_header_size = size;
1134 static void perf_group_attach(struct perf_event *event)
1136 struct perf_event *group_leader = event->group_leader, *pos;
1139 * We can have double attach due to group movement in perf_event_open.
1141 if (event->attach_state & PERF_ATTACH_GROUP)
1144 event->attach_state |= PERF_ATTACH_GROUP;
1146 if (group_leader == event)
1149 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1150 !is_software_event(event))
1151 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1153 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1154 group_leader->nr_siblings++;
1156 perf_event__header_size(group_leader);
1158 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1159 perf_event__header_size(pos);
1163 * Remove a event from the lists for its context.
1164 * Must be called with ctx->mutex and ctx->lock held.
1167 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1169 struct perf_cpu_context *cpuctx;
1171 * We can have double detach due to exit/hot-unplug + close.
1173 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1176 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1178 if (is_cgroup_event(event)) {
1180 cpuctx = __get_cpu_context(ctx);
1182 * if there are no more cgroup events
1183 * then cler cgrp to avoid stale pointer
1184 * in update_cgrp_time_from_cpuctx()
1186 if (!ctx->nr_cgroups)
1187 cpuctx->cgrp = NULL;
1190 if (has_branch_stack(event))
1191 ctx->nr_branch_stack--;
1194 if (event->attr.inherit_stat)
1197 list_del_rcu(&event->event_entry);
1199 if (event->group_leader == event)
1200 list_del_init(&event->group_entry);
1202 update_group_times(event);
1205 * If event was in error state, then keep it
1206 * that way, otherwise bogus counts will be
1207 * returned on read(). The only way to get out
1208 * of error state is by explicit re-enabling
1211 if (event->state > PERF_EVENT_STATE_OFF)
1212 event->state = PERF_EVENT_STATE_OFF;
1215 static void perf_group_detach(struct perf_event *event)
1217 struct perf_event *sibling, *tmp;
1218 struct list_head *list = NULL;
1221 * We can have double detach due to exit/hot-unplug + close.
1223 if (!(event->attach_state & PERF_ATTACH_GROUP))
1226 event->attach_state &= ~PERF_ATTACH_GROUP;
1229 * If this is a sibling, remove it from its group.
1231 if (event->group_leader != event) {
1232 list_del_init(&event->group_entry);
1233 event->group_leader->nr_siblings--;
1237 if (!list_empty(&event->group_entry))
1238 list = &event->group_entry;
1241 * If this was a group event with sibling events then
1242 * upgrade the siblings to singleton events by adding them
1243 * to whatever list we are on.
1245 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1247 list_move_tail(&sibling->group_entry, list);
1248 sibling->group_leader = sibling;
1250 /* Inherit group flags from the previous leader */
1251 sibling->group_flags = event->group_flags;
1255 perf_event__header_size(event->group_leader);
1257 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1258 perf_event__header_size(tmp);
1262 event_filter_match(struct perf_event *event)
1264 return (event->cpu == -1 || event->cpu == smp_processor_id())
1265 && perf_cgroup_match(event);
1269 event_sched_out(struct perf_event *event,
1270 struct perf_cpu_context *cpuctx,
1271 struct perf_event_context *ctx)
1273 u64 tstamp = perf_event_time(event);
1276 * An event which could not be activated because of
1277 * filter mismatch still needs to have its timings
1278 * maintained, otherwise bogus information is return
1279 * via read() for time_enabled, time_running:
1281 if (event->state == PERF_EVENT_STATE_INACTIVE
1282 && !event_filter_match(event)) {
1283 delta = tstamp - event->tstamp_stopped;
1284 event->tstamp_running += delta;
1285 event->tstamp_stopped = tstamp;
1288 if (event->state != PERF_EVENT_STATE_ACTIVE)
1291 event->state = PERF_EVENT_STATE_INACTIVE;
1292 if (event->pending_disable) {
1293 event->pending_disable = 0;
1294 event->state = PERF_EVENT_STATE_OFF;
1296 event->tstamp_stopped = tstamp;
1297 event->pmu->del(event, 0);
1300 if (!is_software_event(event))
1301 cpuctx->active_oncpu--;
1303 if (event->attr.freq && event->attr.sample_freq)
1305 if (event->attr.exclusive || !cpuctx->active_oncpu)
1306 cpuctx->exclusive = 0;
1310 group_sched_out(struct perf_event *group_event,
1311 struct perf_cpu_context *cpuctx,
1312 struct perf_event_context *ctx)
1314 struct perf_event *event;
1315 int state = group_event->state;
1317 event_sched_out(group_event, cpuctx, ctx);
1320 * Schedule out siblings (if any):
1322 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1323 event_sched_out(event, cpuctx, ctx);
1325 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1326 cpuctx->exclusive = 0;
1330 * Cross CPU call to remove a performance event
1332 * We disable the event on the hardware level first. After that we
1333 * remove it from the context list.
1335 static int __perf_remove_from_context(void *info)
1337 struct perf_event *event = info;
1338 struct perf_event_context *ctx = event->ctx;
1339 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1341 raw_spin_lock(&ctx->lock);
1342 event_sched_out(event, cpuctx, ctx);
1343 list_del_event(event, ctx);
1344 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1346 cpuctx->task_ctx = NULL;
1348 raw_spin_unlock(&ctx->lock);
1355 * Remove the event from a task's (or a CPU's) list of events.
1357 * CPU events are removed with a smp call. For task events we only
1358 * call when the task is on a CPU.
1360 * If event->ctx is a cloned context, callers must make sure that
1361 * every task struct that event->ctx->task could possibly point to
1362 * remains valid. This is OK when called from perf_release since
1363 * that only calls us on the top-level context, which can't be a clone.
1364 * When called from perf_event_exit_task, it's OK because the
1365 * context has been detached from its task.
1367 static void perf_remove_from_context(struct perf_event *event)
1369 struct perf_event_context *ctx = event->ctx;
1370 struct task_struct *task = ctx->task;
1372 lockdep_assert_held(&ctx->mutex);
1376 * Per cpu events are removed via an smp call and
1377 * the removal is always successful.
1379 cpu_function_call(event->cpu, __perf_remove_from_context, event);
1384 if (!task_function_call(task, __perf_remove_from_context, event))
1387 raw_spin_lock_irq(&ctx->lock);
1389 * If we failed to find a running task, but find the context active now
1390 * that we've acquired the ctx->lock, retry.
1392 if (ctx->is_active) {
1393 raw_spin_unlock_irq(&ctx->lock);
1398 * Since the task isn't running, its safe to remove the event, us
1399 * holding the ctx->lock ensures the task won't get scheduled in.
1401 list_del_event(event, ctx);
1402 raw_spin_unlock_irq(&ctx->lock);
1406 * Cross CPU call to disable a performance event
1408 int __perf_event_disable(void *info)
1410 struct perf_event *event = info;
1411 struct perf_event_context *ctx = event->ctx;
1412 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1415 * If this is a per-task event, need to check whether this
1416 * event's task is the current task on this cpu.
1418 * Can trigger due to concurrent perf_event_context_sched_out()
1419 * flipping contexts around.
1421 if (ctx->task && cpuctx->task_ctx != ctx)
1424 raw_spin_lock(&ctx->lock);
1427 * If the event is on, turn it off.
1428 * If it is in error state, leave it in error state.
1430 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1431 update_context_time(ctx);
1432 update_cgrp_time_from_event(event);
1433 update_group_times(event);
1434 if (event == event->group_leader)
1435 group_sched_out(event, cpuctx, ctx);
1437 event_sched_out(event, cpuctx, ctx);
1438 event->state = PERF_EVENT_STATE_OFF;
1441 raw_spin_unlock(&ctx->lock);
1449 * If event->ctx is a cloned context, callers must make sure that
1450 * every task struct that event->ctx->task could possibly point to
1451 * remains valid. This condition is satisifed when called through
1452 * perf_event_for_each_child or perf_event_for_each because they
1453 * hold the top-level event's child_mutex, so any descendant that
1454 * goes to exit will block in sync_child_event.
1455 * When called from perf_pending_event it's OK because event->ctx
1456 * is the current context on this CPU and preemption is disabled,
1457 * hence we can't get into perf_event_task_sched_out for this context.
1459 void perf_event_disable(struct perf_event *event)
1461 struct perf_event_context *ctx = event->ctx;
1462 struct task_struct *task = ctx->task;
1466 * Disable the event on the cpu that it's on
1468 cpu_function_call(event->cpu, __perf_event_disable, event);
1473 if (!task_function_call(task, __perf_event_disable, event))
1476 raw_spin_lock_irq(&ctx->lock);
1478 * If the event is still active, we need to retry the cross-call.
1480 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1481 raw_spin_unlock_irq(&ctx->lock);
1483 * Reload the task pointer, it might have been changed by
1484 * a concurrent perf_event_context_sched_out().
1491 * Since we have the lock this context can't be scheduled
1492 * in, so we can change the state safely.
1494 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1495 update_group_times(event);
1496 event->state = PERF_EVENT_STATE_OFF;
1498 raw_spin_unlock_irq(&ctx->lock);
1500 EXPORT_SYMBOL_GPL(perf_event_disable);
1502 static void perf_set_shadow_time(struct perf_event *event,
1503 struct perf_event_context *ctx,
1507 * use the correct time source for the time snapshot
1509 * We could get by without this by leveraging the
1510 * fact that to get to this function, the caller
1511 * has most likely already called update_context_time()
1512 * and update_cgrp_time_xx() and thus both timestamp
1513 * are identical (or very close). Given that tstamp is,
1514 * already adjusted for cgroup, we could say that:
1515 * tstamp - ctx->timestamp
1517 * tstamp - cgrp->timestamp.
1519 * Then, in perf_output_read(), the calculation would
1520 * work with no changes because:
1521 * - event is guaranteed scheduled in
1522 * - no scheduled out in between
1523 * - thus the timestamp would be the same
1525 * But this is a bit hairy.
1527 * So instead, we have an explicit cgroup call to remain
1528 * within the time time source all along. We believe it
1529 * is cleaner and simpler to understand.
1531 if (is_cgroup_event(event))
1532 perf_cgroup_set_shadow_time(event, tstamp);
1534 event->shadow_ctx_time = tstamp - ctx->timestamp;
1537 #define MAX_INTERRUPTS (~0ULL)
1539 static void perf_log_throttle(struct perf_event *event, int enable);
1542 event_sched_in(struct perf_event *event,
1543 struct perf_cpu_context *cpuctx,
1544 struct perf_event_context *ctx)
1546 u64 tstamp = perf_event_time(event);
1548 if (event->state <= PERF_EVENT_STATE_OFF)
1551 event->state = PERF_EVENT_STATE_ACTIVE;
1552 event->oncpu = smp_processor_id();
1555 * Unthrottle events, since we scheduled we might have missed several
1556 * ticks already, also for a heavily scheduling task there is little
1557 * guarantee it'll get a tick in a timely manner.
1559 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1560 perf_log_throttle(event, 1);
1561 event->hw.interrupts = 0;
1565 * The new state must be visible before we turn it on in the hardware:
1569 if (event->pmu->add(event, PERF_EF_START)) {
1570 event->state = PERF_EVENT_STATE_INACTIVE;
1575 event->tstamp_running += tstamp - event->tstamp_stopped;
1577 perf_set_shadow_time(event, ctx, tstamp);
1579 if (!is_software_event(event))
1580 cpuctx->active_oncpu++;
1582 if (event->attr.freq && event->attr.sample_freq)
1585 if (event->attr.exclusive)
1586 cpuctx->exclusive = 1;
1592 group_sched_in(struct perf_event *group_event,
1593 struct perf_cpu_context *cpuctx,
1594 struct perf_event_context *ctx)
1596 struct perf_event *event, *partial_group = NULL;
1597 struct pmu *pmu = group_event->pmu;
1598 u64 now = ctx->time;
1599 bool simulate = false;
1601 if (group_event->state == PERF_EVENT_STATE_OFF)
1604 pmu->start_txn(pmu);
1606 if (event_sched_in(group_event, cpuctx, ctx)) {
1607 pmu->cancel_txn(pmu);
1608 perf_cpu_hrtimer_restart(cpuctx);
1613 * Schedule in siblings as one group (if any):
1615 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1616 if (event_sched_in(event, cpuctx, ctx)) {
1617 partial_group = event;
1622 if (!pmu->commit_txn(pmu))
1627 * Groups can be scheduled in as one unit only, so undo any
1628 * partial group before returning:
1629 * The events up to the failed event are scheduled out normally,
1630 * tstamp_stopped will be updated.
1632 * The failed events and the remaining siblings need to have
1633 * their timings updated as if they had gone thru event_sched_in()
1634 * and event_sched_out(). This is required to get consistent timings
1635 * across the group. This also takes care of the case where the group
1636 * could never be scheduled by ensuring tstamp_stopped is set to mark
1637 * the time the event was actually stopped, such that time delta
1638 * calculation in update_event_times() is correct.
1640 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1641 if (event == partial_group)
1645 event->tstamp_running += now - event->tstamp_stopped;
1646 event->tstamp_stopped = now;
1648 event_sched_out(event, cpuctx, ctx);
1651 event_sched_out(group_event, cpuctx, ctx);
1653 pmu->cancel_txn(pmu);
1655 perf_cpu_hrtimer_restart(cpuctx);
1661 * Work out whether we can put this event group on the CPU now.
1663 static int group_can_go_on(struct perf_event *event,
1664 struct perf_cpu_context *cpuctx,
1668 * Groups consisting entirely of software events can always go on.
1670 if (event->group_flags & PERF_GROUP_SOFTWARE)
1673 * If an exclusive group is already on, no other hardware
1676 if (cpuctx->exclusive)
1679 * If this group is exclusive and there are already
1680 * events on the CPU, it can't go on.
1682 if (event->attr.exclusive && cpuctx->active_oncpu)
1685 * Otherwise, try to add it if all previous groups were able
1691 static void add_event_to_ctx(struct perf_event *event,
1692 struct perf_event_context *ctx)
1694 u64 tstamp = perf_event_time(event);
1696 list_add_event(event, ctx);
1697 perf_group_attach(event);
1698 event->tstamp_enabled = tstamp;
1699 event->tstamp_running = tstamp;
1700 event->tstamp_stopped = tstamp;
1703 static void task_ctx_sched_out(struct perf_event_context *ctx);
1705 ctx_sched_in(struct perf_event_context *ctx,
1706 struct perf_cpu_context *cpuctx,
1707 enum event_type_t event_type,
1708 struct task_struct *task);
1710 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
1711 struct perf_event_context *ctx,
1712 struct task_struct *task)
1714 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
1716 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
1717 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
1719 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
1723 * Cross CPU call to install and enable a performance event
1725 * Must be called with ctx->mutex held
1727 static int __perf_install_in_context(void *info)
1729 struct perf_event *event = info;
1730 struct perf_event_context *ctx = event->ctx;
1731 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1732 struct perf_event_context *task_ctx = cpuctx->task_ctx;
1733 struct task_struct *task = current;
1735 perf_ctx_lock(cpuctx, task_ctx);
1736 perf_pmu_disable(cpuctx->ctx.pmu);
1739 * If there was an active task_ctx schedule it out.
1742 task_ctx_sched_out(task_ctx);
1745 * If the context we're installing events in is not the
1746 * active task_ctx, flip them.
1748 if (ctx->task && task_ctx != ctx) {
1750 raw_spin_unlock(&task_ctx->lock);
1751 raw_spin_lock(&ctx->lock);
1756 cpuctx->task_ctx = task_ctx;
1757 task = task_ctx->task;
1760 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
1762 update_context_time(ctx);
1764 * update cgrp time only if current cgrp
1765 * matches event->cgrp. Must be done before
1766 * calling add_event_to_ctx()
1768 update_cgrp_time_from_event(event);
1770 add_event_to_ctx(event, ctx);
1773 * Schedule everything back in
1775 perf_event_sched_in(cpuctx, task_ctx, task);
1777 perf_pmu_enable(cpuctx->ctx.pmu);
1778 perf_ctx_unlock(cpuctx, task_ctx);
1784 * Attach a performance event to a context
1786 * First we add the event to the list with the hardware enable bit
1787 * in event->hw_config cleared.
1789 * If the event is attached to a task which is on a CPU we use a smp
1790 * call to enable it in the task context. The task might have been
1791 * scheduled away, but we check this in the smp call again.
1794 perf_install_in_context(struct perf_event_context *ctx,
1795 struct perf_event *event,
1798 struct task_struct *task = ctx->task;
1800 lockdep_assert_held(&ctx->mutex);
1803 if (event->cpu != -1)
1808 * Per cpu events are installed via an smp call and
1809 * the install is always successful.
1811 cpu_function_call(cpu, __perf_install_in_context, event);
1816 if (!task_function_call(task, __perf_install_in_context, event))
1819 raw_spin_lock_irq(&ctx->lock);
1821 * If we failed to find a running task, but find the context active now
1822 * that we've acquired the ctx->lock, retry.
1824 if (ctx->is_active) {
1825 raw_spin_unlock_irq(&ctx->lock);
1830 * Since the task isn't running, its safe to add the event, us holding
1831 * the ctx->lock ensures the task won't get scheduled in.
1833 add_event_to_ctx(event, ctx);
1834 raw_spin_unlock_irq(&ctx->lock);
1838 * Put a event into inactive state and update time fields.
1839 * Enabling the leader of a group effectively enables all
1840 * the group members that aren't explicitly disabled, so we
1841 * have to update their ->tstamp_enabled also.
1842 * Note: this works for group members as well as group leaders
1843 * since the non-leader members' sibling_lists will be empty.
1845 static void __perf_event_mark_enabled(struct perf_event *event)
1847 struct perf_event *sub;
1848 u64 tstamp = perf_event_time(event);
1850 event->state = PERF_EVENT_STATE_INACTIVE;
1851 event->tstamp_enabled = tstamp - event->total_time_enabled;
1852 list_for_each_entry(sub, &event->sibling_list, group_entry) {
1853 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
1854 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
1859 * Cross CPU call to enable a performance event
1861 static int __perf_event_enable(void *info)
1863 struct perf_event *event = info;
1864 struct perf_event_context *ctx = event->ctx;
1865 struct perf_event *leader = event->group_leader;
1866 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1869 if (WARN_ON_ONCE(!ctx->is_active))
1872 raw_spin_lock(&ctx->lock);
1873 update_context_time(ctx);
1875 if (event->state >= PERF_EVENT_STATE_INACTIVE)
1879 * set current task's cgroup time reference point
1881 perf_cgroup_set_timestamp(current, ctx);
1883 __perf_event_mark_enabled(event);
1885 if (!event_filter_match(event)) {
1886 if (is_cgroup_event(event))
1887 perf_cgroup_defer_enabled(event);
1892 * If the event is in a group and isn't the group leader,
1893 * then don't put it on unless the group is on.
1895 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
1898 if (!group_can_go_on(event, cpuctx, 1)) {
1901 if (event == leader)
1902 err = group_sched_in(event, cpuctx, ctx);
1904 err = event_sched_in(event, cpuctx, ctx);
1909 * If this event can't go on and it's part of a
1910 * group, then the whole group has to come off.
1912 if (leader != event) {
1913 group_sched_out(leader, cpuctx, ctx);
1914 perf_cpu_hrtimer_restart(cpuctx);
1916 if (leader->attr.pinned) {
1917 update_group_times(leader);
1918 leader->state = PERF_EVENT_STATE_ERROR;
1923 raw_spin_unlock(&ctx->lock);
1931 * If event->ctx is a cloned context, callers must make sure that
1932 * every task struct that event->ctx->task could possibly point to
1933 * remains valid. This condition is satisfied when called through
1934 * perf_event_for_each_child or perf_event_for_each as described
1935 * for perf_event_disable.
1937 void perf_event_enable(struct perf_event *event)
1939 struct perf_event_context *ctx = event->ctx;
1940 struct task_struct *task = ctx->task;
1944 * Enable the event on the cpu that it's on
1946 cpu_function_call(event->cpu, __perf_event_enable, event);
1950 raw_spin_lock_irq(&ctx->lock);
1951 if (event->state >= PERF_EVENT_STATE_INACTIVE)
1955 * If the event is in error state, clear that first.
1956 * That way, if we see the event in error state below, we
1957 * know that it has gone back into error state, as distinct
1958 * from the task having been scheduled away before the
1959 * cross-call arrived.
1961 if (event->state == PERF_EVENT_STATE_ERROR)
1962 event->state = PERF_EVENT_STATE_OFF;
1965 if (!ctx->is_active) {
1966 __perf_event_mark_enabled(event);
1970 raw_spin_unlock_irq(&ctx->lock);
1972 if (!task_function_call(task, __perf_event_enable, event))
1975 raw_spin_lock_irq(&ctx->lock);
1978 * If the context is active and the event is still off,
1979 * we need to retry the cross-call.
1981 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
1983 * task could have been flipped by a concurrent
1984 * perf_event_context_sched_out()
1991 raw_spin_unlock_irq(&ctx->lock);
1993 EXPORT_SYMBOL_GPL(perf_event_enable);
1995 int perf_event_refresh(struct perf_event *event, int refresh)
1998 * not supported on inherited events
2000 if (event->attr.inherit || !is_sampling_event(event))
2003 atomic_add(refresh, &event->event_limit);
2004 perf_event_enable(event);
2008 EXPORT_SYMBOL_GPL(perf_event_refresh);
2010 static void ctx_sched_out(struct perf_event_context *ctx,
2011 struct perf_cpu_context *cpuctx,
2012 enum event_type_t event_type)
2014 struct perf_event *event;
2015 int is_active = ctx->is_active;
2017 ctx->is_active &= ~event_type;
2018 if (likely(!ctx->nr_events))
2021 update_context_time(ctx);
2022 update_cgrp_time_from_cpuctx(cpuctx);
2023 if (!ctx->nr_active)
2026 perf_pmu_disable(ctx->pmu);
2027 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2028 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2029 group_sched_out(event, cpuctx, ctx);
2032 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2033 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2034 group_sched_out(event, cpuctx, ctx);
2036 perf_pmu_enable(ctx->pmu);
2040 * Test whether two contexts are equivalent, i.e. whether they
2041 * have both been cloned from the same version of the same context
2042 * and they both have the same number of enabled events.
2043 * If the number of enabled events is the same, then the set
2044 * of enabled events should be the same, because these are both
2045 * inherited contexts, therefore we can't access individual events
2046 * in them directly with an fd; we can only enable/disable all
2047 * events via prctl, or enable/disable all events in a family
2048 * via ioctl, which will have the same effect on both contexts.
2050 static int context_equiv(struct perf_event_context *ctx1,
2051 struct perf_event_context *ctx2)
2053 return ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx
2054 && ctx1->parent_gen == ctx2->parent_gen
2055 && !ctx1->pin_count && !ctx2->pin_count;
2058 static void __perf_event_sync_stat(struct perf_event *event,
2059 struct perf_event *next_event)
2063 if (!event->attr.inherit_stat)
2067 * Update the event value, we cannot use perf_event_read()
2068 * because we're in the middle of a context switch and have IRQs
2069 * disabled, which upsets smp_call_function_single(), however
2070 * we know the event must be on the current CPU, therefore we
2071 * don't need to use it.
2073 switch (event->state) {
2074 case PERF_EVENT_STATE_ACTIVE:
2075 event->pmu->read(event);
2078 case PERF_EVENT_STATE_INACTIVE:
2079 update_event_times(event);
2087 * In order to keep per-task stats reliable we need to flip the event
2088 * values when we flip the contexts.
2090 value = local64_read(&next_event->count);
2091 value = local64_xchg(&event->count, value);
2092 local64_set(&next_event->count, value);
2094 swap(event->total_time_enabled, next_event->total_time_enabled);
2095 swap(event->total_time_running, next_event->total_time_running);
2098 * Since we swizzled the values, update the user visible data too.
2100 perf_event_update_userpage(event);
2101 perf_event_update_userpage(next_event);
2104 #define list_next_entry(pos, member) \
2105 list_entry(pos->member.next, typeof(*pos), member)
2107 static void perf_event_sync_stat(struct perf_event_context *ctx,
2108 struct perf_event_context *next_ctx)
2110 struct perf_event *event, *next_event;
2115 update_context_time(ctx);
2117 event = list_first_entry(&ctx->event_list,
2118 struct perf_event, event_entry);
2120 next_event = list_first_entry(&next_ctx->event_list,
2121 struct perf_event, event_entry);
2123 while (&event->event_entry != &ctx->event_list &&
2124 &next_event->event_entry != &next_ctx->event_list) {
2126 __perf_event_sync_stat(event, next_event);
2128 event = list_next_entry(event, event_entry);
2129 next_event = list_next_entry(next_event, event_entry);
2133 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2134 struct task_struct *next)
2136 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2137 struct perf_event_context *next_ctx;
2138 struct perf_event_context *parent;
2139 struct perf_cpu_context *cpuctx;
2145 cpuctx = __get_cpu_context(ctx);
2146 if (!cpuctx->task_ctx)
2150 parent = rcu_dereference(ctx->parent_ctx);
2151 next_ctx = next->perf_event_ctxp[ctxn];
2152 if (parent && next_ctx &&
2153 rcu_dereference(next_ctx->parent_ctx) == parent) {
2155 * Looks like the two contexts are clones, so we might be
2156 * able to optimize the context switch. We lock both
2157 * contexts and check that they are clones under the
2158 * lock (including re-checking that neither has been
2159 * uncloned in the meantime). It doesn't matter which
2160 * order we take the locks because no other cpu could
2161 * be trying to lock both of these tasks.
2163 raw_spin_lock(&ctx->lock);
2164 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2165 if (context_equiv(ctx, next_ctx)) {
2167 * XXX do we need a memory barrier of sorts
2168 * wrt to rcu_dereference() of perf_event_ctxp
2170 task->perf_event_ctxp[ctxn] = next_ctx;
2171 next->perf_event_ctxp[ctxn] = ctx;
2173 next_ctx->task = task;
2176 perf_event_sync_stat(ctx, next_ctx);
2178 raw_spin_unlock(&next_ctx->lock);
2179 raw_spin_unlock(&ctx->lock);
2184 raw_spin_lock(&ctx->lock);
2185 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2186 cpuctx->task_ctx = NULL;
2187 raw_spin_unlock(&ctx->lock);
2191 #define for_each_task_context_nr(ctxn) \
2192 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2195 * Called from scheduler to remove the events of the current task,
2196 * with interrupts disabled.
2198 * We stop each event and update the event value in event->count.
2200 * This does not protect us against NMI, but disable()
2201 * sets the disabled bit in the control field of event _before_
2202 * accessing the event control register. If a NMI hits, then it will
2203 * not restart the event.
2205 void __perf_event_task_sched_out(struct task_struct *task,
2206 struct task_struct *next)
2210 for_each_task_context_nr(ctxn)
2211 perf_event_context_sched_out(task, ctxn, next);
2214 * if cgroup events exist on this CPU, then we need
2215 * to check if we have to switch out PMU state.
2216 * cgroup event are system-wide mode only
2218 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2219 perf_cgroup_sched_out(task, next);
2222 static void task_ctx_sched_out(struct perf_event_context *ctx)
2224 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2226 if (!cpuctx->task_ctx)
2229 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2232 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2233 cpuctx->task_ctx = NULL;
2237 * Called with IRQs disabled
2239 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2240 enum event_type_t event_type)
2242 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2246 ctx_pinned_sched_in(struct perf_event_context *ctx,
2247 struct perf_cpu_context *cpuctx)
2249 struct perf_event *event;
2251 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2252 if (event->state <= PERF_EVENT_STATE_OFF)
2254 if (!event_filter_match(event))
2257 /* may need to reset tstamp_enabled */
2258 if (is_cgroup_event(event))
2259 perf_cgroup_mark_enabled(event, ctx);
2261 if (group_can_go_on(event, cpuctx, 1))
2262 group_sched_in(event, cpuctx, ctx);
2265 * If this pinned group hasn't been scheduled,
2266 * put it in error state.
2268 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2269 update_group_times(event);
2270 event->state = PERF_EVENT_STATE_ERROR;
2276 ctx_flexible_sched_in(struct perf_event_context *ctx,
2277 struct perf_cpu_context *cpuctx)
2279 struct perf_event *event;
2282 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2283 /* Ignore events in OFF or ERROR state */
2284 if (event->state <= PERF_EVENT_STATE_OFF)
2287 * Listen to the 'cpu' scheduling filter constraint
2290 if (!event_filter_match(event))
2293 /* may need to reset tstamp_enabled */
2294 if (is_cgroup_event(event))
2295 perf_cgroup_mark_enabled(event, ctx);
2297 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2298 if (group_sched_in(event, cpuctx, ctx))
2305 ctx_sched_in(struct perf_event_context *ctx,
2306 struct perf_cpu_context *cpuctx,
2307 enum event_type_t event_type,
2308 struct task_struct *task)
2311 int is_active = ctx->is_active;
2313 ctx->is_active |= event_type;
2314 if (likely(!ctx->nr_events))
2318 ctx->timestamp = now;
2319 perf_cgroup_set_timestamp(task, ctx);
2321 * First go through the list and put on any pinned groups
2322 * in order to give them the best chance of going on.
2324 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2325 ctx_pinned_sched_in(ctx, cpuctx);
2327 /* Then walk through the lower prio flexible groups */
2328 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2329 ctx_flexible_sched_in(ctx, cpuctx);
2332 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2333 enum event_type_t event_type,
2334 struct task_struct *task)
2336 struct perf_event_context *ctx = &cpuctx->ctx;
2338 ctx_sched_in(ctx, cpuctx, event_type, task);
2341 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2342 struct task_struct *task)
2344 struct perf_cpu_context *cpuctx;
2346 cpuctx = __get_cpu_context(ctx);
2347 if (cpuctx->task_ctx == ctx)
2350 perf_ctx_lock(cpuctx, ctx);
2351 perf_pmu_disable(ctx->pmu);
2353 * We want to keep the following priority order:
2354 * cpu pinned (that don't need to move), task pinned,
2355 * cpu flexible, task flexible.
2357 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2360 cpuctx->task_ctx = ctx;
2362 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2364 perf_pmu_enable(ctx->pmu);
2365 perf_ctx_unlock(cpuctx, ctx);
2368 * Since these rotations are per-cpu, we need to ensure the
2369 * cpu-context we got scheduled on is actually rotating.
2371 perf_pmu_rotate_start(ctx->pmu);
2375 * When sampling the branck stack in system-wide, it may be necessary
2376 * to flush the stack on context switch. This happens when the branch
2377 * stack does not tag its entries with the pid of the current task.
2378 * Otherwise it becomes impossible to associate a branch entry with a
2379 * task. This ambiguity is more likely to appear when the branch stack
2380 * supports priv level filtering and the user sets it to monitor only
2381 * at the user level (which could be a useful measurement in system-wide
2382 * mode). In that case, the risk is high of having a branch stack with
2383 * branch from multiple tasks. Flushing may mean dropping the existing
2384 * entries or stashing them somewhere in the PMU specific code layer.
2386 * This function provides the context switch callback to the lower code
2387 * layer. It is invoked ONLY when there is at least one system-wide context
2388 * with at least one active event using taken branch sampling.
2390 static void perf_branch_stack_sched_in(struct task_struct *prev,
2391 struct task_struct *task)
2393 struct perf_cpu_context *cpuctx;
2395 unsigned long flags;
2397 /* no need to flush branch stack if not changing task */
2401 local_irq_save(flags);
2405 list_for_each_entry_rcu(pmu, &pmus, entry) {
2406 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2409 * check if the context has at least one
2410 * event using PERF_SAMPLE_BRANCH_STACK
2412 if (cpuctx->ctx.nr_branch_stack > 0
2413 && pmu->flush_branch_stack) {
2415 pmu = cpuctx->ctx.pmu;
2417 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2419 perf_pmu_disable(pmu);
2421 pmu->flush_branch_stack();
2423 perf_pmu_enable(pmu);
2425 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2431 local_irq_restore(flags);
2435 * Called from scheduler to add the events of the current task
2436 * with interrupts disabled.
2438 * We restore the event value and then enable it.
2440 * This does not protect us against NMI, but enable()
2441 * sets the enabled bit in the control field of event _before_
2442 * accessing the event control register. If a NMI hits, then it will
2443 * keep the event running.
2445 void __perf_event_task_sched_in(struct task_struct *prev,
2446 struct task_struct *task)
2448 struct perf_event_context *ctx;
2451 for_each_task_context_nr(ctxn) {
2452 ctx = task->perf_event_ctxp[ctxn];
2456 perf_event_context_sched_in(ctx, task);
2459 * if cgroup events exist on this CPU, then we need
2460 * to check if we have to switch in PMU state.
2461 * cgroup event are system-wide mode only
2463 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2464 perf_cgroup_sched_in(prev, task);
2466 /* check for system-wide branch_stack events */
2467 if (atomic_read(&__get_cpu_var(perf_branch_stack_events)))
2468 perf_branch_stack_sched_in(prev, task);
2471 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2473 u64 frequency = event->attr.sample_freq;
2474 u64 sec = NSEC_PER_SEC;
2475 u64 divisor, dividend;
2477 int count_fls, nsec_fls, frequency_fls, sec_fls;
2479 count_fls = fls64(count);
2480 nsec_fls = fls64(nsec);
2481 frequency_fls = fls64(frequency);
2485 * We got @count in @nsec, with a target of sample_freq HZ
2486 * the target period becomes:
2489 * period = -------------------
2490 * @nsec * sample_freq
2495 * Reduce accuracy by one bit such that @a and @b converge
2496 * to a similar magnitude.
2498 #define REDUCE_FLS(a, b) \
2500 if (a##_fls > b##_fls) { \
2510 * Reduce accuracy until either term fits in a u64, then proceed with
2511 * the other, so that finally we can do a u64/u64 division.
2513 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2514 REDUCE_FLS(nsec, frequency);
2515 REDUCE_FLS(sec, count);
2518 if (count_fls + sec_fls > 64) {
2519 divisor = nsec * frequency;
2521 while (count_fls + sec_fls > 64) {
2522 REDUCE_FLS(count, sec);
2526 dividend = count * sec;
2528 dividend = count * sec;
2530 while (nsec_fls + frequency_fls > 64) {
2531 REDUCE_FLS(nsec, frequency);
2535 divisor = nsec * frequency;
2541 return div64_u64(dividend, divisor);
2544 static DEFINE_PER_CPU(int, perf_throttled_count);
2545 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2547 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2549 struct hw_perf_event *hwc = &event->hw;
2550 s64 period, sample_period;
2553 period = perf_calculate_period(event, nsec, count);
2555 delta = (s64)(period - hwc->sample_period);
2556 delta = (delta + 7) / 8; /* low pass filter */
2558 sample_period = hwc->sample_period + delta;
2563 hwc->sample_period = sample_period;
2565 if (local64_read(&hwc->period_left) > 8*sample_period) {
2567 event->pmu->stop(event, PERF_EF_UPDATE);
2569 local64_set(&hwc->period_left, 0);
2572 event->pmu->start(event, PERF_EF_RELOAD);
2577 * combine freq adjustment with unthrottling to avoid two passes over the
2578 * events. At the same time, make sure, having freq events does not change
2579 * the rate of unthrottling as that would introduce bias.
2581 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
2584 struct perf_event *event;
2585 struct hw_perf_event *hwc;
2586 u64 now, period = TICK_NSEC;
2590 * only need to iterate over all events iff:
2591 * - context have events in frequency mode (needs freq adjust)
2592 * - there are events to unthrottle on this cpu
2594 if (!(ctx->nr_freq || needs_unthr))
2597 raw_spin_lock(&ctx->lock);
2598 perf_pmu_disable(ctx->pmu);
2600 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
2601 if (event->state != PERF_EVENT_STATE_ACTIVE)
2604 if (!event_filter_match(event))
2609 if (needs_unthr && hwc->interrupts == MAX_INTERRUPTS) {
2610 hwc->interrupts = 0;
2611 perf_log_throttle(event, 1);
2612 event->pmu->start(event, 0);
2615 if (!event->attr.freq || !event->attr.sample_freq)
2619 * stop the event and update event->count
2621 event->pmu->stop(event, PERF_EF_UPDATE);
2623 now = local64_read(&event->count);
2624 delta = now - hwc->freq_count_stamp;
2625 hwc->freq_count_stamp = now;
2629 * reload only if value has changed
2630 * we have stopped the event so tell that
2631 * to perf_adjust_period() to avoid stopping it
2635 perf_adjust_period(event, period, delta, false);
2637 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
2640 perf_pmu_enable(ctx->pmu);
2641 raw_spin_unlock(&ctx->lock);
2645 * Round-robin a context's events:
2647 static void rotate_ctx(struct perf_event_context *ctx)
2650 * Rotate the first entry last of non-pinned groups. Rotation might be
2651 * disabled by the inheritance code.
2653 if (!ctx->rotate_disable)
2654 list_rotate_left(&ctx->flexible_groups);
2658 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
2659 * because they're strictly cpu affine and rotate_start is called with IRQs
2660 * disabled, while rotate_context is called from IRQ context.
2662 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
2664 struct perf_event_context *ctx = NULL;
2665 int rotate = 0, remove = 1;
2667 if (cpuctx->ctx.nr_events) {
2669 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
2673 ctx = cpuctx->task_ctx;
2674 if (ctx && ctx->nr_events) {
2676 if (ctx->nr_events != ctx->nr_active)
2683 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2684 perf_pmu_disable(cpuctx->ctx.pmu);
2686 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2688 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
2690 rotate_ctx(&cpuctx->ctx);
2694 perf_event_sched_in(cpuctx, ctx, current);
2696 perf_pmu_enable(cpuctx->ctx.pmu);
2697 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2700 list_del_init(&cpuctx->rotation_list);
2705 #ifdef CONFIG_NO_HZ_FULL
2706 bool perf_event_can_stop_tick(void)
2708 if (list_empty(&__get_cpu_var(rotation_list)))
2715 void perf_event_task_tick(void)
2717 struct list_head *head = &__get_cpu_var(rotation_list);
2718 struct perf_cpu_context *cpuctx, *tmp;
2719 struct perf_event_context *ctx;
2722 WARN_ON(!irqs_disabled());
2724 __this_cpu_inc(perf_throttled_seq);
2725 throttled = __this_cpu_xchg(perf_throttled_count, 0);
2727 list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) {
2729 perf_adjust_freq_unthr_context(ctx, throttled);
2731 ctx = cpuctx->task_ctx;
2733 perf_adjust_freq_unthr_context(ctx, throttled);
2737 static int event_enable_on_exec(struct perf_event *event,
2738 struct perf_event_context *ctx)
2740 if (!event->attr.enable_on_exec)
2743 event->attr.enable_on_exec = 0;
2744 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2747 __perf_event_mark_enabled(event);
2753 * Enable all of a task's events that have been marked enable-on-exec.
2754 * This expects task == current.
2756 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
2758 struct perf_event *event;
2759 unsigned long flags;
2763 local_irq_save(flags);
2764 if (!ctx || !ctx->nr_events)
2768 * We must ctxsw out cgroup events to avoid conflict
2769 * when invoking perf_task_event_sched_in() later on
2770 * in this function. Otherwise we end up trying to
2771 * ctxswin cgroup events which are already scheduled
2774 perf_cgroup_sched_out(current, NULL);
2776 raw_spin_lock(&ctx->lock);
2777 task_ctx_sched_out(ctx);
2779 list_for_each_entry(event, &ctx->event_list, event_entry) {
2780 ret = event_enable_on_exec(event, ctx);
2786 * Unclone this context if we enabled any event.
2791 raw_spin_unlock(&ctx->lock);
2794 * Also calls ctxswin for cgroup events, if any:
2796 perf_event_context_sched_in(ctx, ctx->task);
2798 local_irq_restore(flags);
2802 * Cross CPU call to read the hardware event
2804 static void __perf_event_read(void *info)
2806 struct perf_event *event = info;
2807 struct perf_event_context *ctx = event->ctx;
2808 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2811 * If this is a task context, we need to check whether it is
2812 * the current task context of this cpu. If not it has been
2813 * scheduled out before the smp call arrived. In that case
2814 * event->count would have been updated to a recent sample
2815 * when the event was scheduled out.
2817 if (ctx->task && cpuctx->task_ctx != ctx)
2820 raw_spin_lock(&ctx->lock);
2821 if (ctx->is_active) {
2822 update_context_time(ctx);
2823 update_cgrp_time_from_event(event);
2825 update_event_times(event);
2826 if (event->state == PERF_EVENT_STATE_ACTIVE)
2827 event->pmu->read(event);
2828 raw_spin_unlock(&ctx->lock);
2831 static inline u64 perf_event_count(struct perf_event *event)
2833 return local64_read(&event->count) + atomic64_read(&event->child_count);
2836 static u64 perf_event_read(struct perf_event *event)
2839 * If event is enabled and currently active on a CPU, update the
2840 * value in the event structure:
2842 if (event->state == PERF_EVENT_STATE_ACTIVE) {
2843 smp_call_function_single(event->oncpu,
2844 __perf_event_read, event, 1);
2845 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
2846 struct perf_event_context *ctx = event->ctx;
2847 unsigned long flags;
2849 raw_spin_lock_irqsave(&ctx->lock, flags);
2851 * may read while context is not active
2852 * (e.g., thread is blocked), in that case
2853 * we cannot update context time
2855 if (ctx->is_active) {
2856 update_context_time(ctx);
2857 update_cgrp_time_from_event(event);
2859 update_event_times(event);
2860 raw_spin_unlock_irqrestore(&ctx->lock, flags);
2863 return perf_event_count(event);
2867 * Initialize the perf_event context in a task_struct:
2869 static void __perf_event_init_context(struct perf_event_context *ctx)
2871 raw_spin_lock_init(&ctx->lock);
2872 mutex_init(&ctx->mutex);
2873 INIT_LIST_HEAD(&ctx->pinned_groups);
2874 INIT_LIST_HEAD(&ctx->flexible_groups);
2875 INIT_LIST_HEAD(&ctx->event_list);
2876 atomic_set(&ctx->refcount, 1);
2879 static struct perf_event_context *
2880 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
2882 struct perf_event_context *ctx;
2884 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
2888 __perf_event_init_context(ctx);
2891 get_task_struct(task);
2898 static struct task_struct *
2899 find_lively_task_by_vpid(pid_t vpid)
2901 struct task_struct *task;
2908 task = find_task_by_vpid(vpid);
2910 get_task_struct(task);
2914 return ERR_PTR(-ESRCH);
2916 /* Reuse ptrace permission checks for now. */
2918 if (!ptrace_may_access(task, PTRACE_MODE_READ))
2923 put_task_struct(task);
2924 return ERR_PTR(err);
2929 * Returns a matching context with refcount and pincount.
2931 static struct perf_event_context *
2932 find_get_context(struct pmu *pmu, struct task_struct *task, int cpu)
2934 struct perf_event_context *ctx;
2935 struct perf_cpu_context *cpuctx;
2936 unsigned long flags;
2940 /* Must be root to operate on a CPU event: */
2941 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
2942 return ERR_PTR(-EACCES);
2945 * We could be clever and allow to attach a event to an
2946 * offline CPU and activate it when the CPU comes up, but
2949 if (!cpu_online(cpu))
2950 return ERR_PTR(-ENODEV);
2952 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
2961 ctxn = pmu->task_ctx_nr;
2966 ctx = perf_lock_task_context(task, ctxn, &flags);
2970 raw_spin_unlock_irqrestore(&ctx->lock, flags);
2972 ctx = alloc_perf_context(pmu, task);
2978 mutex_lock(&task->perf_event_mutex);
2980 * If it has already passed perf_event_exit_task().
2981 * we must see PF_EXITING, it takes this mutex too.
2983 if (task->flags & PF_EXITING)
2985 else if (task->perf_event_ctxp[ctxn])
2990 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
2992 mutex_unlock(&task->perf_event_mutex);
2994 if (unlikely(err)) {
3006 return ERR_PTR(err);
3009 static void perf_event_free_filter(struct perf_event *event);
3011 static void free_event_rcu(struct rcu_head *head)
3013 struct perf_event *event;
3015 event = container_of(head, struct perf_event, rcu_head);
3017 put_pid_ns(event->ns);
3018 perf_event_free_filter(event);
3022 static void ring_buffer_put(struct ring_buffer *rb);
3023 static void ring_buffer_detach(struct perf_event *event, struct ring_buffer *rb);
3025 static void free_event(struct perf_event *event)
3027 irq_work_sync(&event->pending);
3029 if (!event->parent) {
3030 if (event->attach_state & PERF_ATTACH_TASK)
3031 static_key_slow_dec_deferred(&perf_sched_events);
3032 if (event->attr.mmap || event->attr.mmap_data)
3033 atomic_dec(&nr_mmap_events);
3034 if (event->attr.comm)
3035 atomic_dec(&nr_comm_events);
3036 if (event->attr.task)
3037 atomic_dec(&nr_task_events);
3038 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3039 put_callchain_buffers();
3040 if (is_cgroup_event(event)) {
3041 atomic_dec(&per_cpu(perf_cgroup_events, event->cpu));
3042 static_key_slow_dec_deferred(&perf_sched_events);
3045 if (has_branch_stack(event)) {
3046 static_key_slow_dec_deferred(&perf_sched_events);
3047 /* is system-wide event */
3048 if (!(event->attach_state & PERF_ATTACH_TASK)) {
3049 atomic_dec(&per_cpu(perf_branch_stack_events,
3056 struct ring_buffer *rb;
3059 * Can happen when we close an event with re-directed output.
3061 * Since we have a 0 refcount, perf_mmap_close() will skip
3062 * over us; possibly making our ring_buffer_put() the last.
3064 mutex_lock(&event->mmap_mutex);
3067 rcu_assign_pointer(event->rb, NULL);
3068 ring_buffer_detach(event, rb);
3069 ring_buffer_put(rb); /* could be last */
3071 mutex_unlock(&event->mmap_mutex);
3074 if (is_cgroup_event(event))
3075 perf_detach_cgroup(event);
3078 event->destroy(event);
3081 put_ctx(event->ctx);
3083 call_rcu(&event->rcu_head, free_event_rcu);
3086 int perf_event_release_kernel(struct perf_event *event)
3088 struct perf_event_context *ctx = event->ctx;
3090 WARN_ON_ONCE(ctx->parent_ctx);
3092 * There are two ways this annotation is useful:
3094 * 1) there is a lock recursion from perf_event_exit_task
3095 * see the comment there.
3097 * 2) there is a lock-inversion with mmap_sem through
3098 * perf_event_read_group(), which takes faults while
3099 * holding ctx->mutex, however this is called after
3100 * the last filedesc died, so there is no possibility
3101 * to trigger the AB-BA case.
3103 mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
3104 raw_spin_lock_irq(&ctx->lock);
3105 perf_group_detach(event);
3106 raw_spin_unlock_irq(&ctx->lock);
3107 perf_remove_from_context(event);
3108 mutex_unlock(&ctx->mutex);
3114 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3117 * Called when the last reference to the file is gone.
3119 static void put_event(struct perf_event *event)
3121 struct task_struct *owner;
3123 if (!atomic_long_dec_and_test(&event->refcount))
3127 owner = ACCESS_ONCE(event->owner);
3129 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3130 * !owner it means the list deletion is complete and we can indeed
3131 * free this event, otherwise we need to serialize on
3132 * owner->perf_event_mutex.
3134 smp_read_barrier_depends();
3137 * Since delayed_put_task_struct() also drops the last
3138 * task reference we can safely take a new reference
3139 * while holding the rcu_read_lock().
3141 get_task_struct(owner);
3146 mutex_lock(&owner->perf_event_mutex);
3148 * We have to re-check the event->owner field, if it is cleared
3149 * we raced with perf_event_exit_task(), acquiring the mutex
3150 * ensured they're done, and we can proceed with freeing the
3154 list_del_init(&event->owner_entry);
3155 mutex_unlock(&owner->perf_event_mutex);
3156 put_task_struct(owner);
3159 perf_event_release_kernel(event);
3162 static int perf_release(struct inode *inode, struct file *file)
3164 put_event(file->private_data);
3168 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3170 struct perf_event *child;
3176 mutex_lock(&event->child_mutex);
3177 total += perf_event_read(event);
3178 *enabled += event->total_time_enabled +
3179 atomic64_read(&event->child_total_time_enabled);
3180 *running += event->total_time_running +
3181 atomic64_read(&event->child_total_time_running);
3183 list_for_each_entry(child, &event->child_list, child_list) {
3184 total += perf_event_read(child);
3185 *enabled += child->total_time_enabled;
3186 *running += child->total_time_running;
3188 mutex_unlock(&event->child_mutex);
3192 EXPORT_SYMBOL_GPL(perf_event_read_value);
3194 static int perf_event_read_group(struct perf_event *event,
3195 u64 read_format, char __user *buf)
3197 struct perf_event *leader = event->group_leader, *sub;
3198 int n = 0, size = 0, ret = -EFAULT;
3199 struct perf_event_context *ctx = leader->ctx;
3201 u64 count, enabled, running;
3203 mutex_lock(&ctx->mutex);
3204 count = perf_event_read_value(leader, &enabled, &running);
3206 values[n++] = 1 + leader->nr_siblings;
3207 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3208 values[n++] = enabled;
3209 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3210 values[n++] = running;
3211 values[n++] = count;
3212 if (read_format & PERF_FORMAT_ID)
3213 values[n++] = primary_event_id(leader);
3215 size = n * sizeof(u64);
3217 if (copy_to_user(buf, values, size))
3222 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3225 values[n++] = perf_event_read_value(sub, &enabled, &running);
3226 if (read_format & PERF_FORMAT_ID)
3227 values[n++] = primary_event_id(sub);
3229 size = n * sizeof(u64);
3231 if (copy_to_user(buf + ret, values, size)) {
3239 mutex_unlock(&ctx->mutex);
3244 static int perf_event_read_one(struct perf_event *event,
3245 u64 read_format, char __user *buf)
3247 u64 enabled, running;
3251 values[n++] = perf_event_read_value(event, &enabled, &running);
3252 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3253 values[n++] = enabled;
3254 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3255 values[n++] = running;
3256 if (read_format & PERF_FORMAT_ID)
3257 values[n++] = primary_event_id(event);
3259 if (copy_to_user(buf, values, n * sizeof(u64)))
3262 return n * sizeof(u64);
3266 * Read the performance event - simple non blocking version for now
3269 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
3271 u64 read_format = event->attr.read_format;
3275 * Return end-of-file for a read on a event that is in
3276 * error state (i.e. because it was pinned but it couldn't be
3277 * scheduled on to the CPU at some point).
3279 if (event->state == PERF_EVENT_STATE_ERROR)
3282 if (count < event->read_size)
3285 WARN_ON_ONCE(event->ctx->parent_ctx);
3286 if (read_format & PERF_FORMAT_GROUP)
3287 ret = perf_event_read_group(event, read_format, buf);
3289 ret = perf_event_read_one(event, read_format, buf);
3295 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
3297 struct perf_event *event = file->private_data;
3299 return perf_read_hw(event, buf, count);
3302 static unsigned int perf_poll(struct file *file, poll_table *wait)
3304 struct perf_event *event = file->private_data;
3305 struct ring_buffer *rb;
3306 unsigned int events = POLL_HUP;
3309 * Pin the event->rb by taking event->mmap_mutex; otherwise
3310 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
3312 mutex_lock(&event->mmap_mutex);
3315 events = atomic_xchg(&rb->poll, 0);
3316 mutex_unlock(&event->mmap_mutex);
3318 poll_wait(file, &event->waitq, wait);
3323 static void perf_event_reset(struct perf_event *event)
3325 (void)perf_event_read(event);
3326 local64_set(&event->count, 0);
3327 perf_event_update_userpage(event);
3331 * Holding the top-level event's child_mutex means that any
3332 * descendant process that has inherited this event will block
3333 * in sync_child_event if it goes to exit, thus satisfying the
3334 * task existence requirements of perf_event_enable/disable.
3336 static void perf_event_for_each_child(struct perf_event *event,
3337 void (*func)(struct perf_event *))
3339 struct perf_event *child;
3341 WARN_ON_ONCE(event->ctx->parent_ctx);
3342 mutex_lock(&event->child_mutex);
3344 list_for_each_entry(child, &event->child_list, child_list)
3346 mutex_unlock(&event->child_mutex);
3349 static void perf_event_for_each(struct perf_event *event,
3350 void (*func)(struct perf_event *))
3352 struct perf_event_context *ctx = event->ctx;
3353 struct perf_event *sibling;
3355 WARN_ON_ONCE(ctx->parent_ctx);
3356 mutex_lock(&ctx->mutex);
3357 event = event->group_leader;
3359 perf_event_for_each_child(event, func);
3360 list_for_each_entry(sibling, &event->sibling_list, group_entry)
3361 perf_event_for_each_child(sibling, func);
3362 mutex_unlock(&ctx->mutex);
3365 static int perf_event_period(struct perf_event *event, u64 __user *arg)
3367 struct perf_event_context *ctx = event->ctx;
3371 if (!is_sampling_event(event))
3374 if (copy_from_user(&value, arg, sizeof(value)))
3380 raw_spin_lock_irq(&ctx->lock);
3381 if (event->attr.freq) {
3382 if (value > sysctl_perf_event_sample_rate) {
3387 event->attr.sample_freq = value;
3389 event->attr.sample_period = value;
3390 event->hw.sample_period = value;
3393 raw_spin_unlock_irq(&ctx->lock);
3398 static const struct file_operations perf_fops;
3400 static inline int perf_fget_light(int fd, struct fd *p)
3402 struct fd f = fdget(fd);
3406 if (f.file->f_op != &perf_fops) {
3414 static int perf_event_set_output(struct perf_event *event,
3415 struct perf_event *output_event);
3416 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
3418 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
3420 struct perf_event *event = file->private_data;
3421 void (*func)(struct perf_event *);
3425 case PERF_EVENT_IOC_ENABLE:
3426 func = perf_event_enable;
3428 case PERF_EVENT_IOC_DISABLE:
3429 func = perf_event_disable;
3431 case PERF_EVENT_IOC_RESET:
3432 func = perf_event_reset;
3435 case PERF_EVENT_IOC_REFRESH:
3436 return perf_event_refresh(event, arg);
3438 case PERF_EVENT_IOC_PERIOD:
3439 return perf_event_period(event, (u64 __user *)arg);
3441 case PERF_EVENT_IOC_SET_OUTPUT:
3445 struct perf_event *output_event;
3447 ret = perf_fget_light(arg, &output);
3450 output_event = output.file->private_data;
3451 ret = perf_event_set_output(event, output_event);
3454 ret = perf_event_set_output(event, NULL);
3459 case PERF_EVENT_IOC_SET_FILTER:
3460 return perf_event_set_filter(event, (void __user *)arg);
3466 if (flags & PERF_IOC_FLAG_GROUP)
3467 perf_event_for_each(event, func);
3469 perf_event_for_each_child(event, func);
3474 int perf_event_task_enable(void)
3476 struct perf_event *event;
3478 mutex_lock(¤t->perf_event_mutex);
3479 list_for_each_entry(event, ¤t->perf_event_list, owner_entry)
3480 perf_event_for_each_child(event, perf_event_enable);
3481 mutex_unlock(¤t->perf_event_mutex);
3486 int perf_event_task_disable(void)
3488 struct perf_event *event;
3490 mutex_lock(¤t->perf_event_mutex);
3491 list_for_each_entry(event, ¤t->perf_event_list, owner_entry)
3492 perf_event_for_each_child(event, perf_event_disable);
3493 mutex_unlock(¤t->perf_event_mutex);
3498 static int perf_event_index(struct perf_event *event)
3500 if (event->hw.state & PERF_HES_STOPPED)
3503 if (event->state != PERF_EVENT_STATE_ACTIVE)
3506 return event->pmu->event_idx(event);
3509 static void calc_timer_values(struct perf_event *event,
3516 *now = perf_clock();
3517 ctx_time = event->shadow_ctx_time + *now;
3518 *enabled = ctx_time - event->tstamp_enabled;
3519 *running = ctx_time - event->tstamp_running;
3522 void __weak arch_perf_update_userpage(struct perf_event_mmap_page *userpg, u64 now)
3527 * Callers need to ensure there can be no nesting of this function, otherwise
3528 * the seqlock logic goes bad. We can not serialize this because the arch
3529 * code calls this from NMI context.
3531 void perf_event_update_userpage(struct perf_event *event)
3533 struct perf_event_mmap_page *userpg;
3534 struct ring_buffer *rb;
3535 u64 enabled, running, now;
3539 * compute total_time_enabled, total_time_running
3540 * based on snapshot values taken when the event
3541 * was last scheduled in.
3543 * we cannot simply called update_context_time()
3544 * because of locking issue as we can be called in
3547 calc_timer_values(event, &now, &enabled, &running);
3548 rb = rcu_dereference(event->rb);
3552 userpg = rb->user_page;
3555 * Disable preemption so as to not let the corresponding user-space
3556 * spin too long if we get preempted.
3561 userpg->index = perf_event_index(event);
3562 userpg->offset = perf_event_count(event);
3564 userpg->offset -= local64_read(&event->hw.prev_count);
3566 userpg->time_enabled = enabled +
3567 atomic64_read(&event->child_total_time_enabled);
3569 userpg->time_running = running +
3570 atomic64_read(&event->child_total_time_running);
3572 arch_perf_update_userpage(userpg, now);
3581 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
3583 struct perf_event *event = vma->vm_file->private_data;
3584 struct ring_buffer *rb;
3585 int ret = VM_FAULT_SIGBUS;
3587 if (vmf->flags & FAULT_FLAG_MKWRITE) {
3588 if (vmf->pgoff == 0)
3594 rb = rcu_dereference(event->rb);
3598 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
3601 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
3605 get_page(vmf->page);
3606 vmf->page->mapping = vma->vm_file->f_mapping;
3607 vmf->page->index = vmf->pgoff;
3616 static void ring_buffer_attach(struct perf_event *event,
3617 struct ring_buffer *rb)
3619 unsigned long flags;
3621 if (!list_empty(&event->rb_entry))
3624 spin_lock_irqsave(&rb->event_lock, flags);
3625 if (list_empty(&event->rb_entry))
3626 list_add(&event->rb_entry, &rb->event_list);
3627 spin_unlock_irqrestore(&rb->event_lock, flags);
3630 static void ring_buffer_detach(struct perf_event *event, struct ring_buffer *rb)
3632 unsigned long flags;
3634 if (list_empty(&event->rb_entry))
3637 spin_lock_irqsave(&rb->event_lock, flags);
3638 list_del_init(&event->rb_entry);
3639 wake_up_all(&event->waitq);
3640 spin_unlock_irqrestore(&rb->event_lock, flags);
3643 static void ring_buffer_wakeup(struct perf_event *event)
3645 struct ring_buffer *rb;
3648 rb = rcu_dereference(event->rb);
3650 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
3651 wake_up_all(&event->waitq);
3656 static void rb_free_rcu(struct rcu_head *rcu_head)
3658 struct ring_buffer *rb;
3660 rb = container_of(rcu_head, struct ring_buffer, rcu_head);
3664 static struct ring_buffer *ring_buffer_get(struct perf_event *event)
3666 struct ring_buffer *rb;
3669 rb = rcu_dereference(event->rb);
3671 if (!atomic_inc_not_zero(&rb->refcount))
3679 static void ring_buffer_put(struct ring_buffer *rb)
3681 if (!atomic_dec_and_test(&rb->refcount))
3684 WARN_ON_ONCE(!list_empty(&rb->event_list));
3686 call_rcu(&rb->rcu_head, rb_free_rcu);
3689 static void perf_mmap_open(struct vm_area_struct *vma)
3691 struct perf_event *event = vma->vm_file->private_data;
3693 atomic_inc(&event->mmap_count);
3694 atomic_inc(&event->rb->mmap_count);
3698 * A buffer can be mmap()ed multiple times; either directly through the same
3699 * event, or through other events by use of perf_event_set_output().
3701 * In order to undo the VM accounting done by perf_mmap() we need to destroy
3702 * the buffer here, where we still have a VM context. This means we need
3703 * to detach all events redirecting to us.
3705 static void perf_mmap_close(struct vm_area_struct *vma)
3707 struct perf_event *event = vma->vm_file->private_data;
3709 struct ring_buffer *rb = event->rb;
3710 struct user_struct *mmap_user = rb->mmap_user;
3711 int mmap_locked = rb->mmap_locked;
3712 unsigned long size = perf_data_size(rb);
3714 atomic_dec(&rb->mmap_count);
3716 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
3719 /* Detach current event from the buffer. */
3720 rcu_assign_pointer(event->rb, NULL);
3721 ring_buffer_detach(event, rb);
3722 mutex_unlock(&event->mmap_mutex);
3724 /* If there's still other mmap()s of this buffer, we're done. */
3725 if (atomic_read(&rb->mmap_count)) {
3726 ring_buffer_put(rb); /* can't be last */
3731 * No other mmap()s, detach from all other events that might redirect
3732 * into the now unreachable buffer. Somewhat complicated by the
3733 * fact that rb::event_lock otherwise nests inside mmap_mutex.
3737 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
3738 if (!atomic_long_inc_not_zero(&event->refcount)) {
3740 * This event is en-route to free_event() which will
3741 * detach it and remove it from the list.
3747 mutex_lock(&event->mmap_mutex);
3749 * Check we didn't race with perf_event_set_output() which can
3750 * swizzle the rb from under us while we were waiting to
3751 * acquire mmap_mutex.
3753 * If we find a different rb; ignore this event, a next
3754 * iteration will no longer find it on the list. We have to
3755 * still restart the iteration to make sure we're not now
3756 * iterating the wrong list.
3758 if (event->rb == rb) {
3759 rcu_assign_pointer(event->rb, NULL);
3760 ring_buffer_detach(event, rb);
3761 ring_buffer_put(rb); /* can't be last, we still have one */
3763 mutex_unlock(&event->mmap_mutex);
3767 * Restart the iteration; either we're on the wrong list or
3768 * destroyed its integrity by doing a deletion.
3775 * It could be there's still a few 0-ref events on the list; they'll
3776 * get cleaned up by free_event() -- they'll also still have their
3777 * ref on the rb and will free it whenever they are done with it.
3779 * Aside from that, this buffer is 'fully' detached and unmapped,
3780 * undo the VM accounting.
3783 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
3784 vma->vm_mm->pinned_vm -= mmap_locked;
3785 free_uid(mmap_user);
3787 ring_buffer_put(rb); /* could be last */
3790 static const struct vm_operations_struct perf_mmap_vmops = {
3791 .open = perf_mmap_open,
3792 .close = perf_mmap_close,
3793 .fault = perf_mmap_fault,
3794 .page_mkwrite = perf_mmap_fault,
3797 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
3799 struct perf_event *event = file->private_data;
3800 unsigned long user_locked, user_lock_limit;
3801 struct user_struct *user = current_user();
3802 unsigned long locked, lock_limit;
3803 struct ring_buffer *rb;
3804 unsigned long vma_size;
3805 unsigned long nr_pages;
3806 long user_extra, extra;
3807 int ret = 0, flags = 0;
3810 * Don't allow mmap() of inherited per-task counters. This would
3811 * create a performance issue due to all children writing to the
3814 if (event->cpu == -1 && event->attr.inherit)
3817 if (!(vma->vm_flags & VM_SHARED))
3820 vma_size = vma->vm_end - vma->vm_start;
3821 nr_pages = (vma_size / PAGE_SIZE) - 1;
3824 * If we have rb pages ensure they're a power-of-two number, so we
3825 * can do bitmasks instead of modulo.
3827 if (nr_pages != 0 && !is_power_of_2(nr_pages))
3830 if (vma_size != PAGE_SIZE * (1 + nr_pages))
3833 if (vma->vm_pgoff != 0)
3836 WARN_ON_ONCE(event->ctx->parent_ctx);
3838 mutex_lock(&event->mmap_mutex);
3840 if (event->rb->nr_pages != nr_pages) {
3845 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
3847 * Raced against perf_mmap_close() through
3848 * perf_event_set_output(). Try again, hope for better
3851 mutex_unlock(&event->mmap_mutex);
3858 user_extra = nr_pages + 1;
3859 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
3862 * Increase the limit linearly with more CPUs:
3864 user_lock_limit *= num_online_cpus();
3866 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
3869 if (user_locked > user_lock_limit)
3870 extra = user_locked - user_lock_limit;
3872 lock_limit = rlimit(RLIMIT_MEMLOCK);
3873 lock_limit >>= PAGE_SHIFT;
3874 locked = vma->vm_mm->pinned_vm + extra;
3876 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
3877 !capable(CAP_IPC_LOCK)) {
3884 if (vma->vm_flags & VM_WRITE)
3885 flags |= RING_BUFFER_WRITABLE;
3887 rb = rb_alloc(nr_pages,
3888 event->attr.watermark ? event->attr.wakeup_watermark : 0,
3896 atomic_set(&rb->mmap_count, 1);
3897 rb->mmap_locked = extra;
3898 rb->mmap_user = get_current_user();
3900 atomic_long_add(user_extra, &user->locked_vm);
3901 vma->vm_mm->pinned_vm += extra;
3903 ring_buffer_attach(event, rb);
3904 rcu_assign_pointer(event->rb, rb);
3906 perf_event_update_userpage(event);
3910 atomic_inc(&event->mmap_count);
3911 mutex_unlock(&event->mmap_mutex);
3914 * Since pinned accounting is per vm we cannot allow fork() to copy our
3917 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
3918 vma->vm_ops = &perf_mmap_vmops;
3923 static int perf_fasync(int fd, struct file *filp, int on)
3925 struct inode *inode = file_inode(filp);
3926 struct perf_event *event = filp->private_data;
3929 mutex_lock(&inode->i_mutex);
3930 retval = fasync_helper(fd, filp, on, &event->fasync);
3931 mutex_unlock(&inode->i_mutex);
3939 static const struct file_operations perf_fops = {
3940 .llseek = no_llseek,
3941 .release = perf_release,
3944 .unlocked_ioctl = perf_ioctl,
3945 .compat_ioctl = perf_ioctl,
3947 .fasync = perf_fasync,
3953 * If there's data, ensure we set the poll() state and publish everything
3954 * to user-space before waking everybody up.
3957 void perf_event_wakeup(struct perf_event *event)
3959 ring_buffer_wakeup(event);
3961 if (event->pending_kill) {
3962 kill_fasync(&event->fasync, SIGIO, event->pending_kill);
3963 event->pending_kill = 0;
3967 static void perf_pending_event(struct irq_work *entry)
3969 struct perf_event *event = container_of(entry,
3970 struct perf_event, pending);
3972 if (event->pending_disable) {
3973 event->pending_disable = 0;
3974 __perf_event_disable(event);
3977 if (event->pending_wakeup) {
3978 event->pending_wakeup = 0;
3979 perf_event_wakeup(event);
3984 * We assume there is only KVM supporting the callbacks.
3985 * Later on, we might change it to a list if there is
3986 * another virtualization implementation supporting the callbacks.
3988 struct perf_guest_info_callbacks *perf_guest_cbs;
3990 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
3992 perf_guest_cbs = cbs;
3995 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
3997 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
3999 perf_guest_cbs = NULL;
4002 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
4005 perf_output_sample_regs(struct perf_output_handle *handle,
4006 struct pt_regs *regs, u64 mask)
4010 for_each_set_bit(bit, (const unsigned long *) &mask,
4011 sizeof(mask) * BITS_PER_BYTE) {
4014 val = perf_reg_value(regs, bit);
4015 perf_output_put(handle, val);
4019 static void perf_sample_regs_user(struct perf_regs_user *regs_user,
4020 struct pt_regs *regs)
4022 if (!user_mode(regs)) {
4024 regs = task_pt_regs(current);
4030 regs_user->regs = regs;
4031 regs_user->abi = perf_reg_abi(current);
4036 * Get remaining task size from user stack pointer.
4038 * It'd be better to take stack vma map and limit this more
4039 * precisly, but there's no way to get it safely under interrupt,
4040 * so using TASK_SIZE as limit.
4042 static u64 perf_ustack_task_size(struct pt_regs *regs)
4044 unsigned long addr = perf_user_stack_pointer(regs);
4046 if (!addr || addr >= TASK_SIZE)
4049 return TASK_SIZE - addr;
4053 perf_sample_ustack_size(u16 stack_size, u16 header_size,
4054 struct pt_regs *regs)
4058 /* No regs, no stack pointer, no dump. */
4063 * Check if we fit in with the requested stack size into the:
4065 * If we don't, we limit the size to the TASK_SIZE.
4067 * - remaining sample size
4068 * If we don't, we customize the stack size to
4069 * fit in to the remaining sample size.
4072 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
4073 stack_size = min(stack_size, (u16) task_size);
4075 /* Current header size plus static size and dynamic size. */
4076 header_size += 2 * sizeof(u64);
4078 /* Do we fit in with the current stack dump size? */
4079 if ((u16) (header_size + stack_size) < header_size) {
4081 * If we overflow the maximum size for the sample,
4082 * we customize the stack dump size to fit in.
4084 stack_size = USHRT_MAX - header_size - sizeof(u64);
4085 stack_size = round_up(stack_size, sizeof(u64));
4092 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
4093 struct pt_regs *regs)
4095 /* Case of a kernel thread, nothing to dump */
4098 perf_output_put(handle, size);
4107 * - the size requested by user or the best one we can fit
4108 * in to the sample max size
4110 * - user stack dump data
4112 * - the actual dumped size
4116 perf_output_put(handle, dump_size);
4119 sp = perf_user_stack_pointer(regs);
4120 rem = __output_copy_user(handle, (void *) sp, dump_size);
4121 dyn_size = dump_size - rem;
4123 perf_output_skip(handle, rem);
4126 perf_output_put(handle, dyn_size);
4130 static void __perf_event_header__init_id(struct perf_event_header *header,
4131 struct perf_sample_data *data,
4132 struct perf_event *event)
4134 u64 sample_type = event->attr.sample_type;
4136 data->type = sample_type;
4137 header->size += event->id_header_size;
4139 if (sample_type & PERF_SAMPLE_TID) {
4140 /* namespace issues */
4141 data->tid_entry.pid = perf_event_pid(event, current);
4142 data->tid_entry.tid = perf_event_tid(event, current);
4145 if (sample_type & PERF_SAMPLE_TIME)
4146 data->time = perf_clock();
4148 if (sample_type & PERF_SAMPLE_ID)
4149 data->id = primary_event_id(event);
4151 if (sample_type & PERF_SAMPLE_STREAM_ID)
4152 data->stream_id = event->id;
4154 if (sample_type & PERF_SAMPLE_CPU) {
4155 data->cpu_entry.cpu = raw_smp_processor_id();
4156 data->cpu_entry.reserved = 0;
4160 void perf_event_header__init_id(struct perf_event_header *header,
4161 struct perf_sample_data *data,
4162 struct perf_event *event)
4164 if (event->attr.sample_id_all)
4165 __perf_event_header__init_id(header, data, event);
4168 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
4169 struct perf_sample_data *data)
4171 u64 sample_type = data->type;
4173 if (sample_type & PERF_SAMPLE_TID)
4174 perf_output_put(handle, data->tid_entry);
4176 if (sample_type & PERF_SAMPLE_TIME)
4177 perf_output_put(handle, data->time);
4179 if (sample_type & PERF_SAMPLE_ID)
4180 perf_output_put(handle, data->id);
4182 if (sample_type & PERF_SAMPLE_STREAM_ID)
4183 perf_output_put(handle, data->stream_id);
4185 if (sample_type & PERF_SAMPLE_CPU)
4186 perf_output_put(handle, data->cpu_entry);
4189 void perf_event__output_id_sample(struct perf_event *event,
4190 struct perf_output_handle *handle,
4191 struct perf_sample_data *sample)
4193 if (event->attr.sample_id_all)
4194 __perf_event__output_id_sample(handle, sample);
4197 static void perf_output_read_one(struct perf_output_handle *handle,
4198 struct perf_event *event,
4199 u64 enabled, u64 running)
4201 u64 read_format = event->attr.read_format;
4205 values[n++] = perf_event_count(event);
4206 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4207 values[n++] = enabled +
4208 atomic64_read(&event->child_total_time_enabled);
4210 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4211 values[n++] = running +
4212 atomic64_read(&event->child_total_time_running);
4214 if (read_format & PERF_FORMAT_ID)
4215 values[n++] = primary_event_id(event);
4217 __output_copy(handle, values, n * sizeof(u64));
4221 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
4223 static void perf_output_read_group(struct perf_output_handle *handle,
4224 struct perf_event *event,
4225 u64 enabled, u64 running)
4227 struct perf_event *leader = event->group_leader, *sub;
4228 u64 read_format = event->attr.read_format;
4232 values[n++] = 1 + leader->nr_siblings;
4234 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4235 values[n++] = enabled;
4237 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4238 values[n++] = running;
4240 if (leader != event)
4241 leader->pmu->read(leader);
4243 values[n++] = perf_event_count(leader);
4244 if (read_format & PERF_FORMAT_ID)
4245 values[n++] = primary_event_id(leader);
4247 __output_copy(handle, values, n * sizeof(u64));
4249 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4253 sub->pmu->read(sub);
4255 values[n++] = perf_event_count(sub);
4256 if (read_format & PERF_FORMAT_ID)
4257 values[n++] = primary_event_id(sub);
4259 __output_copy(handle, values, n * sizeof(u64));
4263 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
4264 PERF_FORMAT_TOTAL_TIME_RUNNING)
4266 static void perf_output_read(struct perf_output_handle *handle,
4267 struct perf_event *event)
4269 u64 enabled = 0, running = 0, now;
4270 u64 read_format = event->attr.read_format;
4273 * compute total_time_enabled, total_time_running
4274 * based on snapshot values taken when the event
4275 * was last scheduled in.
4277 * we cannot simply called update_context_time()
4278 * because of locking issue as we are called in
4281 if (read_format & PERF_FORMAT_TOTAL_TIMES)
4282 calc_timer_values(event, &now, &enabled, &running);
4284 if (event->attr.read_format & PERF_FORMAT_GROUP)
4285 perf_output_read_group(handle, event, enabled, running);
4287 perf_output_read_one(handle, event, enabled, running);
4290 void perf_output_sample(struct perf_output_handle *handle,
4291 struct perf_event_header *header,
4292 struct perf_sample_data *data,
4293 struct perf_event *event)
4295 u64 sample_type = data->type;
4297 perf_output_put(handle, *header);
4299 if (sample_type & PERF_SAMPLE_IP)
4300 perf_output_put(handle, data->ip);
4302 if (sample_type & PERF_SAMPLE_TID)
4303 perf_output_put(handle, data->tid_entry);
4305 if (sample_type & PERF_SAMPLE_TIME)
4306 perf_output_put(handle, data->time);
4308 if (sample_type & PERF_SAMPLE_ADDR)
4309 perf_output_put(handle, data->addr);
4311 if (sample_type & PERF_SAMPLE_ID)
4312 perf_output_put(handle, data->id);
4314 if (sample_type & PERF_SAMPLE_STREAM_ID)
4315 perf_output_put(handle, data->stream_id);
4317 if (sample_type & PERF_SAMPLE_CPU)
4318 perf_output_put(handle, data->cpu_entry);
4320 if (sample_type & PERF_SAMPLE_PERIOD)
4321 perf_output_put(handle, data->period);
4323 if (sample_type & PERF_SAMPLE_READ)
4324 perf_output_read(handle, event);
4326 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4327 if (data->callchain) {
4330 if (data->callchain)
4331 size += data->callchain->nr;
4333 size *= sizeof(u64);
4335 __output_copy(handle, data->callchain, size);
4338 perf_output_put(handle, nr);
4342 if (sample_type & PERF_SAMPLE_RAW) {
4344 perf_output_put(handle, data->raw->size);
4345 __output_copy(handle, data->raw->data,
4352 .size = sizeof(u32),
4355 perf_output_put(handle, raw);
4359 if (!event->attr.watermark) {
4360 int wakeup_events = event->attr.wakeup_events;
4362 if (wakeup_events) {
4363 struct ring_buffer *rb = handle->rb;
4364 int events = local_inc_return(&rb->events);
4366 if (events >= wakeup_events) {
4367 local_sub(wakeup_events, &rb->events);
4368 local_inc(&rb->wakeup);
4373 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4374 if (data->br_stack) {
4377 size = data->br_stack->nr
4378 * sizeof(struct perf_branch_entry);
4380 perf_output_put(handle, data->br_stack->nr);
4381 perf_output_copy(handle, data->br_stack->entries, size);
4384 * we always store at least the value of nr
4387 perf_output_put(handle, nr);
4391 if (sample_type & PERF_SAMPLE_REGS_USER) {
4392 u64 abi = data->regs_user.abi;
4395 * If there are no regs to dump, notice it through
4396 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
4398 perf_output_put(handle, abi);
4401 u64 mask = event->attr.sample_regs_user;
4402 perf_output_sample_regs(handle,
4403 data->regs_user.regs,
4408 if (sample_type & PERF_SAMPLE_STACK_USER)
4409 perf_output_sample_ustack(handle,
4410 data->stack_user_size,
4411 data->regs_user.regs);
4413 if (sample_type & PERF_SAMPLE_WEIGHT)
4414 perf_output_put(handle, data->weight);
4416 if (sample_type & PERF_SAMPLE_DATA_SRC)
4417 perf_output_put(handle, data->data_src.val);
4420 void perf_prepare_sample(struct perf_event_header *header,
4421 struct perf_sample_data *data,
4422 struct perf_event *event,
4423 struct pt_regs *regs)
4425 u64 sample_type = event->attr.sample_type;
4427 header->type = PERF_RECORD_SAMPLE;
4428 header->size = sizeof(*header) + event->header_size;
4431 header->misc |= perf_misc_flags(regs);
4433 __perf_event_header__init_id(header, data, event);
4435 if (sample_type & PERF_SAMPLE_IP)
4436 data->ip = perf_instruction_pointer(regs);
4438 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4441 data->callchain = perf_callchain(event, regs);
4443 if (data->callchain)
4444 size += data->callchain->nr;
4446 header->size += size * sizeof(u64);
4449 if (sample_type & PERF_SAMPLE_RAW) {
4450 int size = sizeof(u32);
4453 size += data->raw->size;
4455 size += sizeof(u32);
4457 WARN_ON_ONCE(size & (sizeof(u64)-1));
4458 header->size += size;
4461 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4462 int size = sizeof(u64); /* nr */
4463 if (data->br_stack) {
4464 size += data->br_stack->nr
4465 * sizeof(struct perf_branch_entry);
4467 header->size += size;
4470 if (sample_type & PERF_SAMPLE_REGS_USER) {
4471 /* regs dump ABI info */
4472 int size = sizeof(u64);
4474 perf_sample_regs_user(&data->regs_user, regs);
4476 if (data->regs_user.regs) {
4477 u64 mask = event->attr.sample_regs_user;
4478 size += hweight64(mask) * sizeof(u64);
4481 header->size += size;
4484 if (sample_type & PERF_SAMPLE_STACK_USER) {
4486 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
4487 * processed as the last one or have additional check added
4488 * in case new sample type is added, because we could eat
4489 * up the rest of the sample size.
4491 struct perf_regs_user *uregs = &data->regs_user;
4492 u16 stack_size = event->attr.sample_stack_user;
4493 u16 size = sizeof(u64);
4496 perf_sample_regs_user(uregs, regs);
4498 stack_size = perf_sample_ustack_size(stack_size, header->size,
4502 * If there is something to dump, add space for the dump
4503 * itself and for the field that tells the dynamic size,
4504 * which is how many have been actually dumped.
4507 size += sizeof(u64) + stack_size;
4509 data->stack_user_size = stack_size;
4510 header->size += size;
4514 static void perf_event_output(struct perf_event *event,
4515 struct perf_sample_data *data,
4516 struct pt_regs *regs)
4518 struct perf_output_handle handle;
4519 struct perf_event_header header;
4521 /* protect the callchain buffers */
4524 perf_prepare_sample(&header, data, event, regs);
4526 if (perf_output_begin(&handle, event, header.size))
4529 perf_output_sample(&handle, &header, data, event);
4531 perf_output_end(&handle);
4541 struct perf_read_event {
4542 struct perf_event_header header;
4549 perf_event_read_event(struct perf_event *event,
4550 struct task_struct *task)
4552 struct perf_output_handle handle;
4553 struct perf_sample_data sample;
4554 struct perf_read_event read_event = {
4556 .type = PERF_RECORD_READ,
4558 .size = sizeof(read_event) + event->read_size,
4560 .pid = perf_event_pid(event, task),
4561 .tid = perf_event_tid(event, task),
4565 perf_event_header__init_id(&read_event.header, &sample, event);
4566 ret = perf_output_begin(&handle, event, read_event.header.size);
4570 perf_output_put(&handle, read_event);
4571 perf_output_read(&handle, event);
4572 perf_event__output_id_sample(event, &handle, &sample);
4574 perf_output_end(&handle);
4577 typedef int (perf_event_aux_match_cb)(struct perf_event *event, void *data);
4578 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
4581 perf_event_aux_ctx(struct perf_event_context *ctx,
4582 perf_event_aux_match_cb match,
4583 perf_event_aux_output_cb output,
4586 struct perf_event *event;
4588 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4589 if (event->state < PERF_EVENT_STATE_INACTIVE)
4591 if (!event_filter_match(event))
4593 if (match(event, data))
4594 output(event, data);
4599 perf_event_aux(perf_event_aux_match_cb match,
4600 perf_event_aux_output_cb output,
4602 struct perf_event_context *task_ctx)
4604 struct perf_cpu_context *cpuctx;
4605 struct perf_event_context *ctx;
4610 list_for_each_entry_rcu(pmu, &pmus, entry) {
4611 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4612 if (cpuctx->unique_pmu != pmu)
4614 perf_event_aux_ctx(&cpuctx->ctx, match, output, data);
4617 ctxn = pmu->task_ctx_nr;
4620 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4622 perf_event_aux_ctx(ctx, match, output, data);
4624 put_cpu_ptr(pmu->pmu_cpu_context);
4629 perf_event_aux_ctx(task_ctx, match, output, data);
4636 * task tracking -- fork/exit
4638 * enabled by: attr.comm | attr.mmap | attr.mmap_data | attr.task
4641 struct perf_task_event {
4642 struct task_struct *task;
4643 struct perf_event_context *task_ctx;
4646 struct perf_event_header header;
4656 static void perf_event_task_output(struct perf_event *event,
4659 struct perf_task_event *task_event = data;
4660 struct perf_output_handle handle;
4661 struct perf_sample_data sample;
4662 struct task_struct *task = task_event->task;
4663 int ret, size = task_event->event_id.header.size;
4665 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
4667 ret = perf_output_begin(&handle, event,
4668 task_event->event_id.header.size);
4672 task_event->event_id.pid = perf_event_pid(event, task);
4673 task_event->event_id.ppid = perf_event_pid(event, current);
4675 task_event->event_id.tid = perf_event_tid(event, task);
4676 task_event->event_id.ptid = perf_event_tid(event, current);
4678 perf_output_put(&handle, task_event->event_id);
4680 perf_event__output_id_sample(event, &handle, &sample);
4682 perf_output_end(&handle);
4684 task_event->event_id.header.size = size;
4687 static int perf_event_task_match(struct perf_event *event,
4688 void *data __maybe_unused)
4690 return event->attr.comm || event->attr.mmap ||
4691 event->attr.mmap_data || event->attr.task;
4694 static void perf_event_task(struct task_struct *task,
4695 struct perf_event_context *task_ctx,
4698 struct perf_task_event task_event;
4700 if (!atomic_read(&nr_comm_events) &&
4701 !atomic_read(&nr_mmap_events) &&
4702 !atomic_read(&nr_task_events))
4705 task_event = (struct perf_task_event){
4707 .task_ctx = task_ctx,
4710 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
4712 .size = sizeof(task_event.event_id),
4718 .time = perf_clock(),
4722 perf_event_aux(perf_event_task_match,
4723 perf_event_task_output,
4728 void perf_event_fork(struct task_struct *task)
4730 perf_event_task(task, NULL, 1);
4737 struct perf_comm_event {
4738 struct task_struct *task;
4743 struct perf_event_header header;
4750 static void perf_event_comm_output(struct perf_event *event,
4753 struct perf_comm_event *comm_event = data;
4754 struct perf_output_handle handle;
4755 struct perf_sample_data sample;
4756 int size = comm_event->event_id.header.size;
4759 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
4760 ret = perf_output_begin(&handle, event,
4761 comm_event->event_id.header.size);
4766 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
4767 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
4769 perf_output_put(&handle, comm_event->event_id);
4770 __output_copy(&handle, comm_event->comm,
4771 comm_event->comm_size);
4773 perf_event__output_id_sample(event, &handle, &sample);
4775 perf_output_end(&handle);
4777 comm_event->event_id.header.size = size;
4780 static int perf_event_comm_match(struct perf_event *event,
4781 void *data __maybe_unused)
4783 return event->attr.comm;
4786 static void perf_event_comm_event(struct perf_comm_event *comm_event)
4788 char comm[TASK_COMM_LEN];
4791 memset(comm, 0, sizeof(comm));
4792 strlcpy(comm, comm_event->task->comm, sizeof(comm));
4793 size = ALIGN(strlen(comm)+1, sizeof(u64));
4795 comm_event->comm = comm;
4796 comm_event->comm_size = size;
4798 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
4800 perf_event_aux(perf_event_comm_match,
4801 perf_event_comm_output,
4806 void perf_event_comm(struct task_struct *task)
4808 struct perf_comm_event comm_event;
4809 struct perf_event_context *ctx;
4813 for_each_task_context_nr(ctxn) {
4814 ctx = task->perf_event_ctxp[ctxn];
4818 perf_event_enable_on_exec(ctx);
4822 if (!atomic_read(&nr_comm_events))
4825 comm_event = (struct perf_comm_event){
4831 .type = PERF_RECORD_COMM,
4840 perf_event_comm_event(&comm_event);
4847 struct perf_mmap_event {
4848 struct vm_area_struct *vma;
4850 const char *file_name;
4854 struct perf_event_header header;
4864 static void perf_event_mmap_output(struct perf_event *event,
4867 struct perf_mmap_event *mmap_event = data;
4868 struct perf_output_handle handle;
4869 struct perf_sample_data sample;
4870 int size = mmap_event->event_id.header.size;
4873 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
4874 ret = perf_output_begin(&handle, event,
4875 mmap_event->event_id.header.size);
4879 mmap_event->event_id.pid = perf_event_pid(event, current);
4880 mmap_event->event_id.tid = perf_event_tid(event, current);
4882 perf_output_put(&handle, mmap_event->event_id);
4883 __output_copy(&handle, mmap_event->file_name,
4884 mmap_event->file_size);
4886 perf_event__output_id_sample(event, &handle, &sample);
4888 perf_output_end(&handle);
4890 mmap_event->event_id.header.size = size;
4893 static int perf_event_mmap_match(struct perf_event *event,
4896 struct perf_mmap_event *mmap_event = data;
4897 struct vm_area_struct *vma = mmap_event->vma;
4898 int executable = vma->vm_flags & VM_EXEC;
4900 return (!executable && event->attr.mmap_data) ||
4901 (executable && event->attr.mmap);
4904 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
4906 struct vm_area_struct *vma = mmap_event->vma;
4907 struct file *file = vma->vm_file;
4913 memset(tmp, 0, sizeof(tmp));
4917 * d_path works from the end of the rb backwards, so we
4918 * need to add enough zero bytes after the string to handle
4919 * the 64bit alignment we do later.
4921 buf = kzalloc(PATH_MAX + sizeof(u64), GFP_KERNEL);
4923 name = strncpy(tmp, "//enomem", sizeof(tmp));
4926 name = d_path(&file->f_path, buf, PATH_MAX);
4928 name = strncpy(tmp, "//toolong", sizeof(tmp));
4932 if (arch_vma_name(mmap_event->vma)) {
4933 name = strncpy(tmp, arch_vma_name(mmap_event->vma),
4935 tmp[sizeof(tmp) - 1] = '\0';
4940 name = strncpy(tmp, "[vdso]", sizeof(tmp));
4942 } else if (vma->vm_start <= vma->vm_mm->start_brk &&
4943 vma->vm_end >= vma->vm_mm->brk) {
4944 name = strncpy(tmp, "[heap]", sizeof(tmp));
4946 } else if (vma->vm_start <= vma->vm_mm->start_stack &&
4947 vma->vm_end >= vma->vm_mm->start_stack) {
4948 name = strncpy(tmp, "[stack]", sizeof(tmp));
4952 name = strncpy(tmp, "//anon", sizeof(tmp));
4957 size = ALIGN(strlen(name)+1, sizeof(u64));
4959 mmap_event->file_name = name;
4960 mmap_event->file_size = size;
4962 if (!(vma->vm_flags & VM_EXEC))
4963 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
4965 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
4967 perf_event_aux(perf_event_mmap_match,
4968 perf_event_mmap_output,
4975 void perf_event_mmap(struct vm_area_struct *vma)
4977 struct perf_mmap_event mmap_event;
4979 if (!atomic_read(&nr_mmap_events))
4982 mmap_event = (struct perf_mmap_event){
4988 .type = PERF_RECORD_MMAP,
4989 .misc = PERF_RECORD_MISC_USER,
4994 .start = vma->vm_start,
4995 .len = vma->vm_end - vma->vm_start,
4996 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
5000 perf_event_mmap_event(&mmap_event);
5004 * IRQ throttle logging
5007 static void perf_log_throttle(struct perf_event *event, int enable)
5009 struct perf_output_handle handle;
5010 struct perf_sample_data sample;
5014 struct perf_event_header header;
5018 } throttle_event = {
5020 .type = PERF_RECORD_THROTTLE,
5022 .size = sizeof(throttle_event),
5024 .time = perf_clock(),
5025 .id = primary_event_id(event),
5026 .stream_id = event->id,
5030 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
5032 perf_event_header__init_id(&throttle_event.header, &sample, event);
5034 ret = perf_output_begin(&handle, event,
5035 throttle_event.header.size);
5039 perf_output_put(&handle, throttle_event);
5040 perf_event__output_id_sample(event, &handle, &sample);
5041 perf_output_end(&handle);
5045 * Generic event overflow handling, sampling.
5048 static int __perf_event_overflow(struct perf_event *event,
5049 int throttle, struct perf_sample_data *data,
5050 struct pt_regs *regs)
5052 int events = atomic_read(&event->event_limit);
5053 struct hw_perf_event *hwc = &event->hw;
5058 * Non-sampling counters might still use the PMI to fold short
5059 * hardware counters, ignore those.
5061 if (unlikely(!is_sampling_event(event)))
5064 seq = __this_cpu_read(perf_throttled_seq);
5065 if (seq != hwc->interrupts_seq) {
5066 hwc->interrupts_seq = seq;
5067 hwc->interrupts = 1;
5070 if (unlikely(throttle
5071 && hwc->interrupts >= max_samples_per_tick)) {
5072 __this_cpu_inc(perf_throttled_count);
5073 hwc->interrupts = MAX_INTERRUPTS;
5074 perf_log_throttle(event, 0);
5079 if (event->attr.freq) {
5080 u64 now = perf_clock();
5081 s64 delta = now - hwc->freq_time_stamp;
5083 hwc->freq_time_stamp = now;
5085 if (delta > 0 && delta < 2*TICK_NSEC)
5086 perf_adjust_period(event, delta, hwc->last_period, true);
5090 * XXX event_limit might not quite work as expected on inherited
5094 event->pending_kill = POLL_IN;
5095 if (events && atomic_dec_and_test(&event->event_limit)) {
5097 event->pending_kill = POLL_HUP;
5098 event->pending_disable = 1;
5099 irq_work_queue(&event->pending);
5102 if (event->overflow_handler)
5103 event->overflow_handler(event, data, regs);
5105 perf_event_output(event, data, regs);
5107 if (event->fasync && event->pending_kill) {
5108 event->pending_wakeup = 1;
5109 irq_work_queue(&event->pending);
5115 int perf_event_overflow(struct perf_event *event,
5116 struct perf_sample_data *data,
5117 struct pt_regs *regs)
5119 return __perf_event_overflow(event, 1, data, regs);
5123 * Generic software event infrastructure
5126 struct swevent_htable {
5127 struct swevent_hlist *swevent_hlist;
5128 struct mutex hlist_mutex;
5131 /* Recursion avoidance in each contexts */
5132 int recursion[PERF_NR_CONTEXTS];
5135 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
5138 * We directly increment event->count and keep a second value in
5139 * event->hw.period_left to count intervals. This period event
5140 * is kept in the range [-sample_period, 0] so that we can use the
5144 u64 perf_swevent_set_period(struct perf_event *event)
5146 struct hw_perf_event *hwc = &event->hw;
5147 u64 period = hwc->last_period;
5151 hwc->last_period = hwc->sample_period;
5154 old = val = local64_read(&hwc->period_left);
5158 nr = div64_u64(period + val, period);
5159 offset = nr * period;
5161 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
5167 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
5168 struct perf_sample_data *data,
5169 struct pt_regs *regs)
5171 struct hw_perf_event *hwc = &event->hw;
5175 overflow = perf_swevent_set_period(event);
5177 if (hwc->interrupts == MAX_INTERRUPTS)
5180 for (; overflow; overflow--) {
5181 if (__perf_event_overflow(event, throttle,
5184 * We inhibit the overflow from happening when
5185 * hwc->interrupts == MAX_INTERRUPTS.
5193 static void perf_swevent_event(struct perf_event *event, u64 nr,
5194 struct perf_sample_data *data,
5195 struct pt_regs *regs)
5197 struct hw_perf_event *hwc = &event->hw;
5199 local64_add(nr, &event->count);
5204 if (!is_sampling_event(event))
5207 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
5209 return perf_swevent_overflow(event, 1, data, regs);
5211 data->period = event->hw.last_period;
5213 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
5214 return perf_swevent_overflow(event, 1, data, regs);
5216 if (local64_add_negative(nr, &hwc->period_left))
5219 perf_swevent_overflow(event, 0, data, regs);
5222 static int perf_exclude_event(struct perf_event *event,
5223 struct pt_regs *regs)
5225 if (event->hw.state & PERF_HES_STOPPED)
5229 if (event->attr.exclude_user && user_mode(regs))
5232 if (event->attr.exclude_kernel && !user_mode(regs))
5239 static int perf_swevent_match(struct perf_event *event,
5240 enum perf_type_id type,
5242 struct perf_sample_data *data,
5243 struct pt_regs *regs)
5245 if (event->attr.type != type)
5248 if (event->attr.config != event_id)
5251 if (perf_exclude_event(event, regs))
5257 static inline u64 swevent_hash(u64 type, u32 event_id)
5259 u64 val = event_id | (type << 32);
5261 return hash_64(val, SWEVENT_HLIST_BITS);
5264 static inline struct hlist_head *
5265 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
5267 u64 hash = swevent_hash(type, event_id);
5269 return &hlist->heads[hash];
5272 /* For the read side: events when they trigger */
5273 static inline struct hlist_head *
5274 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
5276 struct swevent_hlist *hlist;
5278 hlist = rcu_dereference(swhash->swevent_hlist);
5282 return __find_swevent_head(hlist, type, event_id);
5285 /* For the event head insertion and removal in the hlist */
5286 static inline struct hlist_head *
5287 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
5289 struct swevent_hlist *hlist;
5290 u32 event_id = event->attr.config;
5291 u64 type = event->attr.type;
5294 * Event scheduling is always serialized against hlist allocation
5295 * and release. Which makes the protected version suitable here.
5296 * The context lock guarantees that.
5298 hlist = rcu_dereference_protected(swhash->swevent_hlist,
5299 lockdep_is_held(&event->ctx->lock));
5303 return __find_swevent_head(hlist, type, event_id);
5306 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
5308 struct perf_sample_data *data,
5309 struct pt_regs *regs)
5311 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5312 struct perf_event *event;
5313 struct hlist_head *head;
5316 head = find_swevent_head_rcu(swhash, type, event_id);
5320 hlist_for_each_entry_rcu(event, head, hlist_entry) {
5321 if (perf_swevent_match(event, type, event_id, data, regs))
5322 perf_swevent_event(event, nr, data, regs);
5328 int perf_swevent_get_recursion_context(void)
5330 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5332 return get_recursion_context(swhash->recursion);
5334 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
5336 inline void perf_swevent_put_recursion_context(int rctx)
5338 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5340 put_recursion_context(swhash->recursion, rctx);
5343 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
5345 struct perf_sample_data data;
5348 preempt_disable_notrace();
5349 rctx = perf_swevent_get_recursion_context();
5353 perf_sample_data_init(&data, addr, 0);
5355 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
5357 perf_swevent_put_recursion_context(rctx);
5358 preempt_enable_notrace();
5361 static void perf_swevent_read(struct perf_event *event)
5365 static int perf_swevent_add(struct perf_event *event, int flags)
5367 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5368 struct hw_perf_event *hwc = &event->hw;
5369 struct hlist_head *head;
5371 if (is_sampling_event(event)) {
5372 hwc->last_period = hwc->sample_period;
5373 perf_swevent_set_period(event);
5376 hwc->state = !(flags & PERF_EF_START);
5378 head = find_swevent_head(swhash, event);
5379 if (WARN_ON_ONCE(!head))
5382 hlist_add_head_rcu(&event->hlist_entry, head);
5387 static void perf_swevent_del(struct perf_event *event, int flags)
5389 hlist_del_rcu(&event->hlist_entry);
5392 static void perf_swevent_start(struct perf_event *event, int flags)
5394 event->hw.state = 0;
5397 static void perf_swevent_stop(struct perf_event *event, int flags)
5399 event->hw.state = PERF_HES_STOPPED;
5402 /* Deref the hlist from the update side */
5403 static inline struct swevent_hlist *
5404 swevent_hlist_deref(struct swevent_htable *swhash)
5406 return rcu_dereference_protected(swhash->swevent_hlist,
5407 lockdep_is_held(&swhash->hlist_mutex));
5410 static void swevent_hlist_release(struct swevent_htable *swhash)
5412 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
5417 rcu_assign_pointer(swhash->swevent_hlist, NULL);
5418 kfree_rcu(hlist, rcu_head);
5421 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
5423 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5425 mutex_lock(&swhash->hlist_mutex);
5427 if (!--swhash->hlist_refcount)
5428 swevent_hlist_release(swhash);
5430 mutex_unlock(&swhash->hlist_mutex);
5433 static void swevent_hlist_put(struct perf_event *event)
5437 if (event->cpu != -1) {
5438 swevent_hlist_put_cpu(event, event->cpu);
5442 for_each_possible_cpu(cpu)
5443 swevent_hlist_put_cpu(event, cpu);
5446 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
5448 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5451 mutex_lock(&swhash->hlist_mutex);
5453 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
5454 struct swevent_hlist *hlist;
5456 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
5461 rcu_assign_pointer(swhash->swevent_hlist, hlist);
5463 swhash->hlist_refcount++;
5465 mutex_unlock(&swhash->hlist_mutex);
5470 static int swevent_hlist_get(struct perf_event *event)
5473 int cpu, failed_cpu;
5475 if (event->cpu != -1)
5476 return swevent_hlist_get_cpu(event, event->cpu);
5479 for_each_possible_cpu(cpu) {
5480 err = swevent_hlist_get_cpu(event, cpu);
5490 for_each_possible_cpu(cpu) {
5491 if (cpu == failed_cpu)
5493 swevent_hlist_put_cpu(event, cpu);
5500 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
5502 static void sw_perf_event_destroy(struct perf_event *event)
5504 u64 event_id = event->attr.config;
5506 WARN_ON(event->parent);
5508 static_key_slow_dec(&perf_swevent_enabled[event_id]);
5509 swevent_hlist_put(event);
5512 static int perf_swevent_init(struct perf_event *event)
5514 u64 event_id = event->attr.config;
5516 if (event->attr.type != PERF_TYPE_SOFTWARE)
5520 * no branch sampling for software events
5522 if (has_branch_stack(event))
5526 case PERF_COUNT_SW_CPU_CLOCK:
5527 case PERF_COUNT_SW_TASK_CLOCK:
5534 if (event_id >= PERF_COUNT_SW_MAX)
5537 if (!event->parent) {
5540 err = swevent_hlist_get(event);
5544 static_key_slow_inc(&perf_swevent_enabled[event_id]);
5545 event->destroy = sw_perf_event_destroy;
5551 static int perf_swevent_event_idx(struct perf_event *event)
5556 static struct pmu perf_swevent = {
5557 .task_ctx_nr = perf_sw_context,
5559 .event_init = perf_swevent_init,
5560 .add = perf_swevent_add,
5561 .del = perf_swevent_del,
5562 .start = perf_swevent_start,
5563 .stop = perf_swevent_stop,
5564 .read = perf_swevent_read,
5566 .event_idx = perf_swevent_event_idx,
5569 #ifdef CONFIG_EVENT_TRACING
5571 static int perf_tp_filter_match(struct perf_event *event,
5572 struct perf_sample_data *data)
5574 void *record = data->raw->data;
5576 if (likely(!event->filter) || filter_match_preds(event->filter, record))
5581 static int perf_tp_event_match(struct perf_event *event,
5582 struct perf_sample_data *data,
5583 struct pt_regs *regs)
5585 if (event->hw.state & PERF_HES_STOPPED)
5588 * All tracepoints are from kernel-space.
5590 if (event->attr.exclude_kernel)
5593 if (!perf_tp_filter_match(event, data))
5599 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
5600 struct pt_regs *regs, struct hlist_head *head, int rctx,
5601 struct task_struct *task)
5603 struct perf_sample_data data;
5604 struct perf_event *event;
5606 struct perf_raw_record raw = {
5611 perf_sample_data_init(&data, addr, 0);
5614 hlist_for_each_entry_rcu(event, head, hlist_entry) {
5615 if (perf_tp_event_match(event, &data, regs))
5616 perf_swevent_event(event, count, &data, regs);
5620 * If we got specified a target task, also iterate its context and
5621 * deliver this event there too.
5623 if (task && task != current) {
5624 struct perf_event_context *ctx;
5625 struct trace_entry *entry = record;
5628 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
5632 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5633 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5635 if (event->attr.config != entry->type)
5637 if (perf_tp_event_match(event, &data, regs))
5638 perf_swevent_event(event, count, &data, regs);
5644 perf_swevent_put_recursion_context(rctx);
5646 EXPORT_SYMBOL_GPL(perf_tp_event);
5648 static void tp_perf_event_destroy(struct perf_event *event)
5650 perf_trace_destroy(event);
5653 static int perf_tp_event_init(struct perf_event *event)
5657 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5661 * no branch sampling for tracepoint events
5663 if (has_branch_stack(event))
5666 err = perf_trace_init(event);
5670 event->destroy = tp_perf_event_destroy;
5675 static struct pmu perf_tracepoint = {
5676 .task_ctx_nr = perf_sw_context,
5678 .event_init = perf_tp_event_init,
5679 .add = perf_trace_add,
5680 .del = perf_trace_del,
5681 .start = perf_swevent_start,
5682 .stop = perf_swevent_stop,
5683 .read = perf_swevent_read,
5685 .event_idx = perf_swevent_event_idx,
5688 static inline void perf_tp_register(void)
5690 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
5693 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
5698 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5701 filter_str = strndup_user(arg, PAGE_SIZE);
5702 if (IS_ERR(filter_str))
5703 return PTR_ERR(filter_str);
5705 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
5711 static void perf_event_free_filter(struct perf_event *event)
5713 ftrace_profile_free_filter(event);
5718 static inline void perf_tp_register(void)
5722 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
5727 static void perf_event_free_filter(struct perf_event *event)
5731 #endif /* CONFIG_EVENT_TRACING */
5733 #ifdef CONFIG_HAVE_HW_BREAKPOINT
5734 void perf_bp_event(struct perf_event *bp, void *data)
5736 struct perf_sample_data sample;
5737 struct pt_regs *regs = data;
5739 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
5741 if (!bp->hw.state && !perf_exclude_event(bp, regs))
5742 perf_swevent_event(bp, 1, &sample, regs);
5747 * hrtimer based swevent callback
5750 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
5752 enum hrtimer_restart ret = HRTIMER_RESTART;
5753 struct perf_sample_data data;
5754 struct pt_regs *regs;
5755 struct perf_event *event;
5758 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
5760 if (event->state != PERF_EVENT_STATE_ACTIVE)
5761 return HRTIMER_NORESTART;
5763 event->pmu->read(event);
5765 perf_sample_data_init(&data, 0, event->hw.last_period);
5766 regs = get_irq_regs();
5768 if (regs && !perf_exclude_event(event, regs)) {
5769 if (!(event->attr.exclude_idle && is_idle_task(current)))
5770 if (__perf_event_overflow(event, 1, &data, regs))
5771 ret = HRTIMER_NORESTART;
5774 period = max_t(u64, 10000, event->hw.sample_period);
5775 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
5780 static void perf_swevent_start_hrtimer(struct perf_event *event)
5782 struct hw_perf_event *hwc = &event->hw;
5785 if (!is_sampling_event(event))
5788 period = local64_read(&hwc->period_left);
5793 local64_set(&hwc->period_left, 0);
5795 period = max_t(u64, 10000, hwc->sample_period);
5797 __hrtimer_start_range_ns(&hwc->hrtimer,
5798 ns_to_ktime(period), 0,
5799 HRTIMER_MODE_REL_PINNED, 0);
5802 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
5804 struct hw_perf_event *hwc = &event->hw;
5806 if (is_sampling_event(event)) {
5807 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
5808 local64_set(&hwc->period_left, ktime_to_ns(remaining));
5810 hrtimer_cancel(&hwc->hrtimer);
5814 static void perf_swevent_init_hrtimer(struct perf_event *event)
5816 struct hw_perf_event *hwc = &event->hw;
5818 if (!is_sampling_event(event))
5821 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
5822 hwc->hrtimer.function = perf_swevent_hrtimer;
5825 * Since hrtimers have a fixed rate, we can do a static freq->period
5826 * mapping and avoid the whole period adjust feedback stuff.
5828 if (event->attr.freq) {
5829 long freq = event->attr.sample_freq;
5831 event->attr.sample_period = NSEC_PER_SEC / freq;
5832 hwc->sample_period = event->attr.sample_period;
5833 local64_set(&hwc->period_left, hwc->sample_period);
5834 hwc->last_period = hwc->sample_period;
5835 event->attr.freq = 0;
5840 * Software event: cpu wall time clock
5843 static void cpu_clock_event_update(struct perf_event *event)
5848 now = local_clock();
5849 prev = local64_xchg(&event->hw.prev_count, now);
5850 local64_add(now - prev, &event->count);
5853 static void cpu_clock_event_start(struct perf_event *event, int flags)
5855 local64_set(&event->hw.prev_count, local_clock());
5856 perf_swevent_start_hrtimer(event);
5859 static void cpu_clock_event_stop(struct perf_event *event, int flags)
5861 perf_swevent_cancel_hrtimer(event);
5862 cpu_clock_event_update(event);
5865 static int cpu_clock_event_add(struct perf_event *event, int flags)
5867 if (flags & PERF_EF_START)
5868 cpu_clock_event_start(event, flags);
5873 static void cpu_clock_event_del(struct perf_event *event, int flags)
5875 cpu_clock_event_stop(event, flags);
5878 static void cpu_clock_event_read(struct perf_event *event)
5880 cpu_clock_event_update(event);
5883 static int cpu_clock_event_init(struct perf_event *event)
5885 if (event->attr.type != PERF_TYPE_SOFTWARE)
5888 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
5892 * no branch sampling for software events
5894 if (has_branch_stack(event))
5897 perf_swevent_init_hrtimer(event);
5902 static struct pmu perf_cpu_clock = {
5903 .task_ctx_nr = perf_sw_context,
5905 .event_init = cpu_clock_event_init,
5906 .add = cpu_clock_event_add,
5907 .del = cpu_clock_event_del,
5908 .start = cpu_clock_event_start,
5909 .stop = cpu_clock_event_stop,
5910 .read = cpu_clock_event_read,
5912 .event_idx = perf_swevent_event_idx,
5916 * Software event: task time clock
5919 static void task_clock_event_update(struct perf_event *event, u64 now)
5924 prev = local64_xchg(&event->hw.prev_count, now);
5926 local64_add(delta, &event->count);
5929 static void task_clock_event_start(struct perf_event *event, int flags)
5931 local64_set(&event->hw.prev_count, event->ctx->time);
5932 perf_swevent_start_hrtimer(event);
5935 static void task_clock_event_stop(struct perf_event *event, int flags)
5937 perf_swevent_cancel_hrtimer(event);
5938 task_clock_event_update(event, event->ctx->time);
5941 static int task_clock_event_add(struct perf_event *event, int flags)
5943 if (flags & PERF_EF_START)
5944 task_clock_event_start(event, flags);
5949 static void task_clock_event_del(struct perf_event *event, int flags)
5951 task_clock_event_stop(event, PERF_EF_UPDATE);
5954 static void task_clock_event_read(struct perf_event *event)
5956 u64 now = perf_clock();
5957 u64 delta = now - event->ctx->timestamp;
5958 u64 time = event->ctx->time + delta;
5960 task_clock_event_update(event, time);
5963 static int task_clock_event_init(struct perf_event *event)
5965 if (event->attr.type != PERF_TYPE_SOFTWARE)
5968 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
5972 * no branch sampling for software events
5974 if (has_branch_stack(event))
5977 perf_swevent_init_hrtimer(event);
5982 static struct pmu perf_task_clock = {
5983 .task_ctx_nr = perf_sw_context,
5985 .event_init = task_clock_event_init,
5986 .add = task_clock_event_add,
5987 .del = task_clock_event_del,
5988 .start = task_clock_event_start,
5989 .stop = task_clock_event_stop,
5990 .read = task_clock_event_read,
5992 .event_idx = perf_swevent_event_idx,
5995 static void perf_pmu_nop_void(struct pmu *pmu)
5999 static int perf_pmu_nop_int(struct pmu *pmu)
6004 static void perf_pmu_start_txn(struct pmu *pmu)
6006 perf_pmu_disable(pmu);
6009 static int perf_pmu_commit_txn(struct pmu *pmu)
6011 perf_pmu_enable(pmu);
6015 static void perf_pmu_cancel_txn(struct pmu *pmu)
6017 perf_pmu_enable(pmu);
6020 static int perf_event_idx_default(struct perf_event *event)
6022 return event->hw.idx + 1;
6026 * Ensures all contexts with the same task_ctx_nr have the same
6027 * pmu_cpu_context too.
6029 static void *find_pmu_context(int ctxn)
6036 list_for_each_entry(pmu, &pmus, entry) {
6037 if (pmu->task_ctx_nr == ctxn)
6038 return pmu->pmu_cpu_context;
6044 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
6048 for_each_possible_cpu(cpu) {
6049 struct perf_cpu_context *cpuctx;
6051 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6053 if (cpuctx->unique_pmu == old_pmu)
6054 cpuctx->unique_pmu = pmu;
6058 static void free_pmu_context(struct pmu *pmu)
6062 mutex_lock(&pmus_lock);
6064 * Like a real lame refcount.
6066 list_for_each_entry(i, &pmus, entry) {
6067 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
6068 update_pmu_context(i, pmu);
6073 free_percpu(pmu->pmu_cpu_context);
6075 mutex_unlock(&pmus_lock);
6077 static struct idr pmu_idr;
6080 type_show(struct device *dev, struct device_attribute *attr, char *page)
6082 struct pmu *pmu = dev_get_drvdata(dev);
6084 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
6088 perf_event_mux_interval_ms_show(struct device *dev,
6089 struct device_attribute *attr,
6092 struct pmu *pmu = dev_get_drvdata(dev);
6094 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
6098 perf_event_mux_interval_ms_store(struct device *dev,
6099 struct device_attribute *attr,
6100 const char *buf, size_t count)
6102 struct pmu *pmu = dev_get_drvdata(dev);
6103 int timer, cpu, ret;
6105 ret = kstrtoint(buf, 0, &timer);
6112 /* same value, noting to do */
6113 if (timer == pmu->hrtimer_interval_ms)
6116 pmu->hrtimer_interval_ms = timer;
6118 /* update all cpuctx for this PMU */
6119 for_each_possible_cpu(cpu) {
6120 struct perf_cpu_context *cpuctx;
6121 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6122 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
6124 if (hrtimer_active(&cpuctx->hrtimer))
6125 hrtimer_forward_now(&cpuctx->hrtimer, cpuctx->hrtimer_interval);
6131 #define __ATTR_RW(attr) __ATTR(attr, 0644, attr##_show, attr##_store)
6133 static struct device_attribute pmu_dev_attrs[] = {
6135 __ATTR_RW(perf_event_mux_interval_ms),
6139 static int pmu_bus_running;
6140 static struct bus_type pmu_bus = {
6141 .name = "event_source",
6142 .dev_attrs = pmu_dev_attrs,
6145 static void pmu_dev_release(struct device *dev)
6150 static int pmu_dev_alloc(struct pmu *pmu)
6154 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
6158 pmu->dev->groups = pmu->attr_groups;
6159 device_initialize(pmu->dev);
6160 ret = dev_set_name(pmu->dev, "%s", pmu->name);
6164 dev_set_drvdata(pmu->dev, pmu);
6165 pmu->dev->bus = &pmu_bus;
6166 pmu->dev->release = pmu_dev_release;
6167 ret = device_add(pmu->dev);
6175 put_device(pmu->dev);
6179 static struct lock_class_key cpuctx_mutex;
6180 static struct lock_class_key cpuctx_lock;
6182 int perf_pmu_register(struct pmu *pmu, char *name, int type)
6186 mutex_lock(&pmus_lock);
6188 pmu->pmu_disable_count = alloc_percpu(int);
6189 if (!pmu->pmu_disable_count)
6198 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
6206 if (pmu_bus_running) {
6207 ret = pmu_dev_alloc(pmu);
6213 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
6214 if (pmu->pmu_cpu_context)
6215 goto got_cpu_context;
6218 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
6219 if (!pmu->pmu_cpu_context)
6222 for_each_possible_cpu(cpu) {
6223 struct perf_cpu_context *cpuctx;
6225 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6226 __perf_event_init_context(&cpuctx->ctx);
6227 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
6228 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
6229 cpuctx->ctx.type = cpu_context;
6230 cpuctx->ctx.pmu = pmu;
6232 __perf_cpu_hrtimer_init(cpuctx, cpu);
6234 INIT_LIST_HEAD(&cpuctx->rotation_list);
6235 cpuctx->unique_pmu = pmu;
6239 if (!pmu->start_txn) {
6240 if (pmu->pmu_enable) {
6242 * If we have pmu_enable/pmu_disable calls, install
6243 * transaction stubs that use that to try and batch
6244 * hardware accesses.
6246 pmu->start_txn = perf_pmu_start_txn;
6247 pmu->commit_txn = perf_pmu_commit_txn;
6248 pmu->cancel_txn = perf_pmu_cancel_txn;
6250 pmu->start_txn = perf_pmu_nop_void;
6251 pmu->commit_txn = perf_pmu_nop_int;
6252 pmu->cancel_txn = perf_pmu_nop_void;
6256 if (!pmu->pmu_enable) {
6257 pmu->pmu_enable = perf_pmu_nop_void;
6258 pmu->pmu_disable = perf_pmu_nop_void;
6261 if (!pmu->event_idx)
6262 pmu->event_idx = perf_event_idx_default;
6264 list_add_rcu(&pmu->entry, &pmus);
6267 mutex_unlock(&pmus_lock);
6272 device_del(pmu->dev);
6273 put_device(pmu->dev);
6276 if (pmu->type >= PERF_TYPE_MAX)
6277 idr_remove(&pmu_idr, pmu->type);
6280 free_percpu(pmu->pmu_disable_count);
6284 void perf_pmu_unregister(struct pmu *pmu)
6286 mutex_lock(&pmus_lock);
6287 list_del_rcu(&pmu->entry);
6288 mutex_unlock(&pmus_lock);
6291 * We dereference the pmu list under both SRCU and regular RCU, so
6292 * synchronize against both of those.
6294 synchronize_srcu(&pmus_srcu);
6297 free_percpu(pmu->pmu_disable_count);
6298 if (pmu->type >= PERF_TYPE_MAX)
6299 idr_remove(&pmu_idr, pmu->type);
6300 device_del(pmu->dev);
6301 put_device(pmu->dev);
6302 free_pmu_context(pmu);
6305 struct pmu *perf_init_event(struct perf_event *event)
6307 struct pmu *pmu = NULL;
6311 idx = srcu_read_lock(&pmus_srcu);
6314 pmu = idr_find(&pmu_idr, event->attr.type);
6318 ret = pmu->event_init(event);
6324 list_for_each_entry_rcu(pmu, &pmus, entry) {
6326 ret = pmu->event_init(event);
6330 if (ret != -ENOENT) {
6335 pmu = ERR_PTR(-ENOENT);
6337 srcu_read_unlock(&pmus_srcu, idx);
6343 * Allocate and initialize a event structure
6345 static struct perf_event *
6346 perf_event_alloc(struct perf_event_attr *attr, int cpu,
6347 struct task_struct *task,
6348 struct perf_event *group_leader,
6349 struct perf_event *parent_event,
6350 perf_overflow_handler_t overflow_handler,
6354 struct perf_event *event;
6355 struct hw_perf_event *hwc;
6358 if ((unsigned)cpu >= nr_cpu_ids) {
6359 if (!task || cpu != -1)
6360 return ERR_PTR(-EINVAL);
6363 event = kzalloc(sizeof(*event), GFP_KERNEL);
6365 return ERR_PTR(-ENOMEM);
6368 * Single events are their own group leaders, with an
6369 * empty sibling list:
6372 group_leader = event;
6374 mutex_init(&event->child_mutex);
6375 INIT_LIST_HEAD(&event->child_list);
6377 INIT_LIST_HEAD(&event->group_entry);
6378 INIT_LIST_HEAD(&event->event_entry);
6379 INIT_LIST_HEAD(&event->sibling_list);
6380 INIT_LIST_HEAD(&event->rb_entry);
6382 init_waitqueue_head(&event->waitq);
6383 init_irq_work(&event->pending, perf_pending_event);
6385 mutex_init(&event->mmap_mutex);
6387 atomic_long_set(&event->refcount, 1);
6389 event->attr = *attr;
6390 event->group_leader = group_leader;
6394 event->parent = parent_event;
6396 event->ns = get_pid_ns(task_active_pid_ns(current));
6397 event->id = atomic64_inc_return(&perf_event_id);
6399 event->state = PERF_EVENT_STATE_INACTIVE;
6402 event->attach_state = PERF_ATTACH_TASK;
6404 if (attr->type == PERF_TYPE_TRACEPOINT)
6405 event->hw.tp_target = task;
6406 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6408 * hw_breakpoint is a bit difficult here..
6410 else if (attr->type == PERF_TYPE_BREAKPOINT)
6411 event->hw.bp_target = task;
6415 if (!overflow_handler && parent_event) {
6416 overflow_handler = parent_event->overflow_handler;
6417 context = parent_event->overflow_handler_context;
6420 event->overflow_handler = overflow_handler;
6421 event->overflow_handler_context = context;
6423 perf_event__state_init(event);
6428 hwc->sample_period = attr->sample_period;
6429 if (attr->freq && attr->sample_freq)
6430 hwc->sample_period = 1;
6431 hwc->last_period = hwc->sample_period;
6433 local64_set(&hwc->period_left, hwc->sample_period);
6436 * we currently do not support PERF_FORMAT_GROUP on inherited events
6438 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
6441 pmu = perf_init_event(event);
6447 else if (IS_ERR(pmu))
6452 put_pid_ns(event->ns);
6454 return ERR_PTR(err);
6457 if (!event->parent) {
6458 if (event->attach_state & PERF_ATTACH_TASK)
6459 static_key_slow_inc(&perf_sched_events.key);
6460 if (event->attr.mmap || event->attr.mmap_data)
6461 atomic_inc(&nr_mmap_events);
6462 if (event->attr.comm)
6463 atomic_inc(&nr_comm_events);
6464 if (event->attr.task)
6465 atomic_inc(&nr_task_events);
6466 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
6467 err = get_callchain_buffers();
6470 return ERR_PTR(err);
6473 if (has_branch_stack(event)) {
6474 static_key_slow_inc(&perf_sched_events.key);
6475 if (!(event->attach_state & PERF_ATTACH_TASK))
6476 atomic_inc(&per_cpu(perf_branch_stack_events,
6484 static int perf_copy_attr(struct perf_event_attr __user *uattr,
6485 struct perf_event_attr *attr)
6490 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
6494 * zero the full structure, so that a short copy will be nice.
6496 memset(attr, 0, sizeof(*attr));
6498 ret = get_user(size, &uattr->size);
6502 if (size > PAGE_SIZE) /* silly large */
6505 if (!size) /* abi compat */
6506 size = PERF_ATTR_SIZE_VER0;
6508 if (size < PERF_ATTR_SIZE_VER0)
6512 * If we're handed a bigger struct than we know of,
6513 * ensure all the unknown bits are 0 - i.e. new
6514 * user-space does not rely on any kernel feature
6515 * extensions we dont know about yet.
6517 if (size > sizeof(*attr)) {
6518 unsigned char __user *addr;
6519 unsigned char __user *end;
6522 addr = (void __user *)uattr + sizeof(*attr);
6523 end = (void __user *)uattr + size;
6525 for (; addr < end; addr++) {
6526 ret = get_user(val, addr);
6532 size = sizeof(*attr);
6535 ret = copy_from_user(attr, uattr, size);
6539 if (attr->__reserved_1)
6542 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
6545 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
6548 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
6549 u64 mask = attr->branch_sample_type;
6551 /* only using defined bits */
6552 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
6555 /* at least one branch bit must be set */
6556 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
6559 /* propagate priv level, when not set for branch */
6560 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
6562 /* exclude_kernel checked on syscall entry */
6563 if (!attr->exclude_kernel)
6564 mask |= PERF_SAMPLE_BRANCH_KERNEL;
6566 if (!attr->exclude_user)
6567 mask |= PERF_SAMPLE_BRANCH_USER;
6569 if (!attr->exclude_hv)
6570 mask |= PERF_SAMPLE_BRANCH_HV;
6572 * adjust user setting (for HW filter setup)
6574 attr->branch_sample_type = mask;
6576 /* kernel level capture: check permissions */
6577 if ((mask & PERF_SAMPLE_BRANCH_KERNEL)
6578 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
6582 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
6583 ret = perf_reg_validate(attr->sample_regs_user);
6588 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
6589 if (!arch_perf_have_user_stack_dump())
6593 * We have __u32 type for the size, but so far
6594 * we can only use __u16 as maximum due to the
6595 * __u16 sample size limit.
6597 if (attr->sample_stack_user >= USHRT_MAX)
6599 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
6607 put_user(sizeof(*attr), &uattr->size);
6613 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
6615 struct ring_buffer *rb = NULL, *old_rb = NULL;
6621 /* don't allow circular references */
6622 if (event == output_event)
6626 * Don't allow cross-cpu buffers
6628 if (output_event->cpu != event->cpu)
6632 * If its not a per-cpu rb, it must be the same task.
6634 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
6638 mutex_lock(&event->mmap_mutex);
6639 /* Can't redirect output if we've got an active mmap() */
6640 if (atomic_read(&event->mmap_count))
6646 /* get the rb we want to redirect to */
6647 rb = ring_buffer_get(output_event);
6653 ring_buffer_detach(event, old_rb);
6656 ring_buffer_attach(event, rb);
6658 rcu_assign_pointer(event->rb, rb);
6661 ring_buffer_put(old_rb);
6663 * Since we detached before setting the new rb, so that we
6664 * could attach the new rb, we could have missed a wakeup.
6667 wake_up_all(&event->waitq);
6672 mutex_unlock(&event->mmap_mutex);
6679 * sys_perf_event_open - open a performance event, associate it to a task/cpu
6681 * @attr_uptr: event_id type attributes for monitoring/sampling
6684 * @group_fd: group leader event fd
6686 SYSCALL_DEFINE5(perf_event_open,
6687 struct perf_event_attr __user *, attr_uptr,
6688 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
6690 struct perf_event *group_leader = NULL, *output_event = NULL;
6691 struct perf_event *event, *sibling;
6692 struct perf_event_attr attr;
6693 struct perf_event_context *ctx;
6694 struct file *event_file = NULL;
6695 struct fd group = {NULL, 0};
6696 struct task_struct *task = NULL;
6702 /* for future expandability... */
6703 if (flags & ~PERF_FLAG_ALL)
6706 err = perf_copy_attr(attr_uptr, &attr);
6710 if (!attr.exclude_kernel) {
6711 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
6716 if (attr.sample_freq > sysctl_perf_event_sample_rate)
6721 * In cgroup mode, the pid argument is used to pass the fd
6722 * opened to the cgroup directory in cgroupfs. The cpu argument
6723 * designates the cpu on which to monitor threads from that
6726 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
6729 event_fd = get_unused_fd();
6733 if (group_fd != -1) {
6734 err = perf_fget_light(group_fd, &group);
6737 group_leader = group.file->private_data;
6738 if (flags & PERF_FLAG_FD_OUTPUT)
6739 output_event = group_leader;
6740 if (flags & PERF_FLAG_FD_NO_GROUP)
6741 group_leader = NULL;
6744 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
6745 task = find_lively_task_by_vpid(pid);
6747 err = PTR_ERR(task);
6754 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
6756 if (IS_ERR(event)) {
6757 err = PTR_ERR(event);
6761 if (flags & PERF_FLAG_PID_CGROUP) {
6762 err = perf_cgroup_connect(pid, event, &attr, group_leader);
6767 * - that has cgroup constraint on event->cpu
6768 * - that may need work on context switch
6770 atomic_inc(&per_cpu(perf_cgroup_events, event->cpu));
6771 static_key_slow_inc(&perf_sched_events.key);
6775 * Special case software events and allow them to be part of
6776 * any hardware group.
6781 (is_software_event(event) != is_software_event(group_leader))) {
6782 if (is_software_event(event)) {
6784 * If event and group_leader are not both a software
6785 * event, and event is, then group leader is not.
6787 * Allow the addition of software events to !software
6788 * groups, this is safe because software events never
6791 pmu = group_leader->pmu;
6792 } else if (is_software_event(group_leader) &&
6793 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
6795 * In case the group is a pure software group, and we
6796 * try to add a hardware event, move the whole group to
6797 * the hardware context.
6804 * Get the target context (task or percpu):
6806 ctx = find_get_context(pmu, task, event->cpu);
6813 put_task_struct(task);
6818 * Look up the group leader (we will attach this event to it):
6824 * Do not allow a recursive hierarchy (this new sibling
6825 * becoming part of another group-sibling):
6827 if (group_leader->group_leader != group_leader)
6830 * Do not allow to attach to a group in a different
6831 * task or CPU context:
6834 if (group_leader->ctx->type != ctx->type)
6837 if (group_leader->ctx != ctx)
6842 * Only a group leader can be exclusive or pinned
6844 if (attr.exclusive || attr.pinned)
6849 err = perf_event_set_output(event, output_event);
6854 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, O_RDWR);
6855 if (IS_ERR(event_file)) {
6856 err = PTR_ERR(event_file);
6861 struct perf_event_context *gctx = group_leader->ctx;
6863 mutex_lock(&gctx->mutex);
6864 perf_remove_from_context(group_leader);
6867 * Removing from the context ends up with disabled
6868 * event. What we want here is event in the initial
6869 * startup state, ready to be add into new context.
6871 perf_event__state_init(group_leader);
6872 list_for_each_entry(sibling, &group_leader->sibling_list,
6874 perf_remove_from_context(sibling);
6875 perf_event__state_init(sibling);
6878 mutex_unlock(&gctx->mutex);
6882 WARN_ON_ONCE(ctx->parent_ctx);
6883 mutex_lock(&ctx->mutex);
6887 perf_install_in_context(ctx, group_leader, event->cpu);
6889 list_for_each_entry(sibling, &group_leader->sibling_list,
6891 perf_install_in_context(ctx, sibling, event->cpu);
6896 perf_install_in_context(ctx, event, event->cpu);
6898 perf_unpin_context(ctx);
6899 mutex_unlock(&ctx->mutex);
6903 event->owner = current;
6905 mutex_lock(¤t->perf_event_mutex);
6906 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
6907 mutex_unlock(¤t->perf_event_mutex);
6910 * Precalculate sample_data sizes
6912 perf_event__header_size(event);
6913 perf_event__id_header_size(event);
6916 * Drop the reference on the group_event after placing the
6917 * new event on the sibling_list. This ensures destruction
6918 * of the group leader will find the pointer to itself in
6919 * perf_group_detach().
6922 fd_install(event_fd, event_file);
6926 perf_unpin_context(ctx);
6933 put_task_struct(task);
6937 put_unused_fd(event_fd);
6942 * perf_event_create_kernel_counter
6944 * @attr: attributes of the counter to create
6945 * @cpu: cpu in which the counter is bound
6946 * @task: task to profile (NULL for percpu)
6949 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
6950 struct task_struct *task,
6951 perf_overflow_handler_t overflow_handler,
6954 struct perf_event_context *ctx;
6955 struct perf_event *event;
6959 * Get the target context (task or percpu):
6962 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
6963 overflow_handler, context);
6964 if (IS_ERR(event)) {
6965 err = PTR_ERR(event);
6969 ctx = find_get_context(event->pmu, task, cpu);
6975 WARN_ON_ONCE(ctx->parent_ctx);
6976 mutex_lock(&ctx->mutex);
6977 perf_install_in_context(ctx, event, cpu);
6979 perf_unpin_context(ctx);
6980 mutex_unlock(&ctx->mutex);
6987 return ERR_PTR(err);
6989 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
6991 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
6993 struct perf_event_context *src_ctx;
6994 struct perf_event_context *dst_ctx;
6995 struct perf_event *event, *tmp;
6998 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
6999 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
7001 mutex_lock(&src_ctx->mutex);
7002 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
7004 perf_remove_from_context(event);
7006 list_add(&event->event_entry, &events);
7008 mutex_unlock(&src_ctx->mutex);
7012 mutex_lock(&dst_ctx->mutex);
7013 list_for_each_entry_safe(event, tmp, &events, event_entry) {
7014 list_del(&event->event_entry);
7015 if (event->state >= PERF_EVENT_STATE_OFF)
7016 event->state = PERF_EVENT_STATE_INACTIVE;
7017 perf_install_in_context(dst_ctx, event, dst_cpu);
7020 mutex_unlock(&dst_ctx->mutex);
7022 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
7024 static void sync_child_event(struct perf_event *child_event,
7025 struct task_struct *child)
7027 struct perf_event *parent_event = child_event->parent;
7030 if (child_event->attr.inherit_stat)
7031 perf_event_read_event(child_event, child);
7033 child_val = perf_event_count(child_event);
7036 * Add back the child's count to the parent's count:
7038 atomic64_add(child_val, &parent_event->child_count);
7039 atomic64_add(child_event->total_time_enabled,
7040 &parent_event->child_total_time_enabled);
7041 atomic64_add(child_event->total_time_running,
7042 &parent_event->child_total_time_running);
7045 * Remove this event from the parent's list
7047 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7048 mutex_lock(&parent_event->child_mutex);
7049 list_del_init(&child_event->child_list);
7050 mutex_unlock(&parent_event->child_mutex);
7053 * Release the parent event, if this was the last
7056 put_event(parent_event);
7060 __perf_event_exit_task(struct perf_event *child_event,
7061 struct perf_event_context *child_ctx,
7062 struct task_struct *child)
7064 if (child_event->parent) {
7065 raw_spin_lock_irq(&child_ctx->lock);
7066 perf_group_detach(child_event);
7067 raw_spin_unlock_irq(&child_ctx->lock);
7070 perf_remove_from_context(child_event);
7073 * It can happen that the parent exits first, and has events
7074 * that are still around due to the child reference. These
7075 * events need to be zapped.
7077 if (child_event->parent) {
7078 sync_child_event(child_event, child);
7079 free_event(child_event);
7083 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
7085 struct perf_event *child_event, *tmp;
7086 struct perf_event_context *child_ctx;
7087 unsigned long flags;
7089 if (likely(!child->perf_event_ctxp[ctxn])) {
7090 perf_event_task(child, NULL, 0);
7094 local_irq_save(flags);
7096 * We can't reschedule here because interrupts are disabled,
7097 * and either child is current or it is a task that can't be
7098 * scheduled, so we are now safe from rescheduling changing
7101 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
7104 * Take the context lock here so that if find_get_context is
7105 * reading child->perf_event_ctxp, we wait until it has
7106 * incremented the context's refcount before we do put_ctx below.
7108 raw_spin_lock(&child_ctx->lock);
7109 task_ctx_sched_out(child_ctx);
7110 child->perf_event_ctxp[ctxn] = NULL;
7112 * If this context is a clone; unclone it so it can't get
7113 * swapped to another process while we're removing all
7114 * the events from it.
7116 unclone_ctx(child_ctx);
7117 update_context_time(child_ctx);
7118 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7121 * Report the task dead after unscheduling the events so that we
7122 * won't get any samples after PERF_RECORD_EXIT. We can however still
7123 * get a few PERF_RECORD_READ events.
7125 perf_event_task(child, child_ctx, 0);
7128 * We can recurse on the same lock type through:
7130 * __perf_event_exit_task()
7131 * sync_child_event()
7133 * mutex_lock(&ctx->mutex)
7135 * But since its the parent context it won't be the same instance.
7137 mutex_lock(&child_ctx->mutex);
7140 list_for_each_entry_safe(child_event, tmp, &child_ctx->pinned_groups,
7142 __perf_event_exit_task(child_event, child_ctx, child);
7144 list_for_each_entry_safe(child_event, tmp, &child_ctx->flexible_groups,
7146 __perf_event_exit_task(child_event, child_ctx, child);
7149 * If the last event was a group event, it will have appended all
7150 * its siblings to the list, but we obtained 'tmp' before that which
7151 * will still point to the list head terminating the iteration.
7153 if (!list_empty(&child_ctx->pinned_groups) ||
7154 !list_empty(&child_ctx->flexible_groups))
7157 mutex_unlock(&child_ctx->mutex);
7163 * When a child task exits, feed back event values to parent events.
7165 void perf_event_exit_task(struct task_struct *child)
7167 struct perf_event *event, *tmp;
7170 mutex_lock(&child->perf_event_mutex);
7171 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
7173 list_del_init(&event->owner_entry);
7176 * Ensure the list deletion is visible before we clear
7177 * the owner, closes a race against perf_release() where
7178 * we need to serialize on the owner->perf_event_mutex.
7181 event->owner = NULL;
7183 mutex_unlock(&child->perf_event_mutex);
7185 for_each_task_context_nr(ctxn)
7186 perf_event_exit_task_context(child, ctxn);
7189 static void perf_free_event(struct perf_event *event,
7190 struct perf_event_context *ctx)
7192 struct perf_event *parent = event->parent;
7194 if (WARN_ON_ONCE(!parent))
7197 mutex_lock(&parent->child_mutex);
7198 list_del_init(&event->child_list);
7199 mutex_unlock(&parent->child_mutex);
7203 perf_group_detach(event);
7204 list_del_event(event, ctx);
7209 * free an unexposed, unused context as created by inheritance by
7210 * perf_event_init_task below, used by fork() in case of fail.
7212 void perf_event_free_task(struct task_struct *task)
7214 struct perf_event_context *ctx;
7215 struct perf_event *event, *tmp;
7218 for_each_task_context_nr(ctxn) {
7219 ctx = task->perf_event_ctxp[ctxn];
7223 mutex_lock(&ctx->mutex);
7225 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
7227 perf_free_event(event, ctx);
7229 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
7231 perf_free_event(event, ctx);
7233 if (!list_empty(&ctx->pinned_groups) ||
7234 !list_empty(&ctx->flexible_groups))
7237 mutex_unlock(&ctx->mutex);
7243 void perf_event_delayed_put(struct task_struct *task)
7247 for_each_task_context_nr(ctxn)
7248 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
7252 * inherit a event from parent task to child task:
7254 static struct perf_event *
7255 inherit_event(struct perf_event *parent_event,
7256 struct task_struct *parent,
7257 struct perf_event_context *parent_ctx,
7258 struct task_struct *child,
7259 struct perf_event *group_leader,
7260 struct perf_event_context *child_ctx)
7262 struct perf_event *child_event;
7263 unsigned long flags;
7266 * Instead of creating recursive hierarchies of events,
7267 * we link inherited events back to the original parent,
7268 * which has a filp for sure, which we use as the reference
7271 if (parent_event->parent)
7272 parent_event = parent_event->parent;
7274 child_event = perf_event_alloc(&parent_event->attr,
7277 group_leader, parent_event,
7279 if (IS_ERR(child_event))
7282 if (!atomic_long_inc_not_zero(&parent_event->refcount)) {
7283 free_event(child_event);
7290 * Make the child state follow the state of the parent event,
7291 * not its attr.disabled bit. We hold the parent's mutex,
7292 * so we won't race with perf_event_{en, dis}able_family.
7294 if (parent_event->state >= PERF_EVENT_STATE_INACTIVE)
7295 child_event->state = PERF_EVENT_STATE_INACTIVE;
7297 child_event->state = PERF_EVENT_STATE_OFF;
7299 if (parent_event->attr.freq) {
7300 u64 sample_period = parent_event->hw.sample_period;
7301 struct hw_perf_event *hwc = &child_event->hw;
7303 hwc->sample_period = sample_period;
7304 hwc->last_period = sample_period;
7306 local64_set(&hwc->period_left, sample_period);
7309 child_event->ctx = child_ctx;
7310 child_event->overflow_handler = parent_event->overflow_handler;
7311 child_event->overflow_handler_context
7312 = parent_event->overflow_handler_context;
7315 * Precalculate sample_data sizes
7317 perf_event__header_size(child_event);
7318 perf_event__id_header_size(child_event);
7321 * Link it up in the child's context:
7323 raw_spin_lock_irqsave(&child_ctx->lock, flags);
7324 add_event_to_ctx(child_event, child_ctx);
7325 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7328 * Link this into the parent event's child list
7330 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7331 mutex_lock(&parent_event->child_mutex);
7332 list_add_tail(&child_event->child_list, &parent_event->child_list);
7333 mutex_unlock(&parent_event->child_mutex);
7338 static int inherit_group(struct perf_event *parent_event,
7339 struct task_struct *parent,
7340 struct perf_event_context *parent_ctx,
7341 struct task_struct *child,
7342 struct perf_event_context *child_ctx)
7344 struct perf_event *leader;
7345 struct perf_event *sub;
7346 struct perf_event *child_ctr;
7348 leader = inherit_event(parent_event, parent, parent_ctx,
7349 child, NULL, child_ctx);
7351 return PTR_ERR(leader);
7352 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
7353 child_ctr = inherit_event(sub, parent, parent_ctx,
7354 child, leader, child_ctx);
7355 if (IS_ERR(child_ctr))
7356 return PTR_ERR(child_ctr);
7362 inherit_task_group(struct perf_event *event, struct task_struct *parent,
7363 struct perf_event_context *parent_ctx,
7364 struct task_struct *child, int ctxn,
7368 struct perf_event_context *child_ctx;
7370 if (!event->attr.inherit) {
7375 child_ctx = child->perf_event_ctxp[ctxn];
7378 * This is executed from the parent task context, so
7379 * inherit events that have been marked for cloning.
7380 * First allocate and initialize a context for the
7384 child_ctx = alloc_perf_context(event->pmu, child);
7388 child->perf_event_ctxp[ctxn] = child_ctx;
7391 ret = inherit_group(event, parent, parent_ctx,
7401 * Initialize the perf_event context in task_struct
7403 int perf_event_init_context(struct task_struct *child, int ctxn)
7405 struct perf_event_context *child_ctx, *parent_ctx;
7406 struct perf_event_context *cloned_ctx;
7407 struct perf_event *event;
7408 struct task_struct *parent = current;
7409 int inherited_all = 1;
7410 unsigned long flags;
7413 if (likely(!parent->perf_event_ctxp[ctxn]))
7417 * If the parent's context is a clone, pin it so it won't get
7420 parent_ctx = perf_pin_task_context(parent, ctxn);
7423 * No need to check if parent_ctx != NULL here; since we saw
7424 * it non-NULL earlier, the only reason for it to become NULL
7425 * is if we exit, and since we're currently in the middle of
7426 * a fork we can't be exiting at the same time.
7430 * Lock the parent list. No need to lock the child - not PID
7431 * hashed yet and not running, so nobody can access it.
7433 mutex_lock(&parent_ctx->mutex);
7436 * We dont have to disable NMIs - we are only looking at
7437 * the list, not manipulating it:
7439 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
7440 ret = inherit_task_group(event, parent, parent_ctx,
7441 child, ctxn, &inherited_all);
7447 * We can't hold ctx->lock when iterating the ->flexible_group list due
7448 * to allocations, but we need to prevent rotation because
7449 * rotate_ctx() will change the list from interrupt context.
7451 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7452 parent_ctx->rotate_disable = 1;
7453 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7455 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
7456 ret = inherit_task_group(event, parent, parent_ctx,
7457 child, ctxn, &inherited_all);
7462 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7463 parent_ctx->rotate_disable = 0;
7465 child_ctx = child->perf_event_ctxp[ctxn];
7467 if (child_ctx && inherited_all) {
7469 * Mark the child context as a clone of the parent
7470 * context, or of whatever the parent is a clone of.
7472 * Note that if the parent is a clone, the holding of
7473 * parent_ctx->lock avoids it from being uncloned.
7475 cloned_ctx = parent_ctx->parent_ctx;
7477 child_ctx->parent_ctx = cloned_ctx;
7478 child_ctx->parent_gen = parent_ctx->parent_gen;
7480 child_ctx->parent_ctx = parent_ctx;
7481 child_ctx->parent_gen = parent_ctx->generation;
7483 get_ctx(child_ctx->parent_ctx);
7486 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7487 mutex_unlock(&parent_ctx->mutex);
7489 perf_unpin_context(parent_ctx);
7490 put_ctx(parent_ctx);
7496 * Initialize the perf_event context in task_struct
7498 int perf_event_init_task(struct task_struct *child)
7502 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
7503 mutex_init(&child->perf_event_mutex);
7504 INIT_LIST_HEAD(&child->perf_event_list);
7506 for_each_task_context_nr(ctxn) {
7507 ret = perf_event_init_context(child, ctxn);
7515 static void __init perf_event_init_all_cpus(void)
7517 struct swevent_htable *swhash;
7520 for_each_possible_cpu(cpu) {
7521 swhash = &per_cpu(swevent_htable, cpu);
7522 mutex_init(&swhash->hlist_mutex);
7523 INIT_LIST_HEAD(&per_cpu(rotation_list, cpu));
7527 static void __cpuinit perf_event_init_cpu(int cpu)
7529 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7531 mutex_lock(&swhash->hlist_mutex);
7532 if (swhash->hlist_refcount > 0) {
7533 struct swevent_hlist *hlist;
7535 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
7537 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7539 mutex_unlock(&swhash->hlist_mutex);
7542 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC
7543 static void perf_pmu_rotate_stop(struct pmu *pmu)
7545 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7547 WARN_ON(!irqs_disabled());
7549 list_del_init(&cpuctx->rotation_list);
7552 static void __perf_event_exit_context(void *__info)
7554 struct perf_event_context *ctx = __info;
7555 struct perf_event *event, *tmp;
7557 perf_pmu_rotate_stop(ctx->pmu);
7559 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups, group_entry)
7560 __perf_remove_from_context(event);
7561 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups, group_entry)
7562 __perf_remove_from_context(event);
7565 static void perf_event_exit_cpu_context(int cpu)
7567 struct perf_event_context *ctx;
7571 idx = srcu_read_lock(&pmus_srcu);
7572 list_for_each_entry_rcu(pmu, &pmus, entry) {
7573 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
7575 mutex_lock(&ctx->mutex);
7576 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
7577 mutex_unlock(&ctx->mutex);
7579 srcu_read_unlock(&pmus_srcu, idx);
7582 static void perf_event_exit_cpu(int cpu)
7584 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7586 mutex_lock(&swhash->hlist_mutex);
7587 swevent_hlist_release(swhash);
7588 mutex_unlock(&swhash->hlist_mutex);
7590 perf_event_exit_cpu_context(cpu);
7593 static inline void perf_event_exit_cpu(int cpu) { }
7597 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
7601 for_each_online_cpu(cpu)
7602 perf_event_exit_cpu(cpu);
7608 * Run the perf reboot notifier at the very last possible moment so that
7609 * the generic watchdog code runs as long as possible.
7611 static struct notifier_block perf_reboot_notifier = {
7612 .notifier_call = perf_reboot,
7613 .priority = INT_MIN,
7616 static int __cpuinit
7617 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
7619 unsigned int cpu = (long)hcpu;
7621 switch (action & ~CPU_TASKS_FROZEN) {
7623 case CPU_UP_PREPARE:
7624 case CPU_DOWN_FAILED:
7625 perf_event_init_cpu(cpu);
7628 case CPU_UP_CANCELED:
7629 case CPU_DOWN_PREPARE:
7630 perf_event_exit_cpu(cpu);
7639 void __init perf_event_init(void)
7645 perf_event_init_all_cpus();
7646 init_srcu_struct(&pmus_srcu);
7647 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
7648 perf_pmu_register(&perf_cpu_clock, NULL, -1);
7649 perf_pmu_register(&perf_task_clock, NULL, -1);
7651 perf_cpu_notifier(perf_cpu_notify);
7652 register_reboot_notifier(&perf_reboot_notifier);
7654 ret = init_hw_breakpoint();
7655 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
7657 /* do not patch jump label more than once per second */
7658 jump_label_rate_limit(&perf_sched_events, HZ);
7661 * Build time assertion that we keep the data_head at the intended
7662 * location. IOW, validation we got the __reserved[] size right.
7664 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
7668 static int __init perf_event_sysfs_init(void)
7673 mutex_lock(&pmus_lock);
7675 ret = bus_register(&pmu_bus);
7679 list_for_each_entry(pmu, &pmus, entry) {
7680 if (!pmu->name || pmu->type < 0)
7683 ret = pmu_dev_alloc(pmu);
7684 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
7686 pmu_bus_running = 1;
7690 mutex_unlock(&pmus_lock);
7694 device_initcall(perf_event_sysfs_init);
7696 #ifdef CONFIG_CGROUP_PERF
7697 static struct cgroup_subsys_state *perf_cgroup_css_alloc(struct cgroup *cont)
7699 struct perf_cgroup *jc;
7701 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
7703 return ERR_PTR(-ENOMEM);
7705 jc->info = alloc_percpu(struct perf_cgroup_info);
7708 return ERR_PTR(-ENOMEM);
7714 static void perf_cgroup_css_free(struct cgroup *cont)
7716 struct perf_cgroup *jc;
7717 jc = container_of(cgroup_subsys_state(cont, perf_subsys_id),
7718 struct perf_cgroup, css);
7719 free_percpu(jc->info);
7723 static int __perf_cgroup_move(void *info)
7725 struct task_struct *task = info;
7726 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
7730 static void perf_cgroup_attach(struct cgroup *cgrp, struct cgroup_taskset *tset)
7732 struct task_struct *task;
7734 cgroup_taskset_for_each(task, cgrp, tset)
7735 task_function_call(task, __perf_cgroup_move, task);
7738 static void perf_cgroup_exit(struct cgroup *cgrp, struct cgroup *old_cgrp,
7739 struct task_struct *task)
7742 * cgroup_exit() is called in the copy_process() failure path.
7743 * Ignore this case since the task hasn't ran yet, this avoids
7744 * trying to poke a half freed task state from generic code.
7746 if (!(task->flags & PF_EXITING))
7749 task_function_call(task, __perf_cgroup_move, task);
7752 struct cgroup_subsys perf_subsys = {
7753 .name = "perf_event",
7754 .subsys_id = perf_subsys_id,
7755 .css_alloc = perf_cgroup_css_alloc,
7756 .css_free = perf_cgroup_css_free,
7757 .exit = perf_cgroup_exit,
7758 .attach = perf_cgroup_attach,
7760 #endif /* CONFIG_CGROUP_PERF */