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);
906 * This must be done under the ctx->lock, such as to serialize against
907 * context_equiv(), therefore we cannot call put_ctx() since that might end up
908 * calling scheduler related locks and ctx->lock nests inside those.
910 static __must_check struct perf_event_context *
911 unclone_ctx(struct perf_event_context *ctx)
913 struct perf_event_context *parent_ctx = ctx->parent_ctx;
915 lockdep_assert_held(&ctx->lock);
918 ctx->parent_ctx = NULL;
924 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
927 * only top level events have the pid namespace they were created in
930 event = event->parent;
932 return task_tgid_nr_ns(p, event->ns);
935 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
938 * only top level events have the pid namespace they were created in
941 event = event->parent;
943 return task_pid_nr_ns(p, event->ns);
947 * If we inherit events we want to return the parent event id
950 static u64 primary_event_id(struct perf_event *event)
955 id = event->parent->id;
961 * Get the perf_event_context for a task and lock it.
962 * This has to cope with with the fact that until it is locked,
963 * the context could get moved to another task.
965 static struct perf_event_context *
966 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
968 struct perf_event_context *ctx;
972 * One of the few rules of preemptible RCU is that one cannot do
973 * rcu_read_unlock() while holding a scheduler (or nested) lock when
974 * part of the read side critical section was preemptible -- see
975 * rcu_read_unlock_special().
977 * Since ctx->lock nests under rq->lock we must ensure the entire read
978 * side critical section is non-preemptible.
982 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
985 * If this context is a clone of another, it might
986 * get swapped for another underneath us by
987 * perf_event_task_sched_out, though the
988 * rcu_read_lock() protects us from any context
989 * getting freed. Lock the context and check if it
990 * got swapped before we could get the lock, and retry
991 * if so. If we locked the right context, then it
992 * can't get swapped on us any more.
994 raw_spin_lock_irqsave(&ctx->lock, *flags);
995 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
996 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
1002 if (!atomic_inc_not_zero(&ctx->refcount)) {
1003 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
1013 * Get the context for a task and increment its pin_count so it
1014 * can't get swapped to another task. This also increments its
1015 * reference count so that the context can't get freed.
1017 static struct perf_event_context *
1018 perf_pin_task_context(struct task_struct *task, int ctxn)
1020 struct perf_event_context *ctx;
1021 unsigned long flags;
1023 ctx = perf_lock_task_context(task, ctxn, &flags);
1026 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1031 static void perf_unpin_context(struct perf_event_context *ctx)
1033 unsigned long flags;
1035 raw_spin_lock_irqsave(&ctx->lock, flags);
1037 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1041 * Update the record of the current time in a context.
1043 static void update_context_time(struct perf_event_context *ctx)
1045 u64 now = perf_clock();
1047 ctx->time += now - ctx->timestamp;
1048 ctx->timestamp = now;
1051 static u64 perf_event_time(struct perf_event *event)
1053 struct perf_event_context *ctx = event->ctx;
1055 if (is_cgroup_event(event))
1056 return perf_cgroup_event_time(event);
1058 return ctx ? ctx->time : 0;
1062 * Update the total_time_enabled and total_time_running fields for a event.
1063 * The caller of this function needs to hold the ctx->lock.
1065 static void update_event_times(struct perf_event *event)
1067 struct perf_event_context *ctx = event->ctx;
1070 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1071 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1074 * in cgroup mode, time_enabled represents
1075 * the time the event was enabled AND active
1076 * tasks were in the monitored cgroup. This is
1077 * independent of the activity of the context as
1078 * there may be a mix of cgroup and non-cgroup events.
1080 * That is why we treat cgroup events differently
1083 if (is_cgroup_event(event))
1084 run_end = perf_cgroup_event_time(event);
1085 else if (ctx->is_active)
1086 run_end = ctx->time;
1088 run_end = event->tstamp_stopped;
1090 event->total_time_enabled = run_end - event->tstamp_enabled;
1092 if (event->state == PERF_EVENT_STATE_INACTIVE)
1093 run_end = event->tstamp_stopped;
1095 run_end = perf_event_time(event);
1097 event->total_time_running = run_end - event->tstamp_running;
1102 * Update total_time_enabled and total_time_running for all events in a group.
1104 static void update_group_times(struct perf_event *leader)
1106 struct perf_event *event;
1108 update_event_times(leader);
1109 list_for_each_entry(event, &leader->sibling_list, group_entry)
1110 update_event_times(event);
1113 static struct list_head *
1114 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1116 if (event->attr.pinned)
1117 return &ctx->pinned_groups;
1119 return &ctx->flexible_groups;
1123 * Add a event from the lists for its context.
1124 * Must be called with ctx->mutex and ctx->lock held.
1127 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1129 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1130 event->attach_state |= PERF_ATTACH_CONTEXT;
1133 * If we're a stand alone event or group leader, we go to the context
1134 * list, group events are kept attached to the group so that
1135 * perf_group_detach can, at all times, locate all siblings.
1137 if (event->group_leader == event) {
1138 struct list_head *list;
1140 if (is_software_event(event))
1141 event->group_flags |= PERF_GROUP_SOFTWARE;
1143 list = ctx_group_list(event, ctx);
1144 list_add_tail(&event->group_entry, list);
1147 if (is_cgroup_event(event))
1150 if (has_branch_stack(event))
1151 ctx->nr_branch_stack++;
1153 list_add_rcu(&event->event_entry, &ctx->event_list);
1154 if (!ctx->nr_events)
1155 perf_pmu_rotate_start(ctx->pmu);
1157 if (event->attr.inherit_stat)
1164 * Initialize event state based on the perf_event_attr::disabled.
1166 static inline void perf_event__state_init(struct perf_event *event)
1168 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1169 PERF_EVENT_STATE_INACTIVE;
1173 * Called at perf_event creation and when events are attached/detached from a
1176 static void perf_event__read_size(struct perf_event *event)
1178 int entry = sizeof(u64); /* value */
1182 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1183 size += sizeof(u64);
1185 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1186 size += sizeof(u64);
1188 if (event->attr.read_format & PERF_FORMAT_ID)
1189 entry += sizeof(u64);
1191 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1192 nr += event->group_leader->nr_siblings;
1193 size += sizeof(u64);
1197 event->read_size = size;
1200 static void perf_event__header_size(struct perf_event *event)
1202 struct perf_sample_data *data;
1203 u64 sample_type = event->attr.sample_type;
1206 perf_event__read_size(event);
1208 if (sample_type & PERF_SAMPLE_IP)
1209 size += sizeof(data->ip);
1211 if (sample_type & PERF_SAMPLE_ADDR)
1212 size += sizeof(data->addr);
1214 if (sample_type & PERF_SAMPLE_PERIOD)
1215 size += sizeof(data->period);
1217 if (sample_type & PERF_SAMPLE_WEIGHT)
1218 size += sizeof(data->weight);
1220 if (sample_type & PERF_SAMPLE_READ)
1221 size += event->read_size;
1223 if (sample_type & PERF_SAMPLE_DATA_SRC)
1224 size += sizeof(data->data_src.val);
1226 if (sample_type & PERF_SAMPLE_TRANSACTION)
1227 size += sizeof(data->txn);
1229 event->header_size = size;
1232 static void perf_event__id_header_size(struct perf_event *event)
1234 struct perf_sample_data *data;
1235 u64 sample_type = event->attr.sample_type;
1238 if (sample_type & PERF_SAMPLE_TID)
1239 size += sizeof(data->tid_entry);
1241 if (sample_type & PERF_SAMPLE_TIME)
1242 size += sizeof(data->time);
1244 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1245 size += sizeof(data->id);
1247 if (sample_type & PERF_SAMPLE_ID)
1248 size += sizeof(data->id);
1250 if (sample_type & PERF_SAMPLE_STREAM_ID)
1251 size += sizeof(data->stream_id);
1253 if (sample_type & PERF_SAMPLE_CPU)
1254 size += sizeof(data->cpu_entry);
1256 event->id_header_size = size;
1259 static void perf_group_attach(struct perf_event *event)
1261 struct perf_event *group_leader = event->group_leader, *pos;
1264 * We can have double attach due to group movement in perf_event_open.
1266 if (event->attach_state & PERF_ATTACH_GROUP)
1269 event->attach_state |= PERF_ATTACH_GROUP;
1271 if (group_leader == event)
1274 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1275 !is_software_event(event))
1276 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1278 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1279 group_leader->nr_siblings++;
1281 perf_event__header_size(group_leader);
1283 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1284 perf_event__header_size(pos);
1288 * Remove a event from the lists for its context.
1289 * Must be called with ctx->mutex and ctx->lock held.
1292 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1294 struct perf_cpu_context *cpuctx;
1296 * We can have double detach due to exit/hot-unplug + close.
1298 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1301 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1303 if (is_cgroup_event(event)) {
1305 cpuctx = __get_cpu_context(ctx);
1307 * if there are no more cgroup events
1308 * then cler cgrp to avoid stale pointer
1309 * in update_cgrp_time_from_cpuctx()
1311 if (!ctx->nr_cgroups)
1312 cpuctx->cgrp = NULL;
1315 if (has_branch_stack(event))
1316 ctx->nr_branch_stack--;
1319 if (event->attr.inherit_stat)
1322 list_del_rcu(&event->event_entry);
1324 if (event->group_leader == event)
1325 list_del_init(&event->group_entry);
1327 update_group_times(event);
1330 * If event was in error state, then keep it
1331 * that way, otherwise bogus counts will be
1332 * returned on read(). The only way to get out
1333 * of error state is by explicit re-enabling
1336 if (event->state > PERF_EVENT_STATE_OFF)
1337 event->state = PERF_EVENT_STATE_OFF;
1342 static void perf_group_detach(struct perf_event *event)
1344 struct perf_event *sibling, *tmp;
1345 struct list_head *list = NULL;
1348 * We can have double detach due to exit/hot-unplug + close.
1350 if (!(event->attach_state & PERF_ATTACH_GROUP))
1353 event->attach_state &= ~PERF_ATTACH_GROUP;
1356 * If this is a sibling, remove it from its group.
1358 if (event->group_leader != event) {
1359 list_del_init(&event->group_entry);
1360 event->group_leader->nr_siblings--;
1364 if (!list_empty(&event->group_entry))
1365 list = &event->group_entry;
1368 * If this was a group event with sibling events then
1369 * upgrade the siblings to singleton events by adding them
1370 * to whatever list we are on.
1372 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1374 list_move_tail(&sibling->group_entry, list);
1375 sibling->group_leader = sibling;
1377 /* Inherit group flags from the previous leader */
1378 sibling->group_flags = event->group_flags;
1382 perf_event__header_size(event->group_leader);
1384 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1385 perf_event__header_size(tmp);
1389 event_filter_match(struct perf_event *event)
1391 return (event->cpu == -1 || event->cpu == smp_processor_id())
1392 && perf_cgroup_match(event);
1396 event_sched_out(struct perf_event *event,
1397 struct perf_cpu_context *cpuctx,
1398 struct perf_event_context *ctx)
1400 u64 tstamp = perf_event_time(event);
1403 * An event which could not be activated because of
1404 * filter mismatch still needs to have its timings
1405 * maintained, otherwise bogus information is return
1406 * via read() for time_enabled, time_running:
1408 if (event->state == PERF_EVENT_STATE_INACTIVE
1409 && !event_filter_match(event)) {
1410 delta = tstamp - event->tstamp_stopped;
1411 event->tstamp_running += delta;
1412 event->tstamp_stopped = tstamp;
1415 if (event->state != PERF_EVENT_STATE_ACTIVE)
1418 perf_pmu_disable(event->pmu);
1420 event->state = PERF_EVENT_STATE_INACTIVE;
1421 if (event->pending_disable) {
1422 event->pending_disable = 0;
1423 event->state = PERF_EVENT_STATE_OFF;
1425 event->tstamp_stopped = tstamp;
1426 event->pmu->del(event, 0);
1429 if (!is_software_event(event))
1430 cpuctx->active_oncpu--;
1432 if (event->attr.freq && event->attr.sample_freq)
1434 if (event->attr.exclusive || !cpuctx->active_oncpu)
1435 cpuctx->exclusive = 0;
1437 perf_pmu_enable(event->pmu);
1441 group_sched_out(struct perf_event *group_event,
1442 struct perf_cpu_context *cpuctx,
1443 struct perf_event_context *ctx)
1445 struct perf_event *event;
1446 int state = group_event->state;
1448 event_sched_out(group_event, cpuctx, ctx);
1451 * Schedule out siblings (if any):
1453 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1454 event_sched_out(event, cpuctx, ctx);
1456 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1457 cpuctx->exclusive = 0;
1460 struct remove_event {
1461 struct perf_event *event;
1466 * Cross CPU call to remove a performance event
1468 * We disable the event on the hardware level first. After that we
1469 * remove it from the context list.
1471 static int __perf_remove_from_context(void *info)
1473 struct remove_event *re = info;
1474 struct perf_event *event = re->event;
1475 struct perf_event_context *ctx = event->ctx;
1476 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1478 raw_spin_lock(&ctx->lock);
1479 event_sched_out(event, cpuctx, ctx);
1480 if (re->detach_group)
1481 perf_group_detach(event);
1482 list_del_event(event, ctx);
1483 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1485 cpuctx->task_ctx = NULL;
1487 raw_spin_unlock(&ctx->lock);
1494 * Remove the event from a task's (or a CPU's) list of events.
1496 * CPU events are removed with a smp call. For task events we only
1497 * call when the task is on a CPU.
1499 * If event->ctx is a cloned context, callers must make sure that
1500 * every task struct that event->ctx->task could possibly point to
1501 * remains valid. This is OK when called from perf_release since
1502 * that only calls us on the top-level context, which can't be a clone.
1503 * When called from perf_event_exit_task, it's OK because the
1504 * context has been detached from its task.
1506 static void perf_remove_from_context(struct perf_event *event, bool detach_group)
1508 struct perf_event_context *ctx = event->ctx;
1509 struct task_struct *task = ctx->task;
1510 struct remove_event re = {
1512 .detach_group = detach_group,
1515 lockdep_assert_held(&ctx->mutex);
1519 * Per cpu events are removed via an smp call and
1520 * the removal is always successful.
1522 cpu_function_call(event->cpu, __perf_remove_from_context, &re);
1527 if (!task_function_call(task, __perf_remove_from_context, &re))
1530 raw_spin_lock_irq(&ctx->lock);
1532 * If we failed to find a running task, but find the context active now
1533 * that we've acquired the ctx->lock, retry.
1535 if (ctx->is_active) {
1536 raw_spin_unlock_irq(&ctx->lock);
1538 * Reload the task pointer, it might have been changed by
1539 * a concurrent perf_event_context_sched_out().
1546 * Since the task isn't running, its safe to remove the event, us
1547 * holding the ctx->lock ensures the task won't get scheduled in.
1550 perf_group_detach(event);
1551 list_del_event(event, ctx);
1552 raw_spin_unlock_irq(&ctx->lock);
1556 * Cross CPU call to disable a performance event
1558 int __perf_event_disable(void *info)
1560 struct perf_event *event = info;
1561 struct perf_event_context *ctx = event->ctx;
1562 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1565 * If this is a per-task event, need to check whether this
1566 * event's task is the current task on this cpu.
1568 * Can trigger due to concurrent perf_event_context_sched_out()
1569 * flipping contexts around.
1571 if (ctx->task && cpuctx->task_ctx != ctx)
1574 raw_spin_lock(&ctx->lock);
1577 * If the event is on, turn it off.
1578 * If it is in error state, leave it in error state.
1580 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1581 update_context_time(ctx);
1582 update_cgrp_time_from_event(event);
1583 update_group_times(event);
1584 if (event == event->group_leader)
1585 group_sched_out(event, cpuctx, ctx);
1587 event_sched_out(event, cpuctx, ctx);
1588 event->state = PERF_EVENT_STATE_OFF;
1591 raw_spin_unlock(&ctx->lock);
1599 * If event->ctx is a cloned context, callers must make sure that
1600 * every task struct that event->ctx->task could possibly point to
1601 * remains valid. This condition is satisifed when called through
1602 * perf_event_for_each_child or perf_event_for_each because they
1603 * hold the top-level event's child_mutex, so any descendant that
1604 * goes to exit will block in sync_child_event.
1605 * When called from perf_pending_event it's OK because event->ctx
1606 * is the current context on this CPU and preemption is disabled,
1607 * hence we can't get into perf_event_task_sched_out for this context.
1609 void perf_event_disable(struct perf_event *event)
1611 struct perf_event_context *ctx = event->ctx;
1612 struct task_struct *task = ctx->task;
1616 * Disable the event on the cpu that it's on
1618 cpu_function_call(event->cpu, __perf_event_disable, event);
1623 if (!task_function_call(task, __perf_event_disable, event))
1626 raw_spin_lock_irq(&ctx->lock);
1628 * If the event is still active, we need to retry the cross-call.
1630 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1631 raw_spin_unlock_irq(&ctx->lock);
1633 * Reload the task pointer, it might have been changed by
1634 * a concurrent perf_event_context_sched_out().
1641 * Since we have the lock this context can't be scheduled
1642 * in, so we can change the state safely.
1644 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1645 update_group_times(event);
1646 event->state = PERF_EVENT_STATE_OFF;
1648 raw_spin_unlock_irq(&ctx->lock);
1650 EXPORT_SYMBOL_GPL(perf_event_disable);
1652 static void perf_set_shadow_time(struct perf_event *event,
1653 struct perf_event_context *ctx,
1657 * use the correct time source for the time snapshot
1659 * We could get by without this by leveraging the
1660 * fact that to get to this function, the caller
1661 * has most likely already called update_context_time()
1662 * and update_cgrp_time_xx() and thus both timestamp
1663 * are identical (or very close). Given that tstamp is,
1664 * already adjusted for cgroup, we could say that:
1665 * tstamp - ctx->timestamp
1667 * tstamp - cgrp->timestamp.
1669 * Then, in perf_output_read(), the calculation would
1670 * work with no changes because:
1671 * - event is guaranteed scheduled in
1672 * - no scheduled out in between
1673 * - thus the timestamp would be the same
1675 * But this is a bit hairy.
1677 * So instead, we have an explicit cgroup call to remain
1678 * within the time time source all along. We believe it
1679 * is cleaner and simpler to understand.
1681 if (is_cgroup_event(event))
1682 perf_cgroup_set_shadow_time(event, tstamp);
1684 event->shadow_ctx_time = tstamp - ctx->timestamp;
1687 #define MAX_INTERRUPTS (~0ULL)
1689 static void perf_log_throttle(struct perf_event *event, int enable);
1692 event_sched_in(struct perf_event *event,
1693 struct perf_cpu_context *cpuctx,
1694 struct perf_event_context *ctx)
1696 u64 tstamp = perf_event_time(event);
1699 lockdep_assert_held(&ctx->lock);
1701 if (event->state <= PERF_EVENT_STATE_OFF)
1704 event->state = PERF_EVENT_STATE_ACTIVE;
1705 event->oncpu = smp_processor_id();
1708 * Unthrottle events, since we scheduled we might have missed several
1709 * ticks already, also for a heavily scheduling task there is little
1710 * guarantee it'll get a tick in a timely manner.
1712 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1713 perf_log_throttle(event, 1);
1714 event->hw.interrupts = 0;
1718 * The new state must be visible before we turn it on in the hardware:
1722 perf_pmu_disable(event->pmu);
1724 if (event->pmu->add(event, PERF_EF_START)) {
1725 event->state = PERF_EVENT_STATE_INACTIVE;
1731 event->tstamp_running += tstamp - event->tstamp_stopped;
1733 perf_set_shadow_time(event, ctx, tstamp);
1735 if (!is_software_event(event))
1736 cpuctx->active_oncpu++;
1738 if (event->attr.freq && event->attr.sample_freq)
1741 if (event->attr.exclusive)
1742 cpuctx->exclusive = 1;
1745 perf_pmu_enable(event->pmu);
1751 group_sched_in(struct perf_event *group_event,
1752 struct perf_cpu_context *cpuctx,
1753 struct perf_event_context *ctx)
1755 struct perf_event *event, *partial_group = NULL;
1756 struct pmu *pmu = ctx->pmu;
1757 u64 now = ctx->time;
1758 bool simulate = false;
1760 if (group_event->state == PERF_EVENT_STATE_OFF)
1763 pmu->start_txn(pmu);
1765 if (event_sched_in(group_event, cpuctx, ctx)) {
1766 pmu->cancel_txn(pmu);
1767 perf_cpu_hrtimer_restart(cpuctx);
1772 * Schedule in siblings as one group (if any):
1774 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1775 if (event_sched_in(event, cpuctx, ctx)) {
1776 partial_group = event;
1781 if (!pmu->commit_txn(pmu))
1786 * Groups can be scheduled in as one unit only, so undo any
1787 * partial group before returning:
1788 * The events up to the failed event are scheduled out normally,
1789 * tstamp_stopped will be updated.
1791 * The failed events and the remaining siblings need to have
1792 * their timings updated as if they had gone thru event_sched_in()
1793 * and event_sched_out(). This is required to get consistent timings
1794 * across the group. This also takes care of the case where the group
1795 * could never be scheduled by ensuring tstamp_stopped is set to mark
1796 * the time the event was actually stopped, such that time delta
1797 * calculation in update_event_times() is correct.
1799 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1800 if (event == partial_group)
1804 event->tstamp_running += now - event->tstamp_stopped;
1805 event->tstamp_stopped = now;
1807 event_sched_out(event, cpuctx, ctx);
1810 event_sched_out(group_event, cpuctx, ctx);
1812 pmu->cancel_txn(pmu);
1814 perf_cpu_hrtimer_restart(cpuctx);
1820 * Work out whether we can put this event group on the CPU now.
1822 static int group_can_go_on(struct perf_event *event,
1823 struct perf_cpu_context *cpuctx,
1827 * Groups consisting entirely of software events can always go on.
1829 if (event->group_flags & PERF_GROUP_SOFTWARE)
1832 * If an exclusive group is already on, no other hardware
1835 if (cpuctx->exclusive)
1838 * If this group is exclusive and there are already
1839 * events on the CPU, it can't go on.
1841 if (event->attr.exclusive && cpuctx->active_oncpu)
1844 * Otherwise, try to add it if all previous groups were able
1850 static void add_event_to_ctx(struct perf_event *event,
1851 struct perf_event_context *ctx)
1853 u64 tstamp = perf_event_time(event);
1855 list_add_event(event, ctx);
1856 perf_group_attach(event);
1857 event->tstamp_enabled = tstamp;
1858 event->tstamp_running = tstamp;
1859 event->tstamp_stopped = tstamp;
1862 static void task_ctx_sched_out(struct perf_event_context *ctx);
1864 ctx_sched_in(struct perf_event_context *ctx,
1865 struct perf_cpu_context *cpuctx,
1866 enum event_type_t event_type,
1867 struct task_struct *task);
1869 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
1870 struct perf_event_context *ctx,
1871 struct task_struct *task)
1873 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
1875 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
1876 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
1878 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
1882 * Cross CPU call to install and enable a performance event
1884 * Must be called with ctx->mutex held
1886 static int __perf_install_in_context(void *info)
1888 struct perf_event *event = info;
1889 struct perf_event_context *ctx = event->ctx;
1890 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1891 struct perf_event_context *task_ctx = cpuctx->task_ctx;
1892 struct task_struct *task = current;
1894 perf_ctx_lock(cpuctx, task_ctx);
1895 perf_pmu_disable(cpuctx->ctx.pmu);
1898 * If there was an active task_ctx schedule it out.
1901 task_ctx_sched_out(task_ctx);
1904 * If the context we're installing events in is not the
1905 * active task_ctx, flip them.
1907 if (ctx->task && task_ctx != ctx) {
1909 raw_spin_unlock(&task_ctx->lock);
1910 raw_spin_lock(&ctx->lock);
1915 cpuctx->task_ctx = task_ctx;
1916 task = task_ctx->task;
1919 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
1921 update_context_time(ctx);
1923 * update cgrp time only if current cgrp
1924 * matches event->cgrp. Must be done before
1925 * calling add_event_to_ctx()
1927 update_cgrp_time_from_event(event);
1929 add_event_to_ctx(event, ctx);
1932 * Schedule everything back in
1934 perf_event_sched_in(cpuctx, task_ctx, task);
1936 perf_pmu_enable(cpuctx->ctx.pmu);
1937 perf_ctx_unlock(cpuctx, task_ctx);
1943 * Attach a performance event to a context
1945 * First we add the event to the list with the hardware enable bit
1946 * in event->hw_config cleared.
1948 * If the event is attached to a task which is on a CPU we use a smp
1949 * call to enable it in the task context. The task might have been
1950 * scheduled away, but we check this in the smp call again.
1953 perf_install_in_context(struct perf_event_context *ctx,
1954 struct perf_event *event,
1957 struct task_struct *task = ctx->task;
1959 lockdep_assert_held(&ctx->mutex);
1962 if (event->cpu != -1)
1967 * Per cpu events are installed via an smp call and
1968 * the install is always successful.
1970 cpu_function_call(cpu, __perf_install_in_context, event);
1975 if (!task_function_call(task, __perf_install_in_context, event))
1978 raw_spin_lock_irq(&ctx->lock);
1980 * If we failed to find a running task, but find the context active now
1981 * that we've acquired the ctx->lock, retry.
1983 if (ctx->is_active) {
1984 raw_spin_unlock_irq(&ctx->lock);
1986 * Reload the task pointer, it might have been changed by
1987 * a concurrent perf_event_context_sched_out().
1994 * Since the task isn't running, its safe to add the event, us holding
1995 * the ctx->lock ensures the task won't get scheduled in.
1997 add_event_to_ctx(event, ctx);
1998 raw_spin_unlock_irq(&ctx->lock);
2002 * Put a event into inactive state and update time fields.
2003 * Enabling the leader of a group effectively enables all
2004 * the group members that aren't explicitly disabled, so we
2005 * have to update their ->tstamp_enabled also.
2006 * Note: this works for group members as well as group leaders
2007 * since the non-leader members' sibling_lists will be empty.
2009 static void __perf_event_mark_enabled(struct perf_event *event)
2011 struct perf_event *sub;
2012 u64 tstamp = perf_event_time(event);
2014 event->state = PERF_EVENT_STATE_INACTIVE;
2015 event->tstamp_enabled = tstamp - event->total_time_enabled;
2016 list_for_each_entry(sub, &event->sibling_list, group_entry) {
2017 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2018 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2023 * Cross CPU call to enable a performance event
2025 static int __perf_event_enable(void *info)
2027 struct perf_event *event = info;
2028 struct perf_event_context *ctx = event->ctx;
2029 struct perf_event *leader = event->group_leader;
2030 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2034 * There's a time window between 'ctx->is_active' check
2035 * in perf_event_enable function and this place having:
2037 * - ctx->lock unlocked
2039 * where the task could be killed and 'ctx' deactivated
2040 * by perf_event_exit_task.
2042 if (!ctx->is_active)
2045 raw_spin_lock(&ctx->lock);
2046 update_context_time(ctx);
2048 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2052 * set current task's cgroup time reference point
2054 perf_cgroup_set_timestamp(current, ctx);
2056 __perf_event_mark_enabled(event);
2058 if (!event_filter_match(event)) {
2059 if (is_cgroup_event(event))
2060 perf_cgroup_defer_enabled(event);
2065 * If the event is in a group and isn't the group leader,
2066 * then don't put it on unless the group is on.
2068 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
2071 if (!group_can_go_on(event, cpuctx, 1)) {
2074 if (event == leader)
2075 err = group_sched_in(event, cpuctx, ctx);
2077 err = event_sched_in(event, cpuctx, ctx);
2082 * If this event can't go on and it's part of a
2083 * group, then the whole group has to come off.
2085 if (leader != event) {
2086 group_sched_out(leader, cpuctx, ctx);
2087 perf_cpu_hrtimer_restart(cpuctx);
2089 if (leader->attr.pinned) {
2090 update_group_times(leader);
2091 leader->state = PERF_EVENT_STATE_ERROR;
2096 raw_spin_unlock(&ctx->lock);
2104 * If event->ctx is a cloned context, callers must make sure that
2105 * every task struct that event->ctx->task could possibly point to
2106 * remains valid. This condition is satisfied when called through
2107 * perf_event_for_each_child or perf_event_for_each as described
2108 * for perf_event_disable.
2110 void perf_event_enable(struct perf_event *event)
2112 struct perf_event_context *ctx = event->ctx;
2113 struct task_struct *task = ctx->task;
2117 * Enable the event on the cpu that it's on
2119 cpu_function_call(event->cpu, __perf_event_enable, event);
2123 raw_spin_lock_irq(&ctx->lock);
2124 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2128 * If the event is in error state, clear that first.
2129 * That way, if we see the event in error state below, we
2130 * know that it has gone back into error state, as distinct
2131 * from the task having been scheduled away before the
2132 * cross-call arrived.
2134 if (event->state == PERF_EVENT_STATE_ERROR)
2135 event->state = PERF_EVENT_STATE_OFF;
2138 if (!ctx->is_active) {
2139 __perf_event_mark_enabled(event);
2143 raw_spin_unlock_irq(&ctx->lock);
2145 if (!task_function_call(task, __perf_event_enable, event))
2148 raw_spin_lock_irq(&ctx->lock);
2151 * If the context is active and the event is still off,
2152 * we need to retry the cross-call.
2154 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
2156 * task could have been flipped by a concurrent
2157 * perf_event_context_sched_out()
2164 raw_spin_unlock_irq(&ctx->lock);
2166 EXPORT_SYMBOL_GPL(perf_event_enable);
2168 int perf_event_refresh(struct perf_event *event, int refresh)
2171 * not supported on inherited events
2173 if (event->attr.inherit || !is_sampling_event(event))
2176 atomic_add(refresh, &event->event_limit);
2177 perf_event_enable(event);
2181 EXPORT_SYMBOL_GPL(perf_event_refresh);
2183 static void ctx_sched_out(struct perf_event_context *ctx,
2184 struct perf_cpu_context *cpuctx,
2185 enum event_type_t event_type)
2187 struct perf_event *event;
2188 int is_active = ctx->is_active;
2190 ctx->is_active &= ~event_type;
2191 if (likely(!ctx->nr_events))
2194 update_context_time(ctx);
2195 update_cgrp_time_from_cpuctx(cpuctx);
2196 if (!ctx->nr_active)
2199 perf_pmu_disable(ctx->pmu);
2200 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2201 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2202 group_sched_out(event, cpuctx, ctx);
2205 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2206 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2207 group_sched_out(event, cpuctx, ctx);
2209 perf_pmu_enable(ctx->pmu);
2213 * Test whether two contexts are equivalent, i.e. whether they have both been
2214 * cloned from the same version of the same context.
2216 * Equivalence is measured using a generation number in the context that is
2217 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2218 * and list_del_event().
2220 static int context_equiv(struct perf_event_context *ctx1,
2221 struct perf_event_context *ctx2)
2223 lockdep_assert_held(&ctx1->lock);
2224 lockdep_assert_held(&ctx2->lock);
2226 /* Pinning disables the swap optimization */
2227 if (ctx1->pin_count || ctx2->pin_count)
2230 /* If ctx1 is the parent of ctx2 */
2231 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2234 /* If ctx2 is the parent of ctx1 */
2235 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2239 * If ctx1 and ctx2 have the same parent; we flatten the parent
2240 * hierarchy, see perf_event_init_context().
2242 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2243 ctx1->parent_gen == ctx2->parent_gen)
2250 static void __perf_event_sync_stat(struct perf_event *event,
2251 struct perf_event *next_event)
2255 if (!event->attr.inherit_stat)
2259 * Update the event value, we cannot use perf_event_read()
2260 * because we're in the middle of a context switch and have IRQs
2261 * disabled, which upsets smp_call_function_single(), however
2262 * we know the event must be on the current CPU, therefore we
2263 * don't need to use it.
2265 switch (event->state) {
2266 case PERF_EVENT_STATE_ACTIVE:
2267 event->pmu->read(event);
2270 case PERF_EVENT_STATE_INACTIVE:
2271 update_event_times(event);
2279 * In order to keep per-task stats reliable we need to flip the event
2280 * values when we flip the contexts.
2282 value = local64_read(&next_event->count);
2283 value = local64_xchg(&event->count, value);
2284 local64_set(&next_event->count, value);
2286 swap(event->total_time_enabled, next_event->total_time_enabled);
2287 swap(event->total_time_running, next_event->total_time_running);
2290 * Since we swizzled the values, update the user visible data too.
2292 perf_event_update_userpage(event);
2293 perf_event_update_userpage(next_event);
2296 static void perf_event_sync_stat(struct perf_event_context *ctx,
2297 struct perf_event_context *next_ctx)
2299 struct perf_event *event, *next_event;
2304 update_context_time(ctx);
2306 event = list_first_entry(&ctx->event_list,
2307 struct perf_event, event_entry);
2309 next_event = list_first_entry(&next_ctx->event_list,
2310 struct perf_event, event_entry);
2312 while (&event->event_entry != &ctx->event_list &&
2313 &next_event->event_entry != &next_ctx->event_list) {
2315 __perf_event_sync_stat(event, next_event);
2317 event = list_next_entry(event, event_entry);
2318 next_event = list_next_entry(next_event, event_entry);
2322 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2323 struct task_struct *next)
2325 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2326 struct perf_event_context *next_ctx;
2327 struct perf_event_context *parent, *next_parent;
2328 struct perf_cpu_context *cpuctx;
2334 cpuctx = __get_cpu_context(ctx);
2335 if (!cpuctx->task_ctx)
2339 next_ctx = next->perf_event_ctxp[ctxn];
2343 parent = rcu_dereference(ctx->parent_ctx);
2344 next_parent = rcu_dereference(next_ctx->parent_ctx);
2346 /* If neither context have a parent context; they cannot be clones. */
2347 if (!parent || !next_parent)
2350 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2352 * Looks like the two contexts are clones, so we might be
2353 * able to optimize the context switch. We lock both
2354 * contexts and check that they are clones under the
2355 * lock (including re-checking that neither has been
2356 * uncloned in the meantime). It doesn't matter which
2357 * order we take the locks because no other cpu could
2358 * be trying to lock both of these tasks.
2360 raw_spin_lock(&ctx->lock);
2361 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2362 if (context_equiv(ctx, next_ctx)) {
2364 * XXX do we need a memory barrier of sorts
2365 * wrt to rcu_dereference() of perf_event_ctxp
2367 task->perf_event_ctxp[ctxn] = next_ctx;
2368 next->perf_event_ctxp[ctxn] = ctx;
2370 next_ctx->task = task;
2373 perf_event_sync_stat(ctx, next_ctx);
2375 raw_spin_unlock(&next_ctx->lock);
2376 raw_spin_unlock(&ctx->lock);
2382 raw_spin_lock(&ctx->lock);
2383 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2384 cpuctx->task_ctx = NULL;
2385 raw_spin_unlock(&ctx->lock);
2389 #define for_each_task_context_nr(ctxn) \
2390 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2393 * Called from scheduler to remove the events of the current task,
2394 * with interrupts disabled.
2396 * We stop each event and update the event value in event->count.
2398 * This does not protect us against NMI, but disable()
2399 * sets the disabled bit in the control field of event _before_
2400 * accessing the event control register. If a NMI hits, then it will
2401 * not restart the event.
2403 void __perf_event_task_sched_out(struct task_struct *task,
2404 struct task_struct *next)
2408 for_each_task_context_nr(ctxn)
2409 perf_event_context_sched_out(task, ctxn, next);
2412 * if cgroup events exist on this CPU, then we need
2413 * to check if we have to switch out PMU state.
2414 * cgroup event are system-wide mode only
2416 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2417 perf_cgroup_sched_out(task, next);
2420 static void task_ctx_sched_out(struct perf_event_context *ctx)
2422 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2424 if (!cpuctx->task_ctx)
2427 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2430 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2431 cpuctx->task_ctx = NULL;
2435 * Called with IRQs disabled
2437 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2438 enum event_type_t event_type)
2440 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2444 ctx_pinned_sched_in(struct perf_event_context *ctx,
2445 struct perf_cpu_context *cpuctx)
2447 struct perf_event *event;
2449 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2450 if (event->state <= PERF_EVENT_STATE_OFF)
2452 if (!event_filter_match(event))
2455 /* may need to reset tstamp_enabled */
2456 if (is_cgroup_event(event))
2457 perf_cgroup_mark_enabled(event, ctx);
2459 if (group_can_go_on(event, cpuctx, 1))
2460 group_sched_in(event, cpuctx, ctx);
2463 * If this pinned group hasn't been scheduled,
2464 * put it in error state.
2466 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2467 update_group_times(event);
2468 event->state = PERF_EVENT_STATE_ERROR;
2474 ctx_flexible_sched_in(struct perf_event_context *ctx,
2475 struct perf_cpu_context *cpuctx)
2477 struct perf_event *event;
2480 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2481 /* Ignore events in OFF or ERROR state */
2482 if (event->state <= PERF_EVENT_STATE_OFF)
2485 * Listen to the 'cpu' scheduling filter constraint
2488 if (!event_filter_match(event))
2491 /* may need to reset tstamp_enabled */
2492 if (is_cgroup_event(event))
2493 perf_cgroup_mark_enabled(event, ctx);
2495 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2496 if (group_sched_in(event, cpuctx, ctx))
2503 ctx_sched_in(struct perf_event_context *ctx,
2504 struct perf_cpu_context *cpuctx,
2505 enum event_type_t event_type,
2506 struct task_struct *task)
2509 int is_active = ctx->is_active;
2511 ctx->is_active |= event_type;
2512 if (likely(!ctx->nr_events))
2516 ctx->timestamp = now;
2517 perf_cgroup_set_timestamp(task, ctx);
2519 * First go through the list and put on any pinned groups
2520 * in order to give them the best chance of going on.
2522 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2523 ctx_pinned_sched_in(ctx, cpuctx);
2525 /* Then walk through the lower prio flexible groups */
2526 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2527 ctx_flexible_sched_in(ctx, cpuctx);
2530 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2531 enum event_type_t event_type,
2532 struct task_struct *task)
2534 struct perf_event_context *ctx = &cpuctx->ctx;
2536 ctx_sched_in(ctx, cpuctx, event_type, task);
2539 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2540 struct task_struct *task)
2542 struct perf_cpu_context *cpuctx;
2544 cpuctx = __get_cpu_context(ctx);
2545 if (cpuctx->task_ctx == ctx)
2548 perf_ctx_lock(cpuctx, ctx);
2549 perf_pmu_disable(ctx->pmu);
2551 * We want to keep the following priority order:
2552 * cpu pinned (that don't need to move), task pinned,
2553 * cpu flexible, task flexible.
2555 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2558 cpuctx->task_ctx = ctx;
2560 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2562 perf_pmu_enable(ctx->pmu);
2563 perf_ctx_unlock(cpuctx, ctx);
2566 * Since these rotations are per-cpu, we need to ensure the
2567 * cpu-context we got scheduled on is actually rotating.
2569 perf_pmu_rotate_start(ctx->pmu);
2573 * When sampling the branck stack in system-wide, it may be necessary
2574 * to flush the stack on context switch. This happens when the branch
2575 * stack does not tag its entries with the pid of the current task.
2576 * Otherwise it becomes impossible to associate a branch entry with a
2577 * task. This ambiguity is more likely to appear when the branch stack
2578 * supports priv level filtering and the user sets it to monitor only
2579 * at the user level (which could be a useful measurement in system-wide
2580 * mode). In that case, the risk is high of having a branch stack with
2581 * branch from multiple tasks. Flushing may mean dropping the existing
2582 * entries or stashing them somewhere in the PMU specific code layer.
2584 * This function provides the context switch callback to the lower code
2585 * layer. It is invoked ONLY when there is at least one system-wide context
2586 * with at least one active event using taken branch sampling.
2588 static void perf_branch_stack_sched_in(struct task_struct *prev,
2589 struct task_struct *task)
2591 struct perf_cpu_context *cpuctx;
2593 unsigned long flags;
2595 /* no need to flush branch stack if not changing task */
2599 local_irq_save(flags);
2603 list_for_each_entry_rcu(pmu, &pmus, entry) {
2604 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2607 * check if the context has at least one
2608 * event using PERF_SAMPLE_BRANCH_STACK
2610 if (cpuctx->ctx.nr_branch_stack > 0
2611 && pmu->flush_branch_stack) {
2613 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2615 perf_pmu_disable(pmu);
2617 pmu->flush_branch_stack();
2619 perf_pmu_enable(pmu);
2621 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2627 local_irq_restore(flags);
2631 * Called from scheduler to add the events of the current task
2632 * with interrupts disabled.
2634 * We restore the event value and then enable it.
2636 * This does not protect us against NMI, but enable()
2637 * sets the enabled bit in the control field of event _before_
2638 * accessing the event control register. If a NMI hits, then it will
2639 * keep the event running.
2641 void __perf_event_task_sched_in(struct task_struct *prev,
2642 struct task_struct *task)
2644 struct perf_event_context *ctx;
2647 for_each_task_context_nr(ctxn) {
2648 ctx = task->perf_event_ctxp[ctxn];
2652 perf_event_context_sched_in(ctx, task);
2655 * if cgroup events exist on this CPU, then we need
2656 * to check if we have to switch in PMU state.
2657 * cgroup event are system-wide mode only
2659 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2660 perf_cgroup_sched_in(prev, task);
2662 /* check for system-wide branch_stack events */
2663 if (atomic_read(&__get_cpu_var(perf_branch_stack_events)))
2664 perf_branch_stack_sched_in(prev, task);
2667 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2669 u64 frequency = event->attr.sample_freq;
2670 u64 sec = NSEC_PER_SEC;
2671 u64 divisor, dividend;
2673 int count_fls, nsec_fls, frequency_fls, sec_fls;
2675 count_fls = fls64(count);
2676 nsec_fls = fls64(nsec);
2677 frequency_fls = fls64(frequency);
2681 * We got @count in @nsec, with a target of sample_freq HZ
2682 * the target period becomes:
2685 * period = -------------------
2686 * @nsec * sample_freq
2691 * Reduce accuracy by one bit such that @a and @b converge
2692 * to a similar magnitude.
2694 #define REDUCE_FLS(a, b) \
2696 if (a##_fls > b##_fls) { \
2706 * Reduce accuracy until either term fits in a u64, then proceed with
2707 * the other, so that finally we can do a u64/u64 division.
2709 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2710 REDUCE_FLS(nsec, frequency);
2711 REDUCE_FLS(sec, count);
2714 if (count_fls + sec_fls > 64) {
2715 divisor = nsec * frequency;
2717 while (count_fls + sec_fls > 64) {
2718 REDUCE_FLS(count, sec);
2722 dividend = count * sec;
2724 dividend = count * sec;
2726 while (nsec_fls + frequency_fls > 64) {
2727 REDUCE_FLS(nsec, frequency);
2731 divisor = nsec * frequency;
2737 return div64_u64(dividend, divisor);
2740 static DEFINE_PER_CPU(int, perf_throttled_count);
2741 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2743 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2745 struct hw_perf_event *hwc = &event->hw;
2746 s64 period, sample_period;
2749 period = perf_calculate_period(event, nsec, count);
2751 delta = (s64)(period - hwc->sample_period);
2752 delta = (delta + 7) / 8; /* low pass filter */
2754 sample_period = hwc->sample_period + delta;
2759 hwc->sample_period = sample_period;
2761 if (local64_read(&hwc->period_left) > 8*sample_period) {
2763 event->pmu->stop(event, PERF_EF_UPDATE);
2765 local64_set(&hwc->period_left, 0);
2768 event->pmu->start(event, PERF_EF_RELOAD);
2773 * combine freq adjustment with unthrottling to avoid two passes over the
2774 * events. At the same time, make sure, having freq events does not change
2775 * the rate of unthrottling as that would introduce bias.
2777 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
2780 struct perf_event *event;
2781 struct hw_perf_event *hwc;
2782 u64 now, period = TICK_NSEC;
2786 * only need to iterate over all events iff:
2787 * - context have events in frequency mode (needs freq adjust)
2788 * - there are events to unthrottle on this cpu
2790 if (!(ctx->nr_freq || needs_unthr))
2793 raw_spin_lock(&ctx->lock);
2794 perf_pmu_disable(ctx->pmu);
2796 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
2797 if (event->state != PERF_EVENT_STATE_ACTIVE)
2800 if (!event_filter_match(event))
2803 perf_pmu_disable(event->pmu);
2807 if (hwc->interrupts == MAX_INTERRUPTS) {
2808 hwc->interrupts = 0;
2809 perf_log_throttle(event, 1);
2810 event->pmu->start(event, 0);
2813 if (!event->attr.freq || !event->attr.sample_freq)
2817 * stop the event and update event->count
2819 event->pmu->stop(event, PERF_EF_UPDATE);
2821 now = local64_read(&event->count);
2822 delta = now - hwc->freq_count_stamp;
2823 hwc->freq_count_stamp = now;
2827 * reload only if value has changed
2828 * we have stopped the event so tell that
2829 * to perf_adjust_period() to avoid stopping it
2833 perf_adjust_period(event, period, delta, false);
2835 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
2837 perf_pmu_enable(event->pmu);
2840 perf_pmu_enable(ctx->pmu);
2841 raw_spin_unlock(&ctx->lock);
2845 * Round-robin a context's events:
2847 static void rotate_ctx(struct perf_event_context *ctx)
2850 * Rotate the first entry last of non-pinned groups. Rotation might be
2851 * disabled by the inheritance code.
2853 if (!ctx->rotate_disable)
2854 list_rotate_left(&ctx->flexible_groups);
2858 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
2859 * because they're strictly cpu affine and rotate_start is called with IRQs
2860 * disabled, while rotate_context is called from IRQ context.
2862 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
2864 struct perf_event_context *ctx = NULL;
2865 int rotate = 0, remove = 1;
2867 if (cpuctx->ctx.nr_events) {
2869 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
2873 ctx = cpuctx->task_ctx;
2874 if (ctx && ctx->nr_events) {
2876 if (ctx->nr_events != ctx->nr_active)
2883 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2884 perf_pmu_disable(cpuctx->ctx.pmu);
2886 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2888 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
2890 rotate_ctx(&cpuctx->ctx);
2894 perf_event_sched_in(cpuctx, ctx, current);
2896 perf_pmu_enable(cpuctx->ctx.pmu);
2897 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2900 list_del_init(&cpuctx->rotation_list);
2905 #ifdef CONFIG_NO_HZ_FULL
2906 bool perf_event_can_stop_tick(void)
2908 if (atomic_read(&nr_freq_events) ||
2909 __this_cpu_read(perf_throttled_count))
2916 void perf_event_task_tick(void)
2918 struct list_head *head = &__get_cpu_var(rotation_list);
2919 struct perf_cpu_context *cpuctx, *tmp;
2920 struct perf_event_context *ctx;
2923 WARN_ON(!irqs_disabled());
2925 __this_cpu_inc(perf_throttled_seq);
2926 throttled = __this_cpu_xchg(perf_throttled_count, 0);
2928 list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) {
2930 perf_adjust_freq_unthr_context(ctx, throttled);
2932 ctx = cpuctx->task_ctx;
2934 perf_adjust_freq_unthr_context(ctx, throttled);
2938 static int event_enable_on_exec(struct perf_event *event,
2939 struct perf_event_context *ctx)
2941 if (!event->attr.enable_on_exec)
2944 event->attr.enable_on_exec = 0;
2945 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2948 __perf_event_mark_enabled(event);
2954 * Enable all of a task's events that have been marked enable-on-exec.
2955 * This expects task == current.
2957 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
2959 struct perf_event_context *clone_ctx = NULL;
2960 struct perf_event *event;
2961 unsigned long flags;
2965 local_irq_save(flags);
2966 if (!ctx || !ctx->nr_events)
2970 * We must ctxsw out cgroup events to avoid conflict
2971 * when invoking perf_task_event_sched_in() later on
2972 * in this function. Otherwise we end up trying to
2973 * ctxswin cgroup events which are already scheduled
2976 perf_cgroup_sched_out(current, NULL);
2978 raw_spin_lock(&ctx->lock);
2979 task_ctx_sched_out(ctx);
2981 list_for_each_entry(event, &ctx->event_list, event_entry) {
2982 ret = event_enable_on_exec(event, ctx);
2988 * Unclone this context if we enabled any event.
2991 clone_ctx = unclone_ctx(ctx);
2993 raw_spin_unlock(&ctx->lock);
2996 * Also calls ctxswin for cgroup events, if any:
2998 perf_event_context_sched_in(ctx, ctx->task);
3000 local_irq_restore(flags);
3006 void perf_event_exec(void)
3008 struct perf_event_context *ctx;
3012 for_each_task_context_nr(ctxn) {
3013 ctx = current->perf_event_ctxp[ctxn];
3017 perf_event_enable_on_exec(ctx);
3023 * Cross CPU call to read the hardware event
3025 static void __perf_event_read(void *info)
3027 struct perf_event *event = info;
3028 struct perf_event_context *ctx = event->ctx;
3029 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3032 * If this is a task context, we need to check whether it is
3033 * the current task context of this cpu. If not it has been
3034 * scheduled out before the smp call arrived. In that case
3035 * event->count would have been updated to a recent sample
3036 * when the event was scheduled out.
3038 if (ctx->task && cpuctx->task_ctx != ctx)
3041 raw_spin_lock(&ctx->lock);
3042 if (ctx->is_active) {
3043 update_context_time(ctx);
3044 update_cgrp_time_from_event(event);
3046 update_event_times(event);
3047 if (event->state == PERF_EVENT_STATE_ACTIVE)
3048 event->pmu->read(event);
3049 raw_spin_unlock(&ctx->lock);
3052 static inline u64 perf_event_count(struct perf_event *event)
3054 return local64_read(&event->count) + atomic64_read(&event->child_count);
3057 static u64 perf_event_read(struct perf_event *event)
3060 * If event is enabled and currently active on a CPU, update the
3061 * value in the event structure:
3063 if (event->state == PERF_EVENT_STATE_ACTIVE) {
3064 smp_call_function_single(event->oncpu,
3065 __perf_event_read, event, 1);
3066 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3067 struct perf_event_context *ctx = event->ctx;
3068 unsigned long flags;
3070 raw_spin_lock_irqsave(&ctx->lock, flags);
3072 * may read while context is not active
3073 * (e.g., thread is blocked), in that case
3074 * we cannot update context time
3076 if (ctx->is_active) {
3077 update_context_time(ctx);
3078 update_cgrp_time_from_event(event);
3080 update_event_times(event);
3081 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3084 return perf_event_count(event);
3088 * Initialize the perf_event context in a task_struct:
3090 static void __perf_event_init_context(struct perf_event_context *ctx)
3092 raw_spin_lock_init(&ctx->lock);
3093 mutex_init(&ctx->mutex);
3094 INIT_LIST_HEAD(&ctx->pinned_groups);
3095 INIT_LIST_HEAD(&ctx->flexible_groups);
3096 INIT_LIST_HEAD(&ctx->event_list);
3097 atomic_set(&ctx->refcount, 1);
3100 static struct perf_event_context *
3101 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3103 struct perf_event_context *ctx;
3105 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3109 __perf_event_init_context(ctx);
3112 get_task_struct(task);
3119 static struct task_struct *
3120 find_lively_task_by_vpid(pid_t vpid)
3122 struct task_struct *task;
3129 task = find_task_by_vpid(vpid);
3131 get_task_struct(task);
3135 return ERR_PTR(-ESRCH);
3137 /* Reuse ptrace permission checks for now. */
3139 if (!ptrace_may_access(task, PTRACE_MODE_READ))
3144 put_task_struct(task);
3145 return ERR_PTR(err);
3150 * Returns a matching context with refcount and pincount.
3152 static struct perf_event_context *
3153 find_get_context(struct pmu *pmu, struct task_struct *task, int cpu)
3155 struct perf_event_context *ctx, *clone_ctx = NULL;
3156 struct perf_cpu_context *cpuctx;
3157 unsigned long flags;
3161 /* Must be root to operate on a CPU event: */
3162 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3163 return ERR_PTR(-EACCES);
3166 * We could be clever and allow to attach a event to an
3167 * offline CPU and activate it when the CPU comes up, but
3170 if (!cpu_online(cpu))
3171 return ERR_PTR(-ENODEV);
3173 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3182 ctxn = pmu->task_ctx_nr;
3187 ctx = perf_lock_task_context(task, ctxn, &flags);
3189 clone_ctx = unclone_ctx(ctx);
3191 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3196 ctx = alloc_perf_context(pmu, task);
3202 mutex_lock(&task->perf_event_mutex);
3204 * If it has already passed perf_event_exit_task().
3205 * we must see PF_EXITING, it takes this mutex too.
3207 if (task->flags & PF_EXITING)
3209 else if (task->perf_event_ctxp[ctxn])
3214 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3216 mutex_unlock(&task->perf_event_mutex);
3218 if (unlikely(err)) {
3230 return ERR_PTR(err);
3233 static void perf_event_free_filter(struct perf_event *event);
3235 static void free_event_rcu(struct rcu_head *head)
3237 struct perf_event *event;
3239 event = container_of(head, struct perf_event, rcu_head);
3241 put_pid_ns(event->ns);
3242 perf_event_free_filter(event);
3246 static void ring_buffer_put(struct ring_buffer *rb);
3247 static void ring_buffer_attach(struct perf_event *event,
3248 struct ring_buffer *rb);
3250 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3255 if (has_branch_stack(event)) {
3256 if (!(event->attach_state & PERF_ATTACH_TASK))
3257 atomic_dec(&per_cpu(perf_branch_stack_events, cpu));
3259 if (is_cgroup_event(event))
3260 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3263 static void unaccount_event(struct perf_event *event)
3268 if (event->attach_state & PERF_ATTACH_TASK)
3269 static_key_slow_dec_deferred(&perf_sched_events);
3270 if (event->attr.mmap || event->attr.mmap_data)
3271 atomic_dec(&nr_mmap_events);
3272 if (event->attr.comm)
3273 atomic_dec(&nr_comm_events);
3274 if (event->attr.task)
3275 atomic_dec(&nr_task_events);
3276 if (event->attr.freq)
3277 atomic_dec(&nr_freq_events);
3278 if (is_cgroup_event(event))
3279 static_key_slow_dec_deferred(&perf_sched_events);
3280 if (has_branch_stack(event))
3281 static_key_slow_dec_deferred(&perf_sched_events);
3283 unaccount_event_cpu(event, event->cpu);
3286 static void __free_event(struct perf_event *event)
3288 if (!event->parent) {
3289 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3290 put_callchain_buffers();
3294 event->destroy(event);
3297 put_ctx(event->ctx);
3300 module_put(event->pmu->module);
3302 call_rcu(&event->rcu_head, free_event_rcu);
3305 static void _free_event(struct perf_event *event)
3307 irq_work_sync(&event->pending);
3309 unaccount_event(event);
3313 * Can happen when we close an event with re-directed output.
3315 * Since we have a 0 refcount, perf_mmap_close() will skip
3316 * over us; possibly making our ring_buffer_put() the last.
3318 mutex_lock(&event->mmap_mutex);
3319 ring_buffer_attach(event, NULL);
3320 mutex_unlock(&event->mmap_mutex);
3323 if (is_cgroup_event(event))
3324 perf_detach_cgroup(event);
3326 __free_event(event);
3330 * Used to free events which have a known refcount of 1, such as in error paths
3331 * where the event isn't exposed yet and inherited events.
3333 static void free_event(struct perf_event *event)
3335 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3336 "unexpected event refcount: %ld; ptr=%p\n",
3337 atomic_long_read(&event->refcount), event)) {
3338 /* leak to avoid use-after-free */
3346 * Called when the last reference to the file is gone.
3348 static void put_event(struct perf_event *event)
3350 struct perf_event_context *ctx = event->ctx;
3351 struct task_struct *owner;
3353 if (!atomic_long_dec_and_test(&event->refcount))
3357 owner = ACCESS_ONCE(event->owner);
3359 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3360 * !owner it means the list deletion is complete and we can indeed
3361 * free this event, otherwise we need to serialize on
3362 * owner->perf_event_mutex.
3364 smp_read_barrier_depends();
3367 * Since delayed_put_task_struct() also drops the last
3368 * task reference we can safely take a new reference
3369 * while holding the rcu_read_lock().
3371 get_task_struct(owner);
3376 mutex_lock(&owner->perf_event_mutex);
3378 * We have to re-check the event->owner field, if it is cleared
3379 * we raced with perf_event_exit_task(), acquiring the mutex
3380 * ensured they're done, and we can proceed with freeing the
3384 list_del_init(&event->owner_entry);
3385 mutex_unlock(&owner->perf_event_mutex);
3386 put_task_struct(owner);
3389 WARN_ON_ONCE(ctx->parent_ctx);
3391 * There are two ways this annotation is useful:
3393 * 1) there is a lock recursion from perf_event_exit_task
3394 * see the comment there.
3396 * 2) there is a lock-inversion with mmap_sem through
3397 * perf_event_read_group(), which takes faults while
3398 * holding ctx->mutex, however this is called after
3399 * the last filedesc died, so there is no possibility
3400 * to trigger the AB-BA case.
3402 mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
3403 perf_remove_from_context(event, true);
3404 mutex_unlock(&ctx->mutex);
3409 int perf_event_release_kernel(struct perf_event *event)
3414 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3416 static int perf_release(struct inode *inode, struct file *file)
3418 put_event(file->private_data);
3422 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3424 struct perf_event *child;