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>
42 #include <linux/module.h>
43 #include <linux/mman.h>
44 #include <linux/compat.h>
48 #include <asm/irq_regs.h>
50 struct remote_function_call {
51 struct task_struct *p;
52 int (*func)(void *info);
57 static void remote_function(void *data)
59 struct remote_function_call *tfc = data;
60 struct task_struct *p = tfc->p;
64 if (task_cpu(p) != smp_processor_id() || !task_curr(p))
68 tfc->ret = tfc->func(tfc->info);
72 * task_function_call - call a function on the cpu on which a task runs
73 * @p: the task to evaluate
74 * @func: the function to be called
75 * @info: the function call argument
77 * Calls the function @func when the task is currently running. This might
78 * be on the current CPU, which just calls the function directly
80 * returns: @func return value, or
81 * -ESRCH - when the process isn't running
82 * -EAGAIN - when the process moved away
85 task_function_call(struct task_struct *p, int (*func) (void *info), void *info)
87 struct remote_function_call data = {
91 .ret = -ESRCH, /* No such (running) process */
95 smp_call_function_single(task_cpu(p), remote_function, &data, 1);
101 * cpu_function_call - call a function on the cpu
102 * @func: the function to be called
103 * @info: the function call argument
105 * Calls the function @func on the remote cpu.
107 * returns: @func return value or -ENXIO when the cpu is offline
109 static int cpu_function_call(int cpu, int (*func) (void *info), void *info)
111 struct remote_function_call data = {
115 .ret = -ENXIO, /* No such CPU */
118 smp_call_function_single(cpu, remote_function, &data, 1);
123 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
124 PERF_FLAG_FD_OUTPUT |\
125 PERF_FLAG_PID_CGROUP |\
126 PERF_FLAG_FD_CLOEXEC)
129 * branch priv levels that need permission checks
131 #define PERF_SAMPLE_BRANCH_PERM_PLM \
132 (PERF_SAMPLE_BRANCH_KERNEL |\
133 PERF_SAMPLE_BRANCH_HV)
136 EVENT_FLEXIBLE = 0x1,
138 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
142 * perf_sched_events : >0 events exist
143 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
145 struct static_key_deferred perf_sched_events __read_mostly;
146 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
147 static DEFINE_PER_CPU(atomic_t, perf_branch_stack_events);
149 static atomic_t nr_mmap_events __read_mostly;
150 static atomic_t nr_comm_events __read_mostly;
151 static atomic_t nr_task_events __read_mostly;
152 static atomic_t nr_freq_events __read_mostly;
154 static LIST_HEAD(pmus);
155 static DEFINE_MUTEX(pmus_lock);
156 static struct srcu_struct pmus_srcu;
159 * perf event paranoia level:
160 * -1 - not paranoid at all
161 * 0 - disallow raw tracepoint access for unpriv
162 * 1 - disallow cpu events for unpriv
163 * 2 - disallow kernel profiling for unpriv
165 int sysctl_perf_event_paranoid __read_mostly = 1;
167 /* Minimum for 512 kiB + 1 user control page */
168 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
171 * max perf event sample rate
173 #define DEFAULT_MAX_SAMPLE_RATE 100000
174 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
175 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
177 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
179 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
180 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
182 static int perf_sample_allowed_ns __read_mostly =
183 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
185 void update_perf_cpu_limits(void)
187 u64 tmp = perf_sample_period_ns;
189 tmp *= sysctl_perf_cpu_time_max_percent;
191 ACCESS_ONCE(perf_sample_allowed_ns) = tmp;
194 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
196 int perf_proc_update_handler(struct ctl_table *table, int write,
197 void __user *buffer, size_t *lenp,
200 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
205 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
206 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
207 update_perf_cpu_limits();
212 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
214 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
215 void __user *buffer, size_t *lenp,
218 int ret = proc_dointvec(table, write, buffer, lenp, ppos);
223 update_perf_cpu_limits();
229 * perf samples are done in some very critical code paths (NMIs).
230 * If they take too much CPU time, the system can lock up and not
231 * get any real work done. This will drop the sample rate when
232 * we detect that events are taking too long.
234 #define NR_ACCUMULATED_SAMPLES 128
235 static DEFINE_PER_CPU(u64, running_sample_length);
237 static void perf_duration_warn(struct irq_work *w)
239 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
240 u64 avg_local_sample_len;
241 u64 local_samples_len;
243 local_samples_len = __get_cpu_var(running_sample_length);
244 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
246 printk_ratelimited(KERN_WARNING
247 "perf interrupt took too long (%lld > %lld), lowering "
248 "kernel.perf_event_max_sample_rate to %d\n",
249 avg_local_sample_len, allowed_ns >> 1,
250 sysctl_perf_event_sample_rate);
253 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
255 void perf_sample_event_took(u64 sample_len_ns)
257 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
258 u64 avg_local_sample_len;
259 u64 local_samples_len;
264 /* decay the counter by 1 average sample */
265 local_samples_len = __get_cpu_var(running_sample_length);
266 local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES;
267 local_samples_len += sample_len_ns;
268 __get_cpu_var(running_sample_length) = local_samples_len;
271 * note: this will be biased artifically low until we have
272 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
273 * from having to maintain a count.
275 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
277 if (avg_local_sample_len <= allowed_ns)
280 if (max_samples_per_tick <= 1)
283 max_samples_per_tick = DIV_ROUND_UP(max_samples_per_tick, 2);
284 sysctl_perf_event_sample_rate = max_samples_per_tick * HZ;
285 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
287 update_perf_cpu_limits();
289 if (!irq_work_queue(&perf_duration_work)) {
290 early_printk("perf interrupt took too long (%lld > %lld), lowering "
291 "kernel.perf_event_max_sample_rate to %d\n",
292 avg_local_sample_len, allowed_ns >> 1,
293 sysctl_perf_event_sample_rate);
297 static atomic64_t perf_event_id;
299 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
300 enum event_type_t event_type);
302 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
303 enum event_type_t event_type,
304 struct task_struct *task);
306 static void update_context_time(struct perf_event_context *ctx);
307 static u64 perf_event_time(struct perf_event *event);
309 void __weak perf_event_print_debug(void) { }
311 extern __weak const char *perf_pmu_name(void)
316 static inline u64 perf_clock(void)
318 return local_clock();
321 static inline struct perf_cpu_context *
322 __get_cpu_context(struct perf_event_context *ctx)
324 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
327 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
328 struct perf_event_context *ctx)
330 raw_spin_lock(&cpuctx->ctx.lock);
332 raw_spin_lock(&ctx->lock);
335 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
336 struct perf_event_context *ctx)
339 raw_spin_unlock(&ctx->lock);
340 raw_spin_unlock(&cpuctx->ctx.lock);
343 #ifdef CONFIG_CGROUP_PERF
346 * perf_cgroup_info keeps track of time_enabled for a cgroup.
347 * This is a per-cpu dynamically allocated data structure.
349 struct perf_cgroup_info {
355 struct cgroup_subsys_state css;
356 struct perf_cgroup_info __percpu *info;
360 * Must ensure cgroup is pinned (css_get) before calling
361 * this function. In other words, we cannot call this function
362 * if there is no cgroup event for the current CPU context.
364 static inline struct perf_cgroup *
365 perf_cgroup_from_task(struct task_struct *task)
367 return container_of(task_css(task, perf_event_cgrp_id),
368 struct perf_cgroup, css);
372 perf_cgroup_match(struct perf_event *event)
374 struct perf_event_context *ctx = event->ctx;
375 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
377 /* @event doesn't care about cgroup */
381 /* wants specific cgroup scope but @cpuctx isn't associated with any */
386 * Cgroup scoping is recursive. An event enabled for a cgroup is
387 * also enabled for all its descendant cgroups. If @cpuctx's
388 * cgroup is a descendant of @event's (the test covers identity
389 * case), it's a match.
391 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
392 event->cgrp->css.cgroup);
395 static inline void perf_detach_cgroup(struct perf_event *event)
397 css_put(&event->cgrp->css);
401 static inline int is_cgroup_event(struct perf_event *event)
403 return event->cgrp != NULL;
406 static inline u64 perf_cgroup_event_time(struct perf_event *event)
408 struct perf_cgroup_info *t;
410 t = per_cpu_ptr(event->cgrp->info, event->cpu);
414 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
416 struct perf_cgroup_info *info;
421 info = this_cpu_ptr(cgrp->info);
423 info->time += now - info->timestamp;
424 info->timestamp = now;
427 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
429 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
431 __update_cgrp_time(cgrp_out);
434 static inline void update_cgrp_time_from_event(struct perf_event *event)
436 struct perf_cgroup *cgrp;
439 * ensure we access cgroup data only when needed and
440 * when we know the cgroup is pinned (css_get)
442 if (!is_cgroup_event(event))
445 cgrp = perf_cgroup_from_task(current);
447 * Do not update time when cgroup is not active
449 if (cgrp == event->cgrp)
450 __update_cgrp_time(event->cgrp);
454 perf_cgroup_set_timestamp(struct task_struct *task,
455 struct perf_event_context *ctx)
457 struct perf_cgroup *cgrp;
458 struct perf_cgroup_info *info;
461 * ctx->lock held by caller
462 * ensure we do not access cgroup data
463 * unless we have the cgroup pinned (css_get)
465 if (!task || !ctx->nr_cgroups)
468 cgrp = perf_cgroup_from_task(task);
469 info = this_cpu_ptr(cgrp->info);
470 info->timestamp = ctx->timestamp;
473 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
474 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
477 * reschedule events based on the cgroup constraint of task.
479 * mode SWOUT : schedule out everything
480 * mode SWIN : schedule in based on cgroup for next
482 void perf_cgroup_switch(struct task_struct *task, int mode)
484 struct perf_cpu_context *cpuctx;
489 * disable interrupts to avoid geting nr_cgroup
490 * changes via __perf_event_disable(). Also
493 local_irq_save(flags);
496 * we reschedule only in the presence of cgroup
497 * constrained events.
501 list_for_each_entry_rcu(pmu, &pmus, entry) {
502 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
503 if (cpuctx->unique_pmu != pmu)
504 continue; /* ensure we process each cpuctx once */
507 * perf_cgroup_events says at least one
508 * context on this CPU has cgroup events.
510 * ctx->nr_cgroups reports the number of cgroup
511 * events for a context.
513 if (cpuctx->ctx.nr_cgroups > 0) {
514 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
515 perf_pmu_disable(cpuctx->ctx.pmu);
517 if (mode & PERF_CGROUP_SWOUT) {
518 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
520 * must not be done before ctxswout due
521 * to event_filter_match() in event_sched_out()
526 if (mode & PERF_CGROUP_SWIN) {
527 WARN_ON_ONCE(cpuctx->cgrp);
529 * set cgrp before ctxsw in to allow
530 * event_filter_match() to not have to pass
533 cpuctx->cgrp = perf_cgroup_from_task(task);
534 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
536 perf_pmu_enable(cpuctx->ctx.pmu);
537 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
543 local_irq_restore(flags);
546 static inline void perf_cgroup_sched_out(struct task_struct *task,
547 struct task_struct *next)
549 struct perf_cgroup *cgrp1;
550 struct perf_cgroup *cgrp2 = NULL;
553 * we come here when we know perf_cgroup_events > 0
555 cgrp1 = perf_cgroup_from_task(task);
558 * next is NULL when called from perf_event_enable_on_exec()
559 * that will systematically cause a cgroup_switch()
562 cgrp2 = perf_cgroup_from_task(next);
565 * only schedule out current cgroup events if we know
566 * that we are switching to a different cgroup. Otherwise,
567 * do no touch the cgroup events.
570 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
573 static inline void perf_cgroup_sched_in(struct task_struct *prev,
574 struct task_struct *task)
576 struct perf_cgroup *cgrp1;
577 struct perf_cgroup *cgrp2 = NULL;
580 * we come here when we know perf_cgroup_events > 0
582 cgrp1 = perf_cgroup_from_task(task);
584 /* prev can never be NULL */
585 cgrp2 = perf_cgroup_from_task(prev);
588 * only need to schedule in cgroup events if we are changing
589 * cgroup during ctxsw. Cgroup events were not scheduled
590 * out of ctxsw out if that was not the case.
593 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
596 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
597 struct perf_event_attr *attr,
598 struct perf_event *group_leader)
600 struct perf_cgroup *cgrp;
601 struct cgroup_subsys_state *css;
602 struct fd f = fdget(fd);
608 css = css_tryget_online_from_dir(f.file->f_dentry,
609 &perf_event_cgrp_subsys);
615 cgrp = container_of(css, struct perf_cgroup, css);
619 * all events in a group must monitor
620 * the same cgroup because a task belongs
621 * to only one perf cgroup at a time
623 if (group_leader && group_leader->cgrp != cgrp) {
624 perf_detach_cgroup(event);
633 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
635 struct perf_cgroup_info *t;
636 t = per_cpu_ptr(event->cgrp->info, event->cpu);
637 event->shadow_ctx_time = now - t->timestamp;
641 perf_cgroup_defer_enabled(struct perf_event *event)
644 * when the current task's perf cgroup does not match
645 * the event's, we need to remember to call the
646 * perf_mark_enable() function the first time a task with
647 * a matching perf cgroup is scheduled in.
649 if (is_cgroup_event(event) && !perf_cgroup_match(event))
650 event->cgrp_defer_enabled = 1;
654 perf_cgroup_mark_enabled(struct perf_event *event,
655 struct perf_event_context *ctx)
657 struct perf_event *sub;
658 u64 tstamp = perf_event_time(event);
660 if (!event->cgrp_defer_enabled)
663 event->cgrp_defer_enabled = 0;
665 event->tstamp_enabled = tstamp - event->total_time_enabled;
666 list_for_each_entry(sub, &event->sibling_list, group_entry) {
667 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
668 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
669 sub->cgrp_defer_enabled = 0;
673 #else /* !CONFIG_CGROUP_PERF */
676 perf_cgroup_match(struct perf_event *event)
681 static inline void perf_detach_cgroup(struct perf_event *event)
684 static inline int is_cgroup_event(struct perf_event *event)
689 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
694 static inline void update_cgrp_time_from_event(struct perf_event *event)
698 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
702 static inline void perf_cgroup_sched_out(struct task_struct *task,
703 struct task_struct *next)
707 static inline void perf_cgroup_sched_in(struct task_struct *prev,
708 struct task_struct *task)
712 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
713 struct perf_event_attr *attr,
714 struct perf_event *group_leader)
720 perf_cgroup_set_timestamp(struct task_struct *task,
721 struct perf_event_context *ctx)
726 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
731 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
735 static inline u64 perf_cgroup_event_time(struct perf_event *event)
741 perf_cgroup_defer_enabled(struct perf_event *event)
746 perf_cgroup_mark_enabled(struct perf_event *event,
747 struct perf_event_context *ctx)
753 * set default to be dependent on timer tick just
756 #define PERF_CPU_HRTIMER (1000 / HZ)
758 * function must be called with interrupts disbled
760 static enum hrtimer_restart perf_cpu_hrtimer_handler(struct hrtimer *hr)
762 struct perf_cpu_context *cpuctx;
763 enum hrtimer_restart ret = HRTIMER_NORESTART;
766 WARN_ON(!irqs_disabled());
768 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
770 rotations = perf_rotate_context(cpuctx);
773 * arm timer if needed
776 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
777 ret = HRTIMER_RESTART;
783 /* CPU is going down */
784 void perf_cpu_hrtimer_cancel(int cpu)
786 struct perf_cpu_context *cpuctx;
790 if (WARN_ON(cpu != smp_processor_id()))
793 local_irq_save(flags);
797 list_for_each_entry_rcu(pmu, &pmus, entry) {
798 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
800 if (pmu->task_ctx_nr == perf_sw_context)
803 hrtimer_cancel(&cpuctx->hrtimer);
808 local_irq_restore(flags);
811 static void __perf_cpu_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
813 struct hrtimer *hr = &cpuctx->hrtimer;
814 struct pmu *pmu = cpuctx->ctx.pmu;
817 /* no multiplexing needed for SW PMU */
818 if (pmu->task_ctx_nr == perf_sw_context)
822 * check default is sane, if not set then force to
823 * default interval (1/tick)
825 timer = pmu->hrtimer_interval_ms;
827 timer = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
829 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
831 hrtimer_init(hr, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
832 hr->function = perf_cpu_hrtimer_handler;
835 static void perf_cpu_hrtimer_restart(struct perf_cpu_context *cpuctx)
837 struct hrtimer *hr = &cpuctx->hrtimer;
838 struct pmu *pmu = cpuctx->ctx.pmu;
841 if (pmu->task_ctx_nr == perf_sw_context)
844 if (hrtimer_active(hr))
847 if (!hrtimer_callback_running(hr))
848 __hrtimer_start_range_ns(hr, cpuctx->hrtimer_interval,
849 0, HRTIMER_MODE_REL_PINNED, 0);
852 void perf_pmu_disable(struct pmu *pmu)
854 int *count = this_cpu_ptr(pmu->pmu_disable_count);
856 pmu->pmu_disable(pmu);
859 void perf_pmu_enable(struct pmu *pmu)
861 int *count = this_cpu_ptr(pmu->pmu_disable_count);
863 pmu->pmu_enable(pmu);
866 static DEFINE_PER_CPU(struct list_head, rotation_list);
869 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
870 * because they're strictly cpu affine and rotate_start is called with IRQs
871 * disabled, while rotate_context is called from IRQ context.
873 static void perf_pmu_rotate_start(struct pmu *pmu)
875 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
876 struct list_head *head = &__get_cpu_var(rotation_list);
878 WARN_ON(!irqs_disabled());
880 if (list_empty(&cpuctx->rotation_list))
881 list_add(&cpuctx->rotation_list, head);
884 static void get_ctx(struct perf_event_context *ctx)
886 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
889 static void put_ctx(struct perf_event_context *ctx)
891 if (atomic_dec_and_test(&ctx->refcount)) {
893 put_ctx(ctx->parent_ctx);
895 put_task_struct(ctx->task);
896 kfree_rcu(ctx, rcu_head);
900 static void unclone_ctx(struct perf_event_context *ctx)
902 if (ctx->parent_ctx) {
903 put_ctx(ctx->parent_ctx);
904 ctx->parent_ctx = NULL;
909 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
912 * only top level events have the pid namespace they were created in
915 event = event->parent;
917 return task_tgid_nr_ns(p, event->ns);
920 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
923 * only top level events have the pid namespace they were created in
926 event = event->parent;
928 return task_pid_nr_ns(p, event->ns);
932 * If we inherit events we want to return the parent event id
935 static u64 primary_event_id(struct perf_event *event)
940 id = event->parent->id;
946 * Get the perf_event_context for a task and lock it.
947 * This has to cope with with the fact that until it is locked,
948 * the context could get moved to another task.
950 static struct perf_event_context *
951 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
953 struct perf_event_context *ctx;
957 * One of the few rules of preemptible RCU is that one cannot do
958 * rcu_read_unlock() while holding a scheduler (or nested) lock when
959 * part of the read side critical section was preemptible -- see
960 * rcu_read_unlock_special().
962 * Since ctx->lock nests under rq->lock we must ensure the entire read
963 * side critical section is non-preemptible.
967 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
970 * If this context is a clone of another, it might
971 * get swapped for another underneath us by
972 * perf_event_task_sched_out, though the
973 * rcu_read_lock() protects us from any context
974 * getting freed. Lock the context and check if it
975 * got swapped before we could get the lock, and retry
976 * if so. If we locked the right context, then it
977 * can't get swapped on us any more.
979 raw_spin_lock_irqsave(&ctx->lock, *flags);
980 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
981 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
987 if (!atomic_inc_not_zero(&ctx->refcount)) {
988 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
998 * Get the context for a task and increment its pin_count so it
999 * can't get swapped to another task. This also increments its
1000 * reference count so that the context can't get freed.
1002 static struct perf_event_context *
1003 perf_pin_task_context(struct task_struct *task, int ctxn)
1005 struct perf_event_context *ctx;
1006 unsigned long flags;
1008 ctx = perf_lock_task_context(task, ctxn, &flags);
1011 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1016 static void perf_unpin_context(struct perf_event_context *ctx)
1018 unsigned long flags;
1020 raw_spin_lock_irqsave(&ctx->lock, flags);
1022 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1026 * Update the record of the current time in a context.
1028 static void update_context_time(struct perf_event_context *ctx)
1030 u64 now = perf_clock();
1032 ctx->time += now - ctx->timestamp;
1033 ctx->timestamp = now;
1036 static u64 perf_event_time(struct perf_event *event)
1038 struct perf_event_context *ctx = event->ctx;
1040 if (is_cgroup_event(event))
1041 return perf_cgroup_event_time(event);
1043 return ctx ? ctx->time : 0;
1047 * Update the total_time_enabled and total_time_running fields for a event.
1048 * The caller of this function needs to hold the ctx->lock.
1050 static void update_event_times(struct perf_event *event)
1052 struct perf_event_context *ctx = event->ctx;
1055 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1056 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1059 * in cgroup mode, time_enabled represents
1060 * the time the event was enabled AND active
1061 * tasks were in the monitored cgroup. This is
1062 * independent of the activity of the context as
1063 * there may be a mix of cgroup and non-cgroup events.
1065 * That is why we treat cgroup events differently
1068 if (is_cgroup_event(event))
1069 run_end = perf_cgroup_event_time(event);
1070 else if (ctx->is_active)
1071 run_end = ctx->time;
1073 run_end = event->tstamp_stopped;
1075 event->total_time_enabled = run_end - event->tstamp_enabled;
1077 if (event->state == PERF_EVENT_STATE_INACTIVE)
1078 run_end = event->tstamp_stopped;
1080 run_end = perf_event_time(event);
1082 event->total_time_running = run_end - event->tstamp_running;
1087 * Update total_time_enabled and total_time_running for all events in a group.
1089 static void update_group_times(struct perf_event *leader)
1091 struct perf_event *event;
1093 update_event_times(leader);
1094 list_for_each_entry(event, &leader->sibling_list, group_entry)
1095 update_event_times(event);
1098 static struct list_head *
1099 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1101 if (event->attr.pinned)
1102 return &ctx->pinned_groups;
1104 return &ctx->flexible_groups;
1108 * Add a event from the lists for its context.
1109 * Must be called with ctx->mutex and ctx->lock held.
1112 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1114 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1115 event->attach_state |= PERF_ATTACH_CONTEXT;
1118 * If we're a stand alone event or group leader, we go to the context
1119 * list, group events are kept attached to the group so that
1120 * perf_group_detach can, at all times, locate all siblings.
1122 if (event->group_leader == event) {
1123 struct list_head *list;
1125 if (is_software_event(event))
1126 event->group_flags |= PERF_GROUP_SOFTWARE;
1128 list = ctx_group_list(event, ctx);
1129 list_add_tail(&event->group_entry, list);
1132 if (is_cgroup_event(event))
1135 if (has_branch_stack(event))
1136 ctx->nr_branch_stack++;
1138 list_add_rcu(&event->event_entry, &ctx->event_list);
1139 if (!ctx->nr_events)
1140 perf_pmu_rotate_start(ctx->pmu);
1142 if (event->attr.inherit_stat)
1149 * Initialize event state based on the perf_event_attr::disabled.
1151 static inline void perf_event__state_init(struct perf_event *event)
1153 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1154 PERF_EVENT_STATE_INACTIVE;
1158 * Called at perf_event creation and when events are attached/detached from a
1161 static void perf_event__read_size(struct perf_event *event)
1163 int entry = sizeof(u64); /* value */
1167 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1168 size += sizeof(u64);
1170 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1171 size += sizeof(u64);
1173 if (event->attr.read_format & PERF_FORMAT_ID)
1174 entry += sizeof(u64);
1176 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1177 nr += event->group_leader->nr_siblings;
1178 size += sizeof(u64);
1182 event->read_size = size;
1185 static void perf_event__header_size(struct perf_event *event)
1187 struct perf_sample_data *data;
1188 u64 sample_type = event->attr.sample_type;
1191 perf_event__read_size(event);
1193 if (sample_type & PERF_SAMPLE_IP)
1194 size += sizeof(data->ip);
1196 if (sample_type & PERF_SAMPLE_ADDR)
1197 size += sizeof(data->addr);
1199 if (sample_type & PERF_SAMPLE_PERIOD)
1200 size += sizeof(data->period);
1202 if (sample_type & PERF_SAMPLE_WEIGHT)
1203 size += sizeof(data->weight);
1205 if (sample_type & PERF_SAMPLE_READ)
1206 size += event->read_size;
1208 if (sample_type & PERF_SAMPLE_DATA_SRC)
1209 size += sizeof(data->data_src.val);
1211 if (sample_type & PERF_SAMPLE_TRANSACTION)
1212 size += sizeof(data->txn);
1214 event->header_size = size;
1217 static void perf_event__id_header_size(struct perf_event *event)
1219 struct perf_sample_data *data;
1220 u64 sample_type = event->attr.sample_type;
1223 if (sample_type & PERF_SAMPLE_TID)
1224 size += sizeof(data->tid_entry);
1226 if (sample_type & PERF_SAMPLE_TIME)
1227 size += sizeof(data->time);
1229 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1230 size += sizeof(data->id);
1232 if (sample_type & PERF_SAMPLE_ID)
1233 size += sizeof(data->id);
1235 if (sample_type & PERF_SAMPLE_STREAM_ID)
1236 size += sizeof(data->stream_id);
1238 if (sample_type & PERF_SAMPLE_CPU)
1239 size += sizeof(data->cpu_entry);
1241 event->id_header_size = size;
1244 static void perf_group_attach(struct perf_event *event)
1246 struct perf_event *group_leader = event->group_leader, *pos;
1249 * We can have double attach due to group movement in perf_event_open.
1251 if (event->attach_state & PERF_ATTACH_GROUP)
1254 event->attach_state |= PERF_ATTACH_GROUP;
1256 if (group_leader == event)
1259 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1260 !is_software_event(event))
1261 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1263 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1264 group_leader->nr_siblings++;
1266 perf_event__header_size(group_leader);
1268 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1269 perf_event__header_size(pos);
1273 * Remove a event from the lists for its context.
1274 * Must be called with ctx->mutex and ctx->lock held.
1277 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1279 struct perf_cpu_context *cpuctx;
1281 * We can have double detach due to exit/hot-unplug + close.
1283 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1286 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1288 if (is_cgroup_event(event)) {
1290 cpuctx = __get_cpu_context(ctx);
1292 * if there are no more cgroup events
1293 * then cler cgrp to avoid stale pointer
1294 * in update_cgrp_time_from_cpuctx()
1296 if (!ctx->nr_cgroups)
1297 cpuctx->cgrp = NULL;
1300 if (has_branch_stack(event))
1301 ctx->nr_branch_stack--;
1304 if (event->attr.inherit_stat)
1307 list_del_rcu(&event->event_entry);
1309 if (event->group_leader == event)
1310 list_del_init(&event->group_entry);
1312 update_group_times(event);
1315 * If event was in error state, then keep it
1316 * that way, otherwise bogus counts will be
1317 * returned on read(). The only way to get out
1318 * of error state is by explicit re-enabling
1321 if (event->state > PERF_EVENT_STATE_OFF)
1322 event->state = PERF_EVENT_STATE_OFF;
1327 static void perf_group_detach(struct perf_event *event)
1329 struct perf_event *sibling, *tmp;
1330 struct list_head *list = NULL;
1333 * We can have double detach due to exit/hot-unplug + close.
1335 if (!(event->attach_state & PERF_ATTACH_GROUP))
1338 event->attach_state &= ~PERF_ATTACH_GROUP;
1341 * If this is a sibling, remove it from its group.
1343 if (event->group_leader != event) {
1344 list_del_init(&event->group_entry);
1345 event->group_leader->nr_siblings--;
1349 if (!list_empty(&event->group_entry))
1350 list = &event->group_entry;
1353 * If this was a group event with sibling events then
1354 * upgrade the siblings to singleton events by adding them
1355 * to whatever list we are on.
1357 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1359 list_move_tail(&sibling->group_entry, list);
1360 sibling->group_leader = sibling;
1362 /* Inherit group flags from the previous leader */
1363 sibling->group_flags = event->group_flags;
1367 perf_event__header_size(event->group_leader);
1369 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1370 perf_event__header_size(tmp);
1374 event_filter_match(struct perf_event *event)
1376 return (event->cpu == -1 || event->cpu == smp_processor_id())
1377 && perf_cgroup_match(event);
1381 event_sched_out(struct perf_event *event,
1382 struct perf_cpu_context *cpuctx,
1383 struct perf_event_context *ctx)
1385 u64 tstamp = perf_event_time(event);
1388 * An event which could not be activated because of
1389 * filter mismatch still needs to have its timings
1390 * maintained, otherwise bogus information is return
1391 * via read() for time_enabled, time_running:
1393 if (event->state == PERF_EVENT_STATE_INACTIVE
1394 && !event_filter_match(event)) {
1395 delta = tstamp - event->tstamp_stopped;
1396 event->tstamp_running += delta;
1397 event->tstamp_stopped = tstamp;
1400 if (event->state != PERF_EVENT_STATE_ACTIVE)
1403 perf_pmu_disable(event->pmu);
1405 event->state = PERF_EVENT_STATE_INACTIVE;
1406 if (event->pending_disable) {
1407 event->pending_disable = 0;
1408 event->state = PERF_EVENT_STATE_OFF;
1410 event->tstamp_stopped = tstamp;
1411 event->pmu->del(event, 0);
1414 if (!is_software_event(event))
1415 cpuctx->active_oncpu--;
1417 if (event->attr.freq && event->attr.sample_freq)
1419 if (event->attr.exclusive || !cpuctx->active_oncpu)
1420 cpuctx->exclusive = 0;
1422 perf_pmu_enable(event->pmu);
1426 group_sched_out(struct perf_event *group_event,
1427 struct perf_cpu_context *cpuctx,
1428 struct perf_event_context *ctx)
1430 struct perf_event *event;
1431 int state = group_event->state;
1433 event_sched_out(group_event, cpuctx, ctx);
1436 * Schedule out siblings (if any):
1438 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1439 event_sched_out(event, cpuctx, ctx);
1441 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1442 cpuctx->exclusive = 0;
1445 struct remove_event {
1446 struct perf_event *event;
1451 * Cross CPU call to remove a performance event
1453 * We disable the event on the hardware level first. After that we
1454 * remove it from the context list.
1456 static int __perf_remove_from_context(void *info)
1458 struct remove_event *re = info;
1459 struct perf_event *event = re->event;
1460 struct perf_event_context *ctx = event->ctx;
1461 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1463 raw_spin_lock(&ctx->lock);
1464 event_sched_out(event, cpuctx, ctx);
1465 if (re->detach_group)
1466 perf_group_detach(event);
1467 list_del_event(event, ctx);
1468 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1470 cpuctx->task_ctx = NULL;
1472 raw_spin_unlock(&ctx->lock);
1479 * Remove the event from a task's (or a CPU's) list of events.
1481 * CPU events are removed with a smp call. For task events we only
1482 * call when the task is on a CPU.
1484 * If event->ctx is a cloned context, callers must make sure that
1485 * every task struct that event->ctx->task could possibly point to
1486 * remains valid. This is OK when called from perf_release since
1487 * that only calls us on the top-level context, which can't be a clone.
1488 * When called from perf_event_exit_task, it's OK because the
1489 * context has been detached from its task.
1491 static void perf_remove_from_context(struct perf_event *event, bool detach_group)
1493 struct perf_event_context *ctx = event->ctx;
1494 struct task_struct *task = ctx->task;
1495 struct remove_event re = {
1497 .detach_group = detach_group,
1500 lockdep_assert_held(&ctx->mutex);
1504 * Per cpu events are removed via an smp call and
1505 * the removal is always successful.
1507 cpu_function_call(event->cpu, __perf_remove_from_context, &re);
1512 if (!task_function_call(task, __perf_remove_from_context, &re))
1515 raw_spin_lock_irq(&ctx->lock);
1517 * If we failed to find a running task, but find the context active now
1518 * that we've acquired the ctx->lock, retry.
1520 if (ctx->is_active) {
1521 raw_spin_unlock_irq(&ctx->lock);
1523 * Reload the task pointer, it might have been changed by
1524 * a concurrent perf_event_context_sched_out().
1531 * Since the task isn't running, its safe to remove the event, us
1532 * holding the ctx->lock ensures the task won't get scheduled in.
1535 perf_group_detach(event);
1536 list_del_event(event, ctx);
1537 raw_spin_unlock_irq(&ctx->lock);
1541 * Cross CPU call to disable a performance event
1543 int __perf_event_disable(void *info)
1545 struct perf_event *event = info;
1546 struct perf_event_context *ctx = event->ctx;
1547 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1550 * If this is a per-task event, need to check whether this
1551 * event's task is the current task on this cpu.
1553 * Can trigger due to concurrent perf_event_context_sched_out()
1554 * flipping contexts around.
1556 if (ctx->task && cpuctx->task_ctx != ctx)
1559 raw_spin_lock(&ctx->lock);
1562 * If the event is on, turn it off.
1563 * If it is in error state, leave it in error state.
1565 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1566 update_context_time(ctx);
1567 update_cgrp_time_from_event(event);
1568 update_group_times(event);
1569 if (event == event->group_leader)
1570 group_sched_out(event, cpuctx, ctx);
1572 event_sched_out(event, cpuctx, ctx);
1573 event->state = PERF_EVENT_STATE_OFF;
1576 raw_spin_unlock(&ctx->lock);
1584 * If event->ctx is a cloned context, callers must make sure that
1585 * every task struct that event->ctx->task could possibly point to
1586 * remains valid. This condition is satisifed when called through
1587 * perf_event_for_each_child or perf_event_for_each because they
1588 * hold the top-level event's child_mutex, so any descendant that
1589 * goes to exit will block in sync_child_event.
1590 * When called from perf_pending_event it's OK because event->ctx
1591 * is the current context on this CPU and preemption is disabled,
1592 * hence we can't get into perf_event_task_sched_out for this context.
1594 void perf_event_disable(struct perf_event *event)
1596 struct perf_event_context *ctx = event->ctx;
1597 struct task_struct *task = ctx->task;
1601 * Disable the event on the cpu that it's on
1603 cpu_function_call(event->cpu, __perf_event_disable, event);
1608 if (!task_function_call(task, __perf_event_disable, event))
1611 raw_spin_lock_irq(&ctx->lock);
1613 * If the event is still active, we need to retry the cross-call.
1615 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1616 raw_spin_unlock_irq(&ctx->lock);
1618 * Reload the task pointer, it might have been changed by
1619 * a concurrent perf_event_context_sched_out().
1626 * Since we have the lock this context can't be scheduled
1627 * in, so we can change the state safely.
1629 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1630 update_group_times(event);
1631 event->state = PERF_EVENT_STATE_OFF;
1633 raw_spin_unlock_irq(&ctx->lock);
1635 EXPORT_SYMBOL_GPL(perf_event_disable);
1637 static void perf_set_shadow_time(struct perf_event *event,
1638 struct perf_event_context *ctx,
1642 * use the correct time source for the time snapshot
1644 * We could get by without this by leveraging the
1645 * fact that to get to this function, the caller
1646 * has most likely already called update_context_time()
1647 * and update_cgrp_time_xx() and thus both timestamp
1648 * are identical (or very close). Given that tstamp is,
1649 * already adjusted for cgroup, we could say that:
1650 * tstamp - ctx->timestamp
1652 * tstamp - cgrp->timestamp.
1654 * Then, in perf_output_read(), the calculation would
1655 * work with no changes because:
1656 * - event is guaranteed scheduled in
1657 * - no scheduled out in between
1658 * - thus the timestamp would be the same
1660 * But this is a bit hairy.
1662 * So instead, we have an explicit cgroup call to remain
1663 * within the time time source all along. We believe it
1664 * is cleaner and simpler to understand.
1666 if (is_cgroup_event(event))
1667 perf_cgroup_set_shadow_time(event, tstamp);
1669 event->shadow_ctx_time = tstamp - ctx->timestamp;
1672 #define MAX_INTERRUPTS (~0ULL)
1674 static void perf_log_throttle(struct perf_event *event, int enable);
1677 event_sched_in(struct perf_event *event,
1678 struct perf_cpu_context *cpuctx,
1679 struct perf_event_context *ctx)
1681 u64 tstamp = perf_event_time(event);
1684 lockdep_assert_held(&ctx->lock);
1686 if (event->state <= PERF_EVENT_STATE_OFF)
1689 event->state = PERF_EVENT_STATE_ACTIVE;
1690 event->oncpu = smp_processor_id();
1693 * Unthrottle events, since we scheduled we might have missed several
1694 * ticks already, also for a heavily scheduling task there is little
1695 * guarantee it'll get a tick in a timely manner.
1697 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1698 perf_log_throttle(event, 1);
1699 event->hw.interrupts = 0;
1703 * The new state must be visible before we turn it on in the hardware:
1707 perf_pmu_disable(event->pmu);
1709 if (event->pmu->add(event, PERF_EF_START)) {
1710 event->state = PERF_EVENT_STATE_INACTIVE;
1716 event->tstamp_running += tstamp - event->tstamp_stopped;
1718 perf_set_shadow_time(event, ctx, tstamp);
1720 if (!is_software_event(event))
1721 cpuctx->active_oncpu++;
1723 if (event->attr.freq && event->attr.sample_freq)
1726 if (event->attr.exclusive)
1727 cpuctx->exclusive = 1;
1730 perf_pmu_enable(event->pmu);
1736 group_sched_in(struct perf_event *group_event,
1737 struct perf_cpu_context *cpuctx,
1738 struct perf_event_context *ctx)
1740 struct perf_event *event, *partial_group = NULL;
1741 struct pmu *pmu = ctx->pmu;
1742 u64 now = ctx->time;
1743 bool simulate = false;
1745 if (group_event->state == PERF_EVENT_STATE_OFF)
1748 pmu->start_txn(pmu);
1750 if (event_sched_in(group_event, cpuctx, ctx)) {
1751 pmu->cancel_txn(pmu);
1752 perf_cpu_hrtimer_restart(cpuctx);
1757 * Schedule in siblings as one group (if any):
1759 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1760 if (event_sched_in(event, cpuctx, ctx)) {
1761 partial_group = event;
1766 if (!pmu->commit_txn(pmu))
1771 * Groups can be scheduled in as one unit only, so undo any
1772 * partial group before returning:
1773 * The events up to the failed event are scheduled out normally,
1774 * tstamp_stopped will be updated.
1776 * The failed events and the remaining siblings need to have
1777 * their timings updated as if they had gone thru event_sched_in()
1778 * and event_sched_out(). This is required to get consistent timings
1779 * across the group. This also takes care of the case where the group
1780 * could never be scheduled by ensuring tstamp_stopped is set to mark
1781 * the time the event was actually stopped, such that time delta
1782 * calculation in update_event_times() is correct.
1784 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1785 if (event == partial_group)
1789 event->tstamp_running += now - event->tstamp_stopped;
1790 event->tstamp_stopped = now;
1792 event_sched_out(event, cpuctx, ctx);
1795 event_sched_out(group_event, cpuctx, ctx);
1797 pmu->cancel_txn(pmu);
1799 perf_cpu_hrtimer_restart(cpuctx);
1805 * Work out whether we can put this event group on the CPU now.
1807 static int group_can_go_on(struct perf_event *event,
1808 struct perf_cpu_context *cpuctx,
1812 * Groups consisting entirely of software events can always go on.
1814 if (event->group_flags & PERF_GROUP_SOFTWARE)
1817 * If an exclusive group is already on, no other hardware
1820 if (cpuctx->exclusive)
1823 * If this group is exclusive and there are already
1824 * events on the CPU, it can't go on.
1826 if (event->attr.exclusive && cpuctx->active_oncpu)
1829 * Otherwise, try to add it if all previous groups were able
1835 static void add_event_to_ctx(struct perf_event *event,
1836 struct perf_event_context *ctx)
1838 u64 tstamp = perf_event_time(event);
1840 list_add_event(event, ctx);
1841 perf_group_attach(event);
1842 event->tstamp_enabled = tstamp;
1843 event->tstamp_running = tstamp;
1844 event->tstamp_stopped = tstamp;
1847 static void task_ctx_sched_out(struct perf_event_context *ctx);
1849 ctx_sched_in(struct perf_event_context *ctx,
1850 struct perf_cpu_context *cpuctx,
1851 enum event_type_t event_type,
1852 struct task_struct *task);
1854 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
1855 struct perf_event_context *ctx,
1856 struct task_struct *task)
1858 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
1860 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
1861 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
1863 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
1867 * Cross CPU call to install and enable a performance event
1869 * Must be called with ctx->mutex held
1871 static int __perf_install_in_context(void *info)
1873 struct perf_event *event = info;
1874 struct perf_event_context *ctx = event->ctx;
1875 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1876 struct perf_event_context *task_ctx = cpuctx->task_ctx;
1877 struct task_struct *task = current;
1879 perf_ctx_lock(cpuctx, task_ctx);
1880 perf_pmu_disable(cpuctx->ctx.pmu);
1883 * If there was an active task_ctx schedule it out.
1886 task_ctx_sched_out(task_ctx);
1889 * If the context we're installing events in is not the
1890 * active task_ctx, flip them.
1892 if (ctx->task && task_ctx != ctx) {
1894 raw_spin_unlock(&task_ctx->lock);
1895 raw_spin_lock(&ctx->lock);
1900 cpuctx->task_ctx = task_ctx;
1901 task = task_ctx->task;
1904 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
1906 update_context_time(ctx);
1908 * update cgrp time only if current cgrp
1909 * matches event->cgrp. Must be done before
1910 * calling add_event_to_ctx()
1912 update_cgrp_time_from_event(event);
1914 add_event_to_ctx(event, ctx);
1917 * Schedule everything back in
1919 perf_event_sched_in(cpuctx, task_ctx, task);
1921 perf_pmu_enable(cpuctx->ctx.pmu);
1922 perf_ctx_unlock(cpuctx, task_ctx);
1928 * Attach a performance event to a context
1930 * First we add the event to the list with the hardware enable bit
1931 * in event->hw_config cleared.
1933 * If the event is attached to a task which is on a CPU we use a smp
1934 * call to enable it in the task context. The task might have been
1935 * scheduled away, but we check this in the smp call again.
1938 perf_install_in_context(struct perf_event_context *ctx,
1939 struct perf_event *event,
1942 struct task_struct *task = ctx->task;
1944 lockdep_assert_held(&ctx->mutex);
1947 if (event->cpu != -1)
1952 * Per cpu events are installed via an smp call and
1953 * the install is always successful.
1955 cpu_function_call(cpu, __perf_install_in_context, event);
1960 if (!task_function_call(task, __perf_install_in_context, event))
1963 raw_spin_lock_irq(&ctx->lock);
1965 * If we failed to find a running task, but find the context active now
1966 * that we've acquired the ctx->lock, retry.
1968 if (ctx->is_active) {
1969 raw_spin_unlock_irq(&ctx->lock);
1971 * Reload the task pointer, it might have been changed by
1972 * a concurrent perf_event_context_sched_out().
1979 * Since the task isn't running, its safe to add the event, us holding
1980 * the ctx->lock ensures the task won't get scheduled in.
1982 add_event_to_ctx(event, ctx);
1983 raw_spin_unlock_irq(&ctx->lock);
1987 * Put a event into inactive state and update time fields.
1988 * Enabling the leader of a group effectively enables all
1989 * the group members that aren't explicitly disabled, so we
1990 * have to update their ->tstamp_enabled also.
1991 * Note: this works for group members as well as group leaders
1992 * since the non-leader members' sibling_lists will be empty.
1994 static void __perf_event_mark_enabled(struct perf_event *event)
1996 struct perf_event *sub;
1997 u64 tstamp = perf_event_time(event);
1999 event->state = PERF_EVENT_STATE_INACTIVE;
2000 event->tstamp_enabled = tstamp - event->total_time_enabled;
2001 list_for_each_entry(sub, &event->sibling_list, group_entry) {
2002 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2003 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2008 * Cross CPU call to enable a performance event
2010 static int __perf_event_enable(void *info)
2012 struct perf_event *event = info;
2013 struct perf_event_context *ctx = event->ctx;
2014 struct perf_event *leader = event->group_leader;
2015 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2019 * There's a time window between 'ctx->is_active' check
2020 * in perf_event_enable function and this place having:
2022 * - ctx->lock unlocked
2024 * where the task could be killed and 'ctx' deactivated
2025 * by perf_event_exit_task.
2027 if (!ctx->is_active)
2030 raw_spin_lock(&ctx->lock);
2031 update_context_time(ctx);
2033 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2037 * set current task's cgroup time reference point
2039 perf_cgroup_set_timestamp(current, ctx);
2041 __perf_event_mark_enabled(event);
2043 if (!event_filter_match(event)) {
2044 if (is_cgroup_event(event))
2045 perf_cgroup_defer_enabled(event);
2050 * If the event is in a group and isn't the group leader,
2051 * then don't put it on unless the group is on.
2053 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
2056 if (!group_can_go_on(event, cpuctx, 1)) {
2059 if (event == leader)
2060 err = group_sched_in(event, cpuctx, ctx);
2062 err = event_sched_in(event, cpuctx, ctx);
2067 * If this event can't go on and it's part of a
2068 * group, then the whole group has to come off.
2070 if (leader != event) {
2071 group_sched_out(leader, cpuctx, ctx);
2072 perf_cpu_hrtimer_restart(cpuctx);
2074 if (leader->attr.pinned) {
2075 update_group_times(leader);
2076 leader->state = PERF_EVENT_STATE_ERROR;
2081 raw_spin_unlock(&ctx->lock);
2089 * If event->ctx is a cloned context, callers must make sure that
2090 * every task struct that event->ctx->task could possibly point to
2091 * remains valid. This condition is satisfied when called through
2092 * perf_event_for_each_child or perf_event_for_each as described
2093 * for perf_event_disable.
2095 void perf_event_enable(struct perf_event *event)
2097 struct perf_event_context *ctx = event->ctx;
2098 struct task_struct *task = ctx->task;
2102 * Enable the event on the cpu that it's on
2104 cpu_function_call(event->cpu, __perf_event_enable, event);
2108 raw_spin_lock_irq(&ctx->lock);
2109 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2113 * If the event is in error state, clear that first.
2114 * That way, if we see the event in error state below, we
2115 * know that it has gone back into error state, as distinct
2116 * from the task having been scheduled away before the
2117 * cross-call arrived.
2119 if (event->state == PERF_EVENT_STATE_ERROR)
2120 event->state = PERF_EVENT_STATE_OFF;
2123 if (!ctx->is_active) {
2124 __perf_event_mark_enabled(event);
2128 raw_spin_unlock_irq(&ctx->lock);
2130 if (!task_function_call(task, __perf_event_enable, event))
2133 raw_spin_lock_irq(&ctx->lock);
2136 * If the context is active and the event is still off,
2137 * we need to retry the cross-call.
2139 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
2141 * task could have been flipped by a concurrent
2142 * perf_event_context_sched_out()
2149 raw_spin_unlock_irq(&ctx->lock);
2151 EXPORT_SYMBOL_GPL(perf_event_enable);
2153 int perf_event_refresh(struct perf_event *event, int refresh)
2156 * not supported on inherited events
2158 if (event->attr.inherit || !is_sampling_event(event))
2161 atomic_add(refresh, &event->event_limit);
2162 perf_event_enable(event);
2166 EXPORT_SYMBOL_GPL(perf_event_refresh);
2168 static void ctx_sched_out(struct perf_event_context *ctx,
2169 struct perf_cpu_context *cpuctx,
2170 enum event_type_t event_type)
2172 struct perf_event *event;
2173 int is_active = ctx->is_active;
2175 ctx->is_active &= ~event_type;
2176 if (likely(!ctx->nr_events))
2179 update_context_time(ctx);
2180 update_cgrp_time_from_cpuctx(cpuctx);
2181 if (!ctx->nr_active)
2184 perf_pmu_disable(ctx->pmu);
2185 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2186 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2187 group_sched_out(event, cpuctx, ctx);
2190 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2191 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2192 group_sched_out(event, cpuctx, ctx);
2194 perf_pmu_enable(ctx->pmu);
2198 * Test whether two contexts are equivalent, i.e. whether they have both been
2199 * cloned from the same version of the same context.
2201 * Equivalence is measured using a generation number in the context that is
2202 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2203 * and list_del_event().
2205 static int context_equiv(struct perf_event_context *ctx1,
2206 struct perf_event_context *ctx2)
2208 /* Pinning disables the swap optimization */
2209 if (ctx1->pin_count || ctx2->pin_count)
2212 /* If ctx1 is the parent of ctx2 */
2213 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2216 /* If ctx2 is the parent of ctx1 */
2217 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2221 * If ctx1 and ctx2 have the same parent; we flatten the parent
2222 * hierarchy, see perf_event_init_context().
2224 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2225 ctx1->parent_gen == ctx2->parent_gen)
2232 static void __perf_event_sync_stat(struct perf_event *event,
2233 struct perf_event *next_event)
2237 if (!event->attr.inherit_stat)
2241 * Update the event value, we cannot use perf_event_read()
2242 * because we're in the middle of a context switch and have IRQs
2243 * disabled, which upsets smp_call_function_single(), however
2244 * we know the event must be on the current CPU, therefore we
2245 * don't need to use it.
2247 switch (event->state) {
2248 case PERF_EVENT_STATE_ACTIVE:
2249 event->pmu->read(event);
2252 case PERF_EVENT_STATE_INACTIVE:
2253 update_event_times(event);
2261 * In order to keep per-task stats reliable we need to flip the event
2262 * values when we flip the contexts.
2264 value = local64_read(&next_event->count);
2265 value = local64_xchg(&event->count, value);
2266 local64_set(&next_event->count, value);
2268 swap(event->total_time_enabled, next_event->total_time_enabled);
2269 swap(event->total_time_running, next_event->total_time_running);
2272 * Since we swizzled the values, update the user visible data too.
2274 perf_event_update_userpage(event);
2275 perf_event_update_userpage(next_event);
2278 static void perf_event_sync_stat(struct perf_event_context *ctx,
2279 struct perf_event_context *next_ctx)
2281 struct perf_event *event, *next_event;
2286 update_context_time(ctx);
2288 event = list_first_entry(&ctx->event_list,
2289 struct perf_event, event_entry);
2291 next_event = list_first_entry(&next_ctx->event_list,
2292 struct perf_event, event_entry);
2294 while (&event->event_entry != &ctx->event_list &&
2295 &next_event->event_entry != &next_ctx->event_list) {
2297 __perf_event_sync_stat(event, next_event);
2299 event = list_next_entry(event, event_entry);
2300 next_event = list_next_entry(next_event, event_entry);
2304 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2305 struct task_struct *next)
2307 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2308 struct perf_event_context *next_ctx;
2309 struct perf_event_context *parent, *next_parent;
2310 struct perf_cpu_context *cpuctx;
2316 cpuctx = __get_cpu_context(ctx);
2317 if (!cpuctx->task_ctx)
2321 next_ctx = next->perf_event_ctxp[ctxn];
2325 parent = rcu_dereference(ctx->parent_ctx);
2326 next_parent = rcu_dereference(next_ctx->parent_ctx);
2328 /* If neither context have a parent context; they cannot be clones. */
2329 if (!parent || !next_parent)
2332 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2334 * Looks like the two contexts are clones, so we might be
2335 * able to optimize the context switch. We lock both
2336 * contexts and check that they are clones under the
2337 * lock (including re-checking that neither has been
2338 * uncloned in the meantime). It doesn't matter which
2339 * order we take the locks because no other cpu could
2340 * be trying to lock both of these tasks.
2342 raw_spin_lock(&ctx->lock);
2343 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2344 if (context_equiv(ctx, next_ctx)) {
2346 * XXX do we need a memory barrier of sorts
2347 * wrt to rcu_dereference() of perf_event_ctxp
2349 task->perf_event_ctxp[ctxn] = next_ctx;
2350 next->perf_event_ctxp[ctxn] = ctx;
2352 next_ctx->task = task;
2355 perf_event_sync_stat(ctx, next_ctx);
2357 raw_spin_unlock(&next_ctx->lock);
2358 raw_spin_unlock(&ctx->lock);
2364 raw_spin_lock(&ctx->lock);
2365 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2366 cpuctx->task_ctx = NULL;
2367 raw_spin_unlock(&ctx->lock);
2371 #define for_each_task_context_nr(ctxn) \
2372 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2375 * Called from scheduler to remove the events of the current task,
2376 * with interrupts disabled.
2378 * We stop each event and update the event value in event->count.
2380 * This does not protect us against NMI, but disable()
2381 * sets the disabled bit in the control field of event _before_
2382 * accessing the event control register. If a NMI hits, then it will
2383 * not restart the event.
2385 void __perf_event_task_sched_out(struct task_struct *task,
2386 struct task_struct *next)
2390 for_each_task_context_nr(ctxn)
2391 perf_event_context_sched_out(task, ctxn, next);
2394 * if cgroup events exist on this CPU, then we need
2395 * to check if we have to switch out PMU state.
2396 * cgroup event are system-wide mode only
2398 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2399 perf_cgroup_sched_out(task, next);
2402 static void task_ctx_sched_out(struct perf_event_context *ctx)
2404 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2406 if (!cpuctx->task_ctx)
2409 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2412 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2413 cpuctx->task_ctx = NULL;
2417 * Called with IRQs disabled
2419 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2420 enum event_type_t event_type)
2422 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2426 ctx_pinned_sched_in(struct perf_event_context *ctx,
2427 struct perf_cpu_context *cpuctx)
2429 struct perf_event *event;
2431 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2432 if (event->state <= PERF_EVENT_STATE_OFF)
2434 if (!event_filter_match(event))
2437 /* may need to reset tstamp_enabled */
2438 if (is_cgroup_event(event))
2439 perf_cgroup_mark_enabled(event, ctx);
2441 if (group_can_go_on(event, cpuctx, 1))
2442 group_sched_in(event, cpuctx, ctx);
2445 * If this pinned group hasn't been scheduled,
2446 * put it in error state.
2448 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2449 update_group_times(event);
2450 event->state = PERF_EVENT_STATE_ERROR;
2456 ctx_flexible_sched_in(struct perf_event_context *ctx,
2457 struct perf_cpu_context *cpuctx)
2459 struct perf_event *event;
2462 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2463 /* Ignore events in OFF or ERROR state */
2464 if (event->state <= PERF_EVENT_STATE_OFF)
2467 * Listen to the 'cpu' scheduling filter constraint
2470 if (!event_filter_match(event))
2473 /* may need to reset tstamp_enabled */
2474 if (is_cgroup_event(event))
2475 perf_cgroup_mark_enabled(event, ctx);
2477 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2478 if (group_sched_in(event, cpuctx, ctx))
2485 ctx_sched_in(struct perf_event_context *ctx,
2486 struct perf_cpu_context *cpuctx,
2487 enum event_type_t event_type,
2488 struct task_struct *task)
2491 int is_active = ctx->is_active;
2493 ctx->is_active |= event_type;
2494 if (likely(!ctx->nr_events))
2498 ctx->timestamp = now;
2499 perf_cgroup_set_timestamp(task, ctx);
2501 * First go through the list and put on any pinned groups
2502 * in order to give them the best chance of going on.
2504 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2505 ctx_pinned_sched_in(ctx, cpuctx);
2507 /* Then walk through the lower prio flexible groups */
2508 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2509 ctx_flexible_sched_in(ctx, cpuctx);
2512 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2513 enum event_type_t event_type,
2514 struct task_struct *task)
2516 struct perf_event_context *ctx = &cpuctx->ctx;
2518 ctx_sched_in(ctx, cpuctx, event_type, task);
2521 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2522 struct task_struct *task)
2524 struct perf_cpu_context *cpuctx;
2526 cpuctx = __get_cpu_context(ctx);
2527 if (cpuctx->task_ctx == ctx)
2530 perf_ctx_lock(cpuctx, ctx);
2531 perf_pmu_disable(ctx->pmu);
2533 * We want to keep the following priority order:
2534 * cpu pinned (that don't need to move), task pinned,
2535 * cpu flexible, task flexible.
2537 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2540 cpuctx->task_ctx = ctx;
2542 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2544 perf_pmu_enable(ctx->pmu);
2545 perf_ctx_unlock(cpuctx, ctx);
2548 * Since these rotations are per-cpu, we need to ensure the
2549 * cpu-context we got scheduled on is actually rotating.
2551 perf_pmu_rotate_start(ctx->pmu);
2555 * When sampling the branck stack in system-wide, it may be necessary
2556 * to flush the stack on context switch. This happens when the branch
2557 * stack does not tag its entries with the pid of the current task.
2558 * Otherwise it becomes impossible to associate a branch entry with a
2559 * task. This ambiguity is more likely to appear when the branch stack
2560 * supports priv level filtering and the user sets it to monitor only
2561 * at the user level (which could be a useful measurement in system-wide
2562 * mode). In that case, the risk is high of having a branch stack with
2563 * branch from multiple tasks. Flushing may mean dropping the existing
2564 * entries or stashing them somewhere in the PMU specific code layer.
2566 * This function provides the context switch callback to the lower code
2567 * layer. It is invoked ONLY when there is at least one system-wide context
2568 * with at least one active event using taken branch sampling.
2570 static void perf_branch_stack_sched_in(struct task_struct *prev,
2571 struct task_struct *task)
2573 struct perf_cpu_context *cpuctx;
2575 unsigned long flags;
2577 /* no need to flush branch stack if not changing task */
2581 local_irq_save(flags);
2585 list_for_each_entry_rcu(pmu, &pmus, entry) {
2586 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2589 * check if the context has at least one
2590 * event using PERF_SAMPLE_BRANCH_STACK
2592 if (cpuctx->ctx.nr_branch_stack > 0
2593 && pmu->flush_branch_stack) {
2595 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2597 perf_pmu_disable(pmu);
2599 pmu->flush_branch_stack();
2601 perf_pmu_enable(pmu);
2603 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2609 local_irq_restore(flags);
2613 * Called from scheduler to add the events of the current task
2614 * with interrupts disabled.
2616 * We restore the event value and then enable it.
2618 * This does not protect us against NMI, but enable()
2619 * sets the enabled bit in the control field of event _before_
2620 * accessing the event control register. If a NMI hits, then it will
2621 * keep the event running.
2623 void __perf_event_task_sched_in(struct task_struct *prev,
2624 struct task_struct *task)
2626 struct perf_event_context *ctx;
2629 for_each_task_context_nr(ctxn) {
2630 ctx = task->perf_event_ctxp[ctxn];
2634 perf_event_context_sched_in(ctx, task);
2637 * if cgroup events exist on this CPU, then we need
2638 * to check if we have to switch in PMU state.
2639 * cgroup event are system-wide mode only
2641 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2642 perf_cgroup_sched_in(prev, task);
2644 /* check for system-wide branch_stack events */
2645 if (atomic_read(&__get_cpu_var(perf_branch_stack_events)))
2646 perf_branch_stack_sched_in(prev, task);
2649 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2651 u64 frequency = event->attr.sample_freq;
2652 u64 sec = NSEC_PER_SEC;
2653 u64 divisor, dividend;
2655 int count_fls, nsec_fls, frequency_fls, sec_fls;
2657 count_fls = fls64(count);
2658 nsec_fls = fls64(nsec);
2659 frequency_fls = fls64(frequency);
2663 * We got @count in @nsec, with a target of sample_freq HZ
2664 * the target period becomes:
2667 * period = -------------------
2668 * @nsec * sample_freq
2673 * Reduce accuracy by one bit such that @a and @b converge
2674 * to a similar magnitude.
2676 #define REDUCE_FLS(a, b) \
2678 if (a##_fls > b##_fls) { \
2688 * Reduce accuracy until either term fits in a u64, then proceed with
2689 * the other, so that finally we can do a u64/u64 division.
2691 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2692 REDUCE_FLS(nsec, frequency);
2693 REDUCE_FLS(sec, count);
2696 if (count_fls + sec_fls > 64) {
2697 divisor = nsec * frequency;
2699 while (count_fls + sec_fls > 64) {
2700 REDUCE_FLS(count, sec);
2704 dividend = count * sec;
2706 dividend = count * sec;
2708 while (nsec_fls + frequency_fls > 64) {
2709 REDUCE_FLS(nsec, frequency);
2713 divisor = nsec * frequency;
2719 return div64_u64(dividend, divisor);
2722 static DEFINE_PER_CPU(int, perf_throttled_count);
2723 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2725 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2727 struct hw_perf_event *hwc = &event->hw;
2728 s64 period, sample_period;
2731 period = perf_calculate_period(event, nsec, count);
2733 delta = (s64)(period - hwc->sample_period);
2734 delta = (delta + 7) / 8; /* low pass filter */
2736 sample_period = hwc->sample_period + delta;
2741 hwc->sample_period = sample_period;
2743 if (local64_read(&hwc->period_left) > 8*sample_period) {
2745 event->pmu->stop(event, PERF_EF_UPDATE);
2747 local64_set(&hwc->period_left, 0);
2750 event->pmu->start(event, PERF_EF_RELOAD);
2755 * combine freq adjustment with unthrottling to avoid two passes over the
2756 * events. At the same time, make sure, having freq events does not change
2757 * the rate of unthrottling as that would introduce bias.
2759 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
2762 struct perf_event *event;
2763 struct hw_perf_event *hwc;
2764 u64 now, period = TICK_NSEC;
2768 * only need to iterate over all events iff:
2769 * - context have events in frequency mode (needs freq adjust)
2770 * - there are events to unthrottle on this cpu
2772 if (!(ctx->nr_freq || needs_unthr))
2775 raw_spin_lock(&ctx->lock);
2776 perf_pmu_disable(ctx->pmu);
2778 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
2779 if (event->state != PERF_EVENT_STATE_ACTIVE)
2782 if (!event_filter_match(event))
2785 perf_pmu_disable(event->pmu);
2789 if (hwc->interrupts == MAX_INTERRUPTS) {
2790 hwc->interrupts = 0;
2791 perf_log_throttle(event, 1);
2792 event->pmu->start(event, 0);
2795 if (!event->attr.freq || !event->attr.sample_freq)
2799 * stop the event and update event->count
2801 event->pmu->stop(event, PERF_EF_UPDATE);
2803 now = local64_read(&event->count);
2804 delta = now - hwc->freq_count_stamp;
2805 hwc->freq_count_stamp = now;
2809 * reload only if value has changed
2810 * we have stopped the event so tell that
2811 * to perf_adjust_period() to avoid stopping it
2815 perf_adjust_period(event, period, delta, false);
2817 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
2819 perf_pmu_enable(event->pmu);
2822 perf_pmu_enable(ctx->pmu);
2823 raw_spin_unlock(&ctx->lock);
2827 * Round-robin a context's events:
2829 static void rotate_ctx(struct perf_event_context *ctx)
2832 * Rotate the first entry last of non-pinned groups. Rotation might be
2833 * disabled by the inheritance code.
2835 if (!ctx->rotate_disable)
2836 list_rotate_left(&ctx->flexible_groups);
2840 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
2841 * because they're strictly cpu affine and rotate_start is called with IRQs
2842 * disabled, while rotate_context is called from IRQ context.
2844 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
2846 struct perf_event_context *ctx = NULL;
2847 int rotate = 0, remove = 1;
2849 if (cpuctx->ctx.nr_events) {
2851 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
2855 ctx = cpuctx->task_ctx;
2856 if (ctx && ctx->nr_events) {
2858 if (ctx->nr_events != ctx->nr_active)
2865 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2866 perf_pmu_disable(cpuctx->ctx.pmu);
2868 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2870 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
2872 rotate_ctx(&cpuctx->ctx);
2876 perf_event_sched_in(cpuctx, ctx, current);
2878 perf_pmu_enable(cpuctx->ctx.pmu);
2879 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2882 list_del_init(&cpuctx->rotation_list);
2887 #ifdef CONFIG_NO_HZ_FULL
2888 bool perf_event_can_stop_tick(void)
2890 if (atomic_read(&nr_freq_events) ||
2891 __this_cpu_read(perf_throttled_count))
2898 void perf_event_task_tick(void)
2900 struct list_head *head = &__get_cpu_var(rotation_list);
2901 struct perf_cpu_context *cpuctx, *tmp;
2902 struct perf_event_context *ctx;
2905 WARN_ON(!irqs_disabled());
2907 __this_cpu_inc(perf_throttled_seq);
2908 throttled = __this_cpu_xchg(perf_throttled_count, 0);
2910 list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) {
2912 perf_adjust_freq_unthr_context(ctx, throttled);
2914 ctx = cpuctx->task_ctx;
2916 perf_adjust_freq_unthr_context(ctx, throttled);
2920 static int event_enable_on_exec(struct perf_event *event,
2921 struct perf_event_context *ctx)
2923 if (!event->attr.enable_on_exec)
2926 event->attr.enable_on_exec = 0;
2927 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2930 __perf_event_mark_enabled(event);
2936 * Enable all of a task's events that have been marked enable-on-exec.
2937 * This expects task == current.
2939 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
2941 struct perf_event *event;
2942 unsigned long flags;
2946 local_irq_save(flags);
2947 if (!ctx || !ctx->nr_events)
2951 * We must ctxsw out cgroup events to avoid conflict
2952 * when invoking perf_task_event_sched_in() later on
2953 * in this function. Otherwise we end up trying to
2954 * ctxswin cgroup events which are already scheduled
2957 perf_cgroup_sched_out(current, NULL);
2959 raw_spin_lock(&ctx->lock);
2960 task_ctx_sched_out(ctx);
2962 list_for_each_entry(event, &ctx->event_list, event_entry) {
2963 ret = event_enable_on_exec(event, ctx);
2969 * Unclone this context if we enabled any event.
2974 raw_spin_unlock(&ctx->lock);
2977 * Also calls ctxswin for cgroup events, if any:
2979 perf_event_context_sched_in(ctx, ctx->task);
2981 local_irq_restore(flags);
2984 void perf_event_exec(void)
2986 struct perf_event_context *ctx;
2990 for_each_task_context_nr(ctxn) {
2991 ctx = current->perf_event_ctxp[ctxn];
2995 perf_event_enable_on_exec(ctx);
3001 * Cross CPU call to read the hardware event
3003 static void __perf_event_read(void *info)
3005 struct perf_event *event = info;
3006 struct perf_event_context *ctx = event->ctx;
3007 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3010 * If this is a task context, we need to check whether it is
3011 * the current task context of this cpu. If not it has been
3012 * scheduled out before the smp call arrived. In that case
3013 * event->count would have been updated to a recent sample
3014 * when the event was scheduled out.
3016 if (ctx->task && cpuctx->task_ctx != ctx)
3019 raw_spin_lock(&ctx->lock);
3020 if (ctx->is_active) {
3021 update_context_time(ctx);
3022 update_cgrp_time_from_event(event);
3024 update_event_times(event);
3025 if (event->state == PERF_EVENT_STATE_ACTIVE)
3026 event->pmu->read(event);
3027 raw_spin_unlock(&ctx->lock);
3030 static inline u64 perf_event_count(struct perf_event *event)
3032 return local64_read(&event->count) + atomic64_read(&event->child_count);
3035 static u64 perf_event_read(struct perf_event *event)
3038 * If event is enabled and currently active on a CPU, update the
3039 * value in the event structure:
3041 if (event->state == PERF_EVENT_STATE_ACTIVE) {
3042 smp_call_function_single(event->oncpu,
3043 __perf_event_read, event, 1);
3044 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3045 struct perf_event_context *ctx = event->ctx;
3046 unsigned long flags;
3048 raw_spin_lock_irqsave(&ctx->lock, flags);
3050 * may read while context is not active
3051 * (e.g., thread is blocked), in that case
3052 * we cannot update context time
3054 if (ctx->is_active) {
3055 update_context_time(ctx);
3056 update_cgrp_time_from_event(event);
3058 update_event_times(event);
3059 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3062 return perf_event_count(event);
3066 * Initialize the perf_event context in a task_struct:
3068 static void __perf_event_init_context(struct perf_event_context *ctx)
3070 raw_spin_lock_init(&ctx->lock);
3071 mutex_init(&ctx->mutex);
3072 INIT_LIST_HEAD(&ctx->pinned_groups);
3073 INIT_LIST_HEAD(&ctx->flexible_groups);
3074 INIT_LIST_HEAD(&ctx->event_list);
3075 atomic_set(&ctx->refcount, 1);
3078 static struct perf_event_context *
3079 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3081 struct perf_event_context *ctx;
3083 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3087 __perf_event_init_context(ctx);
3090 get_task_struct(task);
3097 static struct task_struct *
3098 find_lively_task_by_vpid(pid_t vpid)
3100 struct task_struct *task;
3107 task = find_task_by_vpid(vpid);
3109 get_task_struct(task);
3113 return ERR_PTR(-ESRCH);
3115 /* Reuse ptrace permission checks for now. */
3117 if (!ptrace_may_access(task, PTRACE_MODE_READ))
3122 put_task_struct(task);
3123 return ERR_PTR(err);
3128 * Returns a matching context with refcount and pincount.
3130 static struct perf_event_context *
3131 find_get_context(struct pmu *pmu, struct task_struct *task, int cpu)
3133 struct perf_event_context *ctx;
3134 struct perf_cpu_context *cpuctx;
3135 unsigned long flags;
3139 /* Must be root to operate on a CPU event: */
3140 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3141 return ERR_PTR(-EACCES);
3144 * We could be clever and allow to attach a event to an
3145 * offline CPU and activate it when the CPU comes up, but
3148 if (!cpu_online(cpu))
3149 return ERR_PTR(-ENODEV);
3151 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3160 ctxn = pmu->task_ctx_nr;
3165 ctx = perf_lock_task_context(task, ctxn, &flags);
3169 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3171 ctx = alloc_perf_context(pmu, task);
3177 mutex_lock(&task->perf_event_mutex);
3179 * If it has already passed perf_event_exit_task().
3180 * we must see PF_EXITING, it takes this mutex too.
3182 if (task->flags & PF_EXITING)
3184 else if (task->perf_event_ctxp[ctxn])
3189 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3191 mutex_unlock(&task->perf_event_mutex);
3193 if (unlikely(err)) {
3205 return ERR_PTR(err);
3208 static void perf_event_free_filter(struct perf_event *event);
3210 static void free_event_rcu(struct rcu_head *head)
3212 struct perf_event *event;
3214 event = container_of(head, struct perf_event, rcu_head);
3216 put_pid_ns(event->ns);
3217 perf_event_free_filter(event);
3221 static void ring_buffer_put(struct ring_buffer *rb);
3222 static void ring_buffer_attach(struct perf_event *event,
3223 struct ring_buffer *rb);
3225 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3230 if (has_branch_stack(event)) {
3231 if (!(event->attach_state & PERF_ATTACH_TASK))
3232 atomic_dec(&per_cpu(perf_branch_stack_events, cpu));
3234 if (is_cgroup_event(event))
3235 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3238 static void unaccount_event(struct perf_event *event)
3243 if (event->attach_state & PERF_ATTACH_TASK)
3244 static_key_slow_dec_deferred(&perf_sched_events);
3245 if (event->attr.mmap || event->attr.mmap_data)
3246 atomic_dec(&nr_mmap_events);
3247 if (event->attr.comm)
3248 atomic_dec(&nr_comm_events);
3249 if (event->attr.task)
3250 atomic_dec(&nr_task_events);
3251 if (event->attr.freq)
3252 atomic_dec(&nr_freq_events);
3253 if (is_cgroup_event(event))
3254 static_key_slow_dec_deferred(&perf_sched_events);
3255 if (has_branch_stack(event))
3256 static_key_slow_dec_deferred(&perf_sched_events);
3258 unaccount_event_cpu(event, event->cpu);
3261 static void __free_event(struct perf_event *event)
3263 if (!event->parent) {
3264 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3265 put_callchain_buffers();
3269 event->destroy(event);
3272 put_ctx(event->ctx);
3275 module_put(event->pmu->module);
3277 call_rcu(&event->rcu_head, free_event_rcu);
3280 static void _free_event(struct perf_event *event)
3282 irq_work_sync(&event->pending);
3284 unaccount_event(event);
3288 * Can happen when we close an event with re-directed output.
3290 * Since we have a 0 refcount, perf_mmap_close() will skip
3291 * over us; possibly making our ring_buffer_put() the last.
3293 mutex_lock(&event->mmap_mutex);
3294 ring_buffer_attach(event, NULL);
3295 mutex_unlock(&event->mmap_mutex);
3298 if (is_cgroup_event(event))
3299 perf_detach_cgroup(event);
3301 __free_event(event);
3305 * Used to free events which have a known refcount of 1, such as in error paths
3306 * where the event isn't exposed yet and inherited events.
3308 static void free_event(struct perf_event *event)
3310 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3311 "unexpected event refcount: %ld; ptr=%p\n",
3312 atomic_long_read(&event->refcount), event)) {
3313 /* leak to avoid use-after-free */
3321 * Called when the last reference to the file is gone.
3323 static void put_event(struct perf_event *event)
3325 struct perf_event_context *ctx = event->ctx;
3326 struct task_struct *owner;
3328 if (!atomic_long_dec_and_test(&event->refcount))
3332 owner = ACCESS_ONCE(event->owner);
3334 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3335 * !owner it means the list deletion is complete and we can indeed
3336 * free this event, otherwise we need to serialize on
3337 * owner->perf_event_mutex.
3339 smp_read_barrier_depends();
3342 * Since delayed_put_task_struct() also drops the last
3343 * task reference we can safely take a new reference
3344 * while holding the rcu_read_lock().
3346 get_task_struct(owner);
3351 mutex_lock(&owner->perf_event_mutex);
3353 * We have to re-check the event->owner field, if it is cleared
3354 * we raced with perf_event_exit_task(), acquiring the mutex
3355 * ensured they're done, and we can proceed with freeing the
3359 list_del_init(&event->owner_entry);
3360 mutex_unlock(&owner->perf_event_mutex);
3361 put_task_struct(owner);
3364 WARN_ON_ONCE(ctx->parent_ctx);
3366 * There are two ways this annotation is useful:
3368 * 1) there is a lock recursion from perf_event_exit_task
3369 * see the comment there.
3371 * 2) there is a lock-inversion with mmap_sem through
3372 * perf_event_read_group(), which takes faults while
3373 * holding ctx->mutex, however this is called after
3374 * the last filedesc died, so there is no possibility
3375 * to trigger the AB-BA case.
3377 mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
3378 perf_remove_from_context(event, true);
3379 mutex_unlock(&ctx->mutex);
3384 int perf_event_release_kernel(struct perf_event *event)
3389 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3391 static int perf_release(struct inode *inode, struct file *file)
3393 put_event(file->private_data);
3397 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3399 struct perf_event *child;
3405 mutex_lock(&event->child_mutex);
3406 total += perf_event_read(event);
3407 *enabled += event->total_time_enabled +
3408 atomic64_read(&event->child_total_time_enabled);
3409 *running += event->total_time_running +
3410 atomic64_read(&event->child_total_time_running);
3412 list_for_each_entry(child, &event->child_list, child_list) {
3413 total += perf_event_read(child);
3414 *enabled += child->total_time_enabled;
3415 *running += child->total_time_running;
3417 mutex_unlock(&event->child_mutex);
3421 EXPORT_SYMBOL_GPL(perf_event_read_value);
3423 static int perf_event_read_group(struct perf_event *event,
3424 u64 read_format, char __user *buf)
3426 struct perf_event *leader = event->group_leader, *sub;
3427 int n = 0, size = 0, ret = -EFAULT;
3428 struct perf_event_context *ctx = leader->ctx;
3430 u64 count, enabled, running;
3432 mutex_lock(&ctx->mutex);
3433 count = perf_event_read_value(leader, &enabled, &running);
3435 values[n++] = 1 + leader->nr_siblings;
3436 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3437 values[n++] = enabled;
3438 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3439 values[n++] = running;
3440 values[n++] = count;
3441 if (read_format & PERF_FORMAT_ID)
3442 values[n++] = primary_event_id(leader);
3444 size = n * sizeof(u64);
3446 if (copy_to_user(buf, values, size))
3451 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3454 values[n++] = perf_event_read_value(sub, &enabled, &running);
3455 if (read_format & PERF_FORMAT_ID)
3456 values[n++] = primary_event_id(sub);
3458 size = n * sizeof(u64);
3460 if (copy_to_user(buf + ret, values, size)) {
3468 mutex_unlock(&ctx->mutex);
3473 static int perf_event_read_one(struct perf_event *event,
3474 u64 read_format, char __user *buf)
3476 u64 enabled, running;
3480 values[n++] = perf_event_read_value(event, &enabled, &running);
3481 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3482 values[n++] = enabled;
3483 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3484 values[n++] = running;
3485 if (read_format & PERF_FORMAT_ID)
3486 values[n++] = primary_event_id(event);
3488 if (copy_to_user(buf, values, n * sizeof(u64)))
3491 return n * sizeof(u64);
3495 * Read the performance event - simple non blocking version for now
3498 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
3500 u64 read_format = event->attr.read_format;
3504 * Return end-of-file for a read on a event that is in
3505 * error state (i.e. because it was pinned but it couldn't be
3506 * scheduled on to the CPU at some point).
3508 if (event->state == PERF_EVENT_STATE_ERROR)
3511 if (count < event->read_size)
3514 WARN_ON_ONCE(event->ctx->parent_ctx);
3515 if (read_format & PERF_FORMAT_GROUP)
3516 ret = perf_event_read_group(event, read_format, buf);
3518 ret = perf_event_read_one(event, read_format, buf);
3524 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
3526 struct perf_event *event = file->private_data;
3528 return perf_read_hw(event, buf, count);
3531 static unsigned int perf_poll(struct file *file, poll_table *wait)
3533 struct perf_event *event = file->private_data;
3534 struct ring_buffer *rb;
3535 unsigned int events = POLL_HUP;
3538 * Pin the event->rb by taking event->mmap_mutex; otherwise
3539 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
3541 mutex_lock(&event->mmap_mutex);
3544 events = atomic_xchg(&rb->poll, 0);
3545 mutex_unlock(&event->mmap_mutex);
3547 poll_wait(file, &event->waitq, wait);
3552 static void perf_event_reset(struct perf_event *event)
3554 (void)perf_event_read(event);
3555 local64_set(&event->count, 0);
3556 perf_event_update_userpage(event);
3560 * Holding the top-level event's child_mutex means that any
3561 * descendant process that has inherited this event will block
3562 * in sync_child_event if it goes to exit, thus satisfying the
3563 * task existence requirements of perf_event_enable/disable.
3565 static void perf_event_for_each_child(struct perf_event *event,
3566 void (*func)(struct perf_event *))
3568 struct perf_event *child;
3570 WARN_ON_ONCE(event->ctx->parent_ctx);
3571 mutex_lock(&event->child_mutex);
3573 list_for_each_entry(child, &event->child_list, child_list)
3575 mutex_unlock(&event->child_mutex);
3578 static void perf_event_for_each(struct perf_event *event,
3579 void (*func)(struct perf_event *))
3581 struct perf_event_context *ctx = event->ctx;
3582 struct perf_event *sibling;
3584 WARN_ON_ONCE(ctx->parent_ctx);
3585 mutex_lock(&ctx->mutex);
3586 event = event->group_leader;
3588 perf_event_for_each_child(event, func);
3589 list_for_each_entry(sibling, &event->sibling_list, group_entry)
3590 perf_event_for_each_child(sibling, func);
3591 mutex_unlock(&ctx->mutex);
3594 static int perf_event_period(struct perf_event *event, u64 __user *arg)
3596 struct perf_event_context *ctx = event->ctx;
3597 int ret = 0, active;
3600 if (!is_sampling_event(event))
3603 if (copy_from_user(&value, arg, sizeof(value)))
3609 raw_spin_lock_irq(&ctx->lock);
3610 if (event->attr.freq) {
3611 if (value > sysctl_perf_event_sample_rate) {
3616 event->attr.sample_freq = value;
3618 event->attr.sample_period = value;
3619 event->hw.sample_period = value;
3622 active = (event->state == PERF_EVENT_STATE_ACTIVE);
3624 perf_pmu_disable(ctx->pmu);
3625 event->pmu->stop(event, PERF_EF_UPDATE);
3628 local64_set(&event->hw.period_left, 0);
3631 event->pmu->start(event, PERF_EF_RELOAD);
3632 perf_pmu_enable(ctx->pmu);
3636 raw_spin_unlock_irq(&ctx->lock);
3641 static const struct file_operations perf_fops;
3643 static inline int perf_fget_light(int fd, struct fd *p)
3645 struct fd f = fdget(fd);
3649 if (f.file->f_op != &perf_fops) {
3657 static int perf_event_set_output(struct perf_event *event,
3658 struct perf_event *output_event);
3659 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
3661 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
3663 struct perf_event *event = file->private_data;
3664 void (*func)(struct perf_event *);
3668 case PERF_EVENT_IOC_ENABLE:
3669 func = perf_event_enable;
3671 case PERF_EVENT_IOC_DISABLE:
3672 func = perf_event_disable;
3674 case PERF_EVENT_IOC_RESET:
3675 func = perf_event_reset;
3678 case PERF_EVENT_IOC_REFRESH:
3679 return perf_event_refresh(event, arg);
3681 case PERF_EVENT_IOC_PERIOD:
3682 return perf_event_period(event, (u64 __user *)arg);
3684 case PERF_EVENT_IOC_ID:
3686 u64 id = primary_event_id(event);
3688 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
3693 case PERF_EVENT_IOC_SET_OUTPUT:
3697 struct perf_event *output_event;
3699 ret = perf_fget_light(arg, &output);
3702 output_event = output.file->private_data;
3703 ret = perf_event_set_output(event, output_event);
3706 ret = perf_event_set_output(event, NULL);
3711 case PERF_EVENT_IOC_SET_FILTER:
3712 return perf_event_set_filter(event, (void __user *)arg);
3718 if (flags & PERF_IOC_FLAG_GROUP)
3719 perf_event_for_each(event, func);
3721 perf_event_for_each_child(event, func);
3726 #ifdef CONFIG_COMPAT
3727 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
3730 switch (_IOC_NR(cmd)) {
3731 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
3732 case _IOC_NR(PERF_EVENT_IOC_ID):
3733 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
3734 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
3735 cmd &= ~IOCSIZE_MASK;
3736 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
3740 return perf_ioctl(file, cmd, arg);
3743 # define perf_compat_ioctl NULL
3746 int perf_event_task_enable(void)
3748 struct perf_event *event;
3750 mutex_lock(¤t->perf_event_mutex);
3751 list_for_each_entry(event, ¤t->perf_event_list, owner_entry)
3752 perf_event_for_each_child(event, perf_event_enable);
3753 mutex_unlock(¤t->perf_event_mutex);
3758 int perf_event_task_disable(void)
3760 struct perf_event *event;
3762 mutex_lock(¤t->perf_event_mutex);
3763 list_for_each_entry(event, ¤t->perf_event_list, owner_entry)
3764 perf_event_for_each_child(event, perf_event_disable);
3765 mutex_unlock(¤t->perf_event_mutex);
3770 static int perf_event_index(struct perf_event *event)
3772 if (event->hw.state & PERF_HES_STOPPED)
3775 if (event->state != PERF_EVENT_STATE_ACTIVE)
3778 return event->pmu->event_idx(event);
3781 static void calc_timer_values(struct perf_event *event,
3788 *now = perf_clock();
3789 ctx_time = event->shadow_ctx_time + *now;
3790 *enabled = ctx_time - event->tstamp_enabled;
3791 *running = ctx_time - event->tstamp_running;
3794 static void perf_event_init_userpage(struct perf_event *event)
3796 struct perf_event_mmap_page *userpg;
3797 struct ring_buffer *rb;
3800 rb = rcu_dereference(event->rb);
3804 userpg = rb->user_page;
3806 /* Allow new userspace to detect that bit 0 is deprecated */
3807 userpg->cap_bit0_is_deprecated = 1;
3808 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
3814 void __weak arch_perf_update_userpage(struct perf_event_mmap_page *userpg, u64 now)
3819 * Callers need to ensure there can be no nesting of this function, otherwise
3820 * the seqlock logic goes bad. We can not serialize this because the arch
3821 * code calls this from NMI context.
3823 void perf_event_update_userpage(struct perf_event *event)
3825 struct perf_event_mmap_page *userpg;
3826 struct ring_buffer *rb;
3827 u64 enabled, running, now;
3830 rb = rcu_dereference(event->rb);
3835 * compute total_time_enabled, total_time_running
3836 * based on snapshot values taken when the event
3837 * was last scheduled in.
3839 * we cannot simply called update_context_time()
3840 * because of locking issue as we can be called in
3843 calc_timer_values(event, &now, &enabled, &running);
3845 userpg = rb->user_page;
3847 * Disable preemption so as to not let the corresponding user-space
3848 * spin too long if we get preempted.
3853 userpg->index = perf_event_index(event);
3854 userpg->offset = perf_event_count(event);
3856 userpg->offset -= local64_read(&event->hw.prev_count);
3858 userpg->time_enabled = enabled +
3859 atomic64_read(&event->child_total_time_enabled);
3861 userpg->time_running = running +
3862 atomic64_read(&event->child_total_time_running);
3864 arch_perf_update_userpage(userpg, now);
3873 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
3875 struct perf_event *event = vma->vm_file->private_data;
3876 struct ring_buffer *rb;
3877 int ret = VM_FAULT_SIGBUS;
3879 if (vmf->flags & FAULT_FLAG_MKWRITE) {
3880 if (vmf->pgoff == 0)
3886 rb = rcu_dereference(event->rb);
3890 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
3893 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
3897 get_page(vmf->page);
3898 vmf->page->mapping = vma->vm_file->f_mapping;
3899 vmf->page->index = vmf->pgoff;
3908 static void ring_buffer_attach(struct perf_event *event,
3909 struct ring_buffer *rb)
3911 struct ring_buffer *old_rb = NULL;
3912 unsigned long flags;
3916 * Should be impossible, we set this when removing
3917 * event->rb_entry and wait/clear when adding event->rb_entry.
3919 WARN_ON_ONCE(event->rcu_pending);
3922 event->rcu_batches = get_state_synchronize_rcu();
3923 event->rcu_pending = 1;
3925 spin_lock_irqsave(&old_rb->event_lock, flags);
3926 list_del_rcu(&event->rb_entry);
3927 spin_unlock_irqrestore(&old_rb->event_lock, flags);
3930 if (event->rcu_pending && rb) {
3931 cond_synchronize_rcu(event->rcu_batches);
3932 event->rcu_pending = 0;
3936 spin_lock_irqsave(&rb->event_lock, flags);
3937 list_add_rcu(&event->rb_entry, &rb->event_list);
3938 spin_unlock_irqrestore(&rb->event_lock, flags);
3941 rcu_assign_pointer(event->rb, rb);
3944 ring_buffer_put(old_rb);
3946 * Since we detached before setting the new rb, so that we
3947 * could attach the new rb, we could have missed a wakeup.
3950 wake_up_all(&event->waitq);
3954 static void ring_buffer_wakeup(struct perf_event *event)
3956 struct ring_buffer *rb;
3959 rb = rcu_dereference(event->rb);
3961 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
3962 wake_up_all(&event->waitq);
3967 static void rb_free_rcu(struct rcu_head *rcu_head)
3969 struct ring_buffer *rb;
3971 rb = container_of(rcu_head, struct ring_buffer, rcu_head);
3975 static struct ring_buffer *ring_buffer_get(struct perf_event *event)
3977 struct ring_buffer *rb;
3980 rb = rcu_dereference(event->rb);
3982 if (!atomic_inc_not_zero(&rb->refcount))
3990 static void ring_buffer_put(struct ring_buffer *rb)
3992 if (!atomic_dec_and_test(&rb->refcount))
3995 WARN_ON_ONCE(!list_empty(&rb->event_list));
3997 call_rcu(&rb->rcu_head, rb_free_rcu);
4000 static void perf_mmap_open(struct vm_area_struct *vma)
4002 struct perf_event *event = vma->vm_file->private_data;
4004 atomic_inc(&event->mmap_count);
4005 atomic_inc(&event->rb->mmap_count);
4009 * A buffer can be mmap()ed multiple times; either directly through the same
4010 * event, or through other events by use of perf_event_set_output().
4012 * In order to undo the VM accounting done by perf_mmap() we need to destroy
4013 * the buffer here, where we still have a VM context. This means we need
4014 * to detach all events redirecting to us.
4016 static void perf_mmap_close(struct vm_area_struct *vma)
4018 struct perf_event *event = vma->vm_file->private_data;
4020 struct ring_buffer *rb = ring_buffer_get(event);
4021 struct user_struct *mmap_user = rb->mmap_user;
4022 int mmap_locked = rb->mmap_locked;
4023 unsigned long size = perf_data_size(rb);
4025 atomic_dec(&rb->mmap_count);
4027 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
4030 ring_buffer_attach(event, NULL);
4031 mutex_unlock(&event->mmap_mutex);
4033 /* If there's still other mmap()s of this buffer, we're done. */
4034 if (atomic_read(&rb->mmap_count))
4038 * No other mmap()s, detach from all other events that might redirect
4039 * into the now unreachable buffer. Somewhat complicated by the
4040 * fact that rb::event_lock otherwise nests inside mmap_mutex.
4044 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4045 if (!atomic_long_inc_not_zero(&event->refcount)) {
4047 * This event is en-route to free_event() which will
4048 * detach it and remove it from the list.
4054 mutex_lock(&event->mmap_mutex);
4056 * Check we didn't race with perf_event_set_output() which can
4057 * swizzle the rb from under us while we were waiting to
4058 * acquire mmap_mutex.
4060 * If we find a different rb; ignore this event, a next
4061 * iteration will no longer find it on the list. We have to
4062 * still restart the iteration to make sure we're not now
4063 * iterating the wrong list.
4065 if (event->rb == rb)
4066 ring_buffer_attach(event, NULL);
4068 mutex_unlock(&event->mmap_mutex);
4072 * Restart the iteration; either we're on the wrong list or
4073 * destroyed its integrity by doing a deletion.
4080 * It could be there's still a few 0-ref events on the list; they'll
4081 * get cleaned up by free_event() -- they'll also still have their
4082 * ref on the rb and will free it whenever they are done with it.
4084 * Aside from that, this buffer is 'fully' detached and unmapped,
4085 * undo the VM accounting.
4088 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4089 vma->vm_mm->pinned_vm -= mmap_locked;
4090 free_uid(mmap_user);
4093 ring_buffer_put(rb); /* could be last */
4096 static const struct vm_operations_struct perf_mmap_vmops = {
4097 .open = perf_mmap_open,
4098 .close = perf_mmap_close,
4099 .fault = perf_mmap_fault,
4100 .page_mkwrite = perf_mmap_fault,
4103 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
4105 struct perf_event *event = file->private_data;
4106 unsigned long user_locked, user_lock_limit;
4107 struct user_struct *user = current_user();
4108 unsigned long locked, lock_limit;
4109 struct ring_buffer *rb;
4110 unsigned long vma_size;
4111 unsigned long nr_pages;
4112 long user_extra, extra;
4113 int ret = 0, flags = 0;
4116 * Don't allow mmap() of inherited per-task counters. This would
4117 * create a performance issue due to all children writing to the
4120 if (event->cpu == -1 && event->attr.inherit)
4123 if (!(vma->vm_flags & VM_SHARED))
4126 vma_size = vma->vm_end - vma->vm_start;
4127 nr_pages = (vma_size / PAGE_SIZE) - 1;
4130 * If we have rb pages ensure they're a power-of-two number, so we
4131 * can do bitmasks instead of modulo.
4133 if (nr_pages != 0 && !is_power_of_2(nr_pages))
4136 if (vma_size != PAGE_SIZE * (1 + nr_pages))
4139 if (vma->vm_pgoff != 0)
4142 WARN_ON_ONCE(event->ctx->parent_ctx);
4144 mutex_lock(&event->mmap_mutex);
4146 if (event->rb->nr_pages != nr_pages) {
4151 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4153 * Raced against perf_mmap_close() through
4154 * perf_event_set_output(). Try again, hope for better
4157 mutex_unlock(&event->mmap_mutex);
4164 user_extra = nr_pages + 1;
4165 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
4168 * Increase the limit linearly with more CPUs:
4170 user_lock_limit *= num_online_cpus();
4172 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
4175 if (user_locked > user_lock_limit)
4176 extra = user_locked - user_lock_limit;
4178 lock_limit = rlimit(RLIMIT_MEMLOCK);
4179 lock_limit >>= PAGE_SHIFT;
4180 locked = vma->vm_mm->pinned_vm + extra;
4182 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
4183 !capable(CAP_IPC_LOCK)) {
4190 if (vma->vm_flags & VM_WRITE)
4191 flags |= RING_BUFFER_WRITABLE;
4193 rb = rb_alloc(nr_pages,
4194 event->attr.watermark ? event->attr.wakeup_watermark : 0,
4202 atomic_set(&rb->mmap_count, 1);
4203 rb->mmap_locked = extra;
4204 rb->mmap_user = get_current_user();
4206 atomic_long_add(user_extra, &user->locked_vm);
4207 vma->vm_mm->pinned_vm += extra;
4209 ring_buffer_attach(event, rb);
4211 perf_event_init_userpage(event);
4212 perf_event_update_userpage(event);
4216 atomic_inc(&event->mmap_count);
4217 mutex_unlock(&event->mmap_mutex);
4220 * Since pinned accounting is per vm we cannot allow fork() to copy our
4223 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
4224 vma->vm_ops = &perf_mmap_vmops;
4229 static int perf_fasync(int fd, struct file *filp, int on)
4231 struct inode *inode = file_inode(filp);
4232 struct perf_event *event = filp->private_data;
4235 mutex_lock(&inode->i_mutex);
4236 retval = fasync_helper(fd, filp, on, &event->fasync);
4237 mutex_unlock(&inode->i_mutex);
4245 static const struct file_operations perf_fops = {
4246 .llseek = no_llseek,
4247 .release = perf_release,
4250 .unlocked_ioctl = perf_ioctl,
4251 .compat_ioctl = perf_compat_ioctl,
4253 .fasync = perf_fasync,
4259 * If there's data, ensure we set the poll() state and publish everything
4260 * to user-space before waking everybody up.
4263 void perf_event_wakeup(struct perf_event *event)
4265 ring_buffer_wakeup(event);
4267 if (event->pending_kill) {
4268 kill_fasync(&event->fasync, SIGIO, event->pending_kill);
4269 event->pending_kill = 0;
4273 static void perf_pending_event(struct irq_work *entry)
4275 struct perf_event *event = container_of(entry,
4276 struct perf_event, pending);
4278 if (event->pending_disable) {
4279 event->pending_disable = 0;
4280 __perf_event_disable(event);
4283 if (event->pending_wakeup) {
4284 event->pending_wakeup = 0;
4285 perf_event_wakeup(event);
4290 * We assume there is only KVM supporting the callbacks.
4291 * Later on, we might change it to a list if there is
4292 * another virtualization implementation supporting the callbacks.
4294 struct perf_guest_info_callbacks *perf_guest_cbs;
4296 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4298 perf_guest_cbs = cbs;
4301 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
4303 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4305 perf_guest_cbs = NULL;
4308 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
4311 perf_output_sample_regs(struct perf_output_handle *handle,
4312 struct pt_regs *regs, u64 mask)
4316 for_each_set_bit(bit, (const unsigned long *) &mask,
4317 sizeof(mask) * BITS_PER_BYTE) {
4320 val = perf_reg_value(regs, bit);
4321 perf_output_put(handle, val);
4325 static void perf_sample_regs_user(struct perf_regs_user *regs_user,
4326 struct pt_regs *regs)
4328 if (!user_mode(regs)) {
4330 regs = task_pt_regs(current);
4336 regs_user->regs = regs;
4337 regs_user->abi = perf_reg_abi(current);
4342 * Get remaining task size from user stack pointer.
4344 * It'd be better to take stack vma map and limit this more
4345 * precisly, but there's no way to get it safely under interrupt,
4346 * so using TASK_SIZE as limit.
4348 static u64 perf_ustack_task_size(struct pt_regs *regs)
4350 unsigned long addr = perf_user_stack_pointer(regs);
4352 if (!addr || addr >= TASK_SIZE)
4355 return TASK_SIZE - addr;
4359 perf_sample_ustack_size(u16 stack_size, u16 header_size,
4360 struct pt_regs *regs)
4364 /* No regs, no stack pointer, no dump. */
4369 * Check if we fit in with the requested stack size into the:
4371 * If we don't, we limit the size to the TASK_SIZE.
4373 * - remaining sample size
4374 * If we don't, we customize the stack size to
4375 * fit in to the remaining sample size.
4378 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
4379 stack_size = min(stack_size, (u16) task_size);
4381 /* Current header size plus static size and dynamic size. */
4382 header_size += 2 * sizeof(u64);
4384 /* Do we fit in with the current stack dump size? */
4385 if ((u16) (header_size + stack_size) < header_size) {
4387 * If we overflow the maximum size for the sample,
4388 * we customize the stack dump size to fit in.
4390 stack_size = USHRT_MAX - header_size - sizeof(u64);
4391 stack_size = round_up(stack_size, sizeof(u64));
4398 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
4399 struct pt_regs *regs)
4401 /* Case of a kernel thread, nothing to dump */
4404 perf_output_put(handle, size);
4413 * - the size requested by user or the best one we can fit
4414 * in to the sample max size
4416 * - user stack dump data
4418 * - the actual dumped size
4422 perf_output_put(handle, dump_size);
4425 sp = perf_user_stack_pointer(regs);
4426 rem = __output_copy_user(handle, (void *) sp, dump_size);
4427 dyn_size = dump_size - rem;
4429 perf_output_skip(handle, rem);
4432 perf_output_put(handle, dyn_size);
4436 static void __perf_event_header__init_id(struct perf_event_header *header,
4437 struct perf_sample_data *data,
4438 struct perf_event *event)
4440 u64 sample_type = event->attr.sample_type;
4442 data->type = sample_type;
4443 header->size += event->id_header_size;
4445 if (sample_type & PERF_SAMPLE_TID) {
4446 /* namespace issues */
4447 data->tid_entry.pid = perf_event_pid(event, current);
4448 data->tid_entry.tid = perf_event_tid(event, current);
4451 if (sample_type & PERF_SAMPLE_TIME)
4452 data->time = perf_clock();
4454 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
4455 data->id = primary_event_id(event);
4457 if (sample_type & PERF_SAMPLE_STREAM_ID)
4458 data->stream_id = event->id;
4460 if (sample_type & PERF_SAMPLE_CPU) {
4461 data->cpu_entry.cpu = raw_smp_processor_id();
4462 data->cpu_entry.reserved = 0;
4466 void perf_event_header__init_id(struct perf_event_header *header,
4467 struct perf_sample_data *data,
4468 struct perf_event *event)
4470 if (event->attr.sample_id_all)
4471 __perf_event_header__init_id(header, data, event);
4474 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
4475 struct perf_sample_data *data)
4477 u64 sample_type = data->type;
4479 if (sample_type & PERF_SAMPLE_TID)
4480 perf_output_put(handle, data->tid_entry);
4482 if (sample_type & PERF_SAMPLE_TIME)
4483 perf_output_put(handle, data->time);
4485 if (sample_type & PERF_SAMPLE_ID)
4486 perf_output_put(handle, data->id);
4488 if (sample_type & PERF_SAMPLE_STREAM_ID)
4489 perf_output_put(handle, data->stream_id);
4491 if (sample_type & PERF_SAMPLE_CPU)
4492 perf_output_put(handle, data->cpu_entry);
4494 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4495 perf_output_put(handle, data->id);
4498 void perf_event__output_id_sample(struct perf_event *event,
4499 struct perf_output_handle *handle,
4500 struct perf_sample_data *sample)
4502 if (event->attr.sample_id_all)
4503 __perf_event__output_id_sample(handle, sample);
4506 static void perf_output_read_one(struct perf_output_handle *handle,
4507 struct perf_event *event,
4508 u64 enabled, u64 running)
4510 u64 read_format = event->attr.read_format;
4514 values[n++] = perf_event_count(event);
4515 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4516 values[n++] = enabled +
4517 atomic64_read(&event->child_total_time_enabled);
4519 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4520 values[n++] = running +
4521 atomic64_read(&event->child_total_time_running);
4523 if (read_format & PERF_FORMAT_ID)
4524 values[n++] = primary_event_id(event);
4526 __output_copy(handle, values, n * sizeof(u64));
4530 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
4532 static void perf_output_read_group(struct perf_output_handle *handle,
4533 struct perf_event *event,
4534 u64 enabled, u64 running)
4536 struct perf_event *leader = event->group_leader, *sub;
4537 u64 read_format = event->attr.read_format;
4541 values[n++] = 1 + leader->nr_siblings;
4543 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4544 values[n++] = enabled;
4546 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4547 values[n++] = running;
4549 if (leader != event)
4550 leader->pmu->read(leader);
4552 values[n++] = perf_event_count(leader);
4553 if (read_format & PERF_FORMAT_ID)
4554 values[n++] = primary_event_id(leader);
4556 __output_copy(handle, values, n * sizeof(u64));
4558 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4561 if ((sub != event) &&
4562 (sub->state == PERF_EVENT_STATE_ACTIVE))
4563 sub->pmu->read(sub);
4565 values[n++] = perf_event_count(sub);
4566 if (read_format & PERF_FORMAT_ID)
4567 values[n++] = primary_event_id(sub);
4569 __output_copy(handle, values, n * sizeof(u64));
4573 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
4574 PERF_FORMAT_TOTAL_TIME_RUNNING)
4576 static void perf_output_read(struct perf_output_handle *handle,
4577 struct perf_event *event)
4579 u64 enabled = 0, running = 0, now;
4580 u64 read_format = event->attr.read_format;
4583 * compute total_time_enabled, total_time_running
4584 * based on snapshot values taken when the event
4585 * was last scheduled in.
4587 * we cannot simply called update_context_time()
4588 * because of locking issue as we are called in
4591 if (read_format & PERF_FORMAT_TOTAL_TIMES)
4592 calc_timer_values(event, &now, &enabled, &running);
4594 if (event->attr.read_format & PERF_FORMAT_GROUP)
4595 perf_output_read_group(handle, event, enabled, running);
4597 perf_output_read_one(handle, event, enabled, running);
4600 void perf_output_sample(struct perf_output_handle *handle,
4601 struct perf_event_header *header,
4602 struct perf_sample_data *data,
4603 struct perf_event *event)
4605 u64 sample_type = data->type;
4607 perf_output_put(handle, *header);
4609 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4610 perf_output_put(handle, data->id);
4612 if (sample_type & PERF_SAMPLE_IP)
4613 perf_output_put(handle, data->ip);
4615 if (sample_type & PERF_SAMPLE_TID)
4616 perf_output_put(handle, data->tid_entry);
4618 if (sample_type & PERF_SAMPLE_TIME)
4619 perf_output_put(handle, data->time);
4621 if (sample_type & PERF_SAMPLE_ADDR)
4622 perf_output_put(handle, data->addr);
4624 if (sample_type & PERF_SAMPLE_ID)
4625 perf_output_put(handle, data->id);
4627 if (sample_type & PERF_SAMPLE_STREAM_ID)
4628 perf_output_put(handle, data->stream_id);
4630 if (sample_type & PERF_SAMPLE_CPU)
4631 perf_output_put(handle, data->cpu_entry);
4633 if (sample_type & PERF_SAMPLE_PERIOD)
4634 perf_output_put(handle, data->period);
4636 if (sample_type & PERF_SAMPLE_READ)
4637 perf_output_read(handle, event);
4639 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4640 if (data->callchain) {
4643 if (data->callchain)
4644 size += data->callchain->nr;
4646 size *= sizeof(u64);
4648 __output_copy(handle, data->callchain, size);
4651 perf_output_put(handle, nr);
4655 if (sample_type & PERF_SAMPLE_RAW) {
4657 perf_output_put(handle, data->raw->size);
4658 __output_copy(handle, data->raw->data,
4665 .size = sizeof(u32),
4668 perf_output_put(handle, raw);
4672 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4673 if (data->br_stack) {
4676 size = data->br_stack->nr
4677 * sizeof(struct perf_branch_entry);
4679 perf_output_put(handle, data->br_stack->nr);
4680 perf_output_copy(handle, data->br_stack->entries, size);
4683 * we always store at least the value of nr
4686 perf_output_put(handle, nr);
4690 if (sample_type & PERF_SAMPLE_REGS_USER) {
4691 u64 abi = data->regs_user.abi;
4694 * If there are no regs to dump, notice it through
4695 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
4697 perf_output_put(handle, abi);
4700 u64 mask = event->attr.sample_regs_user;
4701 perf_output_sample_regs(handle,
4702 data->regs_user.regs,
4707 if (sample_type & PERF_SAMPLE_STACK_USER) {
4708 perf_output_sample_ustack(handle,
4709 data->stack_user_size,
4710 data->regs_user.regs);
4713 if (sample_type & PERF_SAMPLE_WEIGHT)
4714 perf_output_put(handle, data->weight);
4716 if (sample_type & PERF_SAMPLE_DATA_SRC)
4717 perf_output_put(handle, data->data_src.val);
4719 if (sample_type & PERF_SAMPLE_TRANSACTION)
4720 perf_output_put(handle, data->txn);
4722 if (!event->attr.watermark) {
4723 int wakeup_events = event->attr.wakeup_events;
4725 if (wakeup_events) {
4726 struct ring_buffer *rb = handle->rb;
4727 int events = local_inc_return(&rb->events);
4729 if (events >= wakeup_events) {
4730 local_sub(wakeup_events, &rb->events);
4731 local_inc(&rb->wakeup);
4737 void perf_prepare_sample(struct perf_event_header *header,
4738 struct perf_sample_data *data,
4739 struct perf_event *event,
4740 struct pt_regs *regs)
4742 u64 sample_type = event->attr.sample_type;
4744 header->type = PERF_RECORD_SAMPLE;
4745 header->size = sizeof(*header) + event->header_size;
4748 header->misc |= perf_misc_flags(regs);
4750 __perf_event_header__init_id(header, data, event);
4752 if (sample_type & PERF_SAMPLE_IP)
4753 data->ip = perf_instruction_pointer(regs);
4755 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4758 data->callchain = perf_callchain(event, regs);
4760 if (data->callchain)
4761 size += data->callchain->nr;
4763 header->size += size * sizeof(u64);
4766 if (sample_type & PERF_SAMPLE_RAW) {
4767 int size = sizeof(u32);
4770 size += data->raw->size;
4772 size += sizeof(u32);
4774 WARN_ON_ONCE(size & (sizeof(u64)-1));
4775 header->size += size;
4778 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4779 int size = sizeof(u64); /* nr */
4780 if (data->br_stack) {
4781 size += data->br_stack->nr
4782 * sizeof(struct perf_branch_entry);
4784 header->size += size;
4787 if (sample_type & PERF_SAMPLE_REGS_USER) {
4788 /* regs dump ABI info */
4789 int size = sizeof(u64);
4791 perf_sample_regs_user(&data->regs_user, regs);
4793 if (data->regs_user.regs) {
4794 u64 mask = event->attr.sample_regs_user;
4795 size += hweight64(mask) * sizeof(u64);
4798 header->size += size;
4801 if (sample_type & PERF_SAMPLE_STACK_USER) {
4803 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
4804 * processed as the last one or have additional check added
4805 * in case new sample type is added, because we could eat
4806 * up the rest of the sample size.
4808 struct perf_regs_user *uregs = &data->regs_user;
4809 u16 stack_size = event->attr.sample_stack_user;
4810 u16 size = sizeof(u64);
4813 perf_sample_regs_user(uregs, regs);
4815 stack_size = perf_sample_ustack_size(stack_size, header->size,
4819 * If there is something to dump, add space for the dump
4820 * itself and for the field that tells the dynamic size,
4821 * which is how many have been actually dumped.
4824 size += sizeof(u64) + stack_size;
4826 data->stack_user_size = stack_size;
4827 header->size += size;
4831 static void perf_event_output(struct perf_event *event,
4832 struct perf_sample_data *data,
4833 struct pt_regs *regs)
4835 struct perf_output_handle handle;
4836 struct perf_event_header header;
4838 /* protect the callchain buffers */
4841 perf_prepare_sample(&header, data, event, regs);
4843 if (perf_output_begin(&handle, event, header.size))
4846 perf_output_sample(&handle, &header, data, event);
4848 perf_output_end(&handle);
4858 struct perf_read_event {
4859 struct perf_event_header header;
4866 perf_event_read_event(struct perf_event *event,
4867 struct task_struct *task)
4869 struct perf_output_handle handle;
4870 struct perf_sample_data sample;
4871 struct perf_read_event read_event = {
4873 .type = PERF_RECORD_READ,
4875 .size = sizeof(read_event) + event->read_size,
4877 .pid = perf_event_pid(event, task),
4878 .tid = perf_event_tid(event, task),
4882 perf_event_header__init_id(&read_event.header, &sample, event);
4883 ret = perf_output_begin(&handle, event, read_event.header.size);
4887 perf_output_put(&handle, read_event);
4888 perf_output_read(&handle, event);
4889 perf_event__output_id_sample(event, &handle, &sample);
4891 perf_output_end(&handle);
4894 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
4897 perf_event_aux_ctx(struct perf_event_context *ctx,
4898 perf_event_aux_output_cb output,
4901 struct perf_event *event;
4903 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4904 if (event->state < PERF_EVENT_STATE_INACTIVE)
4906 if (!event_filter_match(event))
4908 output(event, data);
4913 perf_event_aux(perf_event_aux_output_cb output, void *data,
4914 struct perf_event_context *task_ctx)
4916 struct perf_cpu_context *cpuctx;
4917 struct perf_event_context *ctx;
4922 list_for_each_entry_rcu(pmu, &pmus, entry) {
4923 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4924 if (cpuctx->unique_pmu != pmu)
4926 perf_event_aux_ctx(&cpuctx->ctx, output, data);
4929 ctxn = pmu->task_ctx_nr;
4932 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4934 perf_event_aux_ctx(ctx, output, data);
4936 put_cpu_ptr(pmu->pmu_cpu_context);
4941 perf_event_aux_ctx(task_ctx, output, data);
4948 * task tracking -- fork/exit
4950 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
4953 struct perf_task_event {
4954 struct task_struct *task;
4955 struct perf_event_context *task_ctx;
4958 struct perf_event_header header;
4968 static int perf_event_task_match(struct perf_event *event)
4970 return event->attr.comm || event->attr.mmap ||
4971 event->attr.mmap2 || event->attr.mmap_data ||
4975 static void perf_event_task_output(struct perf_event *event,
4978 struct perf_task_event *task_event = data;
4979 struct perf_output_handle handle;
4980 struct perf_sample_data sample;
4981 struct task_struct *task = task_event->task;
4982 int ret, size = task_event->event_id.header.size;
4984 if (!perf_event_task_match(event))
4987 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
4989 ret = perf_output_begin(&handle, event,
4990 task_event->event_id.header.size);
4994 task_event->event_id.pid = perf_event_pid(event, task);
4995 task_event->event_id.ppid = perf_event_pid(event, current);
4997 task_event->event_id.tid = perf_event_tid(event, task);
4998 task_event->event_id.ptid = perf_event_tid(event, current);
5000 perf_output_put(&handle, task_event->event_id);
5002 perf_event__output_id_sample(event, &handle, &sample);
5004 perf_output_end(&handle);
5006 task_event->event_id.header.size = size;
5009 static void perf_event_task(struct task_struct *task,
5010 struct perf_event_context *task_ctx,
5013 struct perf_task_event task_event;
5015 if (!atomic_read(&nr_comm_events) &&
5016 !atomic_read(&nr_mmap_events) &&
5017 !atomic_read(&nr_task_events))
5020 task_event = (struct perf_task_event){
5022 .task_ctx = task_ctx,
5025 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
5027 .size = sizeof(task_event.event_id),
5033 .time = perf_clock(),
5037 perf_event_aux(perf_event_task_output,
5042 void perf_event_fork(struct task_struct *task)
5044 perf_event_task(task, NULL, 1);
5051 struct perf_comm_event {
5052 struct task_struct *task;
5057 struct perf_event_header header;
5064 static int perf_event_comm_match(struct perf_event *event)
5066 return event->attr.comm;
5069 static void perf_event_comm_output(struct perf_event *event,
5072 struct perf_comm_event *comm_event = data;
5073 struct perf_output_handle handle;
5074 struct perf_sample_data sample;
5075 int size = comm_event->event_id.header.size;
5078 if (!perf_event_comm_match(event))
5081 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
5082 ret = perf_output_begin(&handle, event,
5083 comm_event->event_id.header.size);
5088 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
5089 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
5091 perf_output_put(&handle, comm_event->event_id);
5092 __output_copy(&handle, comm_event->comm,
5093 comm_event->comm_size);
5095 perf_event__output_id_sample(event, &handle, &sample);
5097 perf_output_end(&handle);
5099 comm_event->event_id.header.size = size;
5102 static void perf_event_comm_event(struct perf_comm_event *comm_event)
5104 char comm[TASK_COMM_LEN];
5107 memset(comm, 0, sizeof(comm));
5108 strlcpy(comm, comm_event->task->comm, sizeof(comm));
5109 size = ALIGN(strlen(comm)+1, sizeof(u64));
5111 comm_event->comm = comm;
5112 comm_event->comm_size = size;
5114 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
5116 perf_event_aux(perf_event_comm_output,
5121 void perf_event_comm(struct task_struct *task, bool exec)
5123 struct perf_comm_event comm_event;
5125 if (!atomic_read(&nr_comm_events))
5128 comm_event = (struct perf_comm_event){
5134 .type = PERF_RECORD_COMM,
5135 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
5143 perf_event_comm_event(&comm_event);
5150 struct perf_mmap_event {
5151 struct vm_area_struct *vma;
5153 const char *file_name;
5161 struct perf_event_header header;
5171 static int perf_event_mmap_match(struct perf_event *event,
5174 struct perf_mmap_event *mmap_event = data;
5175 struct vm_area_struct *vma = mmap_event->vma;
5176 int executable = vma->vm_flags & VM_EXEC;
5178 return (!executable && event->attr.mmap_data) ||
5179 (executable && (event->attr.mmap || event->attr.mmap2));
5182 static void perf_event_mmap_output(struct perf_event *event,
5185 struct perf_mmap_event *mmap_event = data;
5186 struct perf_output_handle handle;
5187 struct perf_sample_data sample;
5188 int size = mmap_event->event_id.header.size;
5191 if (!perf_event_mmap_match(event, data))
5194 if (event->attr.mmap2) {
5195 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
5196 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
5197 mmap_event->event_id.header.size += sizeof(mmap_event->min);
5198 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
5199 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
5200 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
5201 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
5204 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
5205 ret = perf_output_begin(&handle, event,
5206 mmap_event->event_id.header.size);
5210 mmap_event->event_id.pid = perf_event_pid(event, current);
5211 mmap_event->event_id.tid = perf_event_tid(event, current);
5213 perf_output_put(&handle, mmap_event->event_id);
5215 if (event->attr.mmap2) {
5216 perf_output_put(&handle, mmap_event->maj);
5217 perf_output_put(&handle, mmap_event->min);
5218 perf_output_put(&handle, mmap_event->ino);
5219 perf_output_put(&handle, mmap_event->ino_generation);
5220 perf_output_put(&handle, mmap_event->prot);
5221 perf_output_put(&handle, mmap_event->flags);
5224 __output_copy(&handle, mmap_event->file_name,
5225 mmap_event->file_size);
5227 perf_event__output_id_sample(event, &handle, &sample);
5229 perf_output_end(&handle);
5231 mmap_event->event_id.header.size = size;
5234 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
5236 struct vm_area_struct *vma = mmap_event->vma;
5237 struct file *file = vma->vm_file;
5238 int maj = 0, min = 0;
5239 u64 ino = 0, gen = 0;
5240 u32 prot = 0, flags = 0;
5247 struct inode *inode;
5250 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5256 * d_path() works from the end of the rb backwards, so we
5257 * need to add enough zero bytes after the string to handle
5258 * the 64bit alignment we do later.
5260 name = d_path(&file->f_path, buf, PATH_MAX - sizeof(u64));
5265 inode = file_inode(vma->vm_file);
5266 dev = inode->i_sb->s_dev;
5268 gen = inode->i_generation;
5272 if (vma->vm_flags & VM_READ)
5274 if (vma->vm_flags & VM_WRITE)
5276 if (vma->vm_flags & VM_EXEC)
5279 if (vma->vm_flags & VM_MAYSHARE)
5282 flags = MAP_PRIVATE;
5284 if (vma->vm_flags & VM_DENYWRITE)
5285 flags |= MAP_DENYWRITE;
5286 if (vma->vm_flags & VM_MAYEXEC)
5287 flags |= MAP_EXECUTABLE;
5288 if (vma->vm_flags & VM_LOCKED)
5289 flags |= MAP_LOCKED;
5290 if (vma->vm_flags & VM_HUGETLB)
5291 flags |= MAP_HUGETLB;
5295 if (vma->vm_ops && vma->vm_ops->name) {
5296 name = (char *) vma->vm_ops->name(vma);
5301 name = (char *)arch_vma_name(vma);
5305 if (vma->vm_start <= vma->vm_mm->start_brk &&
5306 vma->vm_end >= vma->vm_mm->brk) {
5310 if (vma->vm_start <= vma->vm_mm->start_stack &&
5311 vma->vm_end >= vma->vm_mm->start_stack) {
5321 strlcpy(tmp, name, sizeof(tmp));
5325 * Since our buffer works in 8 byte units we need to align our string
5326 * size to a multiple of 8. However, we must guarantee the tail end is
5327 * zero'd out to avoid leaking random bits to userspace.
5329 size = strlen(name)+1;
5330 while (!IS_ALIGNED(size, sizeof(u64)))
5331 name[size++] = '\0';
5333 mmap_event->file_name = name;
5334 mmap_event->file_size = size;
5335 mmap_event->maj = maj;
5336 mmap_event->min = min;
5337 mmap_event->ino = ino;
5338 mmap_event->ino_generation = gen;
5339 mmap_event->prot = prot;
5340 mmap_event->flags = flags;
5342 if (!(vma->vm_flags & VM_EXEC))
5343 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
5345 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
5347 perf_event_aux(perf_event_mmap_output,
5354 void perf_event_mmap(struct vm_area_struct *vma)
5356 struct perf_mmap_event mmap_event;
5358 if (!atomic_read(&nr_mmap_events))
5361 mmap_event = (struct perf_mmap_event){
5367 .type = PERF_RECORD_MMAP,
5368 .misc = PERF_RECORD_MISC_USER,
5373 .start = vma->vm_start,
5374 .len = vma->vm_end - vma->vm_start,
5375 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
5377 /* .maj (attr_mmap2 only) */
5378 /* .min (attr_mmap2 only) */
5379 /* .ino (attr_mmap2 only) */
5380 /* .ino_generation (attr_mmap2 only) */
5381 /* .prot (attr_mmap2 only) */
5382 /* .flags (attr_mmap2 only) */
5385 perf_event_mmap_event(&mmap_event);
5389 * IRQ throttle logging
5392 static void perf_log_throttle(struct perf_event *event, int enable)
5394 struct perf_output_handle handle;
5395 struct perf_sample_data sample;
5399 struct perf_event_header header;
5403 } throttle_event = {
5405 .type = PERF_RECORD_THROTTLE,
5407 .size = sizeof(throttle_event),
5409 .time = perf_clock(),
5410 .id = primary_event_id(event),
5411 .stream_id = event->id,
5415 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
5417 perf_event_header__init_id(&throttle_event.header, &sample, event);
5419 ret = perf_output_begin(&handle, event,
5420 throttle_event.header.size);
5424 perf_output_put(&handle, throttle_event);
5425 perf_event__output_id_sample(event, &handle, &sample);
5426 perf_output_end(&handle);
5430 * Generic event overflow handling, sampling.
5433 static int __perf_event_overflow(struct perf_event *event,
5434 int throttle, struct perf_sample_data *data,
5435 struct pt_regs *regs)
5437 int events = atomic_read(&event->event_limit);
5438 struct hw_perf_event *hwc = &event->hw;
5443 * Non-sampling counters might still use the PMI to fold short
5444 * hardware counters, ignore those.
5446 if (unlikely(!is_sampling_event(event)))
5449 seq = __this_cpu_read(perf_throttled_seq);
5450 if (seq != hwc->interrupts_seq) {
5451 hwc->interrupts_seq = seq;
5452 hwc->interrupts = 1;
5455 if (unlikely(throttle
5456 && hwc->interrupts >= max_samples_per_tick)) {
5457 __this_cpu_inc(perf_throttled_count);
5458 hwc->interrupts = MAX_INTERRUPTS;
5459 perf_log_throttle(event, 0);
5460 tick_nohz_full_kick();
5465 if (event->attr.freq) {
5466 u64 now = perf_clock();
5467 s64 delta = now - hwc->freq_time_stamp;
5469 hwc->freq_time_stamp = now;
5471 if (delta > 0 && delta < 2*TICK_NSEC)
5472 perf_adjust_period(event, delta, hwc->last_period, true);
5476 * XXX event_limit might not quite work as expected on inherited
5480 event->pending_kill = POLL_IN;
5481 if (events && atomic_dec_and_test(&event->event_limit)) {
5483 event->pending_kill = POLL_HUP;
5484 event->pending_disable = 1;
5485 irq_work_queue(&event->pending);
5488 if (event->overflow_handler)
5489 event->overflow_handler(event, data, regs);
5491 perf_event_output(event, data, regs);
5493 if (event->fasync && event->pending_kill) {
5494 event->pending_wakeup = 1;
5495 irq_work_queue(&event->pending);
5501 int perf_event_overflow(struct perf_event *event,
5502 struct perf_sample_data *data,
5503 struct pt_regs *regs)
5505 return __perf_event_overflow(event, 1, data, regs);
5509 * Generic software event infrastructure
5512 struct swevent_htable {
5513 struct swevent_hlist *swevent_hlist;
5514 struct mutex hlist_mutex;
5517 /* Recursion avoidance in each contexts */
5518 int recursion[PERF_NR_CONTEXTS];
5520 /* Keeps track of cpu being initialized/exited */
5524 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
5527 * We directly increment event->count and keep a second value in
5528 * event->hw.period_left to count intervals. This period event
5529 * is kept in the range [-sample_period, 0] so that we can use the
5533 u64 perf_swevent_set_period(struct perf_event *event)
5535 struct hw_perf_event *hwc = &event->hw;
5536 u64 period = hwc->last_period;
5540 hwc->last_period = hwc->sample_period;
5543 old = val = local64_read(&hwc->period_left);
5547 nr = div64_u64(period + val, period);
5548 offset = nr * period;
5550 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
5556 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
5557 struct perf_sample_data *data,
5558 struct pt_regs *regs)
5560 struct hw_perf_event *hwc = &event->hw;
5564 overflow = perf_swevent_set_period(event);
5566 if (hwc->interrupts == MAX_INTERRUPTS)
5569 for (; overflow; overflow--) {
5570 if (__perf_event_overflow(event, throttle,
5573 * We inhibit the overflow from happening when
5574 * hwc->interrupts == MAX_INTERRUPTS.
5582 static void perf_swevent_event(struct perf_event *event, u64 nr,
5583 struct perf_sample_data *data,
5584 struct pt_regs *regs)
5586 struct hw_perf_event *hwc = &event->hw;
5588 local64_add(nr, &event->count);
5593 if (!is_sampling_event(event))
5596 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
5598 return perf_swevent_overflow(event, 1, data, regs);
5600 data->period = event->hw.last_period;
5602 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
5603 return perf_swevent_overflow(event, 1, data, regs);
5605 if (local64_add_negative(nr, &hwc->period_left))
5608 perf_swevent_overflow(event, 0, data, regs);
5611 static int perf_exclude_event(struct perf_event *event,
5612 struct pt_regs *regs)
5614 if (event->hw.state & PERF_HES_STOPPED)
5618 if (event->attr.exclude_user && user_mode(regs))
5621 if (event->attr.exclude_kernel && !user_mode(regs))
5628 static int perf_swevent_match(struct perf_event *event,
5629 enum perf_type_id type,
5631 struct perf_sample_data *data,
5632 struct pt_regs *regs)
5634 if (event->attr.type != type)
5637 if (event->attr.config != event_id)
5640 if (perf_exclude_event(event, regs))
5646 static inline u64 swevent_hash(u64 type, u32 event_id)
5648 u64 val = event_id | (type << 32);
5650 return hash_64(val, SWEVENT_HLIST_BITS);
5653 static inline struct hlist_head *
5654 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
5656 u64 hash = swevent_hash(type, event_id);
5658 return &hlist->heads[hash];
5661 /* For the read side: events when they trigger */
5662 static inline struct hlist_head *
5663 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
5665 struct swevent_hlist *hlist;
5667 hlist = rcu_dereference(swhash->swevent_hlist);
5671 return __find_swevent_head(hlist, type, event_id);
5674 /* For the event head insertion and removal in the hlist */
5675 static inline struct hlist_head *
5676 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
5678 struct swevent_hlist *hlist;
5679 u32 event_id = event->attr.config;
5680 u64 type = event->attr.type;
5683 * Event scheduling is always serialized against hlist allocation
5684 * and release. Which makes the protected version suitable here.
5685 * The context lock guarantees that.
5687 hlist = rcu_dereference_protected(swhash->swevent_hlist,
5688 lockdep_is_held(&event->ctx->lock));
5692 return __find_swevent_head(hlist, type, event_id);
5695 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
5697 struct perf_sample_data *data,
5698 struct pt_regs *regs)
5700 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5701 struct perf_event *event;
5702 struct hlist_head *head;
5705 head = find_swevent_head_rcu(swhash, type, event_id);
5709 hlist_for_each_entry_rcu(event, head, hlist_entry) {
5710 if (perf_swevent_match(event, type, event_id, data, regs))
5711 perf_swevent_event(event, nr, data, regs);
5717 int perf_swevent_get_recursion_context(void)
5719 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5721 return get_recursion_context(swhash->recursion);
5723 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
5725 inline void perf_swevent_put_recursion_context(int rctx)
5727 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5729 put_recursion_context(swhash->recursion, rctx);
5732 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
5734 struct perf_sample_data data;
5737 preempt_disable_notrace();
5738 rctx = perf_swevent_get_recursion_context();
5742 perf_sample_data_init(&data, addr, 0);
5744 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
5746 perf_swevent_put_recursion_context(rctx);
5747 preempt_enable_notrace();
5750 static void perf_swevent_read(struct perf_event *event)
5754 static int perf_swevent_add(struct perf_event *event, int flags)
5756 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5757 struct hw_perf_event *hwc = &event->hw;
5758 struct hlist_head *head;
5760 if (is_sampling_event(event)) {
5761 hwc->last_period = hwc->sample_period;
5762 perf_swevent_set_period(event);
5765 hwc->state = !(flags & PERF_EF_START);
5767 head = find_swevent_head(swhash, event);
5770 * We can race with cpu hotplug code. Do not
5771 * WARN if the cpu just got unplugged.
5773 WARN_ON_ONCE(swhash->online);
5777 hlist_add_head_rcu(&event->hlist_entry, head);
5782 static void perf_swevent_del(struct perf_event *event, int flags)
5784 hlist_del_rcu(&event->hlist_entry);
5787 static void perf_swevent_start(struct perf_event *event, int flags)
5789 event->hw.state = 0;
5792 static void perf_swevent_stop(struct perf_event *event, int flags)
5794 event->hw.state = PERF_HES_STOPPED;
5797 /* Deref the hlist from the update side */
5798 static inline struct swevent_hlist *
5799 swevent_hlist_deref(struct swevent_htable *swhash)
5801 return rcu_dereference_protected(swhash->swevent_hlist,
5802 lockdep_is_held(&swhash->hlist_mutex));
5805 static void swevent_hlist_release(struct swevent_htable *swhash)
5807 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
5812 rcu_assign_pointer(swhash->swevent_hlist, NULL);
5813 kfree_rcu(hlist, rcu_head);
5816 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
5818 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5820 mutex_lock(&swhash->hlist_mutex);
5822 if (!--swhash->hlist_refcount)
5823 swevent_hlist_release(swhash);
5825 mutex_unlock(&swhash->hlist_mutex);
5828 static void swevent_hlist_put(struct perf_event *event)
5832 for_each_possible_cpu(cpu)
5833 swevent_hlist_put_cpu(event, cpu);
5836 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
5838 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5841 mutex_lock(&swhash->hlist_mutex);
5843 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
5844 struct swevent_hlist *hlist;
5846 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
5851 rcu_assign_pointer(swhash->swevent_hlist, hlist);
5853 swhash->hlist_refcount++;
5855 mutex_unlock(&swhash->hlist_mutex);
5860 static int swevent_hlist_get(struct perf_event *event)
5863 int cpu, failed_cpu;
5866 for_each_possible_cpu(cpu) {
5867 err = swevent_hlist_get_cpu(event, cpu);
5877 for_each_possible_cpu(cpu) {
5878 if (cpu == failed_cpu)
5880 swevent_hlist_put_cpu(event, cpu);
5887 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
5889 static void sw_perf_event_destroy(struct perf_event *event)
5891 u64 event_id = event->attr.config;
5893 WARN_ON(event->parent);
5895 static_key_slow_dec(&perf_swevent_enabled[event_id]);
5896 swevent_hlist_put(event);
5899 static int perf_swevent_init(struct perf_event *event)
5901 u64 event_id = event->attr.config;
5903 if (event->attr.type != PERF_TYPE_SOFTWARE)
5907 * no branch sampling for software events
5909 if (has_branch_stack(event))
5913 case PERF_COUNT_SW_CPU_CLOCK:
5914 case PERF_COUNT_SW_TASK_CLOCK:
5921 if (event_id >= PERF_COUNT_SW_MAX)
5924 if (!event->parent) {
5927 err = swevent_hlist_get(event);
5931 static_key_slow_inc(&perf_swevent_enabled[event_id]);
5932 event->destroy = sw_perf_event_destroy;
5938 static int perf_swevent_event_idx(struct perf_event *event)
5943 static struct pmu perf_swevent = {
5944 .task_ctx_nr = perf_sw_context,
5946 .event_init = perf_swevent_init,
5947 .add = perf_swevent_add,
5948 .del = perf_swevent_del,
5949 .start = perf_swevent_start,
5950 .stop = perf_swevent_stop,
5951 .read = perf_swevent_read,
5953 .event_idx = perf_swevent_event_idx,
5956 #ifdef CONFIG_EVENT_TRACING
5958 static int perf_tp_filter_match(struct perf_event *event,
5959 struct perf_sample_data *data)
5961 void *record = data->raw->data;
5963 if (likely(!event->filter) || filter_match_preds(event->filter, record))
5968 static int perf_tp_event_match(struct perf_event *event,
5969 struct perf_sample_data *data,
5970 struct pt_regs *regs)
5972 if (event->hw.state & PERF_HES_STOPPED)
5975 * All tracepoints are from kernel-space.
5977 if (event->attr.exclude_kernel)
5980 if (!perf_tp_filter_match(event, data))
5986 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
5987 struct pt_regs *regs, struct hlist_head *head, int rctx,
5988 struct task_struct *task)
5990 struct perf_sample_data data;
5991 struct perf_event *event;
5993 struct perf_raw_record raw = {
5998 perf_sample_data_init(&data, addr, 0);
6001 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6002 if (perf_tp_event_match(event, &data, regs))
6003 perf_swevent_event(event, count, &data, regs);
6007 * If we got specified a target task, also iterate its context and
6008 * deliver this event there too.
6010 if (task && task != current) {
6011 struct perf_event_context *ctx;
6012 struct trace_entry *entry = record;
6015 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
6019 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
6020 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6022 if (event->attr.config != entry->type)
6024 if (perf_tp_event_match(event, &data, regs))
6025 perf_swevent_event(event, count, &data, regs);
6031 perf_swevent_put_recursion_context(rctx);
6033 EXPORT_SYMBOL_GPL(perf_tp_event);
6035 static void tp_perf_event_destroy(struct perf_event *event)
6037 perf_trace_destroy(event);
6040 static int perf_tp_event_init(struct perf_event *event)
6044 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6048 * no branch sampling for tracepoint events
6050 if (has_branch_stack(event))
6053 err = perf_trace_init(event);
6057 event->destroy = tp_perf_event_destroy;
6062 static struct pmu perf_tracepoint = {
6063 .task_ctx_nr = perf_sw_context,
6065 .event_init = perf_tp_event_init,
6066 .add = perf_trace_add,
6067 .del = perf_trace_del,
6068 .start = perf_swevent_start,
6069 .stop = perf_swevent_stop,
6070 .read = perf_swevent_read,
6072 .event_idx = perf_swevent_event_idx,
6075 static inline void perf_tp_register(void)
6077 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
6080 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
6085 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6088 filter_str = strndup_user(arg, PAGE_SIZE);
6089 if (IS_ERR(filter_str))
6090 return PTR_ERR(filter_str);
6092 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
6098 static void perf_event_free_filter(struct perf_event *event)
6100 ftrace_profile_free_filter(event);
6105 static inline void perf_tp_register(void)
6109 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
6114 static void perf_event_free_filter(struct perf_event *event)
6118 #endif /* CONFIG_EVENT_TRACING */
6120 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6121 void perf_bp_event(struct perf_event *bp, void *data)
6123 struct perf_sample_data sample;
6124 struct pt_regs *regs = data;
6126 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
6128 if (!bp->hw.state && !perf_exclude_event(bp, regs))
6129 perf_swevent_event(bp, 1, &sample, regs);
6134 * hrtimer based swevent callback
6137 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
6139 enum hrtimer_restart ret = HRTIMER_RESTART;
6140 struct perf_sample_data data;
6141 struct pt_regs *regs;
6142 struct perf_event *event;
6145 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
6147 if (event->state != PERF_EVENT_STATE_ACTIVE)
6148 return HRTIMER_NORESTART;
6150 event->pmu->read(event);
6152 perf_sample_data_init(&data, 0, event->hw.last_period);
6153 regs = get_irq_regs();
6155 if (regs && !perf_exclude_event(event, regs)) {
6156 if (!(event->attr.exclude_idle && is_idle_task(current)))
6157 if (__perf_event_overflow(event, 1, &data, regs))
6158 ret = HRTIMER_NORESTART;
6161 period = max_t(u64, 10000, event->hw.sample_period);
6162 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
6167 static void perf_swevent_start_hrtimer(struct perf_event *event)
6169 struct hw_perf_event *hwc = &event->hw;
6172 if (!is_sampling_event(event))
6175 period = local64_read(&hwc->period_left);
6180 local64_set(&hwc->period_left, 0);
6182 period = max_t(u64, 10000, hwc->sample_period);
6184 __hrtimer_start_range_ns(&hwc->hrtimer,
6185 ns_to_ktime(period), 0,
6186 HRTIMER_MODE_REL_PINNED, 0);
6189 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
6191 struct hw_perf_event *hwc = &event->hw;
6193 if (is_sampling_event(event)) {
6194 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
6195 local64_set(&hwc->period_left, ktime_to_ns(remaining));
6197 hrtimer_cancel(&hwc->hrtimer);
6201 static void perf_swevent_init_hrtimer(struct perf_event *event)
6203 struct hw_perf_event *hwc = &event->hw;
6205 if (!is_sampling_event(event))
6208 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6209 hwc->hrtimer.function = perf_swevent_hrtimer;
6212 * Since hrtimers have a fixed rate, we can do a static freq->period
6213 * mapping and avoid the whole period adjust feedback stuff.
6215 if (event->attr.freq) {
6216 long freq = event->attr.sample_freq;
6218 event->attr.sample_period = NSEC_PER_SEC / freq;
6219 hwc->sample_period = event->attr.sample_period;
6220 local64_set(&hwc->period_left, hwc->sample_period);
6221 hwc->last_period = hwc->sample_period;
6222 event->attr.freq = 0;
6227 * Software event: cpu wall time clock
6230 static void cpu_clock_event_update(struct perf_event *event)
6235 now = local_clock();
6236 prev = local64_xchg(&event->hw.prev_count, now);
6237 local64_add(now - prev, &event->count);
6240 static void cpu_clock_event_start(struct perf_event *event, int flags)
6242 local64_set(&event->hw.prev_count, local_clock());
6243 perf_swevent_start_hrtimer(event);
6246 static void cpu_clock_event_stop(struct perf_event *event, int flags)
6248 perf_swevent_cancel_hrtimer(event);
6249 cpu_clock_event_update(event);
6252 static int cpu_clock_event_add(struct perf_event *event, int flags)
6254 if (flags & PERF_EF_START)
6255 cpu_clock_event_start(event, flags);
6260 static void cpu_clock_event_del(struct perf_event *event, int flags)
6262 cpu_clock_event_stop(event, flags);
6265 static void cpu_clock_event_read(struct perf_event *event)
6267 cpu_clock_event_update(event);
6270 static int cpu_clock_event_init(struct perf_event *event)
6272 if (event->attr.type != PERF_TYPE_SOFTWARE)
6275 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
6279 * no branch sampling for software events
6281 if (has_branch_stack(event))
6284 perf_swevent_init_hrtimer(event);
6289 static struct pmu perf_cpu_clock = {
6290 .task_ctx_nr = perf_sw_context,
6292 .event_init = cpu_clock_event_init,
6293 .add = cpu_clock_event_add,
6294 .del = cpu_clock_event_del,
6295 .start = cpu_clock_event_start,
6296 .stop = cpu_clock_event_stop,
6297 .read = cpu_clock_event_read,
6299 .event_idx = perf_swevent_event_idx,
6303 * Software event: task time clock
6306 static void task_clock_event_update(struct perf_event *event, u64 now)
6311 prev = local64_xchg(&event->hw.prev_count, now);
6313 local64_add(delta, &event->count);
6316 static void task_clock_event_start(struct perf_event *event, int flags)
6318 local64_set(&event->hw.prev_count, event->ctx->time);
6319 perf_swevent_start_hrtimer(event);
6322 static void task_clock_event_stop(struct perf_event *event, int flags)
6324 perf_swevent_cancel_hrtimer(event);
6325 task_clock_event_update(event, event->ctx->time);
6328 static int task_clock_event_add(struct perf_event *event, int flags)
6330 if (flags & PERF_EF_START)
6331 task_clock_event_start(event, flags);
6336 static void task_clock_event_del(struct perf_event *event, int flags)
6338 task_clock_event_stop(event, PERF_EF_UPDATE);
6341 static void task_clock_event_read(struct perf_event *event)
6343 u64 now = perf_clock();
6344 u64 delta = now - event->ctx->timestamp;
6345 u64 time = event->ctx->time + delta;
6347 task_clock_event_update(event, time);
6350 static int task_clock_event_init(struct perf_event *event)
6352 if (event->attr.type != PERF_TYPE_SOFTWARE)
6355 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
6359 * no branch sampling for software events
6361 if (has_branch_stack(event))
6364 perf_swevent_init_hrtimer(event);
6369 static struct pmu perf_task_clock = {
6370 .task_ctx_nr = perf_sw_context,
6372 .event_init = task_clock_event_init,
6373 .add = task_clock_event_add,
6374 .del = task_clock_event_del,
6375 .start = task_clock_event_start,
6376 .stop = task_clock_event_stop,
6377 .read = task_clock_event_read,
6379 .event_idx = perf_swevent_event_idx,
6382 static void perf_pmu_nop_void(struct pmu *pmu)
6386 static int perf_pmu_nop_int(struct pmu *pmu)
6391 static void perf_pmu_start_txn(struct pmu *pmu)
6393 perf_pmu_disable(pmu);
6396 static int perf_pmu_commit_txn(struct pmu *pmu)
6398 perf_pmu_enable(pmu);
6402 static void perf_pmu_cancel_txn(struct pmu *pmu)
6404 perf_pmu_enable(pmu);
6407 static int perf_event_idx_default(struct perf_event *event)
6409 return event->hw.idx + 1;
6413 * Ensures all contexts with the same task_ctx_nr have the same
6414 * pmu_cpu_context too.
6416 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
6423 list_for_each_entry(pmu, &pmus, entry) {
6424 if (pmu->task_ctx_nr == ctxn)
6425 return pmu->pmu_cpu_context;
6431 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
6435 for_each_possible_cpu(cpu) {
6436 struct perf_cpu_context *cpuctx;
6438 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6440 if (cpuctx->unique_pmu == old_pmu)
6441 cpuctx->unique_pmu = pmu;
6445 static void free_pmu_context(struct pmu *pmu)
6449 mutex_lock(&pmus_lock);
6451 * Like a real lame refcount.
6453 list_for_each_entry(i, &pmus, entry) {
6454 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
6455 update_pmu_context(i, pmu);
6460 free_percpu(pmu->pmu_cpu_context);
6462 mutex_unlock(&pmus_lock);
6464 static struct idr pmu_idr;
6467 type_show(struct device *dev, struct device_attribute *attr, char *page)
6469 struct pmu *pmu = dev_get_drvdata(dev);
6471 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
6473 static DEVICE_ATTR_RO(type);
6476 perf_event_mux_interval_ms_show(struct device *dev,
6477 struct device_attribute *attr,
6480 struct pmu *pmu = dev_get_drvdata(dev);
6482 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
6486 perf_event_mux_interval_ms_store(struct device *dev,
6487 struct device_attribute *attr,
6488 const char *buf, size_t count)
6490 struct pmu *pmu = dev_get_drvdata(dev);
6491 int timer, cpu, ret;
6493 ret = kstrtoint(buf, 0, &timer);
6500 /* same value, noting to do */
6501 if (timer == pmu->hrtimer_interval_ms)
6504 pmu->hrtimer_interval_ms = timer;
6506 /* update all cpuctx for this PMU */
6507 for_each_possible_cpu(cpu) {
6508 struct perf_cpu_context *cpuctx;
6509 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6510 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
6512 if (hrtimer_active(&cpuctx->hrtimer))
6513 hrtimer_forward_now(&cpuctx->hrtimer, cpuctx->hrtimer_interval);
6518 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
6520 static struct attribute *pmu_dev_attrs[] = {
6521 &dev_attr_type.attr,
6522 &dev_attr_perf_event_mux_interval_ms.attr,
6525 ATTRIBUTE_GROUPS(pmu_dev);
6527 static int pmu_bus_running;
6528 static struct bus_type pmu_bus = {
6529 .name = "event_source",
6530 .dev_groups = pmu_dev_groups,
6533 static void pmu_dev_release(struct device *dev)
6538 static int pmu_dev_alloc(struct pmu *pmu)
6542 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
6546 pmu->dev->groups = pmu->attr_groups;
6547 device_initialize(pmu->dev);
6548 ret = dev_set_name(pmu->dev, "%s", pmu->name);
6552 dev_set_drvdata(pmu->dev, pmu);
6553 pmu->dev->bus = &pmu_bus;
6554 pmu->dev->release = pmu_dev_release;
6555 ret = device_add(pmu->dev);
6563 put_device(pmu->dev);
6567 static struct lock_class_key cpuctx_mutex;
6568 static struct lock_class_key cpuctx_lock;
6570 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
6574 mutex_lock(&pmus_lock);
6576 pmu->pmu_disable_count = alloc_percpu(int);
6577 if (!pmu->pmu_disable_count)
6586 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
6594 if (pmu_bus_running) {
6595 ret = pmu_dev_alloc(pmu);
6601 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
6602 if (pmu->pmu_cpu_context)
6603 goto got_cpu_context;
6606 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
6607 if (!pmu->pmu_cpu_context)
6610 for_each_possible_cpu(cpu) {
6611 struct perf_cpu_context *cpuctx;
6613 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6614 __perf_event_init_context(&cpuctx->ctx);
6615 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
6616 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
6617 cpuctx->ctx.type = cpu_context;
6618 cpuctx->ctx.pmu = pmu;
6620 __perf_cpu_hrtimer_init(cpuctx, cpu);
6622 INIT_LIST_HEAD(&cpuctx->rotation_list);
6623 cpuctx->unique_pmu = pmu;
6627 if (!pmu->start_txn) {
6628 if (pmu->pmu_enable) {
6630 * If we have pmu_enable/pmu_disable calls, install
6631 * transaction stubs that use that to try and batch
6632 * hardware accesses.
6634 pmu->start_txn = perf_pmu_start_txn;
6635 pmu->commit_txn = perf_pmu_commit_txn;
6636 pmu->cancel_txn = perf_pmu_cancel_txn;
6638 pmu->start_txn = perf_pmu_nop_void;
6639 pmu->commit_txn = perf_pmu_nop_int;
6640 pmu->cancel_txn = perf_pmu_nop_void;
6644 if (!pmu->pmu_enable) {
6645 pmu->pmu_enable = perf_pmu_nop_void;
6646 pmu->pmu_disable = perf_pmu_nop_void;
6649 if (!pmu->event_idx)
6650 pmu->event_idx = perf_event_idx_default;
6652 list_add_rcu(&pmu->entry, &pmus);
6655 mutex_unlock(&pmus_lock);
6660 device_del(pmu->dev);
6661 put_device(pmu->dev);
6664 if (pmu->type >= PERF_TYPE_MAX)
6665 idr_remove(&pmu_idr, pmu->type);
6668 free_percpu(pmu->pmu_disable_count);
6671 EXPORT_SYMBOL_GPL(perf_pmu_register);
6673 void perf_pmu_unregister(struct pmu *pmu)
6675 mutex_lock(&pmus_lock);
6676 list_del_rcu(&pmu->entry);
6677 mutex_unlock(&pmus_lock);
6680 * We dereference the pmu list under both SRCU and regular RCU, so
6681 * synchronize against both of those.
6683 synchronize_srcu(&pmus_srcu);
6686 free_percpu(pmu->pmu_disable_count);
6687 if (pmu->type >= PERF_TYPE_MAX)
6688 idr_remove(&pmu_idr, pmu->type);
6689 device_del(pmu->dev);
6690 put_device(pmu->dev);
6691 free_pmu_context(pmu);
6693 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
6695 struct pmu *perf_init_event(struct perf_event *event)
6697 struct pmu *pmu = NULL;
6701 idx = srcu_read_lock(&pmus_srcu);
6704 pmu = idr_find(&pmu_idr, event->attr.type);
6707 if (!try_module_get(pmu->module)) {
6708 pmu = ERR_PTR(-ENODEV);
6712 ret = pmu->event_init(event);
6718 list_for_each_entry_rcu(pmu, &pmus, entry) {
6719 if (!try_module_get(pmu->module)) {
6720 pmu = ERR_PTR(-ENODEV);
6724 ret = pmu->event_init(event);
6728 if (ret != -ENOENT) {
6733 pmu = ERR_PTR(-ENOENT);
6735 srcu_read_unlock(&pmus_srcu, idx);
6740 static void account_event_cpu(struct perf_event *event, int cpu)
6745 if (has_branch_stack(event)) {
6746 if (!(event->attach_state & PERF_ATTACH_TASK))
6747 atomic_inc(&per_cpu(perf_branch_stack_events, cpu));
6749 if (is_cgroup_event(event))
6750 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
6753 static void account_event(struct perf_event *event)
6758 if (event->attach_state & PERF_ATTACH_TASK)
6759 static_key_slow_inc(&perf_sched_events.key);
6760 if (event->attr.mmap || event->attr.mmap_data)
6761 atomic_inc(&nr_mmap_events);
6762 if (event->attr.comm)
6763 atomic_inc(&nr_comm_events);
6764 if (event->attr.task)
6765 atomic_inc(&nr_task_events);
6766 if (event->attr.freq) {
6767 if (atomic_inc_return(&nr_freq_events) == 1)
6768 tick_nohz_full_kick_all();
6770 if (has_branch_stack(event))
6771 static_key_slow_inc(&perf_sched_events.key);
6772 if (is_cgroup_event(event))
6773 static_key_slow_inc(&perf_sched_events.key);
6775 account_event_cpu(event, event->cpu);
6779 * Allocate and initialize a event structure
6781 static struct perf_event *
6782 perf_event_alloc(struct perf_event_attr *attr, int cpu,
6783 struct task_struct *task,
6784 struct perf_event *group_leader,
6785 struct perf_event *parent_event,
6786 perf_overflow_handler_t overflow_handler,
6790 struct perf_event *event;
6791 struct hw_perf_event *hwc;
6794 if ((unsigned)cpu >= nr_cpu_ids) {
6795 if (!task || cpu != -1)
6796 return ERR_PTR(-EINVAL);
6799 event = kzalloc(sizeof(*event), GFP_KERNEL);
6801 return ERR_PTR(-ENOMEM);
6804 * Single events are their own group leaders, with an
6805 * empty sibling list:
6808 group_leader = event;
6810 mutex_init(&event->child_mutex);
6811 INIT_LIST_HEAD(&event->child_list);
6813 INIT_LIST_HEAD(&event->group_entry);
6814 INIT_LIST_HEAD(&event->event_entry);
6815 INIT_LIST_HEAD(&event->sibling_list);
6816 INIT_LIST_HEAD(&event->rb_entry);
6817 INIT_LIST_HEAD(&event->active_entry);
6818 INIT_HLIST_NODE(&event->hlist_entry);
6821 init_waitqueue_head(&event->waitq);
6822 init_irq_work(&event->pending, perf_pending_event);
6824 mutex_init(&event->mmap_mutex);
6826 atomic_long_set(&event->refcount, 1);
6828 event->attr = *attr;
6829 event->group_leader = group_leader;
6833 event->parent = parent_event;
6835 event->ns = get_pid_ns(task_active_pid_ns(current));
6836 event->id = atomic64_inc_return(&perf_event_id);
6838 event->state = PERF_EVENT_STATE_INACTIVE;
6841 event->attach_state = PERF_ATTACH_TASK;
6843 if (attr->type == PERF_TYPE_TRACEPOINT)
6844 event->hw.tp_target = task;
6845 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6847 * hw_breakpoint is a bit difficult here..
6849 else if (attr->type == PERF_TYPE_BREAKPOINT)
6850 event->hw.bp_target = task;
6854 if (!overflow_handler && parent_event) {
6855 overflow_handler = parent_event->overflow_handler;
6856 context = parent_event->overflow_handler_context;
6859 event->overflow_handler = overflow_handler;
6860 event->overflow_handler_context = context;
6862 perf_event__state_init(event);
6867 hwc->sample_period = attr->sample_period;
6868 if (attr->freq && attr->sample_freq)
6869 hwc->sample_period = 1;
6870 hwc->last_period = hwc->sample_period;
6872 local64_set(&hwc->period_left, hwc->sample_period);
6875 * we currently do not support PERF_FORMAT_GROUP on inherited events
6877 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
6880 pmu = perf_init_event(event);
6883 else if (IS_ERR(pmu)) {
6888 if (!event->parent) {
6889 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
6890 err = get_callchain_buffers();
6900 event->destroy(event);
6901 module_put(pmu->module);
6904 put_pid_ns(event->ns);
6907 return ERR_PTR(err);
6910 static int perf_copy_attr(struct perf_event_attr __user *uattr,
6911 struct perf_event_attr *attr)
6916 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
6920 * zero the full structure, so that a short copy will be nice.
6922 memset(attr, 0, sizeof(*attr));
6924 ret = get_user(size, &uattr->size);
6928 if (size > PAGE_SIZE) /* silly large */
6931 if (!size) /* abi compat */
6932 size = PERF_ATTR_SIZE_VER0;
6934 if (size < PERF_ATTR_SIZE_VER0)
6938 * If we're handed a bigger struct than we know of,
6939 * ensure all the unknown bits are 0 - i.e. new
6940 * user-space does not rely on any kernel feature
6941 * extensions we dont know about yet.
6943 if (size > sizeof(*attr)) {
6944 unsigned char __user *addr;
6945 unsigned char __user *end;
6948 addr = (void __user *)uattr + sizeof(*attr);
6949 end = (void __user *)uattr + size;
6951 for (; addr < end; addr++) {
6952 ret = get_user(val, addr);
6958 size = sizeof(*attr);
6961 ret = copy_from_user(attr, uattr, size);
6965 if (attr->__reserved_1)
6968 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
6971 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
6974 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
6975 u64 mask = attr->branch_sample_type;
6977 /* only using defined bits */
6978 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
6981 /* at least one branch bit must be set */
6982 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
6985 /* propagate priv level, when not set for branch */
6986 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
6988 /* exclude_kernel checked on syscall entry */
6989 if (!attr->exclude_kernel)
6990 mask |= PERF_SAMPLE_BRANCH_KERNEL;
6992 if (!attr->exclude_user)
6993 mask |= PERF_SAMPLE_BRANCH_USER;
6995 if (!attr->exclude_hv)
6996 mask |= PERF_SAMPLE_BRANCH_HV;
6998 * adjust user setting (for HW filter setup)
7000 attr->branch_sample_type = mask;
7002 /* privileged levels capture (kernel, hv): check permissions */
7003 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
7004 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
7008 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
7009 ret = perf_reg_validate(attr->sample_regs_user);
7014 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
7015 if (!arch_perf_have_user_stack_dump())
7019 * We have __u32 type for the size, but so far
7020 * we can only use __u16 as maximum due to the
7021 * __u16 sample size limit.
7023 if (attr->sample_stack_user >= USHRT_MAX)
7025 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
7033 put_user(sizeof(*attr), &uattr->size);
7039 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
7041 struct ring_buffer *rb = NULL;
7047 /* don't allow circular references */
7048 if (event == output_event)
7052 * Don't allow cross-cpu buffers
7054 if (output_event->cpu != event->cpu)
7058 * If its not a per-cpu rb, it must be the same task.
7060 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
7064 mutex_lock(&event->mmap_mutex);
7065 /* Can't redirect output if we've got an active mmap() */
7066 if (atomic_read(&event->mmap_count))
7070 /* get the rb we want to redirect to */
7071 rb = ring_buffer_get(output_event);
7076 ring_buffer_attach(event, rb);
7080 mutex_unlock(&event->mmap_mutex);
7087 * sys_perf_event_open - open a performance event, associate it to a task/cpu
7089 * @attr_uptr: event_id type attributes for monitoring/sampling
7092 * @group_fd: group leader event fd
7094 SYSCALL_DEFINE5(perf_event_open,
7095 struct perf_event_attr __user *, attr_uptr,
7096 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
7098 struct perf_event *group_leader = NULL, *output_event = NULL;
7099 struct perf_event *event, *sibling;
7100 struct perf_event_attr attr;
7101 struct perf_event_context *ctx;
7102 struct file *event_file = NULL;
7103 struct fd group = {NULL, 0};
7104 struct task_struct *task = NULL;
7109 int f_flags = O_RDWR;
7111 /* for future expandability... */
7112 if (flags & ~PERF_FLAG_ALL)
7115 err = perf_copy_attr(attr_uptr, &attr);
7119 if (!attr.exclude_kernel) {
7120 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
7125 if (attr.sample_freq > sysctl_perf_event_sample_rate)
7128 if (attr.sample_period & (1ULL << 63))
7133 * In cgroup mode, the pid argument is used to pass the fd
7134 * opened to the cgroup directory in cgroupfs. The cpu argument
7135 * designates the cpu on which to monitor threads from that
7138 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
7141 if (flags & PERF_FLAG_FD_CLOEXEC)
7142 f_flags |= O_CLOEXEC;
7144 event_fd = get_unused_fd_flags(f_flags);
7148 if (group_fd != -1) {
7149 err = perf_fget_light(group_fd, &group);
7152 group_leader = group.file->private_data;
7153 if (flags & PERF_FLAG_FD_OUTPUT)
7154 output_event = group_leader;
7155 if (flags & PERF_FLAG_FD_NO_GROUP)
7156 group_leader = NULL;
7159 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
7160 task = find_lively_task_by_vpid(pid);
7162 err = PTR_ERR(task);
7167 if (task && group_leader &&
7168 group_leader->attr.inherit != attr.inherit) {
7175 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
7177 if (IS_ERR(event)) {
7178 err = PTR_ERR(event);
7182 if (flags & PERF_FLAG_PID_CGROUP) {
7183 err = perf_cgroup_connect(pid, event, &attr, group_leader);
7185 __free_event(event);
7190 if (is_sampling_event(event)) {
7191 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
7197 account_event(event);
7200 * Special case software events and allow them to be part of
7201 * any hardware group.
7206 (is_software_event(event) != is_software_event(group_leader))) {
7207 if (is_software_event(event)) {
7209 * If event and group_leader are not both a software
7210 * event, and event is, then group leader is not.
7212 * Allow the addition of software events to !software
7213 * groups, this is safe because software events never
7216 pmu = group_leader->pmu;
7217 } else if (is_software_event(group_leader) &&
7218 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
7220 * In case the group is a pure software group, and we
7221 * try to add a hardware event, move the whole group to
7222 * the hardware context.
7229 * Get the target context (task or percpu):
7231 ctx = find_get_context(pmu, task, event->cpu);
7238 put_task_struct(task);
7243 * Look up the group leader (we will attach this event to it):
7249 * Do not allow a recursive hierarchy (this new sibling
7250 * becoming part of another group-sibling):
7252 if (group_leader->group_leader != group_leader)
7255 * Do not allow to attach to a group in a different
7256 * task or CPU context:
7259 if (group_leader->ctx->type != ctx->type)
7262 if (group_leader->ctx != ctx)
7267 * Only a group leader can be exclusive or pinned
7269 if (attr.exclusive || attr.pinned)
7274 err = perf_event_set_output(event, output_event);
7279 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
7281 if (IS_ERR(event_file)) {
7282 err = PTR_ERR(event_file);
7287 struct perf_event_context *gctx = group_leader->ctx;
7289 mutex_lock(&gctx->mutex);
7290 perf_remove_from_context(group_leader, false);
7293 * Removing from the context ends up with disabled
7294 * event. What we want here is event in the initial
7295 * startup state, ready to be add into new context.
7297 perf_event__state_init(group_leader);
7298 list_for_each_entry(sibling, &group_leader->sibling_list,
7300 perf_remove_from_context(sibling, false);
7301 perf_event__state_init(sibling);
7304 mutex_unlock(&gctx->mutex);
7308 WARN_ON_ONCE(ctx->parent_ctx);
7309 mutex_lock(&ctx->mutex);
7313 perf_install_in_context(ctx, group_leader, event->cpu);
7315 list_for_each_entry(sibling, &group_leader->sibling_list,
7317 perf_install_in_context(ctx, sibling, event->cpu);
7322 perf_install_in_context(ctx, event, event->cpu);
7323 perf_unpin_context(ctx);
7324 mutex_unlock(&ctx->mutex);
7328 event->owner = current;
7330 mutex_lock(¤t->perf_event_mutex);
7331 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
7332 mutex_unlock(¤t->perf_event_mutex);
7335 * Precalculate sample_data sizes
7337 perf_event__header_size(event);
7338 perf_event__id_header_size(event);
7341 * Drop the reference on the group_event after placing the
7342 * new event on the sibling_list. This ensures destruction
7343 * of the group leader will find the pointer to itself in
7344 * perf_group_detach().
7347 fd_install(event_fd, event_file);
7351 perf_unpin_context(ctx);
7359 put_task_struct(task);
7363 put_unused_fd(event_fd);
7368 * perf_event_create_kernel_counter
7370 * @attr: attributes of the counter to create
7371 * @cpu: cpu in which the counter is bound
7372 * @task: task to profile (NULL for percpu)
7375 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
7376 struct task_struct *task,
7377 perf_overflow_handler_t overflow_handler,
7380 struct perf_event_context *ctx;
7381 struct perf_event *event;
7385 * Get the target context (task or percpu):
7388 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
7389 overflow_handler, context);
7390 if (IS_ERR(event)) {
7391 err = PTR_ERR(event);
7395 account_event(event);
7397 ctx = find_get_context(event->pmu, task, cpu);
7403 WARN_ON_ONCE(ctx->parent_ctx);
7404 mutex_lock(&ctx->mutex);
7405 perf_install_in_context(ctx, event, cpu);
7406 perf_unpin_context(ctx);
7407 mutex_unlock(&ctx->mutex);
7414 return ERR_PTR(err);
7416 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
7418 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
7420 struct perf_event_context *src_ctx;
7421 struct perf_event_context *dst_ctx;
7422 struct perf_event *event, *tmp;
7425 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
7426 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
7428 mutex_lock(&src_ctx->mutex);
7429 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
7431 perf_remove_from_context(event, false);
7432 unaccount_event_cpu(event, src_cpu);
7434 list_add(&event->migrate_entry, &events);
7436 mutex_unlock(&src_ctx->mutex);
7440 mutex_lock(&dst_ctx->mutex);
7441 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
7442 list_del(&event->migrate_entry);
7443 if (event->state >= PERF_EVENT_STATE_OFF)
7444 event->state = PERF_EVENT_STATE_INACTIVE;
7445 account_event_cpu(event, dst_cpu);
7446 perf_install_in_context(dst_ctx, event, dst_cpu);
7449 mutex_unlock(&dst_ctx->mutex);
7451 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
7453 static void sync_child_event(struct perf_event *child_event,
7454 struct task_struct *child)
7456 struct perf_event *parent_event = child_event->parent;
7459 if (child_event->attr.inherit_stat)
7460 perf_event_read_event(child_event, child);
7462 child_val = perf_event_count(child_event);
7465 * Add back the child's count to the parent's count:
7467 atomic64_add(child_val, &parent_event->child_count);
7468 atomic64_add(child_event->total_time_enabled,
7469 &parent_event->child_total_time_enabled);
7470 atomic64_add(child_event->total_time_running,
7471 &parent_event->child_total_time_running);
7474 * Remove this event from the parent's list
7476 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7477 mutex_lock(&parent_event->child_mutex);
7478 list_del_init(&child_event->child_list);
7479 mutex_unlock(&parent_event->child_mutex);
7482 * Release the parent event, if this was the last
7485 put_event(parent_event);
7489 __perf_event_exit_task(struct perf_event *child_event,
7490 struct perf_event_context *child_ctx,
7491 struct task_struct *child)
7494 * Do not destroy the 'original' grouping; because of the context
7495 * switch optimization the original events could've ended up in a
7496 * random child task.
7498 * If we were to destroy the original group, all group related
7499 * operations would cease to function properly after this random
7502 * Do destroy all inherited groups, we don't care about those
7503 * and being thorough is better.
7505 perf_remove_from_context(child_event, !!child_event->parent);
7508 * It can happen that the parent exits first, and has events
7509 * that are still around due to the child reference. These
7510 * events need to be zapped.
7512 if (child_event->parent) {
7513 sync_child_event(child_event, child);
7514 free_event(child_event);
7518 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
7520 struct perf_event *child_event, *next;
7521 struct perf_event_context *child_ctx, *parent_ctx;
7522 unsigned long flags;
7524 if (likely(!child->perf_event_ctxp[ctxn])) {
7525 perf_event_task(child, NULL, 0);
7529 local_irq_save(flags);
7531 * We can't reschedule here because interrupts are disabled,
7532 * and either child is current or it is a task that can't be
7533 * scheduled, so we are now safe from rescheduling changing
7536 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
7539 * Take the context lock here so that if find_get_context is
7540 * reading child->perf_event_ctxp, we wait until it has
7541 * incremented the context's refcount before we do put_ctx below.
7543 raw_spin_lock(&child_ctx->lock);
7544 task_ctx_sched_out(child_ctx);
7545 child->perf_event_ctxp[ctxn] = NULL;
7548 * In order to avoid freeing: child_ctx->parent_ctx->task
7549 * under perf_event_context::lock, grab another reference.
7551 parent_ctx = child_ctx->parent_ctx;
7553 get_ctx(parent_ctx);
7556 * If this context is a clone; unclone it so it can't get
7557 * swapped to another process while we're removing all
7558 * the events from it.
7560 unclone_ctx(child_ctx);
7561 update_context_time(child_ctx);
7562 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7565 * Now that we no longer hold perf_event_context::lock, drop
7566 * our extra child_ctx->parent_ctx reference.
7569 put_ctx(parent_ctx);
7572 * Report the task dead after unscheduling the events so that we
7573 * won't get any samples after PERF_RECORD_EXIT. We can however still
7574 * get a few PERF_RECORD_READ events.
7576 perf_event_task(child, child_ctx, 0);
7579 * We can recurse on the same lock type through:
7581 * __perf_event_exit_task()
7582 * sync_child_event()
7584 * mutex_lock(&ctx->mutex)
7586 * But since its the parent context it won't be the same instance.
7588 mutex_lock(&child_ctx->mutex);
7590 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
7591 __perf_event_exit_task(child_event, child_ctx, child);
7593 mutex_unlock(&child_ctx->mutex);
7599 * When a child task exits, feed back event values to parent events.
7601 void perf_event_exit_task(struct task_struct *child)
7603 struct perf_event *event, *tmp;
7606 mutex_lock(&child->perf_event_mutex);
7607 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
7609 list_del_init(&event->owner_entry);
7612 * Ensure the list deletion is visible before we clear
7613 * the owner, closes a race against perf_release() where
7614 * we need to serialize on the owner->perf_event_mutex.
7617 event->owner = NULL;
7619 mutex_unlock(&child->perf_event_mutex);
7621 for_each_task_context_nr(ctxn)
7622 perf_event_exit_task_context(child, ctxn);
7625 static void perf_free_event(struct perf_event *event,
7626 struct perf_event_context *ctx)
7628 struct perf_event *parent = event->parent;
7630 if (WARN_ON_ONCE(!parent))
7633 mutex_lock(&parent->child_mutex);
7634 list_del_init(&event->child_list);
7635 mutex_unlock(&parent->child_mutex);
7639 perf_group_detach(event);
7640 list_del_event(event, ctx);
7645 * free an unexposed, unused context as created by inheritance by
7646 * perf_event_init_task below, used by fork() in case of fail.
7648 void perf_event_free_task(struct task_struct *task)
7650 struct perf_event_context *ctx;
7651 struct perf_event *event, *tmp;
7654 for_each_task_context_nr(ctxn) {
7655 ctx = task->perf_event_ctxp[ctxn];
7659 mutex_lock(&ctx->mutex);
7661 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
7663 perf_free_event(event, ctx);
7665 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
7667 perf_free_event(event, ctx);
7669 if (!list_empty(&ctx->pinned_groups) ||
7670 !list_empty(&ctx->flexible_groups))
7673 mutex_unlock(&ctx->mutex);
7679 void perf_event_delayed_put(struct task_struct *task)
7683 for_each_task_context_nr(ctxn)
7684 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
7688 * inherit a event from parent task to child task:
7690 static struct perf_event *
7691 inherit_event(struct perf_event *parent_event,
7692 struct task_struct *parent,
7693 struct perf_event_context *parent_ctx,
7694 struct task_struct *child,
7695 struct perf_event *group_leader,
7696 struct perf_event_context *child_ctx)
7698 struct perf_event *child_event;
7699 unsigned long flags;
7702 * Instead of creating recursive hierarchies of events,
7703 * we link inherited events back to the original parent,
7704 * which has a filp for sure, which we use as the reference
7707 if (parent_event->parent)
7708 parent_event = parent_event->parent;
7710 child_event = perf_event_alloc(&parent_event->attr,
7713 group_leader, parent_event,
7715 if (IS_ERR(child_event))
7718 if (!atomic_long_inc_not_zero(&parent_event->refcount)) {
7719 free_event(child_event);
7726 * Make the child state follow the state of the parent event,
7727 * not its attr.disabled bit. We hold the parent's mutex,
7728 * so we won't race with perf_event_{en, dis}able_family.
7730 if (parent_event->state >= PERF_EVENT_STATE_INACTIVE)
7731 child_event->state = PERF_EVENT_STATE_INACTIVE;
7733 child_event->state = PERF_EVENT_STATE_OFF;
7735 if (parent_event->attr.freq) {
7736 u64 sample_period = parent_event->hw.sample_period;
7737 struct hw_perf_event *hwc = &child_event->hw;
7739 hwc->sample_period = sample_period;
7740 hwc->last_period = sample_period;
7742 local64_set(&hwc->period_left, sample_period);
7745 child_event->ctx = child_ctx;
7746 child_event->overflow_handler = parent_event->overflow_handler;
7747 child_event->overflow_handler_context
7748 = parent_event->overflow_handler_context;
7751 * Precalculate sample_data sizes
7753 perf_event__header_size(child_event);
7754 perf_event__id_header_size(child_event);
7757 * Link it up in the child's context:
7759 raw_spin_lock_irqsave(&child_ctx->lock, flags);
7760 add_event_to_ctx(child_event, child_ctx);
7761 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7764 * Link this into the parent event's child list
7766 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7767 mutex_lock(&parent_event->child_mutex);
7768 list_add_tail(&child_event->child_list, &parent_event->child_list);
7769 mutex_unlock(&parent_event->child_mutex);
7774 static int inherit_group(struct perf_event *parent_event,
7775 struct task_struct *parent,
7776 struct perf_event_context *parent_ctx,
7777 struct task_struct *child,
7778 struct perf_event_context *child_ctx)
7780 struct perf_event *leader;
7781 struct perf_event *sub;
7782 struct perf_event *child_ctr;
7784 leader = inherit_event(parent_event, parent, parent_ctx,
7785 child, NULL, child_ctx);
7787 return PTR_ERR(leader);
7788 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
7789 child_ctr = inherit_event(sub, parent, parent_ctx,
7790 child, leader, child_ctx);
7791 if (IS_ERR(child_ctr))
7792 return PTR_ERR(child_ctr);
7798 inherit_task_group(struct perf_event *event, struct task_struct *parent,
7799 struct perf_event_context *parent_ctx,
7800 struct task_struct *child, int ctxn,
7804 struct perf_event_context *child_ctx;
7806 if (!event->attr.inherit) {
7811 child_ctx = child->perf_event_ctxp[ctxn];
7814 * This is executed from the parent task context, so
7815 * inherit events that have been marked for cloning.
7816 * First allocate and initialize a context for the
7820 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
7824 child->perf_event_ctxp[ctxn] = child_ctx;
7827 ret = inherit_group(event, parent, parent_ctx,
7837 * Initialize the perf_event context in task_struct
7839 static int perf_event_init_context(struct task_struct *child, int ctxn)
7841 struct perf_event_context *child_ctx, *parent_ctx;
7842 struct perf_event_context *cloned_ctx;
7843 struct perf_event *event;
7844 struct task_struct *parent = current;
7845 int inherited_all = 1;
7846 unsigned long flags;
7849 if (likely(!parent->perf_event_ctxp[ctxn]))
7853 * If the parent's context is a clone, pin it so it won't get
7856 parent_ctx = perf_pin_task_context(parent, ctxn);
7861 * No need to check if parent_ctx != NULL here; since we saw
7862 * it non-NULL earlier, the only reason for it to become NULL
7863 * is if we exit, and since we're currently in the middle of
7864 * a fork we can't be exiting at the same time.
7868 * Lock the parent list. No need to lock the child - not PID
7869 * hashed yet and not running, so nobody can access it.
7871 mutex_lock(&parent_ctx->mutex);
7874 * We dont have to disable NMIs - we are only looking at
7875 * the list, not manipulating it:
7877 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
7878 ret = inherit_task_group(event, parent, parent_ctx,
7879 child, ctxn, &inherited_all);
7885 * We can't hold ctx->lock when iterating the ->flexible_group list due
7886 * to allocations, but we need to prevent rotation because
7887 * rotate_ctx() will change the list from interrupt context.
7889 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7890 parent_ctx->rotate_disable = 1;
7891 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7893 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
7894 ret = inherit_task_group(event, parent, parent_ctx,
7895 child, ctxn, &inherited_all);
7900 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7901 parent_ctx->rotate_disable = 0;
7903 child_ctx = child->perf_event_ctxp[ctxn];
7905 if (child_ctx && inherited_all) {
7907 * Mark the child context as a clone of the parent
7908 * context, or of whatever the parent is a clone of.
7910 * Note that if the parent is a clone, the holding of
7911 * parent_ctx->lock avoids it from being uncloned.
7913 cloned_ctx = parent_ctx->parent_ctx;
7915 child_ctx->parent_ctx = cloned_ctx;
7916 child_ctx->parent_gen = parent_ctx->parent_gen;
7918 child_ctx->parent_ctx = parent_ctx;
7919 child_ctx->parent_gen = parent_ctx->generation;
7921 get_ctx(child_ctx->parent_ctx);
7924 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7925 mutex_unlock(&parent_ctx->mutex);
7927 perf_unpin_context(parent_ctx);
7928 put_ctx(parent_ctx);
7934 * Initialize the perf_event context in task_struct
7936 int perf_event_init_task(struct task_struct *child)
7940 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
7941 mutex_init(&child->perf_event_mutex);
7942 INIT_LIST_HEAD(&child->perf_event_list);
7944 for_each_task_context_nr(ctxn) {
7945 ret = perf_event_init_context(child, ctxn);
7947 perf_event_free_task(child);
7955 static void __init perf_event_init_all_cpus(void)
7957 struct swevent_htable *swhash;
7960 for_each_possible_cpu(cpu) {
7961 swhash = &per_cpu(swevent_htable, cpu);
7962 mutex_init(&swhash->hlist_mutex);
7963 INIT_LIST_HEAD(&per_cpu(rotation_list, cpu));
7967 static void perf_event_init_cpu(int cpu)
7969 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7971 mutex_lock(&swhash->hlist_mutex);
7972 swhash->online = true;
7973 if (swhash->hlist_refcount > 0) {
7974 struct swevent_hlist *hlist;
7976 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
7978 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7980 mutex_unlock(&swhash->hlist_mutex);
7983 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC
7984 static void perf_pmu_rotate_stop(struct pmu *pmu)
7986 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7988 WARN_ON(!irqs_disabled());
7990 list_del_init(&cpuctx->rotation_list);
7993 static void __perf_event_exit_context(void *__info)
7995 struct remove_event re = { .detach_group = false };
7996 struct perf_event_context *ctx = __info;
7998 perf_pmu_rotate_stop(ctx->pmu);
8001 list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
8002 __perf_remove_from_context(&re);
8006 static void perf_event_exit_cpu_context(int cpu)
8008 struct perf_event_context *ctx;
8012 idx = srcu_read_lock(&pmus_srcu);
8013 list_for_each_entry_rcu(pmu, &pmus, entry) {
8014 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
8016 mutex_lock(&ctx->mutex);
8017 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
8018 mutex_unlock(&ctx->mutex);
8020 srcu_read_unlock(&pmus_srcu, idx);
8023 static void perf_event_exit_cpu(int cpu)
8025 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
8027 perf_event_exit_cpu_context(cpu);
8029 mutex_lock(&swhash->hlist_mutex);
8030 swhash->online = false;
8031 swevent_hlist_release(swhash);
8032 mutex_unlock(&swhash->hlist_mutex);
8035 static inline void perf_event_exit_cpu(int cpu) { }
8039 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
8043 for_each_online_cpu(cpu)
8044 perf_event_exit_cpu(cpu);
8050 * Run the perf reboot notifier at the very last possible moment so that
8051 * the generic watchdog code runs as long as possible.
8053 static struct notifier_block perf_reboot_notifier = {
8054 .notifier_call = perf_reboot,
8055 .priority = INT_MIN,
8059 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
8061 unsigned int cpu = (long)hcpu;
8063 switch (action & ~CPU_TASKS_FROZEN) {
8065 case CPU_UP_PREPARE:
8066 case CPU_DOWN_FAILED:
8067 perf_event_init_cpu(cpu);
8070 case CPU_UP_CANCELED:
8071 case CPU_DOWN_PREPARE:
8072 perf_event_exit_cpu(cpu);
8081 void __init perf_event_init(void)
8087 perf_event_init_all_cpus();
8088 init_srcu_struct(&pmus_srcu);
8089 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
8090 perf_pmu_register(&perf_cpu_clock, NULL, -1);
8091 perf_pmu_register(&perf_task_clock, NULL, -1);
8093 perf_cpu_notifier(perf_cpu_notify);
8094 register_reboot_notifier(&perf_reboot_notifier);
8096 ret = init_hw_breakpoint();
8097 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
8099 /* do not patch jump label more than once per second */
8100 jump_label_rate_limit(&perf_sched_events, HZ);
8103 * Build time assertion that we keep the data_head at the intended
8104 * location. IOW, validation we got the __reserved[] size right.
8106 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
8110 static int __init perf_event_sysfs_init(void)
8115 mutex_lock(&pmus_lock);
8117 ret = bus_register(&pmu_bus);
8121 list_for_each_entry(pmu, &pmus, entry) {
8122 if (!pmu->name || pmu->type < 0)
8125 ret = pmu_dev_alloc(pmu);
8126 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
8128 pmu_bus_running = 1;
8132 mutex_unlock(&pmus_lock);
8136 device_initcall(perf_event_sysfs_init);
8138 #ifdef CONFIG_CGROUP_PERF
8139 static struct cgroup_subsys_state *
8140 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
8142 struct perf_cgroup *jc;
8144 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
8146 return ERR_PTR(-ENOMEM);
8148 jc->info = alloc_percpu(struct perf_cgroup_info);
8151 return ERR_PTR(-ENOMEM);
8157 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
8159 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
8161 free_percpu(jc->info);
8165 static int __perf_cgroup_move(void *info)
8167 struct task_struct *task = info;
8168 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
8172 static void perf_cgroup_attach(struct cgroup_subsys_state *css,
8173 struct cgroup_taskset *tset)
8175 struct task_struct *task;
8177 cgroup_taskset_for_each(task, tset)
8178 task_function_call(task, __perf_cgroup_move, task);
8181 static void perf_cgroup_exit(struct cgroup_subsys_state *css,
8182 struct cgroup_subsys_state *old_css,
8183 struct task_struct *task)
8186 * cgroup_exit() is called in the copy_process() failure path.
8187 * Ignore this case since the task hasn't ran yet, this avoids
8188 * trying to poke a half freed task state from generic code.
8190 if (!(task->flags & PF_EXITING))
8193 task_function_call(task, __perf_cgroup_move, task);
8196 struct cgroup_subsys perf_event_cgrp_subsys = {
8197 .css_alloc = perf_cgroup_css_alloc,
8198 .css_free = perf_cgroup_css_free,
8199 .exit = perf_cgroup_exit,
8200 .attach = perf_cgroup_attach,
8202 #endif /* CONFIG_CGROUP_PERF */