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_put_cgroup(struct perf_event *event)
397 css_put(&event->cgrp->css);
400 static inline void perf_detach_cgroup(struct perf_event *event)
402 perf_put_cgroup(event);
406 static inline int is_cgroup_event(struct perf_event *event)
408 return event->cgrp != NULL;
411 static inline u64 perf_cgroup_event_time(struct perf_event *event)
413 struct perf_cgroup_info *t;
415 t = per_cpu_ptr(event->cgrp->info, event->cpu);
419 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
421 struct perf_cgroup_info *info;
426 info = this_cpu_ptr(cgrp->info);
428 info->time += now - info->timestamp;
429 info->timestamp = now;
432 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
434 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
436 __update_cgrp_time(cgrp_out);
439 static inline void update_cgrp_time_from_event(struct perf_event *event)
441 struct perf_cgroup *cgrp;
444 * ensure we access cgroup data only when needed and
445 * when we know the cgroup is pinned (css_get)
447 if (!is_cgroup_event(event))
450 cgrp = perf_cgroup_from_task(current);
452 * Do not update time when cgroup is not active
454 if (cgrp == event->cgrp)
455 __update_cgrp_time(event->cgrp);
459 perf_cgroup_set_timestamp(struct task_struct *task,
460 struct perf_event_context *ctx)
462 struct perf_cgroup *cgrp;
463 struct perf_cgroup_info *info;
466 * ctx->lock held by caller
467 * ensure we do not access cgroup data
468 * unless we have the cgroup pinned (css_get)
470 if (!task || !ctx->nr_cgroups)
473 cgrp = perf_cgroup_from_task(task);
474 info = this_cpu_ptr(cgrp->info);
475 info->timestamp = ctx->timestamp;
478 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
479 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
482 * reschedule events based on the cgroup constraint of task.
484 * mode SWOUT : schedule out everything
485 * mode SWIN : schedule in based on cgroup for next
487 void perf_cgroup_switch(struct task_struct *task, int mode)
489 struct perf_cpu_context *cpuctx;
494 * disable interrupts to avoid geting nr_cgroup
495 * changes via __perf_event_disable(). Also
498 local_irq_save(flags);
501 * we reschedule only in the presence of cgroup
502 * constrained events.
506 list_for_each_entry_rcu(pmu, &pmus, entry) {
507 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
508 if (cpuctx->unique_pmu != pmu)
509 continue; /* ensure we process each cpuctx once */
512 * perf_cgroup_events says at least one
513 * context on this CPU has cgroup events.
515 * ctx->nr_cgroups reports the number of cgroup
516 * events for a context.
518 if (cpuctx->ctx.nr_cgroups > 0) {
519 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
520 perf_pmu_disable(cpuctx->ctx.pmu);
522 if (mode & PERF_CGROUP_SWOUT) {
523 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
525 * must not be done before ctxswout due
526 * to event_filter_match() in event_sched_out()
531 if (mode & PERF_CGROUP_SWIN) {
532 WARN_ON_ONCE(cpuctx->cgrp);
534 * set cgrp before ctxsw in to allow
535 * event_filter_match() to not have to pass
538 cpuctx->cgrp = perf_cgroup_from_task(task);
539 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
541 perf_pmu_enable(cpuctx->ctx.pmu);
542 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
548 local_irq_restore(flags);
551 static inline void perf_cgroup_sched_out(struct task_struct *task,
552 struct task_struct *next)
554 struct perf_cgroup *cgrp1;
555 struct perf_cgroup *cgrp2 = NULL;
558 * we come here when we know perf_cgroup_events > 0
560 cgrp1 = perf_cgroup_from_task(task);
563 * next is NULL when called from perf_event_enable_on_exec()
564 * that will systematically cause a cgroup_switch()
567 cgrp2 = perf_cgroup_from_task(next);
570 * only schedule out current cgroup events if we know
571 * that we are switching to a different cgroup. Otherwise,
572 * do no touch the cgroup events.
575 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
578 static inline void perf_cgroup_sched_in(struct task_struct *prev,
579 struct task_struct *task)
581 struct perf_cgroup *cgrp1;
582 struct perf_cgroup *cgrp2 = NULL;
585 * we come here when we know perf_cgroup_events > 0
587 cgrp1 = perf_cgroup_from_task(task);
589 /* prev can never be NULL */
590 cgrp2 = perf_cgroup_from_task(prev);
593 * only need to schedule in cgroup events if we are changing
594 * cgroup during ctxsw. Cgroup events were not scheduled
595 * out of ctxsw out if that was not the case.
598 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
601 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
602 struct perf_event_attr *attr,
603 struct perf_event *group_leader)
605 struct perf_cgroup *cgrp;
606 struct cgroup_subsys_state *css;
607 struct fd f = fdget(fd);
613 css = css_tryget_online_from_dir(f.file->f_dentry,
614 &perf_event_cgrp_subsys);
620 cgrp = container_of(css, struct perf_cgroup, css);
624 * all events in a group must monitor
625 * the same cgroup because a task belongs
626 * to only one perf cgroup at a time
628 if (group_leader && group_leader->cgrp != cgrp) {
629 perf_detach_cgroup(event);
638 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
640 struct perf_cgroup_info *t;
641 t = per_cpu_ptr(event->cgrp->info, event->cpu);
642 event->shadow_ctx_time = now - t->timestamp;
646 perf_cgroup_defer_enabled(struct perf_event *event)
649 * when the current task's perf cgroup does not match
650 * the event's, we need to remember to call the
651 * perf_mark_enable() function the first time a task with
652 * a matching perf cgroup is scheduled in.
654 if (is_cgroup_event(event) && !perf_cgroup_match(event))
655 event->cgrp_defer_enabled = 1;
659 perf_cgroup_mark_enabled(struct perf_event *event,
660 struct perf_event_context *ctx)
662 struct perf_event *sub;
663 u64 tstamp = perf_event_time(event);
665 if (!event->cgrp_defer_enabled)
668 event->cgrp_defer_enabled = 0;
670 event->tstamp_enabled = tstamp - event->total_time_enabled;
671 list_for_each_entry(sub, &event->sibling_list, group_entry) {
672 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
673 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
674 sub->cgrp_defer_enabled = 0;
678 #else /* !CONFIG_CGROUP_PERF */
681 perf_cgroup_match(struct perf_event *event)
686 static inline void perf_detach_cgroup(struct perf_event *event)
689 static inline int is_cgroup_event(struct perf_event *event)
694 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
699 static inline void update_cgrp_time_from_event(struct perf_event *event)
703 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
707 static inline void perf_cgroup_sched_out(struct task_struct *task,
708 struct task_struct *next)
712 static inline void perf_cgroup_sched_in(struct task_struct *prev,
713 struct task_struct *task)
717 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
718 struct perf_event_attr *attr,
719 struct perf_event *group_leader)
725 perf_cgroup_set_timestamp(struct task_struct *task,
726 struct perf_event_context *ctx)
731 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
736 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
740 static inline u64 perf_cgroup_event_time(struct perf_event *event)
746 perf_cgroup_defer_enabled(struct perf_event *event)
751 perf_cgroup_mark_enabled(struct perf_event *event,
752 struct perf_event_context *ctx)
758 * set default to be dependent on timer tick just
761 #define PERF_CPU_HRTIMER (1000 / HZ)
763 * function must be called with interrupts disbled
765 static enum hrtimer_restart perf_cpu_hrtimer_handler(struct hrtimer *hr)
767 struct perf_cpu_context *cpuctx;
768 enum hrtimer_restart ret = HRTIMER_NORESTART;
771 WARN_ON(!irqs_disabled());
773 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
775 rotations = perf_rotate_context(cpuctx);
778 * arm timer if needed
781 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
782 ret = HRTIMER_RESTART;
788 /* CPU is going down */
789 void perf_cpu_hrtimer_cancel(int cpu)
791 struct perf_cpu_context *cpuctx;
795 if (WARN_ON(cpu != smp_processor_id()))
798 local_irq_save(flags);
802 list_for_each_entry_rcu(pmu, &pmus, entry) {
803 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
805 if (pmu->task_ctx_nr == perf_sw_context)
808 hrtimer_cancel(&cpuctx->hrtimer);
813 local_irq_restore(flags);
816 static void __perf_cpu_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
818 struct hrtimer *hr = &cpuctx->hrtimer;
819 struct pmu *pmu = cpuctx->ctx.pmu;
822 /* no multiplexing needed for SW PMU */
823 if (pmu->task_ctx_nr == perf_sw_context)
827 * check default is sane, if not set then force to
828 * default interval (1/tick)
830 timer = pmu->hrtimer_interval_ms;
832 timer = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
834 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
836 hrtimer_init(hr, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
837 hr->function = perf_cpu_hrtimer_handler;
840 static void perf_cpu_hrtimer_restart(struct perf_cpu_context *cpuctx)
842 struct hrtimer *hr = &cpuctx->hrtimer;
843 struct pmu *pmu = cpuctx->ctx.pmu;
846 if (pmu->task_ctx_nr == perf_sw_context)
849 if (hrtimer_active(hr))
852 if (!hrtimer_callback_running(hr))
853 __hrtimer_start_range_ns(hr, cpuctx->hrtimer_interval,
854 0, HRTIMER_MODE_REL_PINNED, 0);
857 void perf_pmu_disable(struct pmu *pmu)
859 int *count = this_cpu_ptr(pmu->pmu_disable_count);
861 pmu->pmu_disable(pmu);
864 void perf_pmu_enable(struct pmu *pmu)
866 int *count = this_cpu_ptr(pmu->pmu_disable_count);
868 pmu->pmu_enable(pmu);
871 static DEFINE_PER_CPU(struct list_head, rotation_list);
874 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
875 * because they're strictly cpu affine and rotate_start is called with IRQs
876 * disabled, while rotate_context is called from IRQ context.
878 static void perf_pmu_rotate_start(struct pmu *pmu)
880 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
881 struct list_head *head = &__get_cpu_var(rotation_list);
883 WARN_ON(!irqs_disabled());
885 if (list_empty(&cpuctx->rotation_list))
886 list_add(&cpuctx->rotation_list, head);
889 static void get_ctx(struct perf_event_context *ctx)
891 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
894 static void put_ctx(struct perf_event_context *ctx)
896 if (atomic_dec_and_test(&ctx->refcount)) {
898 put_ctx(ctx->parent_ctx);
900 put_task_struct(ctx->task);
901 kfree_rcu(ctx, rcu_head);
905 static void unclone_ctx(struct perf_event_context *ctx)
907 if (ctx->parent_ctx) {
908 put_ctx(ctx->parent_ctx);
909 ctx->parent_ctx = NULL;
914 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
917 * only top level events have the pid namespace they were created in
920 event = event->parent;
922 return task_tgid_nr_ns(p, event->ns);
925 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
928 * only top level events have the pid namespace they were created in
931 event = event->parent;
933 return task_pid_nr_ns(p, event->ns);
937 * If we inherit events we want to return the parent event id
940 static u64 primary_event_id(struct perf_event *event)
945 id = event->parent->id;
951 * Get the perf_event_context for a task and lock it.
952 * This has to cope with with the fact that until it is locked,
953 * the context could get moved to another task.
955 static struct perf_event_context *
956 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
958 struct perf_event_context *ctx;
962 * One of the few rules of preemptible RCU is that one cannot do
963 * rcu_read_unlock() while holding a scheduler (or nested) lock when
964 * part of the read side critical section was preemptible -- see
965 * rcu_read_unlock_special().
967 * Since ctx->lock nests under rq->lock we must ensure the entire read
968 * side critical section is non-preemptible.
972 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
975 * If this context is a clone of another, it might
976 * get swapped for another underneath us by
977 * perf_event_task_sched_out, though the
978 * rcu_read_lock() protects us from any context
979 * getting freed. Lock the context and check if it
980 * got swapped before we could get the lock, and retry
981 * if so. If we locked the right context, then it
982 * can't get swapped on us any more.
984 raw_spin_lock_irqsave(&ctx->lock, *flags);
985 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
986 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
992 if (!atomic_inc_not_zero(&ctx->refcount)) {
993 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
1003 * Get the context for a task and increment its pin_count so it
1004 * can't get swapped to another task. This also increments its
1005 * reference count so that the context can't get freed.
1007 static struct perf_event_context *
1008 perf_pin_task_context(struct task_struct *task, int ctxn)
1010 struct perf_event_context *ctx;
1011 unsigned long flags;
1013 ctx = perf_lock_task_context(task, ctxn, &flags);
1016 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1021 static void perf_unpin_context(struct perf_event_context *ctx)
1023 unsigned long flags;
1025 raw_spin_lock_irqsave(&ctx->lock, flags);
1027 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1031 * Update the record of the current time in a context.
1033 static void update_context_time(struct perf_event_context *ctx)
1035 u64 now = perf_clock();
1037 ctx->time += now - ctx->timestamp;
1038 ctx->timestamp = now;
1041 static u64 perf_event_time(struct perf_event *event)
1043 struct perf_event_context *ctx = event->ctx;
1045 if (is_cgroup_event(event))
1046 return perf_cgroup_event_time(event);
1048 return ctx ? ctx->time : 0;
1052 * Update the total_time_enabled and total_time_running fields for a event.
1053 * The caller of this function needs to hold the ctx->lock.
1055 static void update_event_times(struct perf_event *event)
1057 struct perf_event_context *ctx = event->ctx;
1060 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1061 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1064 * in cgroup mode, time_enabled represents
1065 * the time the event was enabled AND active
1066 * tasks were in the monitored cgroup. This is
1067 * independent of the activity of the context as
1068 * there may be a mix of cgroup and non-cgroup events.
1070 * That is why we treat cgroup events differently
1073 if (is_cgroup_event(event))
1074 run_end = perf_cgroup_event_time(event);
1075 else if (ctx->is_active)
1076 run_end = ctx->time;
1078 run_end = event->tstamp_stopped;
1080 event->total_time_enabled = run_end - event->tstamp_enabled;
1082 if (event->state == PERF_EVENT_STATE_INACTIVE)
1083 run_end = event->tstamp_stopped;
1085 run_end = perf_event_time(event);
1087 event->total_time_running = run_end - event->tstamp_running;
1092 * Update total_time_enabled and total_time_running for all events in a group.
1094 static void update_group_times(struct perf_event *leader)
1096 struct perf_event *event;
1098 update_event_times(leader);
1099 list_for_each_entry(event, &leader->sibling_list, group_entry)
1100 update_event_times(event);
1103 static struct list_head *
1104 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1106 if (event->attr.pinned)
1107 return &ctx->pinned_groups;
1109 return &ctx->flexible_groups;
1113 * Add a event from the lists for its context.
1114 * Must be called with ctx->mutex and ctx->lock held.
1117 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1119 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1120 event->attach_state |= PERF_ATTACH_CONTEXT;
1123 * If we're a stand alone event or group leader, we go to the context
1124 * list, group events are kept attached to the group so that
1125 * perf_group_detach can, at all times, locate all siblings.
1127 if (event->group_leader == event) {
1128 struct list_head *list;
1130 if (is_software_event(event))
1131 event->group_flags |= PERF_GROUP_SOFTWARE;
1133 list = ctx_group_list(event, ctx);
1134 list_add_tail(&event->group_entry, list);
1137 if (is_cgroup_event(event))
1140 if (has_branch_stack(event))
1141 ctx->nr_branch_stack++;
1143 list_add_rcu(&event->event_entry, &ctx->event_list);
1144 if (!ctx->nr_events)
1145 perf_pmu_rotate_start(ctx->pmu);
1147 if (event->attr.inherit_stat)
1154 * Initialize event state based on the perf_event_attr::disabled.
1156 static inline void perf_event__state_init(struct perf_event *event)
1158 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1159 PERF_EVENT_STATE_INACTIVE;
1163 * Called at perf_event creation and when events are attached/detached from a
1166 static void perf_event__read_size(struct perf_event *event)
1168 int entry = sizeof(u64); /* value */
1172 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1173 size += sizeof(u64);
1175 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1176 size += sizeof(u64);
1178 if (event->attr.read_format & PERF_FORMAT_ID)
1179 entry += sizeof(u64);
1181 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1182 nr += event->group_leader->nr_siblings;
1183 size += sizeof(u64);
1187 event->read_size = size;
1190 static void perf_event__header_size(struct perf_event *event)
1192 struct perf_sample_data *data;
1193 u64 sample_type = event->attr.sample_type;
1196 perf_event__read_size(event);
1198 if (sample_type & PERF_SAMPLE_IP)
1199 size += sizeof(data->ip);
1201 if (sample_type & PERF_SAMPLE_ADDR)
1202 size += sizeof(data->addr);
1204 if (sample_type & PERF_SAMPLE_PERIOD)
1205 size += sizeof(data->period);
1207 if (sample_type & PERF_SAMPLE_WEIGHT)
1208 size += sizeof(data->weight);
1210 if (sample_type & PERF_SAMPLE_READ)
1211 size += event->read_size;
1213 if (sample_type & PERF_SAMPLE_DATA_SRC)
1214 size += sizeof(data->data_src.val);
1216 if (sample_type & PERF_SAMPLE_TRANSACTION)
1217 size += sizeof(data->txn);
1219 event->header_size = size;
1222 static void perf_event__id_header_size(struct perf_event *event)
1224 struct perf_sample_data *data;
1225 u64 sample_type = event->attr.sample_type;
1228 if (sample_type & PERF_SAMPLE_TID)
1229 size += sizeof(data->tid_entry);
1231 if (sample_type & PERF_SAMPLE_TIME)
1232 size += sizeof(data->time);
1234 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1235 size += sizeof(data->id);
1237 if (sample_type & PERF_SAMPLE_ID)
1238 size += sizeof(data->id);
1240 if (sample_type & PERF_SAMPLE_STREAM_ID)
1241 size += sizeof(data->stream_id);
1243 if (sample_type & PERF_SAMPLE_CPU)
1244 size += sizeof(data->cpu_entry);
1246 event->id_header_size = size;
1249 static void perf_group_attach(struct perf_event *event)
1251 struct perf_event *group_leader = event->group_leader, *pos;
1254 * We can have double attach due to group movement in perf_event_open.
1256 if (event->attach_state & PERF_ATTACH_GROUP)
1259 event->attach_state |= PERF_ATTACH_GROUP;
1261 if (group_leader == event)
1264 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1265 !is_software_event(event))
1266 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1268 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1269 group_leader->nr_siblings++;
1271 perf_event__header_size(group_leader);
1273 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1274 perf_event__header_size(pos);
1278 * Remove a event from the lists for its context.
1279 * Must be called with ctx->mutex and ctx->lock held.
1282 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1284 struct perf_cpu_context *cpuctx;
1286 * We can have double detach due to exit/hot-unplug + close.
1288 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1291 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1293 if (is_cgroup_event(event)) {
1295 cpuctx = __get_cpu_context(ctx);
1297 * if there are no more cgroup events
1298 * then cler cgrp to avoid stale pointer
1299 * in update_cgrp_time_from_cpuctx()
1301 if (!ctx->nr_cgroups)
1302 cpuctx->cgrp = NULL;
1305 if (has_branch_stack(event))
1306 ctx->nr_branch_stack--;
1309 if (event->attr.inherit_stat)
1312 list_del_rcu(&event->event_entry);
1314 if (event->group_leader == event)
1315 list_del_init(&event->group_entry);
1317 update_group_times(event);
1320 * If event was in error state, then keep it
1321 * that way, otherwise bogus counts will be
1322 * returned on read(). The only way to get out
1323 * of error state is by explicit re-enabling
1326 if (event->state > PERF_EVENT_STATE_OFF)
1327 event->state = PERF_EVENT_STATE_OFF;
1332 static void perf_group_detach(struct perf_event *event)
1334 struct perf_event *sibling, *tmp;
1335 struct list_head *list = NULL;
1338 * We can have double detach due to exit/hot-unplug + close.
1340 if (!(event->attach_state & PERF_ATTACH_GROUP))
1343 event->attach_state &= ~PERF_ATTACH_GROUP;
1346 * If this is a sibling, remove it from its group.
1348 if (event->group_leader != event) {
1349 list_del_init(&event->group_entry);
1350 event->group_leader->nr_siblings--;
1354 if (!list_empty(&event->group_entry))
1355 list = &event->group_entry;
1358 * If this was a group event with sibling events then
1359 * upgrade the siblings to singleton events by adding them
1360 * to whatever list we are on.
1362 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1364 list_move_tail(&sibling->group_entry, list);
1365 sibling->group_leader = sibling;
1367 /* Inherit group flags from the previous leader */
1368 sibling->group_flags = event->group_flags;
1372 perf_event__header_size(event->group_leader);
1374 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1375 perf_event__header_size(tmp);
1379 event_filter_match(struct perf_event *event)
1381 return (event->cpu == -1 || event->cpu == smp_processor_id())
1382 && perf_cgroup_match(event);
1386 event_sched_out(struct perf_event *event,
1387 struct perf_cpu_context *cpuctx,
1388 struct perf_event_context *ctx)
1390 u64 tstamp = perf_event_time(event);
1393 * An event which could not be activated because of
1394 * filter mismatch still needs to have its timings
1395 * maintained, otherwise bogus information is return
1396 * via read() for time_enabled, time_running:
1398 if (event->state == PERF_EVENT_STATE_INACTIVE
1399 && !event_filter_match(event)) {
1400 delta = tstamp - event->tstamp_stopped;
1401 event->tstamp_running += delta;
1402 event->tstamp_stopped = tstamp;
1405 if (event->state != PERF_EVENT_STATE_ACTIVE)
1408 perf_pmu_disable(event->pmu);
1410 event->state = PERF_EVENT_STATE_INACTIVE;
1411 if (event->pending_disable) {
1412 event->pending_disable = 0;
1413 event->state = PERF_EVENT_STATE_OFF;
1415 event->tstamp_stopped = tstamp;
1416 event->pmu->del(event, 0);
1419 if (!is_software_event(event))
1420 cpuctx->active_oncpu--;
1422 if (event->attr.freq && event->attr.sample_freq)
1424 if (event->attr.exclusive || !cpuctx->active_oncpu)
1425 cpuctx->exclusive = 0;
1427 perf_pmu_enable(event->pmu);
1431 group_sched_out(struct perf_event *group_event,
1432 struct perf_cpu_context *cpuctx,
1433 struct perf_event_context *ctx)
1435 struct perf_event *event;
1436 int state = group_event->state;
1438 event_sched_out(group_event, cpuctx, ctx);
1441 * Schedule out siblings (if any):
1443 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1444 event_sched_out(event, cpuctx, ctx);
1446 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1447 cpuctx->exclusive = 0;
1450 struct remove_event {
1451 struct perf_event *event;
1456 * Cross CPU call to remove a performance event
1458 * We disable the event on the hardware level first. After that we
1459 * remove it from the context list.
1461 static int __perf_remove_from_context(void *info)
1463 struct remove_event *re = info;
1464 struct perf_event *event = re->event;
1465 struct perf_event_context *ctx = event->ctx;
1466 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1468 raw_spin_lock(&ctx->lock);
1469 event_sched_out(event, cpuctx, ctx);
1470 if (re->detach_group)
1471 perf_group_detach(event);
1472 list_del_event(event, ctx);
1473 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1475 cpuctx->task_ctx = NULL;
1477 raw_spin_unlock(&ctx->lock);
1484 * Remove the event from a task's (or a CPU's) list of events.
1486 * CPU events are removed with a smp call. For task events we only
1487 * call when the task is on a CPU.
1489 * If event->ctx is a cloned context, callers must make sure that
1490 * every task struct that event->ctx->task could possibly point to
1491 * remains valid. This is OK when called from perf_release since
1492 * that only calls us on the top-level context, which can't be a clone.
1493 * When called from perf_event_exit_task, it's OK because the
1494 * context has been detached from its task.
1496 static void perf_remove_from_context(struct perf_event *event, bool detach_group)
1498 struct perf_event_context *ctx = event->ctx;
1499 struct task_struct *task = ctx->task;
1500 struct remove_event re = {
1502 .detach_group = detach_group,
1505 lockdep_assert_held(&ctx->mutex);
1509 * Per cpu events are removed via an smp call and
1510 * the removal is always successful.
1512 cpu_function_call(event->cpu, __perf_remove_from_context, &re);
1517 if (!task_function_call(task, __perf_remove_from_context, &re))
1520 raw_spin_lock_irq(&ctx->lock);
1522 * If we failed to find a running task, but find the context active now
1523 * that we've acquired the ctx->lock, retry.
1525 if (ctx->is_active) {
1526 raw_spin_unlock_irq(&ctx->lock);
1528 * Reload the task pointer, it might have been changed by
1529 * a concurrent perf_event_context_sched_out().
1536 * Since the task isn't running, its safe to remove the event, us
1537 * holding the ctx->lock ensures the task won't get scheduled in.
1540 perf_group_detach(event);
1541 list_del_event(event, ctx);
1542 raw_spin_unlock_irq(&ctx->lock);
1546 * Cross CPU call to disable a performance event
1548 int __perf_event_disable(void *info)
1550 struct perf_event *event = info;
1551 struct perf_event_context *ctx = event->ctx;
1552 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1555 * If this is a per-task event, need to check whether this
1556 * event's task is the current task on this cpu.
1558 * Can trigger due to concurrent perf_event_context_sched_out()
1559 * flipping contexts around.
1561 if (ctx->task && cpuctx->task_ctx != ctx)
1564 raw_spin_lock(&ctx->lock);
1567 * If the event is on, turn it off.
1568 * If it is in error state, leave it in error state.
1570 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1571 update_context_time(ctx);
1572 update_cgrp_time_from_event(event);
1573 update_group_times(event);
1574 if (event == event->group_leader)
1575 group_sched_out(event, cpuctx, ctx);
1577 event_sched_out(event, cpuctx, ctx);
1578 event->state = PERF_EVENT_STATE_OFF;
1581 raw_spin_unlock(&ctx->lock);
1589 * If event->ctx is a cloned context, callers must make sure that
1590 * every task struct that event->ctx->task could possibly point to
1591 * remains valid. This condition is satisifed when called through
1592 * perf_event_for_each_child or perf_event_for_each because they
1593 * hold the top-level event's child_mutex, so any descendant that
1594 * goes to exit will block in sync_child_event.
1595 * When called from perf_pending_event it's OK because event->ctx
1596 * is the current context on this CPU and preemption is disabled,
1597 * hence we can't get into perf_event_task_sched_out for this context.
1599 void perf_event_disable(struct perf_event *event)
1601 struct perf_event_context *ctx = event->ctx;
1602 struct task_struct *task = ctx->task;
1606 * Disable the event on the cpu that it's on
1608 cpu_function_call(event->cpu, __perf_event_disable, event);
1613 if (!task_function_call(task, __perf_event_disable, event))
1616 raw_spin_lock_irq(&ctx->lock);
1618 * If the event is still active, we need to retry the cross-call.
1620 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1621 raw_spin_unlock_irq(&ctx->lock);
1623 * Reload the task pointer, it might have been changed by
1624 * a concurrent perf_event_context_sched_out().
1631 * Since we have the lock this context can't be scheduled
1632 * in, so we can change the state safely.
1634 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1635 update_group_times(event);
1636 event->state = PERF_EVENT_STATE_OFF;
1638 raw_spin_unlock_irq(&ctx->lock);
1640 EXPORT_SYMBOL_GPL(perf_event_disable);
1642 static void perf_set_shadow_time(struct perf_event *event,
1643 struct perf_event_context *ctx,
1647 * use the correct time source for the time snapshot
1649 * We could get by without this by leveraging the
1650 * fact that to get to this function, the caller
1651 * has most likely already called update_context_time()
1652 * and update_cgrp_time_xx() and thus both timestamp
1653 * are identical (or very close). Given that tstamp is,
1654 * already adjusted for cgroup, we could say that:
1655 * tstamp - ctx->timestamp
1657 * tstamp - cgrp->timestamp.
1659 * Then, in perf_output_read(), the calculation would
1660 * work with no changes because:
1661 * - event is guaranteed scheduled in
1662 * - no scheduled out in between
1663 * - thus the timestamp would be the same
1665 * But this is a bit hairy.
1667 * So instead, we have an explicit cgroup call to remain
1668 * within the time time source all along. We believe it
1669 * is cleaner and simpler to understand.
1671 if (is_cgroup_event(event))
1672 perf_cgroup_set_shadow_time(event, tstamp);
1674 event->shadow_ctx_time = tstamp - ctx->timestamp;
1677 #define MAX_INTERRUPTS (~0ULL)
1679 static void perf_log_throttle(struct perf_event *event, int enable);
1682 event_sched_in(struct perf_event *event,
1683 struct perf_cpu_context *cpuctx,
1684 struct perf_event_context *ctx)
1686 u64 tstamp = perf_event_time(event);
1689 lockdep_assert_held(&ctx->lock);
1691 if (event->state <= PERF_EVENT_STATE_OFF)
1694 event->state = PERF_EVENT_STATE_ACTIVE;
1695 event->oncpu = smp_processor_id();
1698 * Unthrottle events, since we scheduled we might have missed several
1699 * ticks already, also for a heavily scheduling task there is little
1700 * guarantee it'll get a tick in a timely manner.
1702 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1703 perf_log_throttle(event, 1);
1704 event->hw.interrupts = 0;
1708 * The new state must be visible before we turn it on in the hardware:
1712 perf_pmu_disable(event->pmu);
1714 if (event->pmu->add(event, PERF_EF_START)) {
1715 event->state = PERF_EVENT_STATE_INACTIVE;
1721 event->tstamp_running += tstamp - event->tstamp_stopped;
1723 perf_set_shadow_time(event, ctx, tstamp);
1725 if (!is_software_event(event))
1726 cpuctx->active_oncpu++;
1728 if (event->attr.freq && event->attr.sample_freq)
1731 if (event->attr.exclusive)
1732 cpuctx->exclusive = 1;
1735 perf_pmu_enable(event->pmu);
1741 group_sched_in(struct perf_event *group_event,
1742 struct perf_cpu_context *cpuctx,
1743 struct perf_event_context *ctx)
1745 struct perf_event *event, *partial_group = NULL;
1746 struct pmu *pmu = ctx->pmu;
1747 u64 now = ctx->time;
1748 bool simulate = false;
1750 if (group_event->state == PERF_EVENT_STATE_OFF)
1753 pmu->start_txn(pmu);
1755 if (event_sched_in(group_event, cpuctx, ctx)) {
1756 pmu->cancel_txn(pmu);
1757 perf_cpu_hrtimer_restart(cpuctx);
1762 * Schedule in siblings as one group (if any):
1764 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1765 if (event_sched_in(event, cpuctx, ctx)) {
1766 partial_group = event;
1771 if (!pmu->commit_txn(pmu))
1776 * Groups can be scheduled in as one unit only, so undo any
1777 * partial group before returning:
1778 * The events up to the failed event are scheduled out normally,
1779 * tstamp_stopped will be updated.
1781 * The failed events and the remaining siblings need to have
1782 * their timings updated as if they had gone thru event_sched_in()
1783 * and event_sched_out(). This is required to get consistent timings
1784 * across the group. This also takes care of the case where the group
1785 * could never be scheduled by ensuring tstamp_stopped is set to mark
1786 * the time the event was actually stopped, such that time delta
1787 * calculation in update_event_times() is correct.
1789 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1790 if (event == partial_group)
1794 event->tstamp_running += now - event->tstamp_stopped;
1795 event->tstamp_stopped = now;
1797 event_sched_out(event, cpuctx, ctx);
1800 event_sched_out(group_event, cpuctx, ctx);
1802 pmu->cancel_txn(pmu);
1804 perf_cpu_hrtimer_restart(cpuctx);
1810 * Work out whether we can put this event group on the CPU now.
1812 static int group_can_go_on(struct perf_event *event,
1813 struct perf_cpu_context *cpuctx,
1817 * Groups consisting entirely of software events can always go on.
1819 if (event->group_flags & PERF_GROUP_SOFTWARE)
1822 * If an exclusive group is already on, no other hardware
1825 if (cpuctx->exclusive)
1828 * If this group is exclusive and there are already
1829 * events on the CPU, it can't go on.
1831 if (event->attr.exclusive && cpuctx->active_oncpu)
1834 * Otherwise, try to add it if all previous groups were able
1840 static void add_event_to_ctx(struct perf_event *event,
1841 struct perf_event_context *ctx)
1843 u64 tstamp = perf_event_time(event);
1845 list_add_event(event, ctx);
1846 perf_group_attach(event);
1847 event->tstamp_enabled = tstamp;
1848 event->tstamp_running = tstamp;
1849 event->tstamp_stopped = tstamp;
1852 static void task_ctx_sched_out(struct perf_event_context *ctx);
1854 ctx_sched_in(struct perf_event_context *ctx,
1855 struct perf_cpu_context *cpuctx,
1856 enum event_type_t event_type,
1857 struct task_struct *task);
1859 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
1860 struct perf_event_context *ctx,
1861 struct task_struct *task)
1863 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
1865 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
1866 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
1868 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
1872 * Cross CPU call to install and enable a performance event
1874 * Must be called with ctx->mutex held
1876 static int __perf_install_in_context(void *info)
1878 struct perf_event *event = info;
1879 struct perf_event_context *ctx = event->ctx;
1880 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1881 struct perf_event_context *task_ctx = cpuctx->task_ctx;
1882 struct task_struct *task = current;
1884 perf_ctx_lock(cpuctx, task_ctx);
1885 perf_pmu_disable(cpuctx->ctx.pmu);
1888 * If there was an active task_ctx schedule it out.
1891 task_ctx_sched_out(task_ctx);
1894 * If the context we're installing events in is not the
1895 * active task_ctx, flip them.
1897 if (ctx->task && task_ctx != ctx) {
1899 raw_spin_unlock(&task_ctx->lock);
1900 raw_spin_lock(&ctx->lock);
1905 cpuctx->task_ctx = task_ctx;
1906 task = task_ctx->task;
1909 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
1911 update_context_time(ctx);
1913 * update cgrp time only if current cgrp
1914 * matches event->cgrp. Must be done before
1915 * calling add_event_to_ctx()
1917 update_cgrp_time_from_event(event);
1919 add_event_to_ctx(event, ctx);
1922 * Schedule everything back in
1924 perf_event_sched_in(cpuctx, task_ctx, task);
1926 perf_pmu_enable(cpuctx->ctx.pmu);
1927 perf_ctx_unlock(cpuctx, task_ctx);
1933 * Attach a performance event to a context
1935 * First we add the event to the list with the hardware enable bit
1936 * in event->hw_config cleared.
1938 * If the event is attached to a task which is on a CPU we use a smp
1939 * call to enable it in the task context. The task might have been
1940 * scheduled away, but we check this in the smp call again.
1943 perf_install_in_context(struct perf_event_context *ctx,
1944 struct perf_event *event,
1947 struct task_struct *task = ctx->task;
1949 lockdep_assert_held(&ctx->mutex);
1952 if (event->cpu != -1)
1957 * Per cpu events are installed via an smp call and
1958 * the install is always successful.
1960 cpu_function_call(cpu, __perf_install_in_context, event);
1965 if (!task_function_call(task, __perf_install_in_context, event))
1968 raw_spin_lock_irq(&ctx->lock);
1970 * If we failed to find a running task, but find the context active now
1971 * that we've acquired the ctx->lock, retry.
1973 if (ctx->is_active) {
1974 raw_spin_unlock_irq(&ctx->lock);
1976 * Reload the task pointer, it might have been changed by
1977 * a concurrent perf_event_context_sched_out().
1984 * Since the task isn't running, its safe to add the event, us holding
1985 * the ctx->lock ensures the task won't get scheduled in.
1987 add_event_to_ctx(event, ctx);
1988 raw_spin_unlock_irq(&ctx->lock);
1992 * Put a event into inactive state and update time fields.
1993 * Enabling the leader of a group effectively enables all
1994 * the group members that aren't explicitly disabled, so we
1995 * have to update their ->tstamp_enabled also.
1996 * Note: this works for group members as well as group leaders
1997 * since the non-leader members' sibling_lists will be empty.
1999 static void __perf_event_mark_enabled(struct perf_event *event)
2001 struct perf_event *sub;
2002 u64 tstamp = perf_event_time(event);
2004 event->state = PERF_EVENT_STATE_INACTIVE;
2005 event->tstamp_enabled = tstamp - event->total_time_enabled;
2006 list_for_each_entry(sub, &event->sibling_list, group_entry) {
2007 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2008 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2013 * Cross CPU call to enable a performance event
2015 static int __perf_event_enable(void *info)
2017 struct perf_event *event = info;
2018 struct perf_event_context *ctx = event->ctx;
2019 struct perf_event *leader = event->group_leader;
2020 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2024 * There's a time window between 'ctx->is_active' check
2025 * in perf_event_enable function and this place having:
2027 * - ctx->lock unlocked
2029 * where the task could be killed and 'ctx' deactivated
2030 * by perf_event_exit_task.
2032 if (!ctx->is_active)
2035 raw_spin_lock(&ctx->lock);
2036 update_context_time(ctx);
2038 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2042 * set current task's cgroup time reference point
2044 perf_cgroup_set_timestamp(current, ctx);
2046 __perf_event_mark_enabled(event);
2048 if (!event_filter_match(event)) {
2049 if (is_cgroup_event(event))
2050 perf_cgroup_defer_enabled(event);
2055 * If the event is in a group and isn't the group leader,
2056 * then don't put it on unless the group is on.
2058 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
2061 if (!group_can_go_on(event, cpuctx, 1)) {
2064 if (event == leader)
2065 err = group_sched_in(event, cpuctx, ctx);
2067 err = event_sched_in(event, cpuctx, ctx);
2072 * If this event can't go on and it's part of a
2073 * group, then the whole group has to come off.
2075 if (leader != event) {
2076 group_sched_out(leader, cpuctx, ctx);
2077 perf_cpu_hrtimer_restart(cpuctx);
2079 if (leader->attr.pinned) {
2080 update_group_times(leader);
2081 leader->state = PERF_EVENT_STATE_ERROR;
2086 raw_spin_unlock(&ctx->lock);
2094 * If event->ctx is a cloned context, callers must make sure that
2095 * every task struct that event->ctx->task could possibly point to
2096 * remains valid. This condition is satisfied when called through
2097 * perf_event_for_each_child or perf_event_for_each as described
2098 * for perf_event_disable.
2100 void perf_event_enable(struct perf_event *event)
2102 struct perf_event_context *ctx = event->ctx;
2103 struct task_struct *task = ctx->task;
2107 * Enable the event on the cpu that it's on
2109 cpu_function_call(event->cpu, __perf_event_enable, event);
2113 raw_spin_lock_irq(&ctx->lock);
2114 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2118 * If the event is in error state, clear that first.
2119 * That way, if we see the event in error state below, we
2120 * know that it has gone back into error state, as distinct
2121 * from the task having been scheduled away before the
2122 * cross-call arrived.
2124 if (event->state == PERF_EVENT_STATE_ERROR)
2125 event->state = PERF_EVENT_STATE_OFF;
2128 if (!ctx->is_active) {
2129 __perf_event_mark_enabled(event);
2133 raw_spin_unlock_irq(&ctx->lock);
2135 if (!task_function_call(task, __perf_event_enable, event))
2138 raw_spin_lock_irq(&ctx->lock);
2141 * If the context is active and the event is still off,
2142 * we need to retry the cross-call.
2144 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
2146 * task could have been flipped by a concurrent
2147 * perf_event_context_sched_out()
2154 raw_spin_unlock_irq(&ctx->lock);
2156 EXPORT_SYMBOL_GPL(perf_event_enable);
2158 int perf_event_refresh(struct perf_event *event, int refresh)
2161 * not supported on inherited events
2163 if (event->attr.inherit || !is_sampling_event(event))
2166 atomic_add(refresh, &event->event_limit);
2167 perf_event_enable(event);
2171 EXPORT_SYMBOL_GPL(perf_event_refresh);
2173 static void ctx_sched_out(struct perf_event_context *ctx,
2174 struct perf_cpu_context *cpuctx,
2175 enum event_type_t event_type)
2177 struct perf_event *event;
2178 int is_active = ctx->is_active;
2180 ctx->is_active &= ~event_type;
2181 if (likely(!ctx->nr_events))
2184 update_context_time(ctx);
2185 update_cgrp_time_from_cpuctx(cpuctx);
2186 if (!ctx->nr_active)
2189 perf_pmu_disable(ctx->pmu);
2190 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2191 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2192 group_sched_out(event, cpuctx, ctx);
2195 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2196 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2197 group_sched_out(event, cpuctx, ctx);
2199 perf_pmu_enable(ctx->pmu);
2203 * Test whether two contexts are equivalent, i.e. whether they have both been
2204 * cloned from the same version of the same context.
2206 * Equivalence is measured using a generation number in the context that is
2207 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2208 * and list_del_event().
2210 static int context_equiv(struct perf_event_context *ctx1,
2211 struct perf_event_context *ctx2)
2213 /* Pinning disables the swap optimization */
2214 if (ctx1->pin_count || ctx2->pin_count)
2217 /* If ctx1 is the parent of ctx2 */
2218 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2221 /* If ctx2 is the parent of ctx1 */
2222 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2226 * If ctx1 and ctx2 have the same parent; we flatten the parent
2227 * hierarchy, see perf_event_init_context().
2229 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2230 ctx1->parent_gen == ctx2->parent_gen)
2237 static void __perf_event_sync_stat(struct perf_event *event,
2238 struct perf_event *next_event)
2242 if (!event->attr.inherit_stat)
2246 * Update the event value, we cannot use perf_event_read()
2247 * because we're in the middle of a context switch and have IRQs
2248 * disabled, which upsets smp_call_function_single(), however
2249 * we know the event must be on the current CPU, therefore we
2250 * don't need to use it.
2252 switch (event->state) {
2253 case PERF_EVENT_STATE_ACTIVE:
2254 event->pmu->read(event);
2257 case PERF_EVENT_STATE_INACTIVE:
2258 update_event_times(event);
2266 * In order to keep per-task stats reliable we need to flip the event
2267 * values when we flip the contexts.
2269 value = local64_read(&next_event->count);
2270 value = local64_xchg(&event->count, value);
2271 local64_set(&next_event->count, value);
2273 swap(event->total_time_enabled, next_event->total_time_enabled);
2274 swap(event->total_time_running, next_event->total_time_running);
2277 * Since we swizzled the values, update the user visible data too.
2279 perf_event_update_userpage(event);
2280 perf_event_update_userpage(next_event);
2283 static void perf_event_sync_stat(struct perf_event_context *ctx,
2284 struct perf_event_context *next_ctx)
2286 struct perf_event *event, *next_event;
2291 update_context_time(ctx);
2293 event = list_first_entry(&ctx->event_list,
2294 struct perf_event, event_entry);
2296 next_event = list_first_entry(&next_ctx->event_list,
2297 struct perf_event, event_entry);
2299 while (&event->event_entry != &ctx->event_list &&
2300 &next_event->event_entry != &next_ctx->event_list) {
2302 __perf_event_sync_stat(event, next_event);
2304 event = list_next_entry(event, event_entry);
2305 next_event = list_next_entry(next_event, event_entry);
2309 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2310 struct task_struct *next)
2312 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2313 struct perf_event_context *next_ctx;
2314 struct perf_event_context *parent, *next_parent;
2315 struct perf_cpu_context *cpuctx;
2321 cpuctx = __get_cpu_context(ctx);
2322 if (!cpuctx->task_ctx)
2326 next_ctx = next->perf_event_ctxp[ctxn];
2330 parent = rcu_dereference(ctx->parent_ctx);
2331 next_parent = rcu_dereference(next_ctx->parent_ctx);
2333 /* If neither context have a parent context; they cannot be clones. */
2334 if (!parent || !next_parent)
2337 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2339 * Looks like the two contexts are clones, so we might be
2340 * able to optimize the context switch. We lock both
2341 * contexts and check that they are clones under the
2342 * lock (including re-checking that neither has been
2343 * uncloned in the meantime). It doesn't matter which
2344 * order we take the locks because no other cpu could
2345 * be trying to lock both of these tasks.
2347 raw_spin_lock(&ctx->lock);
2348 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2349 if (context_equiv(ctx, next_ctx)) {
2351 * XXX do we need a memory barrier of sorts
2352 * wrt to rcu_dereference() of perf_event_ctxp
2354 task->perf_event_ctxp[ctxn] = next_ctx;
2355 next->perf_event_ctxp[ctxn] = ctx;
2357 next_ctx->task = task;
2360 perf_event_sync_stat(ctx, next_ctx);
2362 raw_spin_unlock(&next_ctx->lock);
2363 raw_spin_unlock(&ctx->lock);
2369 raw_spin_lock(&ctx->lock);
2370 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2371 cpuctx->task_ctx = NULL;
2372 raw_spin_unlock(&ctx->lock);
2376 #define for_each_task_context_nr(ctxn) \
2377 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2380 * Called from scheduler to remove the events of the current task,
2381 * with interrupts disabled.
2383 * We stop each event and update the event value in event->count.
2385 * This does not protect us against NMI, but disable()
2386 * sets the disabled bit in the control field of event _before_
2387 * accessing the event control register. If a NMI hits, then it will
2388 * not restart the event.
2390 void __perf_event_task_sched_out(struct task_struct *task,
2391 struct task_struct *next)
2395 for_each_task_context_nr(ctxn)
2396 perf_event_context_sched_out(task, ctxn, next);
2399 * if cgroup events exist on this CPU, then we need
2400 * to check if we have to switch out PMU state.
2401 * cgroup event are system-wide mode only
2403 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2404 perf_cgroup_sched_out(task, next);
2407 static void task_ctx_sched_out(struct perf_event_context *ctx)
2409 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2411 if (!cpuctx->task_ctx)
2414 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2417 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2418 cpuctx->task_ctx = NULL;
2422 * Called with IRQs disabled
2424 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2425 enum event_type_t event_type)
2427 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2431 ctx_pinned_sched_in(struct perf_event_context *ctx,
2432 struct perf_cpu_context *cpuctx)
2434 struct perf_event *event;
2436 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2437 if (event->state <= PERF_EVENT_STATE_OFF)
2439 if (!event_filter_match(event))
2442 /* may need to reset tstamp_enabled */
2443 if (is_cgroup_event(event))
2444 perf_cgroup_mark_enabled(event, ctx);
2446 if (group_can_go_on(event, cpuctx, 1))
2447 group_sched_in(event, cpuctx, ctx);
2450 * If this pinned group hasn't been scheduled,
2451 * put it in error state.
2453 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2454 update_group_times(event);
2455 event->state = PERF_EVENT_STATE_ERROR;
2461 ctx_flexible_sched_in(struct perf_event_context *ctx,
2462 struct perf_cpu_context *cpuctx)
2464 struct perf_event *event;
2467 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2468 /* Ignore events in OFF or ERROR state */
2469 if (event->state <= PERF_EVENT_STATE_OFF)
2472 * Listen to the 'cpu' scheduling filter constraint
2475 if (!event_filter_match(event))
2478 /* may need to reset tstamp_enabled */
2479 if (is_cgroup_event(event))
2480 perf_cgroup_mark_enabled(event, ctx);
2482 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2483 if (group_sched_in(event, cpuctx, ctx))
2490 ctx_sched_in(struct perf_event_context *ctx,
2491 struct perf_cpu_context *cpuctx,
2492 enum event_type_t event_type,
2493 struct task_struct *task)
2496 int is_active = ctx->is_active;
2498 ctx->is_active |= event_type;
2499 if (likely(!ctx->nr_events))
2503 ctx->timestamp = now;
2504 perf_cgroup_set_timestamp(task, ctx);
2506 * First go through the list and put on any pinned groups
2507 * in order to give them the best chance of going on.
2509 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2510 ctx_pinned_sched_in(ctx, cpuctx);
2512 /* Then walk through the lower prio flexible groups */
2513 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2514 ctx_flexible_sched_in(ctx, cpuctx);
2517 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2518 enum event_type_t event_type,
2519 struct task_struct *task)
2521 struct perf_event_context *ctx = &cpuctx->ctx;
2523 ctx_sched_in(ctx, cpuctx, event_type, task);
2526 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2527 struct task_struct *task)
2529 struct perf_cpu_context *cpuctx;
2531 cpuctx = __get_cpu_context(ctx);
2532 if (cpuctx->task_ctx == ctx)
2535 perf_ctx_lock(cpuctx, ctx);
2536 perf_pmu_disable(ctx->pmu);
2538 * We want to keep the following priority order:
2539 * cpu pinned (that don't need to move), task pinned,
2540 * cpu flexible, task flexible.
2542 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2545 cpuctx->task_ctx = ctx;
2547 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2549 perf_pmu_enable(ctx->pmu);
2550 perf_ctx_unlock(cpuctx, ctx);
2553 * Since these rotations are per-cpu, we need to ensure the
2554 * cpu-context we got scheduled on is actually rotating.
2556 perf_pmu_rotate_start(ctx->pmu);
2560 * When sampling the branck stack in system-wide, it may be necessary
2561 * to flush the stack on context switch. This happens when the branch
2562 * stack does not tag its entries with the pid of the current task.
2563 * Otherwise it becomes impossible to associate a branch entry with a
2564 * task. This ambiguity is more likely to appear when the branch stack
2565 * supports priv level filtering and the user sets it to monitor only
2566 * at the user level (which could be a useful measurement in system-wide
2567 * mode). In that case, the risk is high of having a branch stack with
2568 * branch from multiple tasks. Flushing may mean dropping the existing
2569 * entries or stashing them somewhere in the PMU specific code layer.
2571 * This function provides the context switch callback to the lower code
2572 * layer. It is invoked ONLY when there is at least one system-wide context
2573 * with at least one active event using taken branch sampling.
2575 static void perf_branch_stack_sched_in(struct task_struct *prev,
2576 struct task_struct *task)
2578 struct perf_cpu_context *cpuctx;
2580 unsigned long flags;
2582 /* no need to flush branch stack if not changing task */
2586 local_irq_save(flags);
2590 list_for_each_entry_rcu(pmu, &pmus, entry) {
2591 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2594 * check if the context has at least one
2595 * event using PERF_SAMPLE_BRANCH_STACK
2597 if (cpuctx->ctx.nr_branch_stack > 0
2598 && pmu->flush_branch_stack) {
2600 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2602 perf_pmu_disable(pmu);
2604 pmu->flush_branch_stack();
2606 perf_pmu_enable(pmu);
2608 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2614 local_irq_restore(flags);
2618 * Called from scheduler to add the events of the current task
2619 * with interrupts disabled.
2621 * We restore the event value and then enable it.
2623 * This does not protect us against NMI, but enable()
2624 * sets the enabled bit in the control field of event _before_
2625 * accessing the event control register. If a NMI hits, then it will
2626 * keep the event running.
2628 void __perf_event_task_sched_in(struct task_struct *prev,
2629 struct task_struct *task)
2631 struct perf_event_context *ctx;
2634 for_each_task_context_nr(ctxn) {
2635 ctx = task->perf_event_ctxp[ctxn];
2639 perf_event_context_sched_in(ctx, task);
2642 * if cgroup events exist on this CPU, then we need
2643 * to check if we have to switch in PMU state.
2644 * cgroup event are system-wide mode only
2646 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2647 perf_cgroup_sched_in(prev, task);
2649 /* check for system-wide branch_stack events */
2650 if (atomic_read(&__get_cpu_var(perf_branch_stack_events)))
2651 perf_branch_stack_sched_in(prev, task);
2654 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2656 u64 frequency = event->attr.sample_freq;
2657 u64 sec = NSEC_PER_SEC;
2658 u64 divisor, dividend;
2660 int count_fls, nsec_fls, frequency_fls, sec_fls;
2662 count_fls = fls64(count);
2663 nsec_fls = fls64(nsec);
2664 frequency_fls = fls64(frequency);
2668 * We got @count in @nsec, with a target of sample_freq HZ
2669 * the target period becomes:
2672 * period = -------------------
2673 * @nsec * sample_freq
2678 * Reduce accuracy by one bit such that @a and @b converge
2679 * to a similar magnitude.
2681 #define REDUCE_FLS(a, b) \
2683 if (a##_fls > b##_fls) { \
2693 * Reduce accuracy until either term fits in a u64, then proceed with
2694 * the other, so that finally we can do a u64/u64 division.
2696 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2697 REDUCE_FLS(nsec, frequency);
2698 REDUCE_FLS(sec, count);
2701 if (count_fls + sec_fls > 64) {
2702 divisor = nsec * frequency;
2704 while (count_fls + sec_fls > 64) {
2705 REDUCE_FLS(count, sec);
2709 dividend = count * sec;
2711 dividend = count * sec;
2713 while (nsec_fls + frequency_fls > 64) {
2714 REDUCE_FLS(nsec, frequency);
2718 divisor = nsec * frequency;
2724 return div64_u64(dividend, divisor);
2727 static DEFINE_PER_CPU(int, perf_throttled_count);
2728 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2730 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2732 struct hw_perf_event *hwc = &event->hw;
2733 s64 period, sample_period;
2736 period = perf_calculate_period(event, nsec, count);
2738 delta = (s64)(period - hwc->sample_period);
2739 delta = (delta + 7) / 8; /* low pass filter */
2741 sample_period = hwc->sample_period + delta;
2746 hwc->sample_period = sample_period;
2748 if (local64_read(&hwc->period_left) > 8*sample_period) {
2750 event->pmu->stop(event, PERF_EF_UPDATE);
2752 local64_set(&hwc->period_left, 0);
2755 event->pmu->start(event, PERF_EF_RELOAD);
2760 * combine freq adjustment with unthrottling to avoid two passes over the
2761 * events. At the same time, make sure, having freq events does not change
2762 * the rate of unthrottling as that would introduce bias.
2764 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
2767 struct perf_event *event;
2768 struct hw_perf_event *hwc;
2769 u64 now, period = TICK_NSEC;
2773 * only need to iterate over all events iff:
2774 * - context have events in frequency mode (needs freq adjust)
2775 * - there are events to unthrottle on this cpu
2777 if (!(ctx->nr_freq || needs_unthr))
2780 raw_spin_lock(&ctx->lock);
2781 perf_pmu_disable(ctx->pmu);
2783 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
2784 if (event->state != PERF_EVENT_STATE_ACTIVE)
2787 if (!event_filter_match(event))
2790 perf_pmu_disable(event->pmu);
2794 if (hwc->interrupts == MAX_INTERRUPTS) {
2795 hwc->interrupts = 0;
2796 perf_log_throttle(event, 1);
2797 event->pmu->start(event, 0);
2800 if (!event->attr.freq || !event->attr.sample_freq)
2804 * stop the event and update event->count
2806 event->pmu->stop(event, PERF_EF_UPDATE);
2808 now = local64_read(&event->count);
2809 delta = now - hwc->freq_count_stamp;
2810 hwc->freq_count_stamp = now;
2814 * reload only if value has changed
2815 * we have stopped the event so tell that
2816 * to perf_adjust_period() to avoid stopping it
2820 perf_adjust_period(event, period, delta, false);
2822 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
2824 perf_pmu_enable(event->pmu);
2827 perf_pmu_enable(ctx->pmu);
2828 raw_spin_unlock(&ctx->lock);
2832 * Round-robin a context's events:
2834 static void rotate_ctx(struct perf_event_context *ctx)
2837 * Rotate the first entry last of non-pinned groups. Rotation might be
2838 * disabled by the inheritance code.
2840 if (!ctx->rotate_disable)
2841 list_rotate_left(&ctx->flexible_groups);
2845 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
2846 * because they're strictly cpu affine and rotate_start is called with IRQs
2847 * disabled, while rotate_context is called from IRQ context.
2849 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
2851 struct perf_event_context *ctx = NULL;
2852 int rotate = 0, remove = 1;
2854 if (cpuctx->ctx.nr_events) {
2856 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
2860 ctx = cpuctx->task_ctx;
2861 if (ctx && ctx->nr_events) {
2863 if (ctx->nr_events != ctx->nr_active)
2870 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2871 perf_pmu_disable(cpuctx->ctx.pmu);
2873 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2875 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
2877 rotate_ctx(&cpuctx->ctx);
2881 perf_event_sched_in(cpuctx, ctx, current);
2883 perf_pmu_enable(cpuctx->ctx.pmu);
2884 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2887 list_del_init(&cpuctx->rotation_list);
2892 #ifdef CONFIG_NO_HZ_FULL
2893 bool perf_event_can_stop_tick(void)
2895 if (atomic_read(&nr_freq_events) ||
2896 __this_cpu_read(perf_throttled_count))
2903 void perf_event_task_tick(void)
2905 struct list_head *head = &__get_cpu_var(rotation_list);
2906 struct perf_cpu_context *cpuctx, *tmp;
2907 struct perf_event_context *ctx;
2910 WARN_ON(!irqs_disabled());
2912 __this_cpu_inc(perf_throttled_seq);
2913 throttled = __this_cpu_xchg(perf_throttled_count, 0);
2915 list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) {
2917 perf_adjust_freq_unthr_context(ctx, throttled);
2919 ctx = cpuctx->task_ctx;
2921 perf_adjust_freq_unthr_context(ctx, throttled);
2925 static int event_enable_on_exec(struct perf_event *event,
2926 struct perf_event_context *ctx)
2928 if (!event->attr.enable_on_exec)
2931 event->attr.enable_on_exec = 0;
2932 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2935 __perf_event_mark_enabled(event);
2941 * Enable all of a task's events that have been marked enable-on-exec.
2942 * This expects task == current.
2944 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
2946 struct perf_event *event;
2947 unsigned long flags;
2951 local_irq_save(flags);
2952 if (!ctx || !ctx->nr_events)
2956 * We must ctxsw out cgroup events to avoid conflict
2957 * when invoking perf_task_event_sched_in() later on
2958 * in this function. Otherwise we end up trying to
2959 * ctxswin cgroup events which are already scheduled
2962 perf_cgroup_sched_out(current, NULL);
2964 raw_spin_lock(&ctx->lock);
2965 task_ctx_sched_out(ctx);
2967 list_for_each_entry(event, &ctx->event_list, event_entry) {
2968 ret = event_enable_on_exec(event, ctx);
2974 * Unclone this context if we enabled any event.
2979 raw_spin_unlock(&ctx->lock);
2982 * Also calls ctxswin for cgroup events, if any:
2984 perf_event_context_sched_in(ctx, ctx->task);
2986 local_irq_restore(flags);
2989 void perf_event_exec(void)
2991 struct perf_event_context *ctx;
2995 for_each_task_context_nr(ctxn) {
2996 ctx = current->perf_event_ctxp[ctxn];
3000 perf_event_enable_on_exec(ctx);
3006 * Cross CPU call to read the hardware event
3008 static void __perf_event_read(void *info)
3010 struct perf_event *event = info;
3011 struct perf_event_context *ctx = event->ctx;
3012 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3015 * If this is a task context, we need to check whether it is
3016 * the current task context of this cpu. If not it has been
3017 * scheduled out before the smp call arrived. In that case
3018 * event->count would have been updated to a recent sample
3019 * when the event was scheduled out.
3021 if (ctx->task && cpuctx->task_ctx != ctx)
3024 raw_spin_lock(&ctx->lock);
3025 if (ctx->is_active) {
3026 update_context_time(ctx);
3027 update_cgrp_time_from_event(event);
3029 update_event_times(event);
3030 if (event->state == PERF_EVENT_STATE_ACTIVE)
3031 event->pmu->read(event);
3032 raw_spin_unlock(&ctx->lock);
3035 static inline u64 perf_event_count(struct perf_event *event)
3037 return local64_read(&event->count) + atomic64_read(&event->child_count);
3040 static u64 perf_event_read(struct perf_event *event)
3043 * If event is enabled and currently active on a CPU, update the
3044 * value in the event structure:
3046 if (event->state == PERF_EVENT_STATE_ACTIVE) {
3047 smp_call_function_single(event->oncpu,
3048 __perf_event_read, event, 1);
3049 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3050 struct perf_event_context *ctx = event->ctx;
3051 unsigned long flags;
3053 raw_spin_lock_irqsave(&ctx->lock, flags);
3055 * may read while context is not active
3056 * (e.g., thread is blocked), in that case
3057 * we cannot update context time
3059 if (ctx->is_active) {
3060 update_context_time(ctx);
3061 update_cgrp_time_from_event(event);
3063 update_event_times(event);
3064 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3067 return perf_event_count(event);
3071 * Initialize the perf_event context in a task_struct:
3073 static void __perf_event_init_context(struct perf_event_context *ctx)
3075 raw_spin_lock_init(&ctx->lock);
3076 mutex_init(&ctx->mutex);
3077 INIT_LIST_HEAD(&ctx->pinned_groups);
3078 INIT_LIST_HEAD(&ctx->flexible_groups);
3079 INIT_LIST_HEAD(&ctx->event_list);
3080 atomic_set(&ctx->refcount, 1);
3083 static struct perf_event_context *
3084 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3086 struct perf_event_context *ctx;
3088 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3092 __perf_event_init_context(ctx);
3095 get_task_struct(task);
3102 static struct task_struct *
3103 find_lively_task_by_vpid(pid_t vpid)
3105 struct task_struct *task;
3112 task = find_task_by_vpid(vpid);
3114 get_task_struct(task);
3118 return ERR_PTR(-ESRCH);
3120 /* Reuse ptrace permission checks for now. */
3122 if (!ptrace_may_access(task, PTRACE_MODE_READ))
3127 put_task_struct(task);
3128 return ERR_PTR(err);
3133 * Returns a matching context with refcount and pincount.
3135 static struct perf_event_context *
3136 find_get_context(struct pmu *pmu, struct task_struct *task, int cpu)
3138 struct perf_event_context *ctx;
3139 struct perf_cpu_context *cpuctx;
3140 unsigned long flags;
3144 /* Must be root to operate on a CPU event: */
3145 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3146 return ERR_PTR(-EACCES);
3149 * We could be clever and allow to attach a event to an
3150 * offline CPU and activate it when the CPU comes up, but
3153 if (!cpu_online(cpu))
3154 return ERR_PTR(-ENODEV);
3156 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3165 ctxn = pmu->task_ctx_nr;
3170 ctx = perf_lock_task_context(task, ctxn, &flags);
3174 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3176 ctx = alloc_perf_context(pmu, task);
3182 mutex_lock(&task->perf_event_mutex);
3184 * If it has already passed perf_event_exit_task().
3185 * we must see PF_EXITING, it takes this mutex too.
3187 if (task->flags & PF_EXITING)
3189 else if (task->perf_event_ctxp[ctxn])
3194 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3196 mutex_unlock(&task->perf_event_mutex);
3198 if (unlikely(err)) {
3210 return ERR_PTR(err);
3213 static void perf_event_free_filter(struct perf_event *event);
3215 static void free_event_rcu(struct rcu_head *head)
3217 struct perf_event *event;
3219 event = container_of(head, struct perf_event, rcu_head);
3221 put_pid_ns(event->ns);
3222 perf_event_free_filter(event);
3226 static void ring_buffer_put(struct ring_buffer *rb);
3227 static void ring_buffer_attach(struct perf_event *event,
3228 struct ring_buffer *rb);
3230 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3235 if (has_branch_stack(event)) {
3236 if (!(event->attach_state & PERF_ATTACH_TASK))
3237 atomic_dec(&per_cpu(perf_branch_stack_events, cpu));
3239 if (is_cgroup_event(event))
3240 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3243 static void unaccount_event(struct perf_event *event)
3248 if (event->attach_state & PERF_ATTACH_TASK)
3249 static_key_slow_dec_deferred(&perf_sched_events);
3250 if (event->attr.mmap || event->attr.mmap_data)
3251 atomic_dec(&nr_mmap_events);
3252 if (event->attr.comm)
3253 atomic_dec(&nr_comm_events);
3254 if (event->attr.task)
3255 atomic_dec(&nr_task_events);
3256 if (event->attr.freq)
3257 atomic_dec(&nr_freq_events);
3258 if (is_cgroup_event(event))
3259 static_key_slow_dec_deferred(&perf_sched_events);
3260 if (has_branch_stack(event))
3261 static_key_slow_dec_deferred(&perf_sched_events);
3263 unaccount_event_cpu(event, event->cpu);
3266 static void __free_event(struct perf_event *event)
3268 if (!event->parent) {
3269 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3270 put_callchain_buffers();
3274 event->destroy(event);
3277 put_ctx(event->ctx);
3280 module_put(event->pmu->module);
3282 call_rcu(&event->rcu_head, free_event_rcu);
3285 static void _free_event(struct perf_event *event)
3287 irq_work_sync(&event->pending);
3289 unaccount_event(event);
3293 * Can happen when we close an event with re-directed output.
3295 * Since we have a 0 refcount, perf_mmap_close() will skip
3296 * over us; possibly making our ring_buffer_put() the last.
3298 mutex_lock(&event->mmap_mutex);
3299 ring_buffer_attach(event, NULL);
3300 mutex_unlock(&event->mmap_mutex);
3303 if (is_cgroup_event(event))
3304 perf_detach_cgroup(event);
3306 __free_event(event);
3310 * Used to free events which have a known refcount of 1, such as in error paths
3311 * where the event isn't exposed yet and inherited events.
3313 static void free_event(struct perf_event *event)
3315 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3316 "unexpected event refcount: %ld; ptr=%p\n",
3317 atomic_long_read(&event->refcount), event)) {
3318 /* leak to avoid use-after-free */
3326 * Called when the last reference to the file is gone.
3328 static void put_event(struct perf_event *event)
3330 struct perf_event_context *ctx = event->ctx;
3331 struct task_struct *owner;
3333 if (!atomic_long_dec_and_test(&event->refcount))
3337 owner = ACCESS_ONCE(event->owner);
3339 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3340 * !owner it means the list deletion is complete and we can indeed
3341 * free this event, otherwise we need to serialize on
3342 * owner->perf_event_mutex.
3344 smp_read_barrier_depends();
3347 * Since delayed_put_task_struct() also drops the last
3348 * task reference we can safely take a new reference
3349 * while holding the rcu_read_lock().
3351 get_task_struct(owner);
3356 mutex_lock(&owner->perf_event_mutex);
3358 * We have to re-check the event->owner field, if it is cleared
3359 * we raced with perf_event_exit_task(), acquiring the mutex
3360 * ensured they're done, and we can proceed with freeing the
3364 list_del_init(&event->owner_entry);
3365 mutex_unlock(&owner->perf_event_mutex);
3366 put_task_struct(owner);
3369 WARN_ON_ONCE(ctx->parent_ctx);
3371 * There are two ways this annotation is useful:
3373 * 1) there is a lock recursion from perf_event_exit_task
3374 * see the comment there.
3376 * 2) there is a lock-inversion with mmap_sem through
3377 * perf_event_read_group(), which takes faults while
3378 * holding ctx->mutex, however this is called after
3379 * the last filedesc died, so there is no possibility
3380 * to trigger the AB-BA case.
3382 mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
3383 perf_remove_from_context(event, true);
3384 mutex_unlock(&ctx->mutex);
3389 int perf_event_release_kernel(struct perf_event *event)
3394 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3396 static int perf_release(struct inode *inode, struct file *file)
3398 put_event(file->private_data);
3402 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3404 struct perf_event *child;
3410 mutex_lock(&event->child_mutex);
3411 total += perf_event_read(event);
3412 *enabled += event->total_time_enabled +
3413 atomic64_read(&event->child_total_time_enabled);
3414 *running += event->total_time_running +
3415 atomic64_read(&event->child_total_time_running);
3417 list_for_each_entry(child, &event->child_list, child_list) {
3418 total += perf_event_read(child);
3419 *enabled += child->total_time_enabled;
3420 *running += child->total_time_running;
3422 mutex_unlock(&event->child_mutex);
3426 EXPORT_SYMBOL_GPL(perf_event_read_value);
3428 static int perf_event_read_group(struct perf_event *event,
3429 u64 read_format, char __user *buf)
3431 struct perf_event *leader = event->group_leader, *sub;
3432 int n = 0, size = 0, ret = -EFAULT;
3433 struct perf_event_context *ctx = leader->ctx;
3435 u64 count, enabled, running;
3437 mutex_lock(&ctx->mutex);
3438 count = perf_event_read_value(leader, &enabled, &running);
3440 values[n++] = 1 + leader->nr_siblings;
3441 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3442 values[n++] = enabled;
3443 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3444 values[n++] = running;
3445 values[n++] = count;
3446 if (read_format & PERF_FORMAT_ID)
3447 values[n++] = primary_event_id(leader);
3449 size = n * sizeof(u64);
3451 if (copy_to_user(buf, values, size))
3456 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3459 values[n++] = perf_event_read_value(sub, &enabled, &running);
3460 if (read_format & PERF_FORMAT_ID)
3461 values[n++] = primary_event_id(sub);
3463 size = n * sizeof(u64);
3465 if (copy_to_user(buf + ret, values, size)) {
3473 mutex_unlock(&ctx->mutex);
3478 static int perf_event_read_one(struct perf_event *event,
3479 u64 read_format, char __user *buf)
3481 u64 enabled, running;
3485 values[n++] = perf_event_read_value(event, &enabled, &running);
3486 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3487 values[n++] = enabled;
3488 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3489 values[n++] = running;
3490 if (read_format & PERF_FORMAT_ID)
3491 values[n++] = primary_event_id(event);
3493 if (copy_to_user(buf, values, n * sizeof(u64)))
3496 return n * sizeof(u64);
3500 * Read the performance event - simple non blocking version for now
3503 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
3505 u64 read_format = event->attr.read_format;
3509 * Return end-of-file for a read on a event that is in
3510 * error state (i.e. because it was pinned but it couldn't be
3511 * scheduled on to the CPU at some point).
3513 if (event->state == PERF_EVENT_STATE_ERROR)
3516 if (count < event->read_size)
3519 WARN_ON_ONCE(event->ctx->parent_ctx);
3520 if (read_format & PERF_FORMAT_GROUP)
3521 ret = perf_event_read_group(event, read_format, buf);
3523 ret = perf_event_read_one(event, read_format, buf);
3529 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
3531 struct perf_event *event = file->private_data;
3533 return perf_read_hw(event, buf, count);
3536 static unsigned int perf_poll(struct file *file, poll_table *wait)
3538 struct perf_event *event = file->private_data;
3539 struct ring_buffer *rb;
3540 unsigned int events = POLL_HUP;
3543 * Pin the event->rb by taking event->mmap_mutex; otherwise
3544 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
3546 mutex_lock(&event->mmap_mutex);
3549 events = atomic_xchg(&rb->poll, 0);
3550 mutex_unlock(&event->mmap_mutex);
3552 poll_wait(file, &event->waitq, wait);
3557 static void perf_event_reset(struct perf_event *event)
3559 (void)perf_event_read(event);
3560 local64_set(&event->count, 0);
3561 perf_event_update_userpage(event);
3565 * Holding the top-level event's child_mutex means that any
3566 * descendant process that has inherited this event will block
3567 * in sync_child_event if it goes to exit, thus satisfying the
3568 * task existence requirements of perf_event_enable/disable.
3570 static void perf_event_for_each_child(struct perf_event *event,
3571 void (*func)(struct perf_event *))
3573 struct perf_event *child;
3575 WARN_ON_ONCE(event->ctx->parent_ctx);
3576 mutex_lock(&event->child_mutex);
3578 list_for_each_entry(child, &event->child_list, child_list)
3580 mutex_unlock(&event->child_mutex);
3583 static void perf_event_for_each(struct perf_event *event,
3584 void (*func)(struct perf_event *))
3586 struct perf_event_context *ctx = event->ctx;
3587 struct perf_event *sibling;
3589 WARN_ON_ONCE(ctx->parent_ctx);
3590 mutex_lock(&ctx->mutex);
3591 event = event->group_leader;
3593 perf_event_for_each_child(event, func);
3594 list_for_each_entry(sibling, &event->sibling_list, group_entry)
3595 perf_event_for_each_child(sibling, func);
3596 mutex_unlock(&ctx->mutex);
3599 static int perf_event_period(struct perf_event *event, u64 __user *arg)
3601 struct perf_event_context *ctx = event->ctx;
3602 int ret = 0, active;
3605 if (!is_sampling_event(event))
3608 if (copy_from_user(&value, arg, sizeof(value)))
3614 raw_spin_lock_irq(&ctx->lock);
3615 if (event->attr.freq) {
3616 if (value > sysctl_perf_event_sample_rate) {
3621 event->attr.sample_freq = value;
3623 event->attr.sample_period = value;
3624 event->hw.sample_period = value;
3627 active = (event->state == PERF_EVENT_STATE_ACTIVE);
3629 perf_pmu_disable(ctx->pmu);
3630 event->pmu->stop(event, PERF_EF_UPDATE);
3633 local64_set(&event->hw.period_left, 0);
3636 event->pmu->start(event, PERF_EF_RELOAD);
3637 perf_pmu_enable(ctx->pmu);
3641 raw_spin_unlock_irq(&ctx->lock);
3646 static const struct file_operations perf_fops;
3648 static inline int perf_fget_light(int fd, struct fd *p)
3650 struct fd f = fdget(fd);
3654 if (f.file->f_op != &perf_fops) {
3662 static int perf_event_set_output(struct perf_event *event,
3663 struct perf_event *output_event);
3664 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
3666 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
3668 struct perf_event *event = file->private_data;
3669 void (*func)(struct perf_event *);
3673 case PERF_EVENT_IOC_ENABLE:
3674 func = perf_event_enable;
3676 case PERF_EVENT_IOC_DISABLE:
3677 func = perf_event_disable;
3679 case PERF_EVENT_IOC_RESET:
3680 func = perf_event_reset;
3683 case PERF_EVENT_IOC_REFRESH:
3684 return perf_event_refresh(event, arg);
3686 case PERF_EVENT_IOC_PERIOD:
3687 return perf_event_period(event, (u64 __user *)arg);
3689 case PERF_EVENT_IOC_ID:
3691 u64 id = primary_event_id(event);
3693 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
3698 case PERF_EVENT_IOC_SET_OUTPUT:
3702 struct perf_event *output_event;
3704 ret = perf_fget_light(arg, &output);
3707 output_event = output.file->private_data;
3708 ret = perf_event_set_output(event, output_event);
3711 ret = perf_event_set_output(event, NULL);
3716 case PERF_EVENT_IOC_SET_FILTER:
3717 return perf_event_set_filter(event, (void __user *)arg);
3723 if (flags & PERF_IOC_FLAG_GROUP)
3724 perf_event_for_each(event, func);
3726 perf_event_for_each_child(event, func);
3731 #ifdef CONFIG_COMPAT
3732 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
3735 switch (_IOC_NR(cmd)) {
3736 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
3737 case _IOC_NR(PERF_EVENT_IOC_ID):
3738 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
3739 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
3740 cmd &= ~IOCSIZE_MASK;
3741 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
3745 return perf_ioctl(file, cmd, arg);
3748 # define perf_compat_ioctl NULL
3751 int perf_event_task_enable(void)
3753 struct perf_event *event;
3755 mutex_lock(¤t->perf_event_mutex);
3756 list_for_each_entry(event, ¤t->perf_event_list, owner_entry)
3757 perf_event_for_each_child(event, perf_event_enable);
3758 mutex_unlock(¤t->perf_event_mutex);
3763 int perf_event_task_disable(void)
3765 struct perf_event *event;
3767 mutex_lock(¤t->perf_event_mutex);
3768 list_for_each_entry(event, ¤t->perf_event_list, owner_entry)
3769 perf_event_for_each_child(event, perf_event_disable);
3770 mutex_unlock(¤t->perf_event_mutex);
3775 static int perf_event_index(struct perf_event *event)
3777 if (event->hw.state & PERF_HES_STOPPED)
3780 if (event->state != PERF_EVENT_STATE_ACTIVE)
3783 return event->pmu->event_idx(event);
3786 static void calc_timer_values(struct perf_event *event,
3793 *now = perf_clock();
3794 ctx_time = event->shadow_ctx_time + *now;
3795 *enabled = ctx_time - event->tstamp_enabled;
3796 *running = ctx_time - event->tstamp_running;
3799 static void perf_event_init_userpage(struct perf_event *event)
3801 struct perf_event_mmap_page *userpg;
3802 struct ring_buffer *rb;
3805 rb = rcu_dereference(event->rb);
3809 userpg = rb->user_page;
3811 /* Allow new userspace to detect that bit 0 is deprecated */
3812 userpg->cap_bit0_is_deprecated = 1;
3813 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
3819 void __weak arch_perf_update_userpage(struct perf_event_mmap_page *userpg, u64 now)
3824 * Callers need to ensure there can be no nesting of this function, otherwise
3825 * the seqlock logic goes bad. We can not serialize this because the arch
3826 * code calls this from NMI context.
3828 void perf_event_update_userpage(struct perf_event *event)
3830 struct perf_event_mmap_page *userpg;
3831 struct ring_buffer *rb;
3832 u64 enabled, running, now;
3835 rb = rcu_dereference(event->rb);
3840 * compute total_time_enabled, total_time_running
3841 * based on snapshot values taken when the event
3842 * was last scheduled in.
3844 * we cannot simply called update_context_time()
3845 * because of locking issue as we can be called in
3848 calc_timer_values(event, &now, &enabled, &running);
3850 userpg = rb->user_page;
3852 * Disable preemption so as to not let the corresponding user-space
3853 * spin too long if we get preempted.
3858 userpg->index = perf_event_index(event);
3859 userpg->offset = perf_event_count(event);
3861 userpg->offset -= local64_read(&event->hw.prev_count);
3863 userpg->time_enabled = enabled +
3864 atomic64_read(&event->child_total_time_enabled);
3866 userpg->time_running = running +
3867 atomic64_read(&event->child_total_time_running);
3869 arch_perf_update_userpage(userpg, now);
3878 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
3880 struct perf_event *event = vma->vm_file->private_data;
3881 struct ring_buffer *rb;
3882 int ret = VM_FAULT_SIGBUS;
3884 if (vmf->flags & FAULT_FLAG_MKWRITE) {
3885 if (vmf->pgoff == 0)
3891 rb = rcu_dereference(event->rb);
3895 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
3898 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
3902 get_page(vmf->page);
3903 vmf->page->mapping = vma->vm_file->f_mapping;
3904 vmf->page->index = vmf->pgoff;
3913 static void ring_buffer_attach(struct perf_event *event,
3914 struct ring_buffer *rb)
3916 struct ring_buffer *old_rb = NULL;
3917 unsigned long flags;
3921 * Should be impossible, we set this when removing
3922 * event->rb_entry and wait/clear when adding event->rb_entry.
3924 WARN_ON_ONCE(event->rcu_pending);
3927 event->rcu_batches = get_state_synchronize_rcu();
3928 event->rcu_pending = 1;
3930 spin_lock_irqsave(&old_rb->event_lock, flags);
3931 list_del_rcu(&event->rb_entry);
3932 spin_unlock_irqrestore(&old_rb->event_lock, flags);
3935 if (event->rcu_pending && rb) {
3936 cond_synchronize_rcu(event->rcu_batches);
3937 event->rcu_pending = 0;
3941 spin_lock_irqsave(&rb->event_lock, flags);
3942 list_add_rcu(&event->rb_entry, &rb->event_list);
3943 spin_unlock_irqrestore(&rb->event_lock, flags);
3946 rcu_assign_pointer(event->rb, rb);
3949 ring_buffer_put(old_rb);
3951 * Since we detached before setting the new rb, so that we
3952 * could attach the new rb, we could have missed a wakeup.
3955 wake_up_all(&event->waitq);
3959 static void ring_buffer_wakeup(struct perf_event *event)
3961 struct ring_buffer *rb;
3964 rb = rcu_dereference(event->rb);
3966 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
3967 wake_up_all(&event->waitq);
3972 static void rb_free_rcu(struct rcu_head *rcu_head)
3974 struct ring_buffer *rb;
3976 rb = container_of(rcu_head, struct ring_buffer, rcu_head);
3980 static struct ring_buffer *ring_buffer_get(struct perf_event *event)
3982 struct ring_buffer *rb;
3985 rb = rcu_dereference(event->rb);
3987 if (!atomic_inc_not_zero(&rb->refcount))
3995 static void ring_buffer_put(struct ring_buffer *rb)
3997 if (!atomic_dec_and_test(&rb->refcount))
4000 WARN_ON_ONCE(!list_empty(&rb->event_list));
4002 call_rcu(&rb->rcu_head, rb_free_rcu);
4005 static void perf_mmap_open(struct vm_area_struct *vma)
4007 struct perf_event *event = vma->vm_file->private_data;
4009 atomic_inc(&event->mmap_count);
4010 atomic_inc(&event->rb->mmap_count);
4014 * A buffer can be mmap()ed multiple times; either directly through the same
4015 * event, or through other events by use of perf_event_set_output().
4017 * In order to undo the VM accounting done by perf_mmap() we need to destroy
4018 * the buffer here, where we still have a VM context. This means we need
4019 * to detach all events redirecting to us.
4021 static void perf_mmap_close(struct vm_area_struct *vma)
4023 struct perf_event *event = vma->vm_file->private_data;
4025 struct ring_buffer *rb = ring_buffer_get(event);
4026 struct user_struct *mmap_user = rb->mmap_user;
4027 int mmap_locked = rb->mmap_locked;
4028 unsigned long size = perf_data_size(rb);
4030 atomic_dec(&rb->mmap_count);
4032 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
4035 ring_buffer_attach(event, NULL);
4036 mutex_unlock(&event->mmap_mutex);
4038 /* If there's still other mmap()s of this buffer, we're done. */
4039 if (atomic_read(&rb->mmap_count))
4043 * No other mmap()s, detach from all other events that might redirect
4044 * into the now unreachable buffer. Somewhat complicated by the
4045 * fact that rb::event_lock otherwise nests inside mmap_mutex.
4049 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4050 if (!atomic_long_inc_not_zero(&event->refcount)) {
4052 * This event is en-route to free_event() which will
4053 * detach it and remove it from the list.
4059 mutex_lock(&event->mmap_mutex);
4061 * Check we didn't race with perf_event_set_output() which can
4062 * swizzle the rb from under us while we were waiting to
4063 * acquire mmap_mutex.
4065 * If we find a different rb; ignore this event, a next
4066 * iteration will no longer find it on the list. We have to
4067 * still restart the iteration to make sure we're not now
4068 * iterating the wrong list.
4070 if (event->rb == rb)
4071 ring_buffer_attach(event, NULL);
4073 mutex_unlock(&event->mmap_mutex);
4077 * Restart the iteration; either we're on the wrong list or
4078 * destroyed its integrity by doing a deletion.
4085 * It could be there's still a few 0-ref events on the list; they'll
4086 * get cleaned up by free_event() -- they'll also still have their
4087 * ref on the rb and will free it whenever they are done with it.
4089 * Aside from that, this buffer is 'fully' detached and unmapped,
4090 * undo the VM accounting.
4093 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4094 vma->vm_mm->pinned_vm -= mmap_locked;
4095 free_uid(mmap_user);
4098 ring_buffer_put(rb); /* could be last */
4101 static const struct vm_operations_struct perf_mmap_vmops = {
4102 .open = perf_mmap_open,
4103 .close = perf_mmap_close,
4104 .fault = perf_mmap_fault,
4105 .page_mkwrite = perf_mmap_fault,
4108 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
4110 struct perf_event *event = file->private_data;
4111 unsigned long user_locked, user_lock_limit;
4112 struct user_struct *user = current_user();
4113 unsigned long locked, lock_limit;
4114 struct ring_buffer *rb;
4115 unsigned long vma_size;
4116 unsigned long nr_pages;
4117 long user_extra, extra;
4118 int ret = 0, flags = 0;
4121 * Don't allow mmap() of inherited per-task counters. This would
4122 * create a performance issue due to all children writing to the
4125 if (event->cpu == -1 && event->attr.inherit)
4128 if (!(vma->vm_flags & VM_SHARED))
4131 vma_size = vma->vm_end - vma->vm_start;
4132 nr_pages = (vma_size / PAGE_SIZE) - 1;
4135 * If we have rb pages ensure they're a power-of-two number, so we
4136 * can do bitmasks instead of modulo.
4138 if (nr_pages != 0 && !is_power_of_2(nr_pages))
4141 if (vma_size != PAGE_SIZE * (1 + nr_pages))
4144 if (vma->vm_pgoff != 0)
4147 WARN_ON_ONCE(event->ctx->parent_ctx);
4149 mutex_lock(&event->mmap_mutex);
4151 if (event->rb->nr_pages != nr_pages) {
4156 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4158 * Raced against perf_mmap_close() through
4159 * perf_event_set_output(). Try again, hope for better
4162 mutex_unlock(&event->mmap_mutex);
4169 user_extra = nr_pages + 1;
4170 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
4173 * Increase the limit linearly with more CPUs:
4175 user_lock_limit *= num_online_cpus();
4177 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
4180 if (user_locked > user_lock_limit)
4181 extra = user_locked - user_lock_limit;
4183 lock_limit = rlimit(RLIMIT_MEMLOCK);
4184 lock_limit >>= PAGE_SHIFT;
4185 locked = vma->vm_mm->pinned_vm + extra;
4187 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
4188 !capable(CAP_IPC_LOCK)) {
4195 if (vma->vm_flags & VM_WRITE)
4196 flags |= RING_BUFFER_WRITABLE;
4198 rb = rb_alloc(nr_pages,
4199 event->attr.watermark ? event->attr.wakeup_watermark : 0,
4207 atomic_set(&rb->mmap_count, 1);
4208 rb->mmap_locked = extra;
4209 rb->mmap_user = get_current_user();
4211 atomic_long_add(user_extra, &user->locked_vm);
4212 vma->vm_mm->pinned_vm += extra;
4214 ring_buffer_attach(event, rb);
4216 perf_event_init_userpage(event);
4217 perf_event_update_userpage(event);
4221 atomic_inc(&event->mmap_count);
4222 mutex_unlock(&event->mmap_mutex);
4225 * Since pinned accounting is per vm we cannot allow fork() to copy our
4228 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
4229 vma->vm_ops = &perf_mmap_vmops;
4234 static int perf_fasync(int fd, struct file *filp, int on)
4236 struct inode *inode = file_inode(filp);
4237 struct perf_event *event = filp->private_data;
4240 mutex_lock(&inode->i_mutex);
4241 retval = fasync_helper(fd, filp, on, &event->fasync);
4242 mutex_unlock(&inode->i_mutex);
4250 static const struct file_operations perf_fops = {
4251 .llseek = no_llseek,
4252 .release = perf_release,
4255 .unlocked_ioctl = perf_ioctl,
4256 .compat_ioctl = perf_compat_ioctl,
4258 .fasync = perf_fasync,
4264 * If there's data, ensure we set the poll() state and publish everything
4265 * to user-space before waking everybody up.
4268 void perf_event_wakeup(struct perf_event *event)
4270 ring_buffer_wakeup(event);
4272 if (event->pending_kill) {
4273 kill_fasync(&event->fasync, SIGIO, event->pending_kill);
4274 event->pending_kill = 0;
4278 static void perf_pending_event(struct irq_work *entry)
4280 struct perf_event *event = container_of(entry,
4281 struct perf_event, pending);
4283 if (event->pending_disable) {
4284 event->pending_disable = 0;
4285 __perf_event_disable(event);
4288 if (event->pending_wakeup) {
4289 event->pending_wakeup = 0;
4290 perf_event_wakeup(event);
4295 * We assume there is only KVM supporting the callbacks.
4296 * Later on, we might change it to a list if there is
4297 * another virtualization implementation supporting the callbacks.
4299 struct perf_guest_info_callbacks *perf_guest_cbs;
4301 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4303 perf_guest_cbs = cbs;
4306 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
4308 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4310 perf_guest_cbs = NULL;
4313 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
4316 perf_output_sample_regs(struct perf_output_handle *handle,
4317 struct pt_regs *regs, u64 mask)
4321 for_each_set_bit(bit, (const unsigned long *) &mask,
4322 sizeof(mask) * BITS_PER_BYTE) {
4325 val = perf_reg_value(regs, bit);
4326 perf_output_put(handle, val);
4330 static void perf_sample_regs_user(struct perf_regs_user *regs_user,
4331 struct pt_regs *regs)
4333 if (!user_mode(regs)) {
4335 regs = task_pt_regs(current);
4341 regs_user->regs = regs;
4342 regs_user->abi = perf_reg_abi(current);
4347 * Get remaining task size from user stack pointer.
4349 * It'd be better to take stack vma map and limit this more
4350 * precisly, but there's no way to get it safely under interrupt,
4351 * so using TASK_SIZE as limit.
4353 static u64 perf_ustack_task_size(struct pt_regs *regs)
4355 unsigned long addr = perf_user_stack_pointer(regs);
4357 if (!addr || addr >= TASK_SIZE)
4360 return TASK_SIZE - addr;
4364 perf_sample_ustack_size(u16 stack_size, u16 header_size,
4365 struct pt_regs *regs)
4369 /* No regs, no stack pointer, no dump. */
4374 * Check if we fit in with the requested stack size into the:
4376 * If we don't, we limit the size to the TASK_SIZE.
4378 * - remaining sample size
4379 * If we don't, we customize the stack size to
4380 * fit in to the remaining sample size.
4383 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
4384 stack_size = min(stack_size, (u16) task_size);
4386 /* Current header size plus static size and dynamic size. */
4387 header_size += 2 * sizeof(u64);
4389 /* Do we fit in with the current stack dump size? */
4390 if ((u16) (header_size + stack_size) < header_size) {
4392 * If we overflow the maximum size for the sample,
4393 * we customize the stack dump size to fit in.
4395 stack_size = USHRT_MAX - header_size - sizeof(u64);
4396 stack_size = round_up(stack_size, sizeof(u64));
4403 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
4404 struct pt_regs *regs)
4406 /* Case of a kernel thread, nothing to dump */
4409 perf_output_put(handle, size);
4418 * - the size requested by user or the best one we can fit
4419 * in to the sample max size
4421 * - user stack dump data
4423 * - the actual dumped size
4427 perf_output_put(handle, dump_size);
4430 sp = perf_user_stack_pointer(regs);
4431 rem = __output_copy_user(handle, (void *) sp, dump_size);
4432 dyn_size = dump_size - rem;
4434 perf_output_skip(handle, rem);
4437 perf_output_put(handle, dyn_size);
4441 static void __perf_event_header__init_id(struct perf_event_header *header,
4442 struct perf_sample_data *data,
4443 struct perf_event *event)
4445 u64 sample_type = event->attr.sample_type;
4447 data->type = sample_type;
4448 header->size += event->id_header_size;
4450 if (sample_type & PERF_SAMPLE_TID) {
4451 /* namespace issues */
4452 data->tid_entry.pid = perf_event_pid(event, current);
4453 data->tid_entry.tid = perf_event_tid(event, current);
4456 if (sample_type & PERF_SAMPLE_TIME)
4457 data->time = perf_clock();
4459 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
4460 data->id = primary_event_id(event);
4462 if (sample_type & PERF_SAMPLE_STREAM_ID)
4463 data->stream_id = event->id;
4465 if (sample_type & PERF_SAMPLE_CPU) {
4466 data->cpu_entry.cpu = raw_smp_processor_id();
4467 data->cpu_entry.reserved = 0;
4471 void perf_event_header__init_id(struct perf_event_header *header,
4472 struct perf_sample_data *data,
4473 struct perf_event *event)
4475 if (event->attr.sample_id_all)
4476 __perf_event_header__init_id(header, data, event);
4479 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
4480 struct perf_sample_data *data)
4482 u64 sample_type = data->type;
4484 if (sample_type & PERF_SAMPLE_TID)
4485 perf_output_put(handle, data->tid_entry);
4487 if (sample_type & PERF_SAMPLE_TIME)
4488 perf_output_put(handle, data->time);
4490 if (sample_type & PERF_SAMPLE_ID)
4491 perf_output_put(handle, data->id);
4493 if (sample_type & PERF_SAMPLE_STREAM_ID)
4494 perf_output_put(handle, data->stream_id);
4496 if (sample_type & PERF_SAMPLE_CPU)
4497 perf_output_put(handle, data->cpu_entry);
4499 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4500 perf_output_put(handle, data->id);
4503 void perf_event__output_id_sample(struct perf_event *event,
4504 struct perf_output_handle *handle,
4505 struct perf_sample_data *sample)
4507 if (event->attr.sample_id_all)
4508 __perf_event__output_id_sample(handle, sample);
4511 static void perf_output_read_one(struct perf_output_handle *handle,
4512 struct perf_event *event,
4513 u64 enabled, u64 running)
4515 u64 read_format = event->attr.read_format;
4519 values[n++] = perf_event_count(event);
4520 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4521 values[n++] = enabled +
4522 atomic64_read(&event->child_total_time_enabled);
4524 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4525 values[n++] = running +
4526 atomic64_read(&event->child_total_time_running);
4528 if (read_format & PERF_FORMAT_ID)
4529 values[n++] = primary_event_id(event);
4531 __output_copy(handle, values, n * sizeof(u64));
4535 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
4537 static void perf_output_read_group(struct perf_output_handle *handle,
4538 struct perf_event *event,
4539 u64 enabled, u64 running)
4541 struct perf_event *leader = event->group_leader, *sub;
4542 u64 read_format = event->attr.read_format;
4546 values[n++] = 1 + leader->nr_siblings;
4548 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4549 values[n++] = enabled;
4551 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4552 values[n++] = running;
4554 if (leader != event)
4555 leader->pmu->read(leader);
4557 values[n++] = perf_event_count(leader);
4558 if (read_format & PERF_FORMAT_ID)
4559 values[n++] = primary_event_id(leader);
4561 __output_copy(handle, values, n * sizeof(u64));
4563 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4566 if ((sub != event) &&
4567 (sub->state == PERF_EVENT_STATE_ACTIVE))
4568 sub->pmu->read(sub);
4570 values[n++] = perf_event_count(sub);
4571 if (read_format & PERF_FORMAT_ID)
4572 values[n++] = primary_event_id(sub);
4574 __output_copy(handle, values, n * sizeof(u64));
4578 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
4579 PERF_FORMAT_TOTAL_TIME_RUNNING)
4581 static void perf_output_read(struct perf_output_handle *handle,
4582 struct perf_event *event)
4584 u64 enabled = 0, running = 0, now;
4585 u64 read_format = event->attr.read_format;
4588 * compute total_time_enabled, total_time_running
4589 * based on snapshot values taken when the event
4590 * was last scheduled in.
4592 * we cannot simply called update_context_time()
4593 * because of locking issue as we are called in
4596 if (read_format & PERF_FORMAT_TOTAL_TIMES)
4597 calc_timer_values(event, &now, &enabled, &running);
4599 if (event->attr.read_format & PERF_FORMAT_GROUP)
4600 perf_output_read_group(handle, event, enabled, running);
4602 perf_output_read_one(handle, event, enabled, running);
4605 void perf_output_sample(struct perf_output_handle *handle,
4606 struct perf_event_header *header,
4607 struct perf_sample_data *data,
4608 struct perf_event *event)
4610 u64 sample_type = data->type;
4612 perf_output_put(handle, *header);
4614 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4615 perf_output_put(handle, data->id);
4617 if (sample_type & PERF_SAMPLE_IP)
4618 perf_output_put(handle, data->ip);
4620 if (sample_type & PERF_SAMPLE_TID)
4621 perf_output_put(handle, data->tid_entry);
4623 if (sample_type & PERF_SAMPLE_TIME)
4624 perf_output_put(handle, data->time);
4626 if (sample_type & PERF_SAMPLE_ADDR)
4627 perf_output_put(handle, data->addr);
4629 if (sample_type & PERF_SAMPLE_ID)
4630 perf_output_put(handle, data->id);
4632 if (sample_type & PERF_SAMPLE_STREAM_ID)
4633 perf_output_put(handle, data->stream_id);
4635 if (sample_type & PERF_SAMPLE_CPU)
4636 perf_output_put(handle, data->cpu_entry);
4638 if (sample_type & PERF_SAMPLE_PERIOD)
4639 perf_output_put(handle, data->period);
4641 if (sample_type & PERF_SAMPLE_READ)
4642 perf_output_read(handle, event);
4644 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4645 if (data->callchain) {
4648 if (data->callchain)
4649 size += data->callchain->nr;
4651 size *= sizeof(u64);
4653 __output_copy(handle, data->callchain, size);
4656 perf_output_put(handle, nr);
4660 if (sample_type & PERF_SAMPLE_RAW) {
4662 perf_output_put(handle, data->raw->size);
4663 __output_copy(handle, data->raw->data,
4670 .size = sizeof(u32),
4673 perf_output_put(handle, raw);
4677 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4678 if (data->br_stack) {
4681 size = data->br_stack->nr
4682 * sizeof(struct perf_branch_entry);
4684 perf_output_put(handle, data->br_stack->nr);
4685 perf_output_copy(handle, data->br_stack->entries, size);
4688 * we always store at least the value of nr
4691 perf_output_put(handle, nr);
4695 if (sample_type & PERF_SAMPLE_REGS_USER) {
4696 u64 abi = data->regs_user.abi;
4699 * If there are no regs to dump, notice it through
4700 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
4702 perf_output_put(handle, abi);
4705 u64 mask = event->attr.sample_regs_user;
4706 perf_output_sample_regs(handle,
4707 data->regs_user.regs,
4712 if (sample_type & PERF_SAMPLE_STACK_USER) {
4713 perf_output_sample_ustack(handle,
4714 data->stack_user_size,
4715 data->regs_user.regs);
4718 if (sample_type & PERF_SAMPLE_WEIGHT)
4719 perf_output_put(handle, data->weight);
4721 if (sample_type & PERF_SAMPLE_DATA_SRC)
4722 perf_output_put(handle, data->data_src.val);
4724 if (sample_type & PERF_SAMPLE_TRANSACTION)
4725 perf_output_put(handle, data->txn);
4727 if (!event->attr.watermark) {
4728 int wakeup_events = event->attr.wakeup_events;
4730 if (wakeup_events) {
4731 struct ring_buffer *rb = handle->rb;
4732 int events = local_inc_return(&rb->events);
4734 if (events >= wakeup_events) {
4735 local_sub(wakeup_events, &rb->events);
4736 local_inc(&rb->wakeup);
4742 void perf_prepare_sample(struct perf_event_header *header,
4743 struct perf_sample_data *data,
4744 struct perf_event *event,
4745 struct pt_regs *regs)
4747 u64 sample_type = event->attr.sample_type;
4749 header->type = PERF_RECORD_SAMPLE;
4750 header->size = sizeof(*header) + event->header_size;
4753 header->misc |= perf_misc_flags(regs);
4755 __perf_event_header__init_id(header, data, event);
4757 if (sample_type & PERF_SAMPLE_IP)
4758 data->ip = perf_instruction_pointer(regs);
4760 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4763 data->callchain = perf_callchain(event, regs);
4765 if (data->callchain)
4766 size += data->callchain->nr;
4768 header->size += size * sizeof(u64);
4771 if (sample_type & PERF_SAMPLE_RAW) {
4772 int size = sizeof(u32);
4775 size += data->raw->size;
4777 size += sizeof(u32);
4779 WARN_ON_ONCE(size & (sizeof(u64)-1));
4780 header->size += size;
4783 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4784 int size = sizeof(u64); /* nr */
4785 if (data->br_stack) {
4786 size += data->br_stack->nr
4787 * sizeof(struct perf_branch_entry);
4789 header->size += size;
4792 if (sample_type & PERF_SAMPLE_REGS_USER) {
4793 /* regs dump ABI info */
4794 int size = sizeof(u64);
4796 perf_sample_regs_user(&data->regs_user, regs);
4798 if (data->regs_user.regs) {
4799 u64 mask = event->attr.sample_regs_user;
4800 size += hweight64(mask) * sizeof(u64);
4803 header->size += size;
4806 if (sample_type & PERF_SAMPLE_STACK_USER) {
4808 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
4809 * processed as the last one or have additional check added
4810 * in case new sample type is added, because we could eat
4811 * up the rest of the sample size.
4813 struct perf_regs_user *uregs = &data->regs_user;
4814 u16 stack_size = event->attr.sample_stack_user;
4815 u16 size = sizeof(u64);
4818 perf_sample_regs_user(uregs, regs);
4820 stack_size = perf_sample_ustack_size(stack_size, header->size,
4824 * If there is something to dump, add space for the dump
4825 * itself and for the field that tells the dynamic size,
4826 * which is how many have been actually dumped.
4829 size += sizeof(u64) + stack_size;
4831 data->stack_user_size = stack_size;
4832 header->size += size;
4836 static void perf_event_output(struct perf_event *event,
4837 struct perf_sample_data *data,
4838 struct pt_regs *regs)
4840 struct perf_output_handle handle;
4841 struct perf_event_header header;
4843 /* protect the callchain buffers */
4846 perf_prepare_sample(&header, data, event, regs);
4848 if (perf_output_begin(&handle, event, header.size))
4851 perf_output_sample(&handle, &header, data, event);
4853 perf_output_end(&handle);
4863 struct perf_read_event {
4864 struct perf_event_header header;
4871 perf_event_read_event(struct perf_event *event,
4872 struct task_struct *task)
4874 struct perf_output_handle handle;
4875 struct perf_sample_data sample;
4876 struct perf_read_event read_event = {
4878 .type = PERF_RECORD_READ,
4880 .size = sizeof(read_event) + event->read_size,
4882 .pid = perf_event_pid(event, task),
4883 .tid = perf_event_tid(event, task),
4887 perf_event_header__init_id(&read_event.header, &sample, event);
4888 ret = perf_output_begin(&handle, event, read_event.header.size);
4892 perf_output_put(&handle, read_event);
4893 perf_output_read(&handle, event);
4894 perf_event__output_id_sample(event, &handle, &sample);
4896 perf_output_end(&handle);
4899 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
4902 perf_event_aux_ctx(struct perf_event_context *ctx,
4903 perf_event_aux_output_cb output,
4906 struct perf_event *event;
4908 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4909 if (event->state < PERF_EVENT_STATE_INACTIVE)
4911 if (!event_filter_match(event))
4913 output(event, data);
4918 perf_event_aux(perf_event_aux_output_cb output, void *data,
4919 struct perf_event_context *task_ctx)
4921 struct perf_cpu_context *cpuctx;
4922 struct perf_event_context *ctx;
4927 list_for_each_entry_rcu(pmu, &pmus, entry) {
4928 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4929 if (cpuctx->unique_pmu != pmu)
4931 perf_event_aux_ctx(&cpuctx->ctx, output, data);
4934 ctxn = pmu->task_ctx_nr;
4937 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4939 perf_event_aux_ctx(ctx, output, data);
4941 put_cpu_ptr(pmu->pmu_cpu_context);
4946 perf_event_aux_ctx(task_ctx, output, data);
4953 * task tracking -- fork/exit
4955 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
4958 struct perf_task_event {
4959 struct task_struct *task;
4960 struct perf_event_context *task_ctx;
4963 struct perf_event_header header;
4973 static int perf_event_task_match(struct perf_event *event)
4975 return event->attr.comm || event->attr.mmap ||
4976 event->attr.mmap2 || event->attr.mmap_data ||
4980 static void perf_event_task_output(struct perf_event *event,
4983 struct perf_task_event *task_event = data;
4984 struct perf_output_handle handle;
4985 struct perf_sample_data sample;
4986 struct task_struct *task = task_event->task;
4987 int ret, size = task_event->event_id.header.size;
4989 if (!perf_event_task_match(event))
4992 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
4994 ret = perf_output_begin(&handle, event,
4995 task_event->event_id.header.size);
4999 task_event->event_id.pid = perf_event_pid(event, task);
5000 task_event->event_id.ppid = perf_event_pid(event, current);
5002 task_event->event_id.tid = perf_event_tid(event, task);
5003 task_event->event_id.ptid = perf_event_tid(event, current);
5005 perf_output_put(&handle, task_event->event_id);
5007 perf_event__output_id_sample(event, &handle, &sample);
5009 perf_output_end(&handle);
5011 task_event->event_id.header.size = size;
5014 static void perf_event_task(struct task_struct *task,
5015 struct perf_event_context *task_ctx,
5018 struct perf_task_event task_event;
5020 if (!atomic_read(&nr_comm_events) &&
5021 !atomic_read(&nr_mmap_events) &&
5022 !atomic_read(&nr_task_events))
5025 task_event = (struct perf_task_event){
5027 .task_ctx = task_ctx,
5030 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
5032 .size = sizeof(task_event.event_id),
5038 .time = perf_clock(),
5042 perf_event_aux(perf_event_task_output,
5047 void perf_event_fork(struct task_struct *task)
5049 perf_event_task(task, NULL, 1);
5056 struct perf_comm_event {
5057 struct task_struct *task;
5062 struct perf_event_header header;
5069 static int perf_event_comm_match(struct perf_event *event)
5071 return event->attr.comm;
5074 static void perf_event_comm_output(struct perf_event *event,
5077 struct perf_comm_event *comm_event = data;
5078 struct perf_output_handle handle;
5079 struct perf_sample_data sample;
5080 int size = comm_event->event_id.header.size;
5083 if (!perf_event_comm_match(event))
5086 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
5087 ret = perf_output_begin(&handle, event,
5088 comm_event->event_id.header.size);
5093 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
5094 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
5096 perf_output_put(&handle, comm_event->event_id);
5097 __output_copy(&handle, comm_event->comm,
5098 comm_event->comm_size);
5100 perf_event__output_id_sample(event, &handle, &sample);
5102 perf_output_end(&handle);
5104 comm_event->event_id.header.size = size;
5107 static void perf_event_comm_event(struct perf_comm_event *comm_event)
5109 char comm[TASK_COMM_LEN];
5112 memset(comm, 0, sizeof(comm));
5113 strlcpy(comm, comm_event->task->comm, sizeof(comm));
5114 size = ALIGN(strlen(comm)+1, sizeof(u64));
5116 comm_event->comm = comm;
5117 comm_event->comm_size = size;
5119 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
5121 perf_event_aux(perf_event_comm_output,
5126 void perf_event_comm(struct task_struct *task, bool exec)
5128 struct perf_comm_event comm_event;
5130 if (!atomic_read(&nr_comm_events))
5133 comm_event = (struct perf_comm_event){
5139 .type = PERF_RECORD_COMM,
5140 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
5148 perf_event_comm_event(&comm_event);
5155 struct perf_mmap_event {
5156 struct vm_area_struct *vma;
5158 const char *file_name;
5166 struct perf_event_header header;
5176 static int perf_event_mmap_match(struct perf_event *event,
5179 struct perf_mmap_event *mmap_event = data;
5180 struct vm_area_struct *vma = mmap_event->vma;
5181 int executable = vma->vm_flags & VM_EXEC;
5183 return (!executable && event->attr.mmap_data) ||
5184 (executable && (event->attr.mmap || event->attr.mmap2));
5187 static void perf_event_mmap_output(struct perf_event *event,
5190 struct perf_mmap_event *mmap_event = data;
5191 struct perf_output_handle handle;
5192 struct perf_sample_data sample;
5193 int size = mmap_event->event_id.header.size;
5196 if (!perf_event_mmap_match(event, data))
5199 if (event->attr.mmap2) {
5200 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
5201 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
5202 mmap_event->event_id.header.size += sizeof(mmap_event->min);
5203 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
5204 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
5205 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
5206 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
5209 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
5210 ret = perf_output_begin(&handle, event,
5211 mmap_event->event_id.header.size);
5215 mmap_event->event_id.pid = perf_event_pid(event, current);
5216 mmap_event->event_id.tid = perf_event_tid(event, current);
5218 perf_output_put(&handle, mmap_event->event_id);
5220 if (event->attr.mmap2) {
5221 perf_output_put(&handle, mmap_event->maj);
5222 perf_output_put(&handle, mmap_event->min);
5223 perf_output_put(&handle, mmap_event->ino);
5224 perf_output_put(&handle, mmap_event->ino_generation);
5225 perf_output_put(&handle, mmap_event->prot);
5226 perf_output_put(&handle, mmap_event->flags);
5229 __output_copy(&handle, mmap_event->file_name,
5230 mmap_event->file_size);
5232 perf_event__output_id_sample(event, &handle, &sample);
5234 perf_output_end(&handle);
5236 mmap_event->event_id.header.size = size;
5239 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
5241 struct vm_area_struct *vma = mmap_event->vma;
5242 struct file *file = vma->vm_file;
5243 int maj = 0, min = 0;
5244 u64 ino = 0, gen = 0;
5245 u32 prot = 0, flags = 0;
5252 struct inode *inode;
5255 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5261 * d_path() works from the end of the rb backwards, so we
5262 * need to add enough zero bytes after the string to handle
5263 * the 64bit alignment we do later.
5265 name = d_path(&file->f_path, buf, PATH_MAX - sizeof(u64));
5270 inode = file_inode(vma->vm_file);
5271 dev = inode->i_sb->s_dev;
5273 gen = inode->i_generation;
5277 if (vma->vm_flags & VM_READ)
5279 if (vma->vm_flags & VM_WRITE)
5281 if (vma->vm_flags & VM_EXEC)
5284 if (vma->vm_flags & VM_MAYSHARE)
5287 flags = MAP_PRIVATE;
5289 if (vma->vm_flags & VM_DENYWRITE)
5290 flags |= MAP_DENYWRITE;
5291 if (vma->vm_flags & VM_MAYEXEC)
5292 flags |= MAP_EXECUTABLE;
5293 if (vma->vm_flags & VM_LOCKED)
5294 flags |= MAP_LOCKED;
5295 if (vma->vm_flags & VM_HUGETLB)
5296 flags |= MAP_HUGETLB;
5300 if (vma->vm_ops && vma->vm_ops->name) {
5301 name = (char *) vma->vm_ops->name(vma);
5306 name = (char *)arch_vma_name(vma);
5310 if (vma->vm_start <= vma->vm_mm->start_brk &&
5311 vma->vm_end >= vma->vm_mm->brk) {
5315 if (vma->vm_start <= vma->vm_mm->start_stack &&
5316 vma->vm_end >= vma->vm_mm->start_stack) {
5326 strlcpy(tmp, name, sizeof(tmp));
5330 * Since our buffer works in 8 byte units we need to align our string
5331 * size to a multiple of 8. However, we must guarantee the tail end is
5332 * zero'd out to avoid leaking random bits to userspace.
5334 size = strlen(name)+1;
5335 while (!IS_ALIGNED(size, sizeof(u64)))
5336 name[size++] = '\0';
5338 mmap_event->file_name = name;
5339 mmap_event->file_size = size;
5340 mmap_event->maj = maj;
5341 mmap_event->min = min;
5342 mmap_event->ino = ino;
5343 mmap_event->ino_generation = gen;
5344 mmap_event->prot = prot;
5345 mmap_event->flags = flags;
5347 if (!(vma->vm_flags & VM_EXEC))
5348 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
5350 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
5352 perf_event_aux(perf_event_mmap_output,
5359 void perf_event_mmap(struct vm_area_struct *vma)
5361 struct perf_mmap_event mmap_event;
5363 if (!atomic_read(&nr_mmap_events))
5366 mmap_event = (struct perf_mmap_event){
5372 .type = PERF_RECORD_MMAP,
5373 .misc = PERF_RECORD_MISC_USER,
5378 .start = vma->vm_start,
5379 .len = vma->vm_end - vma->vm_start,
5380 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
5382 /* .maj (attr_mmap2 only) */
5383 /* .min (attr_mmap2 only) */
5384 /* .ino (attr_mmap2 only) */
5385 /* .ino_generation (attr_mmap2 only) */
5386 /* .prot (attr_mmap2 only) */
5387 /* .flags (attr_mmap2 only) */
5390 perf_event_mmap_event(&mmap_event);
5394 * IRQ throttle logging
5397 static void perf_log_throttle(struct perf_event *event, int enable)
5399 struct perf_output_handle handle;
5400 struct perf_sample_data sample;
5404 struct perf_event_header header;
5408 } throttle_event = {
5410 .type = PERF_RECORD_THROTTLE,
5412 .size = sizeof(throttle_event),
5414 .time = perf_clock(),
5415 .id = primary_event_id(event),
5416 .stream_id = event->id,
5420 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
5422 perf_event_header__init_id(&throttle_event.header, &sample, event);
5424 ret = perf_output_begin(&handle, event,
5425 throttle_event.header.size);
5429 perf_output_put(&handle, throttle_event);
5430 perf_event__output_id_sample(event, &handle, &sample);
5431 perf_output_end(&handle);
5435 * Generic event overflow handling, sampling.
5438 static int __perf_event_overflow(struct perf_event *event,
5439 int throttle, struct perf_sample_data *data,
5440 struct pt_regs *regs)
5442 int events = atomic_read(&event->event_limit);
5443 struct hw_perf_event *hwc = &event->hw;
5448 * Non-sampling counters might still use the PMI to fold short
5449 * hardware counters, ignore those.
5451 if (unlikely(!is_sampling_event(event)))
5454 seq = __this_cpu_read(perf_throttled_seq);
5455 if (seq != hwc->interrupts_seq) {
5456 hwc->interrupts_seq = seq;
5457 hwc->interrupts = 1;
5460 if (unlikely(throttle
5461 && hwc->interrupts >= max_samples_per_tick)) {
5462 __this_cpu_inc(perf_throttled_count);
5463 hwc->interrupts = MAX_INTERRUPTS;
5464 perf_log_throttle(event, 0);
5465 tick_nohz_full_kick();
5470 if (event->attr.freq) {
5471 u64 now = perf_clock();
5472 s64 delta = now - hwc->freq_time_stamp;
5474 hwc->freq_time_stamp = now;
5476 if (delta > 0 && delta < 2*TICK_NSEC)
5477 perf_adjust_period(event, delta, hwc->last_period, true);
5481 * XXX event_limit might not quite work as expected on inherited
5485 event->pending_kill = POLL_IN;
5486 if (events && atomic_dec_and_test(&event->event_limit)) {
5488 event->pending_kill = POLL_HUP;
5489 event->pending_disable = 1;
5490 irq_work_queue(&event->pending);
5493 if (event->overflow_handler)
5494 event->overflow_handler(event, data, regs);
5496 perf_event_output(event, data, regs);
5498 if (event->fasync && event->pending_kill) {
5499 event->pending_wakeup = 1;
5500 irq_work_queue(&event->pending);
5506 int perf_event_overflow(struct perf_event *event,
5507 struct perf_sample_data *data,
5508 struct pt_regs *regs)
5510 return __perf_event_overflow(event, 1, data, regs);
5514 * Generic software event infrastructure
5517 struct swevent_htable {
5518 struct swevent_hlist *swevent_hlist;
5519 struct mutex hlist_mutex;
5522 /* Recursion avoidance in each contexts */
5523 int recursion[PERF_NR_CONTEXTS];
5525 /* Keeps track of cpu being initialized/exited */
5529 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
5532 * We directly increment event->count and keep a second value in
5533 * event->hw.period_left to count intervals. This period event
5534 * is kept in the range [-sample_period, 0] so that we can use the
5538 u64 perf_swevent_set_period(struct perf_event *event)
5540 struct hw_perf_event *hwc = &event->hw;
5541 u64 period = hwc->last_period;
5545 hwc->last_period = hwc->sample_period;
5548 old = val = local64_read(&hwc->period_left);
5552 nr = div64_u64(period + val, period);
5553 offset = nr * period;
5555 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
5561 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
5562 struct perf_sample_data *data,
5563 struct pt_regs *regs)
5565 struct hw_perf_event *hwc = &event->hw;
5569 overflow = perf_swevent_set_period(event);
5571 if (hwc->interrupts == MAX_INTERRUPTS)
5574 for (; overflow; overflow--) {
5575 if (__perf_event_overflow(event, throttle,
5578 * We inhibit the overflow from happening when
5579 * hwc->interrupts == MAX_INTERRUPTS.
5587 static void perf_swevent_event(struct perf_event *event, u64 nr,
5588 struct perf_sample_data *data,
5589 struct pt_regs *regs)
5591 struct hw_perf_event *hwc = &event->hw;
5593 local64_add(nr, &event->count);
5598 if (!is_sampling_event(event))
5601 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
5603 return perf_swevent_overflow(event, 1, data, regs);
5605 data->period = event->hw.last_period;
5607 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
5608 return perf_swevent_overflow(event, 1, data, regs);
5610 if (local64_add_negative(nr, &hwc->period_left))
5613 perf_swevent_overflow(event, 0, data, regs);
5616 static int perf_exclude_event(struct perf_event *event,
5617 struct pt_regs *regs)
5619 if (event->hw.state & PERF_HES_STOPPED)
5623 if (event->attr.exclude_user && user_mode(regs))
5626 if (event->attr.exclude_kernel && !user_mode(regs))
5633 static int perf_swevent_match(struct perf_event *event,
5634 enum perf_type_id type,
5636 struct perf_sample_data *data,
5637 struct pt_regs *regs)
5639 if (event->attr.type != type)
5642 if (event->attr.config != event_id)
5645 if (perf_exclude_event(event, regs))
5651 static inline u64 swevent_hash(u64 type, u32 event_id)
5653 u64 val = event_id | (type << 32);
5655 return hash_64(val, SWEVENT_HLIST_BITS);
5658 static inline struct hlist_head *
5659 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
5661 u64 hash = swevent_hash(type, event_id);
5663 return &hlist->heads[hash];
5666 /* For the read side: events when they trigger */
5667 static inline struct hlist_head *
5668 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
5670 struct swevent_hlist *hlist;
5672 hlist = rcu_dereference(swhash->swevent_hlist);
5676 return __find_swevent_head(hlist, type, event_id);
5679 /* For the event head insertion and removal in the hlist */
5680 static inline struct hlist_head *
5681 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
5683 struct swevent_hlist *hlist;
5684 u32 event_id = event->attr.config;
5685 u64 type = event->attr.type;
5688 * Event scheduling is always serialized against hlist allocation
5689 * and release. Which makes the protected version suitable here.
5690 * The context lock guarantees that.
5692 hlist = rcu_dereference_protected(swhash->swevent_hlist,
5693 lockdep_is_held(&event->ctx->lock));
5697 return __find_swevent_head(hlist, type, event_id);
5700 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
5702 struct perf_sample_data *data,
5703 struct pt_regs *regs)
5705 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5706 struct perf_event *event;
5707 struct hlist_head *head;
5710 head = find_swevent_head_rcu(swhash, type, event_id);
5714 hlist_for_each_entry_rcu(event, head, hlist_entry) {
5715 if (perf_swevent_match(event, type, event_id, data, regs))
5716 perf_swevent_event(event, nr, data, regs);
5722 int perf_swevent_get_recursion_context(void)
5724 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5726 return get_recursion_context(swhash->recursion);
5728 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
5730 inline void perf_swevent_put_recursion_context(int rctx)
5732 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5734 put_recursion_context(swhash->recursion, rctx);
5737 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
5739 struct perf_sample_data data;
5742 preempt_disable_notrace();
5743 rctx = perf_swevent_get_recursion_context();
5747 perf_sample_data_init(&data, addr, 0);
5749 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
5751 perf_swevent_put_recursion_context(rctx);
5752 preempt_enable_notrace();
5755 static void perf_swevent_read(struct perf_event *event)
5759 static int perf_swevent_add(struct perf_event *event, int flags)
5761 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5762 struct hw_perf_event *hwc = &event->hw;
5763 struct hlist_head *head;
5765 if (is_sampling_event(event)) {
5766 hwc->last_period = hwc->sample_period;
5767 perf_swevent_set_period(event);
5770 hwc->state = !(flags & PERF_EF_START);
5772 head = find_swevent_head(swhash, event);
5775 * We can race with cpu hotplug code. Do not
5776 * WARN if the cpu just got unplugged.
5778 WARN_ON_ONCE(swhash->online);
5782 hlist_add_head_rcu(&event->hlist_entry, head);
5787 static void perf_swevent_del(struct perf_event *event, int flags)
5789 hlist_del_rcu(&event->hlist_entry);
5792 static void perf_swevent_start(struct perf_event *event, int flags)
5794 event->hw.state = 0;
5797 static void perf_swevent_stop(struct perf_event *event, int flags)
5799 event->hw.state = PERF_HES_STOPPED;
5802 /* Deref the hlist from the update side */
5803 static inline struct swevent_hlist *
5804 swevent_hlist_deref(struct swevent_htable *swhash)
5806 return rcu_dereference_protected(swhash->swevent_hlist,
5807 lockdep_is_held(&swhash->hlist_mutex));
5810 static void swevent_hlist_release(struct swevent_htable *swhash)
5812 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
5817 rcu_assign_pointer(swhash->swevent_hlist, NULL);
5818 kfree_rcu(hlist, rcu_head);
5821 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
5823 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5825 mutex_lock(&swhash->hlist_mutex);
5827 if (!--swhash->hlist_refcount)
5828 swevent_hlist_release(swhash);
5830 mutex_unlock(&swhash->hlist_mutex);
5833 static void swevent_hlist_put(struct perf_event *event)
5837 for_each_possible_cpu(cpu)
5838 swevent_hlist_put_cpu(event, cpu);
5841 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
5843 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5846 mutex_lock(&swhash->hlist_mutex);
5848 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
5849 struct swevent_hlist *hlist;
5851 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
5856 rcu_assign_pointer(swhash->swevent_hlist, hlist);
5858 swhash->hlist_refcount++;
5860 mutex_unlock(&swhash->hlist_mutex);
5865 static int swevent_hlist_get(struct perf_event *event)
5868 int cpu, failed_cpu;
5871 for_each_possible_cpu(cpu) {
5872 err = swevent_hlist_get_cpu(event, cpu);
5882 for_each_possible_cpu(cpu) {
5883 if (cpu == failed_cpu)
5885 swevent_hlist_put_cpu(event, cpu);
5892 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
5894 static void sw_perf_event_destroy(struct perf_event *event)
5896 u64 event_id = event->attr.config;
5898 WARN_ON(event->parent);
5900 static_key_slow_dec(&perf_swevent_enabled[event_id]);
5901 swevent_hlist_put(event);
5904 static int perf_swevent_init(struct perf_event *event)
5906 u64 event_id = event->attr.config;
5908 if (event->attr.type != PERF_TYPE_SOFTWARE)
5912 * no branch sampling for software events
5914 if (has_branch_stack(event))
5918 case PERF_COUNT_SW_CPU_CLOCK:
5919 case PERF_COUNT_SW_TASK_CLOCK:
5926 if (event_id >= PERF_COUNT_SW_MAX)
5929 if (!event->parent) {
5932 err = swevent_hlist_get(event);
5936 static_key_slow_inc(&perf_swevent_enabled[event_id]);
5937 event->destroy = sw_perf_event_destroy;
5943 static int perf_swevent_event_idx(struct perf_event *event)
5948 static struct pmu perf_swevent = {
5949 .task_ctx_nr = perf_sw_context,
5951 .event_init = perf_swevent_init,
5952 .add = perf_swevent_add,
5953 .del = perf_swevent_del,
5954 .start = perf_swevent_start,
5955 .stop = perf_swevent_stop,
5956 .read = perf_swevent_read,
5958 .event_idx = perf_swevent_event_idx,
5961 #ifdef CONFIG_EVENT_TRACING
5963 static int perf_tp_filter_match(struct perf_event *event,
5964 struct perf_sample_data *data)
5966 void *record = data->raw->data;
5968 if (likely(!event->filter) || filter_match_preds(event->filter, record))
5973 static int perf_tp_event_match(struct perf_event *event,
5974 struct perf_sample_data *data,
5975 struct pt_regs *regs)
5977 if (event->hw.state & PERF_HES_STOPPED)
5980 * All tracepoints are from kernel-space.
5982 if (event->attr.exclude_kernel)
5985 if (!perf_tp_filter_match(event, data))
5991 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
5992 struct pt_regs *regs, struct hlist_head *head, int rctx,
5993 struct task_struct *task)
5995 struct perf_sample_data data;
5996 struct perf_event *event;
5998 struct perf_raw_record raw = {
6003 perf_sample_data_init(&data, addr, 0);
6006 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6007 if (perf_tp_event_match(event, &data, regs))
6008 perf_swevent_event(event, count, &data, regs);
6012 * If we got specified a target task, also iterate its context and
6013 * deliver this event there too.
6015 if (task && task != current) {
6016 struct perf_event_context *ctx;
6017 struct trace_entry *entry = record;
6020 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
6024 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
6025 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6027 if (event->attr.config != entry->type)
6029 if (perf_tp_event_match(event, &data, regs))
6030 perf_swevent_event(event, count, &data, regs);
6036 perf_swevent_put_recursion_context(rctx);
6038 EXPORT_SYMBOL_GPL(perf_tp_event);
6040 static void tp_perf_event_destroy(struct perf_event *event)
6042 perf_trace_destroy(event);
6045 static int perf_tp_event_init(struct perf_event *event)
6049 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6053 * no branch sampling for tracepoint events
6055 if (has_branch_stack(event))
6058 err = perf_trace_init(event);
6062 event->destroy = tp_perf_event_destroy;
6067 static struct pmu perf_tracepoint = {
6068 .task_ctx_nr = perf_sw_context,
6070 .event_init = perf_tp_event_init,
6071 .add = perf_trace_add,
6072 .del = perf_trace_del,
6073 .start = perf_swevent_start,
6074 .stop = perf_swevent_stop,
6075 .read = perf_swevent_read,
6077 .event_idx = perf_swevent_event_idx,
6080 static inline void perf_tp_register(void)
6082 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
6085 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
6090 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6093 filter_str = strndup_user(arg, PAGE_SIZE);
6094 if (IS_ERR(filter_str))
6095 return PTR_ERR(filter_str);
6097 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
6103 static void perf_event_free_filter(struct perf_event *event)
6105 ftrace_profile_free_filter(event);
6110 static inline void perf_tp_register(void)
6114 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
6119 static void perf_event_free_filter(struct perf_event *event)
6123 #endif /* CONFIG_EVENT_TRACING */
6125 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6126 void perf_bp_event(struct perf_event *bp, void *data)
6128 struct perf_sample_data sample;
6129 struct pt_regs *regs = data;
6131 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
6133 if (!bp->hw.state && !perf_exclude_event(bp, regs))
6134 perf_swevent_event(bp, 1, &sample, regs);
6139 * hrtimer based swevent callback
6142 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
6144 enum hrtimer_restart ret = HRTIMER_RESTART;
6145 struct perf_sample_data data;
6146 struct pt_regs *regs;
6147 struct perf_event *event;
6150 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
6152 if (event->state != PERF_EVENT_STATE_ACTIVE)
6153 return HRTIMER_NORESTART;
6155 event->pmu->read(event);
6157 perf_sample_data_init(&data, 0, event->hw.last_period);
6158 regs = get_irq_regs();
6160 if (regs && !perf_exclude_event(event, regs)) {
6161 if (!(event->attr.exclude_idle && is_idle_task(current)))
6162 if (__perf_event_overflow(event, 1, &data, regs))
6163 ret = HRTIMER_NORESTART;
6166 period = max_t(u64, 10000, event->hw.sample_period);
6167 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
6172 static void perf_swevent_start_hrtimer(struct perf_event *event)
6174 struct hw_perf_event *hwc = &event->hw;
6177 if (!is_sampling_event(event))
6180 period = local64_read(&hwc->period_left);
6185 local64_set(&hwc->period_left, 0);
6187 period = max_t(u64, 10000, hwc->sample_period);
6189 __hrtimer_start_range_ns(&hwc->hrtimer,
6190 ns_to_ktime(period), 0,
6191 HRTIMER_MODE_REL_PINNED, 0);
6194 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
6196 struct hw_perf_event *hwc = &event->hw;
6198 if (is_sampling_event(event)) {
6199 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
6200 local64_set(&hwc->period_left, ktime_to_ns(remaining));
6202 hrtimer_cancel(&hwc->hrtimer);
6206 static void perf_swevent_init_hrtimer(struct perf_event *event)
6208 struct hw_perf_event *hwc = &event->hw;
6210 if (!is_sampling_event(event))
6213 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6214 hwc->hrtimer.function = perf_swevent_hrtimer;
6217 * Since hrtimers have a fixed rate, we can do a static freq->period
6218 * mapping and avoid the whole period adjust feedback stuff.
6220 if (event->attr.freq) {
6221 long freq = event->attr.sample_freq;
6223 event->attr.sample_period = NSEC_PER_SEC / freq;
6224 hwc->sample_period = event->attr.sample_period;
6225 local64_set(&hwc->period_left, hwc->sample_period);
6226 hwc->last_period = hwc->sample_period;
6227 event->attr.freq = 0;
6232 * Software event: cpu wall time clock
6235 static void cpu_clock_event_update(struct perf_event *event)
6240 now = local_clock();
6241 prev = local64_xchg(&event->hw.prev_count, now);
6242 local64_add(now - prev, &event->count);
6245 static void cpu_clock_event_start(struct perf_event *event, int flags)
6247 local64_set(&event->hw.prev_count, local_clock());
6248 perf_swevent_start_hrtimer(event);
6251 static void cpu_clock_event_stop(struct perf_event *event, int flags)
6253 perf_swevent_cancel_hrtimer(event);
6254 cpu_clock_event_update(event);
6257 static int cpu_clock_event_add(struct perf_event *event, int flags)
6259 if (flags & PERF_EF_START)
6260 cpu_clock_event_start(event, flags);
6265 static void cpu_clock_event_del(struct perf_event *event, int flags)
6267 cpu_clock_event_stop(event, flags);
6270 static void cpu_clock_event_read(struct perf_event *event)
6272 cpu_clock_event_update(event);
6275 static int cpu_clock_event_init(struct perf_event *event)
6277 if (event->attr.type != PERF_TYPE_SOFTWARE)
6280 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
6284 * no branch sampling for software events
6286 if (has_branch_stack(event))
6289 perf_swevent_init_hrtimer(event);
6294 static struct pmu perf_cpu_clock = {
6295 .task_ctx_nr = perf_sw_context,
6297 .event_init = cpu_clock_event_init,
6298 .add = cpu_clock_event_add,
6299 .del = cpu_clock_event_del,
6300 .start = cpu_clock_event_start,
6301 .stop = cpu_clock_event_stop,
6302 .read = cpu_clock_event_read,
6304 .event_idx = perf_swevent_event_idx,
6308 * Software event: task time clock
6311 static void task_clock_event_update(struct perf_event *event, u64 now)
6316 prev = local64_xchg(&event->hw.prev_count, now);
6318 local64_add(delta, &event->count);
6321 static void task_clock_event_start(struct perf_event *event, int flags)
6323 local64_set(&event->hw.prev_count, event->ctx->time);
6324 perf_swevent_start_hrtimer(event);
6327 static void task_clock_event_stop(struct perf_event *event, int flags)
6329 perf_swevent_cancel_hrtimer(event);
6330 task_clock_event_update(event, event->ctx->time);
6333 static int task_clock_event_add(struct perf_event *event, int flags)
6335 if (flags & PERF_EF_START)
6336 task_clock_event_start(event, flags);
6341 static void task_clock_event_del(struct perf_event *event, int flags)
6343 task_clock_event_stop(event, PERF_EF_UPDATE);
6346 static void task_clock_event_read(struct perf_event *event)
6348 u64 now = perf_clock();
6349 u64 delta = now - event->ctx->timestamp;
6350 u64 time = event->ctx->time + delta;
6352 task_clock_event_update(event, time);
6355 static int task_clock_event_init(struct perf_event *event)
6357 if (event->attr.type != PERF_TYPE_SOFTWARE)
6360 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
6364 * no branch sampling for software events
6366 if (has_branch_stack(event))
6369 perf_swevent_init_hrtimer(event);
6374 static struct pmu perf_task_clock = {
6375 .task_ctx_nr = perf_sw_context,
6377 .event_init = task_clock_event_init,
6378 .add = task_clock_event_add,
6379 .del = task_clock_event_del,
6380 .start = task_clock_event_start,
6381 .stop = task_clock_event_stop,
6382 .read = task_clock_event_read,
6384 .event_idx = perf_swevent_event_idx,
6387 static void perf_pmu_nop_void(struct pmu *pmu)
6391 static int perf_pmu_nop_int(struct pmu *pmu)
6396 static void perf_pmu_start_txn(struct pmu *pmu)
6398 perf_pmu_disable(pmu);
6401 static int perf_pmu_commit_txn(struct pmu *pmu)
6403 perf_pmu_enable(pmu);
6407 static void perf_pmu_cancel_txn(struct pmu *pmu)
6409 perf_pmu_enable(pmu);
6412 static int perf_event_idx_default(struct perf_event *event)
6414 return event->hw.idx + 1;
6418 * Ensures all contexts with the same task_ctx_nr have the same
6419 * pmu_cpu_context too.
6421 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
6428 list_for_each_entry(pmu, &pmus, entry) {
6429 if (pmu->task_ctx_nr == ctxn)
6430 return pmu->pmu_cpu_context;
6436 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
6440 for_each_possible_cpu(cpu) {
6441 struct perf_cpu_context *cpuctx;
6443 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6445 if (cpuctx->unique_pmu == old_pmu)
6446 cpuctx->unique_pmu = pmu;
6450 static void free_pmu_context(struct pmu *pmu)
6454 mutex_lock(&pmus_lock);
6456 * Like a real lame refcount.
6458 list_for_each_entry(i, &pmus, entry) {
6459 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
6460 update_pmu_context(i, pmu);
6465 free_percpu(pmu->pmu_cpu_context);
6467 mutex_unlock(&pmus_lock);
6469 static struct idr pmu_idr;
6472 type_show(struct device *dev, struct device_attribute *attr, char *page)
6474 struct pmu *pmu = dev_get_drvdata(dev);
6476 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
6478 static DEVICE_ATTR_RO(type);
6481 perf_event_mux_interval_ms_show(struct device *dev,
6482 struct device_attribute *attr,
6485 struct pmu *pmu = dev_get_drvdata(dev);
6487 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
6491 perf_event_mux_interval_ms_store(struct device *dev,
6492 struct device_attribute *attr,
6493 const char *buf, size_t count)
6495 struct pmu *pmu = dev_get_drvdata(dev);
6496 int timer, cpu, ret;
6498 ret = kstrtoint(buf, 0, &timer);
6505 /* same value, noting to do */
6506 if (timer == pmu->hrtimer_interval_ms)
6509 pmu->hrtimer_interval_ms = timer;
6511 /* update all cpuctx for this PMU */
6512 for_each_possible_cpu(cpu) {
6513 struct perf_cpu_context *cpuctx;
6514 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6515 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
6517 if (hrtimer_active(&cpuctx->hrtimer))
6518 hrtimer_forward_now(&cpuctx->hrtimer, cpuctx->hrtimer_interval);
6523 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
6525 static struct attribute *pmu_dev_attrs[] = {
6526 &dev_attr_type.attr,
6527 &dev_attr_perf_event_mux_interval_ms.attr,
6530 ATTRIBUTE_GROUPS(pmu_dev);
6532 static int pmu_bus_running;
6533 static struct bus_type pmu_bus = {
6534 .name = "event_source",
6535 .dev_groups = pmu_dev_groups,
6538 static void pmu_dev_release(struct device *dev)
6543 static int pmu_dev_alloc(struct pmu *pmu)
6547 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
6551 pmu->dev->groups = pmu->attr_groups;
6552 device_initialize(pmu->dev);
6553 ret = dev_set_name(pmu->dev, "%s", pmu->name);
6557 dev_set_drvdata(pmu->dev, pmu);
6558 pmu->dev->bus = &pmu_bus;
6559 pmu->dev->release = pmu_dev_release;
6560 ret = device_add(pmu->dev);
6568 put_device(pmu->dev);
6572 static struct lock_class_key cpuctx_mutex;
6573 static struct lock_class_key cpuctx_lock;
6575 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
6579 mutex_lock(&pmus_lock);
6581 pmu->pmu_disable_count = alloc_percpu(int);
6582 if (!pmu->pmu_disable_count)
6591 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
6599 if (pmu_bus_running) {
6600 ret = pmu_dev_alloc(pmu);
6606 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
6607 if (pmu->pmu_cpu_context)
6608 goto got_cpu_context;
6611 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
6612 if (!pmu->pmu_cpu_context)
6615 for_each_possible_cpu(cpu) {
6616 struct perf_cpu_context *cpuctx;
6618 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6619 __perf_event_init_context(&cpuctx->ctx);
6620 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
6621 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
6622 cpuctx->ctx.type = cpu_context;
6623 cpuctx->ctx.pmu = pmu;
6625 __perf_cpu_hrtimer_init(cpuctx, cpu);
6627 INIT_LIST_HEAD(&cpuctx->rotation_list);
6628 cpuctx->unique_pmu = pmu;
6632 if (!pmu->start_txn) {
6633 if (pmu->pmu_enable) {
6635 * If we have pmu_enable/pmu_disable calls, install
6636 * transaction stubs that use that to try and batch
6637 * hardware accesses.
6639 pmu->start_txn = perf_pmu_start_txn;
6640 pmu->commit_txn = perf_pmu_commit_txn;
6641 pmu->cancel_txn = perf_pmu_cancel_txn;
6643 pmu->start_txn = perf_pmu_nop_void;
6644 pmu->commit_txn = perf_pmu_nop_int;
6645 pmu->cancel_txn = perf_pmu_nop_void;
6649 if (!pmu->pmu_enable) {
6650 pmu->pmu_enable = perf_pmu_nop_void;
6651 pmu->pmu_disable = perf_pmu_nop_void;
6654 if (!pmu->event_idx)
6655 pmu->event_idx = perf_event_idx_default;
6657 list_add_rcu(&pmu->entry, &pmus);
6660 mutex_unlock(&pmus_lock);
6665 device_del(pmu->dev);
6666 put_device(pmu->dev);
6669 if (pmu->type >= PERF_TYPE_MAX)
6670 idr_remove(&pmu_idr, pmu->type);
6673 free_percpu(pmu->pmu_disable_count);
6676 EXPORT_SYMBOL_GPL(perf_pmu_register);
6678 void perf_pmu_unregister(struct pmu *pmu)
6680 mutex_lock(&pmus_lock);
6681 list_del_rcu(&pmu->entry);
6682 mutex_unlock(&pmus_lock);
6685 * We dereference the pmu list under both SRCU and regular RCU, so
6686 * synchronize against both of those.
6688 synchronize_srcu(&pmus_srcu);
6691 free_percpu(pmu->pmu_disable_count);
6692 if (pmu->type >= PERF_TYPE_MAX)
6693 idr_remove(&pmu_idr, pmu->type);
6694 device_del(pmu->dev);
6695 put_device(pmu->dev);
6696 free_pmu_context(pmu);
6698 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
6700 struct pmu *perf_init_event(struct perf_event *event)
6702 struct pmu *pmu = NULL;
6706 idx = srcu_read_lock(&pmus_srcu);
6709 pmu = idr_find(&pmu_idr, event->attr.type);
6712 if (!try_module_get(pmu->module)) {
6713 pmu = ERR_PTR(-ENODEV);
6717 ret = pmu->event_init(event);
6723 list_for_each_entry_rcu(pmu, &pmus, entry) {
6724 if (!try_module_get(pmu->module)) {
6725 pmu = ERR_PTR(-ENODEV);
6729 ret = pmu->event_init(event);
6733 if (ret != -ENOENT) {
6738 pmu = ERR_PTR(-ENOENT);
6740 srcu_read_unlock(&pmus_srcu, idx);
6745 static void account_event_cpu(struct perf_event *event, int cpu)
6750 if (has_branch_stack(event)) {
6751 if (!(event->attach_state & PERF_ATTACH_TASK))
6752 atomic_inc(&per_cpu(perf_branch_stack_events, cpu));
6754 if (is_cgroup_event(event))
6755 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
6758 static void account_event(struct perf_event *event)
6763 if (event->attach_state & PERF_ATTACH_TASK)
6764 static_key_slow_inc(&perf_sched_events.key);
6765 if (event->attr.mmap || event->attr.mmap_data)
6766 atomic_inc(&nr_mmap_events);
6767 if (event->attr.comm)
6768 atomic_inc(&nr_comm_events);
6769 if (event->attr.task)
6770 atomic_inc(&nr_task_events);
6771 if (event->attr.freq) {
6772 if (atomic_inc_return(&nr_freq_events) == 1)
6773 tick_nohz_full_kick_all();
6775 if (has_branch_stack(event))
6776 static_key_slow_inc(&perf_sched_events.key);
6777 if (is_cgroup_event(event))
6778 static_key_slow_inc(&perf_sched_events.key);
6780 account_event_cpu(event, event->cpu);
6784 * Allocate and initialize a event structure
6786 static struct perf_event *
6787 perf_event_alloc(struct perf_event_attr *attr, int cpu,
6788 struct task_struct *task,
6789 struct perf_event *group_leader,
6790 struct perf_event *parent_event,
6791 perf_overflow_handler_t overflow_handler,
6795 struct perf_event *event;
6796 struct hw_perf_event *hwc;
6799 if ((unsigned)cpu >= nr_cpu_ids) {
6800 if (!task || cpu != -1)
6801 return ERR_PTR(-EINVAL);
6804 event = kzalloc(sizeof(*event), GFP_KERNEL);
6806 return ERR_PTR(-ENOMEM);
6809 * Single events are their own group leaders, with an
6810 * empty sibling list:
6813 group_leader = event;
6815 mutex_init(&event->child_mutex);
6816 INIT_LIST_HEAD(&event->child_list);
6818 INIT_LIST_HEAD(&event->group_entry);
6819 INIT_LIST_HEAD(&event->event_entry);
6820 INIT_LIST_HEAD(&event->sibling_list);
6821 INIT_LIST_HEAD(&event->rb_entry);
6822 INIT_LIST_HEAD(&event->active_entry);
6823 INIT_HLIST_NODE(&event->hlist_entry);
6826 init_waitqueue_head(&event->waitq);
6827 init_irq_work(&event->pending, perf_pending_event);
6829 mutex_init(&event->mmap_mutex);
6831 atomic_long_set(&event->refcount, 1);
6833 event->attr = *attr;
6834 event->group_leader = group_leader;
6838 event->parent = parent_event;
6840 event->ns = get_pid_ns(task_active_pid_ns(current));
6841 event->id = atomic64_inc_return(&perf_event_id);
6843 event->state = PERF_EVENT_STATE_INACTIVE;
6846 event->attach_state = PERF_ATTACH_TASK;
6848 if (attr->type == PERF_TYPE_TRACEPOINT)
6849 event->hw.tp_target = task;
6850 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6852 * hw_breakpoint is a bit difficult here..
6854 else if (attr->type == PERF_TYPE_BREAKPOINT)
6855 event->hw.bp_target = task;
6859 if (!overflow_handler && parent_event) {
6860 overflow_handler = parent_event->overflow_handler;
6861 context = parent_event->overflow_handler_context;
6864 event->overflow_handler = overflow_handler;
6865 event->overflow_handler_context = context;
6867 perf_event__state_init(event);
6872 hwc->sample_period = attr->sample_period;
6873 if (attr->freq && attr->sample_freq)
6874 hwc->sample_period = 1;
6875 hwc->last_period = hwc->sample_period;
6877 local64_set(&hwc->period_left, hwc->sample_period);
6880 * we currently do not support PERF_FORMAT_GROUP on inherited events
6882 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
6885 pmu = perf_init_event(event);
6888 else if (IS_ERR(pmu)) {
6893 if (!event->parent) {
6894 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
6895 err = get_callchain_buffers();
6905 event->destroy(event);
6906 module_put(pmu->module);
6909 put_pid_ns(event->ns);
6912 return ERR_PTR(err);
6915 static int perf_copy_attr(struct perf_event_attr __user *uattr,
6916 struct perf_event_attr *attr)
6921 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
6925 * zero the full structure, so that a short copy will be nice.
6927 memset(attr, 0, sizeof(*attr));
6929 ret = get_user(size, &uattr->size);
6933 if (size > PAGE_SIZE) /* silly large */
6936 if (!size) /* abi compat */
6937 size = PERF_ATTR_SIZE_VER0;
6939 if (size < PERF_ATTR_SIZE_VER0)
6943 * If we're handed a bigger struct than we know of,
6944 * ensure all the unknown bits are 0 - i.e. new
6945 * user-space does not rely on any kernel feature
6946 * extensions we dont know about yet.
6948 if (size > sizeof(*attr)) {
6949 unsigned char __user *addr;
6950 unsigned char __user *end;
6953 addr = (void __user *)uattr + sizeof(*attr);
6954 end = (void __user *)uattr + size;
6956 for (; addr < end; addr++) {
6957 ret = get_user(val, addr);
6963 size = sizeof(*attr);
6966 ret = copy_from_user(attr, uattr, size);
6970 if (attr->__reserved_1)
6973 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
6976 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
6979 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
6980 u64 mask = attr->branch_sample_type;
6982 /* only using defined bits */
6983 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
6986 /* at least one branch bit must be set */
6987 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
6990 /* propagate priv level, when not set for branch */
6991 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
6993 /* exclude_kernel checked on syscall entry */
6994 if (!attr->exclude_kernel)
6995 mask |= PERF_SAMPLE_BRANCH_KERNEL;
6997 if (!attr->exclude_user)
6998 mask |= PERF_SAMPLE_BRANCH_USER;
7000 if (!attr->exclude_hv)
7001 mask |= PERF_SAMPLE_BRANCH_HV;
7003 * adjust user setting (for HW filter setup)
7005 attr->branch_sample_type = mask;
7007 /* privileged levels capture (kernel, hv): check permissions */
7008 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
7009 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
7013 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
7014 ret = perf_reg_validate(attr->sample_regs_user);
7019 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
7020 if (!arch_perf_have_user_stack_dump())
7024 * We have __u32 type for the size, but so far
7025 * we can only use __u16 as maximum due to the
7026 * __u16 sample size limit.
7028 if (attr->sample_stack_user >= USHRT_MAX)
7030 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
7038 put_user(sizeof(*attr), &uattr->size);
7044 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
7046 struct ring_buffer *rb = NULL;
7052 /* don't allow circular references */
7053 if (event == output_event)
7057 * Don't allow cross-cpu buffers
7059 if (output_event->cpu != event->cpu)
7063 * If its not a per-cpu rb, it must be the same task.
7065 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
7069 mutex_lock(&event->mmap_mutex);
7070 /* Can't redirect output if we've got an active mmap() */
7071 if (atomic_read(&event->mmap_count))
7075 /* get the rb we want to redirect to */
7076 rb = ring_buffer_get(output_event);
7081 ring_buffer_attach(event, rb);
7085 mutex_unlock(&event->mmap_mutex);
7092 * sys_perf_event_open - open a performance event, associate it to a task/cpu
7094 * @attr_uptr: event_id type attributes for monitoring/sampling
7097 * @group_fd: group leader event fd
7099 SYSCALL_DEFINE5(perf_event_open,
7100 struct perf_event_attr __user *, attr_uptr,
7101 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
7103 struct perf_event *group_leader = NULL, *output_event = NULL;
7104 struct perf_event *event, *sibling;
7105 struct perf_event_attr attr;
7106 struct perf_event_context *ctx;
7107 struct file *event_file = NULL;
7108 struct fd group = {NULL, 0};
7109 struct task_struct *task = NULL;
7114 int f_flags = O_RDWR;
7116 /* for future expandability... */
7117 if (flags & ~PERF_FLAG_ALL)
7120 err = perf_copy_attr(attr_uptr, &attr);
7124 if (!attr.exclude_kernel) {
7125 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
7130 if (attr.sample_freq > sysctl_perf_event_sample_rate)
7133 if (attr.sample_period & (1ULL << 63))
7138 * In cgroup mode, the pid argument is used to pass the fd
7139 * opened to the cgroup directory in cgroupfs. The cpu argument
7140 * designates the cpu on which to monitor threads from that
7143 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
7146 if (flags & PERF_FLAG_FD_CLOEXEC)
7147 f_flags |= O_CLOEXEC;
7149 event_fd = get_unused_fd_flags(f_flags);
7153 if (group_fd != -1) {
7154 err = perf_fget_light(group_fd, &group);
7157 group_leader = group.file->private_data;
7158 if (flags & PERF_FLAG_FD_OUTPUT)
7159 output_event = group_leader;
7160 if (flags & PERF_FLAG_FD_NO_GROUP)
7161 group_leader = NULL;
7164 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
7165 task = find_lively_task_by_vpid(pid);
7167 err = PTR_ERR(task);
7172 if (task && group_leader &&
7173 group_leader->attr.inherit != attr.inherit) {
7180 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
7182 if (IS_ERR(event)) {
7183 err = PTR_ERR(event);
7187 if (flags & PERF_FLAG_PID_CGROUP) {
7188 err = perf_cgroup_connect(pid, event, &attr, group_leader);
7190 __free_event(event);
7195 if (is_sampling_event(event)) {
7196 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
7202 account_event(event);
7205 * Special case software events and allow them to be part of
7206 * any hardware group.
7211 (is_software_event(event) != is_software_event(group_leader))) {
7212 if (is_software_event(event)) {
7214 * If event and group_leader are not both a software
7215 * event, and event is, then group leader is not.
7217 * Allow the addition of software events to !software
7218 * groups, this is safe because software events never
7221 pmu = group_leader->pmu;
7222 } else if (is_software_event(group_leader) &&
7223 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
7225 * In case the group is a pure software group, and we
7226 * try to add a hardware event, move the whole group to
7227 * the hardware context.
7234 * Get the target context (task or percpu):
7236 ctx = find_get_context(pmu, task, event->cpu);
7243 put_task_struct(task);
7248 * Look up the group leader (we will attach this event to it):
7254 * Do not allow a recursive hierarchy (this new sibling
7255 * becoming part of another group-sibling):
7257 if (group_leader->group_leader != group_leader)
7260 * Do not allow to attach to a group in a different
7261 * task or CPU context:
7264 if (group_leader->ctx->type != ctx->type)
7267 if (group_leader->ctx != ctx)
7272 * Only a group leader can be exclusive or pinned
7274 if (attr.exclusive || attr.pinned)
7279 err = perf_event_set_output(event, output_event);
7284 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
7286 if (IS_ERR(event_file)) {
7287 err = PTR_ERR(event_file);
7292 struct perf_event_context *gctx = group_leader->ctx;
7294 mutex_lock(&gctx->mutex);
7295 perf_remove_from_context(group_leader, false);
7298 * Removing from the context ends up with disabled
7299 * event. What we want here is event in the initial
7300 * startup state, ready to be add into new context.
7302 perf_event__state_init(group_leader);
7303 list_for_each_entry(sibling, &group_leader->sibling_list,
7305 perf_remove_from_context(sibling, false);
7306 perf_event__state_init(sibling);
7309 mutex_unlock(&gctx->mutex);
7313 WARN_ON_ONCE(ctx->parent_ctx);
7314 mutex_lock(&ctx->mutex);
7318 perf_install_in_context(ctx, group_leader, event->cpu);
7320 list_for_each_entry(sibling, &group_leader->sibling_list,
7322 perf_install_in_context(ctx, sibling, event->cpu);
7327 perf_install_in_context(ctx, event, event->cpu);
7328 perf_unpin_context(ctx);
7329 mutex_unlock(&ctx->mutex);
7333 event->owner = current;
7335 mutex_lock(¤t->perf_event_mutex);
7336 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
7337 mutex_unlock(¤t->perf_event_mutex);
7340 * Precalculate sample_data sizes
7342 perf_event__header_size(event);
7343 perf_event__id_header_size(event);
7346 * Drop the reference on the group_event after placing the
7347 * new event on the sibling_list. This ensures destruction
7348 * of the group leader will find the pointer to itself in
7349 * perf_group_detach().
7352 fd_install(event_fd, event_file);
7356 perf_unpin_context(ctx);
7364 put_task_struct(task);
7368 put_unused_fd(event_fd);
7373 * perf_event_create_kernel_counter
7375 * @attr: attributes of the counter to create
7376 * @cpu: cpu in which the counter is bound
7377 * @task: task to profile (NULL for percpu)
7380 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
7381 struct task_struct *task,
7382 perf_overflow_handler_t overflow_handler,
7385 struct perf_event_context *ctx;
7386 struct perf_event *event;
7390 * Get the target context (task or percpu):
7393 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
7394 overflow_handler, context);
7395 if (IS_ERR(event)) {
7396 err = PTR_ERR(event);
7400 account_event(event);
7402 ctx = find_get_context(event->pmu, task, cpu);
7408 WARN_ON_ONCE(ctx->parent_ctx);
7409 mutex_lock(&ctx->mutex);
7410 perf_install_in_context(ctx, event, cpu);
7411 perf_unpin_context(ctx);
7412 mutex_unlock(&ctx->mutex);
7419 return ERR_PTR(err);
7421 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
7423 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
7425 struct perf_event_context *src_ctx;
7426 struct perf_event_context *dst_ctx;
7427 struct perf_event *event, *tmp;
7430 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
7431 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
7433 mutex_lock(&src_ctx->mutex);
7434 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
7436 perf_remove_from_context(event, false);
7437 unaccount_event_cpu(event, src_cpu);
7439 list_add(&event->migrate_entry, &events);
7441 mutex_unlock(&src_ctx->mutex);
7445 mutex_lock(&dst_ctx->mutex);
7446 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
7447 list_del(&event->migrate_entry);
7448 if (event->state >= PERF_EVENT_STATE_OFF)
7449 event->state = PERF_EVENT_STATE_INACTIVE;
7450 account_event_cpu(event, dst_cpu);
7451 perf_install_in_context(dst_ctx, event, dst_cpu);
7454 mutex_unlock(&dst_ctx->mutex);
7456 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
7458 static void sync_child_event(struct perf_event *child_event,
7459 struct task_struct *child)
7461 struct perf_event *parent_event = child_event->parent;
7464 if (child_event->attr.inherit_stat)
7465 perf_event_read_event(child_event, child);
7467 child_val = perf_event_count(child_event);
7470 * Add back the child's count to the parent's count:
7472 atomic64_add(child_val, &parent_event->child_count);
7473 atomic64_add(child_event->total_time_enabled,
7474 &parent_event->child_total_time_enabled);
7475 atomic64_add(child_event->total_time_running,
7476 &parent_event->child_total_time_running);
7479 * Remove this event from the parent's list
7481 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7482 mutex_lock(&parent_event->child_mutex);
7483 list_del_init(&child_event->child_list);
7484 mutex_unlock(&parent_event->child_mutex);
7487 * Release the parent event, if this was the last
7490 put_event(parent_event);
7494 __perf_event_exit_task(struct perf_event *child_event,
7495 struct perf_event_context *child_ctx,
7496 struct task_struct *child)
7499 * Do not destroy the 'original' grouping; because of the context
7500 * switch optimization the original events could've ended up in a
7501 * random child task.
7503 * If we were to destroy the original group, all group related
7504 * operations would cease to function properly after this random
7507 * Do destroy all inherited groups, we don't care about those
7508 * and being thorough is better.
7510 perf_remove_from_context(child_event, !!child_event->parent);
7513 * It can happen that the parent exits first, and has events
7514 * that are still around due to the child reference. These
7515 * events need to be zapped.
7517 if (child_event->parent) {
7518 sync_child_event(child_event, child);
7519 free_event(child_event);
7523 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
7525 struct perf_event *child_event, *next;
7526 struct perf_event_context *child_ctx, *parent_ctx;
7527 unsigned long flags;
7529 if (likely(!child->perf_event_ctxp[ctxn])) {
7530 perf_event_task(child, NULL, 0);
7534 local_irq_save(flags);
7536 * We can't reschedule here because interrupts are disabled,
7537 * and either child is current or it is a task that can't be
7538 * scheduled, so we are now safe from rescheduling changing
7541 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
7544 * Take the context lock here so that if find_get_context is
7545 * reading child->perf_event_ctxp, we wait until it has
7546 * incremented the context's refcount before we do put_ctx below.
7548 raw_spin_lock(&child_ctx->lock);
7549 task_ctx_sched_out(child_ctx);
7550 child->perf_event_ctxp[ctxn] = NULL;
7553 * In order to avoid freeing: child_ctx->parent_ctx->task
7554 * under perf_event_context::lock, grab another reference.
7556 parent_ctx = child_ctx->parent_ctx;
7558 get_ctx(parent_ctx);
7561 * If this context is a clone; unclone it so it can't get
7562 * swapped to another process while we're removing all
7563 * the events from it.
7565 unclone_ctx(child_ctx);
7566 update_context_time(child_ctx);
7567 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7570 * Now that we no longer hold perf_event_context::lock, drop
7571 * our extra child_ctx->parent_ctx reference.
7574 put_ctx(parent_ctx);
7577 * Report the task dead after unscheduling the events so that we
7578 * won't get any samples after PERF_RECORD_EXIT. We can however still
7579 * get a few PERF_RECORD_READ events.
7581 perf_event_task(child, child_ctx, 0);
7584 * We can recurse on the same lock type through:
7586 * __perf_event_exit_task()
7587 * sync_child_event()
7589 * mutex_lock(&ctx->mutex)
7591 * But since its the parent context it won't be the same instance.
7593 mutex_lock(&child_ctx->mutex);
7595 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
7596 __perf_event_exit_task(child_event, child_ctx, child);
7598 mutex_unlock(&child_ctx->mutex);
7604 * When a child task exits, feed back event values to parent events.
7606 void perf_event_exit_task(struct task_struct *child)
7608 struct perf_event *event, *tmp;
7611 mutex_lock(&child->perf_event_mutex);
7612 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
7614 list_del_init(&event->owner_entry);
7617 * Ensure the list deletion is visible before we clear
7618 * the owner, closes a race against perf_release() where
7619 * we need to serialize on the owner->perf_event_mutex.
7622 event->owner = NULL;
7624 mutex_unlock(&child->perf_event_mutex);
7626 for_each_task_context_nr(ctxn)
7627 perf_event_exit_task_context(child, ctxn);
7630 static void perf_free_event(struct perf_event *event,
7631 struct perf_event_context *ctx)
7633 struct perf_event *parent = event->parent;
7635 if (WARN_ON_ONCE(!parent))
7638 mutex_lock(&parent->child_mutex);
7639 list_del_init(&event->child_list);
7640 mutex_unlock(&parent->child_mutex);
7644 perf_group_detach(event);
7645 list_del_event(event, ctx);
7650 * free an unexposed, unused context as created by inheritance by
7651 * perf_event_init_task below, used by fork() in case of fail.
7653 void perf_event_free_task(struct task_struct *task)
7655 struct perf_event_context *ctx;
7656 struct perf_event *event, *tmp;
7659 for_each_task_context_nr(ctxn) {
7660 ctx = task->perf_event_ctxp[ctxn];
7664 mutex_lock(&ctx->mutex);
7666 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
7668 perf_free_event(event, ctx);
7670 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
7672 perf_free_event(event, ctx);
7674 if (!list_empty(&ctx->pinned_groups) ||
7675 !list_empty(&ctx->flexible_groups))
7678 mutex_unlock(&ctx->mutex);
7684 void perf_event_delayed_put(struct task_struct *task)
7688 for_each_task_context_nr(ctxn)
7689 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
7693 * inherit a event from parent task to child task:
7695 static struct perf_event *
7696 inherit_event(struct perf_event *parent_event,
7697 struct task_struct *parent,
7698 struct perf_event_context *parent_ctx,
7699 struct task_struct *child,
7700 struct perf_event *group_leader,
7701 struct perf_event_context *child_ctx)
7703 struct perf_event *child_event;
7704 unsigned long flags;
7707 * Instead of creating recursive hierarchies of events,
7708 * we link inherited events back to the original parent,
7709 * which has a filp for sure, which we use as the reference
7712 if (parent_event->parent)
7713 parent_event = parent_event->parent;
7715 child_event = perf_event_alloc(&parent_event->attr,
7718 group_leader, parent_event,
7720 if (IS_ERR(child_event))
7723 if (!atomic_long_inc_not_zero(&parent_event->refcount)) {
7724 free_event(child_event);
7731 * Make the child state follow the state of the parent event,
7732 * not its attr.disabled bit. We hold the parent's mutex,
7733 * so we won't race with perf_event_{en, dis}able_family.
7735 if (parent_event->state >= PERF_EVENT_STATE_INACTIVE)
7736 child_event->state = PERF_EVENT_STATE_INACTIVE;
7738 child_event->state = PERF_EVENT_STATE_OFF;
7740 if (parent_event->attr.freq) {
7741 u64 sample_period = parent_event->hw.sample_period;
7742 struct hw_perf_event *hwc = &child_event->hw;
7744 hwc->sample_period = sample_period;
7745 hwc->last_period = sample_period;
7747 local64_set(&hwc->period_left, sample_period);
7750 child_event->ctx = child_ctx;
7751 child_event->overflow_handler = parent_event->overflow_handler;
7752 child_event->overflow_handler_context
7753 = parent_event->overflow_handler_context;
7756 * Precalculate sample_data sizes
7758 perf_event__header_size(child_event);
7759 perf_event__id_header_size(child_event);
7762 * Link it up in the child's context:
7764 raw_spin_lock_irqsave(&child_ctx->lock, flags);
7765 add_event_to_ctx(child_event, child_ctx);
7766 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7769 * Link this into the parent event's child list
7771 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7772 mutex_lock(&parent_event->child_mutex);
7773 list_add_tail(&child_event->child_list, &parent_event->child_list);
7774 mutex_unlock(&parent_event->child_mutex);
7779 static int inherit_group(struct perf_event *parent_event,
7780 struct task_struct *parent,
7781 struct perf_event_context *parent_ctx,
7782 struct task_struct *child,
7783 struct perf_event_context *child_ctx)
7785 struct perf_event *leader;
7786 struct perf_event *sub;
7787 struct perf_event *child_ctr;
7789 leader = inherit_event(parent_event, parent, parent_ctx,
7790 child, NULL, child_ctx);
7792 return PTR_ERR(leader);
7793 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
7794 child_ctr = inherit_event(sub, parent, parent_ctx,
7795 child, leader, child_ctx);
7796 if (IS_ERR(child_ctr))
7797 return PTR_ERR(child_ctr);
7803 inherit_task_group(struct perf_event *event, struct task_struct *parent,
7804 struct perf_event_context *parent_ctx,
7805 struct task_struct *child, int ctxn,
7809 struct perf_event_context *child_ctx;
7811 if (!event->attr.inherit) {
7816 child_ctx = child->perf_event_ctxp[ctxn];
7819 * This is executed from the parent task context, so
7820 * inherit events that have been marked for cloning.
7821 * First allocate and initialize a context for the
7825 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
7829 child->perf_event_ctxp[ctxn] = child_ctx;
7832 ret = inherit_group(event, parent, parent_ctx,
7842 * Initialize the perf_event context in task_struct
7844 static int perf_event_init_context(struct task_struct *child, int ctxn)
7846 struct perf_event_context *child_ctx, *parent_ctx;
7847 struct perf_event_context *cloned_ctx;
7848 struct perf_event *event;
7849 struct task_struct *parent = current;
7850 int inherited_all = 1;
7851 unsigned long flags;
7854 if (likely(!parent->perf_event_ctxp[ctxn]))
7858 * If the parent's context is a clone, pin it so it won't get
7861 parent_ctx = perf_pin_task_context(parent, ctxn);
7866 * No need to check if parent_ctx != NULL here; since we saw
7867 * it non-NULL earlier, the only reason for it to become NULL
7868 * is if we exit, and since we're currently in the middle of
7869 * a fork we can't be exiting at the same time.
7873 * Lock the parent list. No need to lock the child - not PID
7874 * hashed yet and not running, so nobody can access it.
7876 mutex_lock(&parent_ctx->mutex);
7879 * We dont have to disable NMIs - we are only looking at
7880 * the list, not manipulating it:
7882 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
7883 ret = inherit_task_group(event, parent, parent_ctx,
7884 child, ctxn, &inherited_all);
7890 * We can't hold ctx->lock when iterating the ->flexible_group list due
7891 * to allocations, but we need to prevent rotation because
7892 * rotate_ctx() will change the list from interrupt context.
7894 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7895 parent_ctx->rotate_disable = 1;
7896 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7898 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
7899 ret = inherit_task_group(event, parent, parent_ctx,
7900 child, ctxn, &inherited_all);
7905 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7906 parent_ctx->rotate_disable = 0;
7908 child_ctx = child->perf_event_ctxp[ctxn];
7910 if (child_ctx && inherited_all) {
7912 * Mark the child context as a clone of the parent
7913 * context, or of whatever the parent is a clone of.
7915 * Note that if the parent is a clone, the holding of
7916 * parent_ctx->lock avoids it from being uncloned.
7918 cloned_ctx = parent_ctx->parent_ctx;
7920 child_ctx->parent_ctx = cloned_ctx;
7921 child_ctx->parent_gen = parent_ctx->parent_gen;
7923 child_ctx->parent_ctx = parent_ctx;
7924 child_ctx->parent_gen = parent_ctx->generation;
7926 get_ctx(child_ctx->parent_ctx);
7929 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7930 mutex_unlock(&parent_ctx->mutex);
7932 perf_unpin_context(parent_ctx);
7933 put_ctx(parent_ctx);
7939 * Initialize the perf_event context in task_struct
7941 int perf_event_init_task(struct task_struct *child)
7945 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
7946 mutex_init(&child->perf_event_mutex);
7947 INIT_LIST_HEAD(&child->perf_event_list);
7949 for_each_task_context_nr(ctxn) {
7950 ret = perf_event_init_context(child, ctxn);
7952 perf_event_free_task(child);
7960 static void __init perf_event_init_all_cpus(void)
7962 struct swevent_htable *swhash;
7965 for_each_possible_cpu(cpu) {
7966 swhash = &per_cpu(swevent_htable, cpu);
7967 mutex_init(&swhash->hlist_mutex);
7968 INIT_LIST_HEAD(&per_cpu(rotation_list, cpu));
7972 static void perf_event_init_cpu(int cpu)
7974 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7976 mutex_lock(&swhash->hlist_mutex);
7977 swhash->online = true;
7978 if (swhash->hlist_refcount > 0) {
7979 struct swevent_hlist *hlist;
7981 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
7983 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7985 mutex_unlock(&swhash->hlist_mutex);
7988 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC
7989 static void perf_pmu_rotate_stop(struct pmu *pmu)
7991 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7993 WARN_ON(!irqs_disabled());
7995 list_del_init(&cpuctx->rotation_list);
7998 static void __perf_event_exit_context(void *__info)
8000 struct remove_event re = { .detach_group = false };
8001 struct perf_event_context *ctx = __info;
8003 perf_pmu_rotate_stop(ctx->pmu);
8006 list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
8007 __perf_remove_from_context(&re);
8011 static void perf_event_exit_cpu_context(int cpu)
8013 struct perf_event_context *ctx;
8017 idx = srcu_read_lock(&pmus_srcu);
8018 list_for_each_entry_rcu(pmu, &pmus, entry) {
8019 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
8021 mutex_lock(&ctx->mutex);
8022 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
8023 mutex_unlock(&ctx->mutex);
8025 srcu_read_unlock(&pmus_srcu, idx);
8028 static void perf_event_exit_cpu(int cpu)
8030 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
8032 perf_event_exit_cpu_context(cpu);
8034 mutex_lock(&swhash->hlist_mutex);
8035 swhash->online = false;
8036 swevent_hlist_release(swhash);
8037 mutex_unlock(&swhash->hlist_mutex);
8040 static inline void perf_event_exit_cpu(int cpu) { }
8044 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
8048 for_each_online_cpu(cpu)
8049 perf_event_exit_cpu(cpu);
8055 * Run the perf reboot notifier at the very last possible moment so that
8056 * the generic watchdog code runs as long as possible.
8058 static struct notifier_block perf_reboot_notifier = {
8059 .notifier_call = perf_reboot,
8060 .priority = INT_MIN,
8064 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
8066 unsigned int cpu = (long)hcpu;
8068 switch (action & ~CPU_TASKS_FROZEN) {
8070 case CPU_UP_PREPARE:
8071 case CPU_DOWN_FAILED:
8072 perf_event_init_cpu(cpu);
8075 case CPU_UP_CANCELED:
8076 case CPU_DOWN_PREPARE:
8077 perf_event_exit_cpu(cpu);
8086 void __init perf_event_init(void)
8092 perf_event_init_all_cpus();
8093 init_srcu_struct(&pmus_srcu);
8094 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
8095 perf_pmu_register(&perf_cpu_clock, NULL, -1);
8096 perf_pmu_register(&perf_task_clock, NULL, -1);
8098 perf_cpu_notifier(perf_cpu_notify);
8099 register_reboot_notifier(&perf_reboot_notifier);
8101 ret = init_hw_breakpoint();
8102 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
8104 /* do not patch jump label more than once per second */
8105 jump_label_rate_limit(&perf_sched_events, HZ);
8108 * Build time assertion that we keep the data_head at the intended
8109 * location. IOW, validation we got the __reserved[] size right.
8111 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
8115 static int __init perf_event_sysfs_init(void)
8120 mutex_lock(&pmus_lock);
8122 ret = bus_register(&pmu_bus);
8126 list_for_each_entry(pmu, &pmus, entry) {
8127 if (!pmu->name || pmu->type < 0)
8130 ret = pmu_dev_alloc(pmu);
8131 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
8133 pmu_bus_running = 1;
8137 mutex_unlock(&pmus_lock);
8141 device_initcall(perf_event_sysfs_init);
8143 #ifdef CONFIG_CGROUP_PERF
8144 static struct cgroup_subsys_state *
8145 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
8147 struct perf_cgroup *jc;
8149 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
8151 return ERR_PTR(-ENOMEM);
8153 jc->info = alloc_percpu(struct perf_cgroup_info);
8156 return ERR_PTR(-ENOMEM);
8162 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
8164 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
8166 free_percpu(jc->info);
8170 static int __perf_cgroup_move(void *info)
8172 struct task_struct *task = info;
8173 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
8177 static void perf_cgroup_attach(struct cgroup_subsys_state *css,
8178 struct cgroup_taskset *tset)
8180 struct task_struct *task;
8182 cgroup_taskset_for_each(task, tset)
8183 task_function_call(task, __perf_cgroup_move, task);
8186 static void perf_cgroup_exit(struct cgroup_subsys_state *css,
8187 struct cgroup_subsys_state *old_css,
8188 struct task_struct *task)
8191 * cgroup_exit() is called in the copy_process() failure path.
8192 * Ignore this case since the task hasn't ran yet, this avoids
8193 * trying to poke a half freed task state from generic code.
8195 if (!(task->flags & PF_EXITING))
8198 task_function_call(task, __perf_cgroup_move, task);
8201 struct cgroup_subsys perf_event_cgrp_subsys = {
8202 .css_alloc = perf_cgroup_css_alloc,
8203 .css_free = perf_cgroup_css_free,
8204 .exit = perf_cgroup_exit,
8205 .attach = perf_cgroup_attach,
8207 #endif /* CONFIG_CGROUP_PERF */