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 static struct workqueue_struct *perf_wq;
52 struct remote_function_call {
53 struct task_struct *p;
54 int (*func)(void *info);
59 static void remote_function(void *data)
61 struct remote_function_call *tfc = data;
62 struct task_struct *p = tfc->p;
66 if (task_cpu(p) != smp_processor_id() || !task_curr(p))
70 tfc->ret = tfc->func(tfc->info);
74 * task_function_call - call a function on the cpu on which a task runs
75 * @p: the task to evaluate
76 * @func: the function to be called
77 * @info: the function call argument
79 * Calls the function @func when the task is currently running. This might
80 * be on the current CPU, which just calls the function directly
82 * returns: @func return value, or
83 * -ESRCH - when the process isn't running
84 * -EAGAIN - when the process moved away
87 task_function_call(struct task_struct *p, int (*func) (void *info), void *info)
89 struct remote_function_call data = {
93 .ret = -ESRCH, /* No such (running) process */
97 smp_call_function_single(task_cpu(p), remote_function, &data, 1);
103 * cpu_function_call - call a function on the cpu
104 * @func: the function to be called
105 * @info: the function call argument
107 * Calls the function @func on the remote cpu.
109 * returns: @func return value or -ENXIO when the cpu is offline
111 static int cpu_function_call(int cpu, int (*func) (void *info), void *info)
113 struct remote_function_call data = {
117 .ret = -ENXIO, /* No such CPU */
120 smp_call_function_single(cpu, remote_function, &data, 1);
125 #define EVENT_OWNER_KERNEL ((void *) -1)
127 static bool is_kernel_event(struct perf_event *event)
129 return event->owner == EVENT_OWNER_KERNEL;
132 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
133 PERF_FLAG_FD_OUTPUT |\
134 PERF_FLAG_PID_CGROUP |\
135 PERF_FLAG_FD_CLOEXEC)
138 * branch priv levels that need permission checks
140 #define PERF_SAMPLE_BRANCH_PERM_PLM \
141 (PERF_SAMPLE_BRANCH_KERNEL |\
142 PERF_SAMPLE_BRANCH_HV)
145 EVENT_FLEXIBLE = 0x1,
147 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
151 * perf_sched_events : >0 events exist
152 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
154 struct static_key_deferred perf_sched_events __read_mostly;
155 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
156 static DEFINE_PER_CPU(atomic_t, perf_branch_stack_events);
158 static atomic_t nr_mmap_events __read_mostly;
159 static atomic_t nr_comm_events __read_mostly;
160 static atomic_t nr_task_events __read_mostly;
161 static atomic_t nr_freq_events __read_mostly;
163 static LIST_HEAD(pmus);
164 static DEFINE_MUTEX(pmus_lock);
165 static struct srcu_struct pmus_srcu;
168 * perf event paranoia level:
169 * -1 - not paranoid at all
170 * 0 - disallow raw tracepoint access for unpriv
171 * 1 - disallow cpu events for unpriv
172 * 2 - disallow kernel profiling for unpriv
174 int sysctl_perf_event_paranoid __read_mostly = 1;
176 /* Minimum for 512 kiB + 1 user control page */
177 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
180 * max perf event sample rate
182 #define DEFAULT_MAX_SAMPLE_RATE 100000
183 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
184 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
186 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
188 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
189 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
191 static int perf_sample_allowed_ns __read_mostly =
192 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
194 void update_perf_cpu_limits(void)
196 u64 tmp = perf_sample_period_ns;
198 tmp *= sysctl_perf_cpu_time_max_percent;
200 ACCESS_ONCE(perf_sample_allowed_ns) = tmp;
203 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
205 int perf_proc_update_handler(struct ctl_table *table, int write,
206 void __user *buffer, size_t *lenp,
209 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
214 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
215 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
216 update_perf_cpu_limits();
221 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
223 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
224 void __user *buffer, size_t *lenp,
227 int ret = proc_dointvec(table, write, buffer, lenp, ppos);
232 update_perf_cpu_limits();
238 * perf samples are done in some very critical code paths (NMIs).
239 * If they take too much CPU time, the system can lock up and not
240 * get any real work done. This will drop the sample rate when
241 * we detect that events are taking too long.
243 #define NR_ACCUMULATED_SAMPLES 128
244 static DEFINE_PER_CPU(u64, running_sample_length);
246 static void perf_duration_warn(struct irq_work *w)
248 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
249 u64 avg_local_sample_len;
250 u64 local_samples_len;
252 local_samples_len = __get_cpu_var(running_sample_length);
253 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
255 printk_ratelimited(KERN_WARNING
256 "perf interrupt took too long (%lld > %lld), lowering "
257 "kernel.perf_event_max_sample_rate to %d\n",
258 avg_local_sample_len, allowed_ns >> 1,
259 sysctl_perf_event_sample_rate);
262 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
264 void perf_sample_event_took(u64 sample_len_ns)
266 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
267 u64 avg_local_sample_len;
268 u64 local_samples_len;
273 /* decay the counter by 1 average sample */
274 local_samples_len = __get_cpu_var(running_sample_length);
275 local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES;
276 local_samples_len += sample_len_ns;
277 __get_cpu_var(running_sample_length) = local_samples_len;
280 * note: this will be biased artifically low until we have
281 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
282 * from having to maintain a count.
284 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
286 if (avg_local_sample_len <= allowed_ns)
289 if (max_samples_per_tick <= 1)
292 max_samples_per_tick = DIV_ROUND_UP(max_samples_per_tick, 2);
293 sysctl_perf_event_sample_rate = max_samples_per_tick * HZ;
294 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
296 update_perf_cpu_limits();
298 if (!irq_work_queue(&perf_duration_work)) {
299 early_printk("perf interrupt took too long (%lld > %lld), lowering "
300 "kernel.perf_event_max_sample_rate to %d\n",
301 avg_local_sample_len, allowed_ns >> 1,
302 sysctl_perf_event_sample_rate);
306 static atomic64_t perf_event_id;
308 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
309 enum event_type_t event_type);
311 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
312 enum event_type_t event_type,
313 struct task_struct *task);
315 static void update_context_time(struct perf_event_context *ctx);
316 static u64 perf_event_time(struct perf_event *event);
318 void __weak perf_event_print_debug(void) { }
320 extern __weak const char *perf_pmu_name(void)
325 static inline u64 perf_clock(void)
327 return local_clock();
330 static inline struct perf_cpu_context *
331 __get_cpu_context(struct perf_event_context *ctx)
333 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
336 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
337 struct perf_event_context *ctx)
339 raw_spin_lock(&cpuctx->ctx.lock);
341 raw_spin_lock(&ctx->lock);
344 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
345 struct perf_event_context *ctx)
348 raw_spin_unlock(&ctx->lock);
349 raw_spin_unlock(&cpuctx->ctx.lock);
352 #ifdef CONFIG_CGROUP_PERF
355 * perf_cgroup_info keeps track of time_enabled for a cgroup.
356 * This is a per-cpu dynamically allocated data structure.
358 struct perf_cgroup_info {
364 struct cgroup_subsys_state css;
365 struct perf_cgroup_info __percpu *info;
369 * Must ensure cgroup is pinned (css_get) before calling
370 * this function. In other words, we cannot call this function
371 * if there is no cgroup event for the current CPU context.
373 static inline struct perf_cgroup *
374 perf_cgroup_from_task(struct task_struct *task)
376 return container_of(task_css(task, perf_event_cgrp_id),
377 struct perf_cgroup, css);
381 perf_cgroup_match(struct perf_event *event)
383 struct perf_event_context *ctx = event->ctx;
384 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
386 /* @event doesn't care about cgroup */
390 /* wants specific cgroup scope but @cpuctx isn't associated with any */
395 * Cgroup scoping is recursive. An event enabled for a cgroup is
396 * also enabled for all its descendant cgroups. If @cpuctx's
397 * cgroup is a descendant of @event's (the test covers identity
398 * case), it's a match.
400 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
401 event->cgrp->css.cgroup);
404 static inline void perf_detach_cgroup(struct perf_event *event)
406 css_put(&event->cgrp->css);
410 static inline int is_cgroup_event(struct perf_event *event)
412 return event->cgrp != NULL;
415 static inline u64 perf_cgroup_event_time(struct perf_event *event)
417 struct perf_cgroup_info *t;
419 t = per_cpu_ptr(event->cgrp->info, event->cpu);
423 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
425 struct perf_cgroup_info *info;
430 info = this_cpu_ptr(cgrp->info);
432 info->time += now - info->timestamp;
433 info->timestamp = now;
436 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
438 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
440 __update_cgrp_time(cgrp_out);
443 static inline void update_cgrp_time_from_event(struct perf_event *event)
445 struct perf_cgroup *cgrp;
448 * ensure we access cgroup data only when needed and
449 * when we know the cgroup is pinned (css_get)
451 if (!is_cgroup_event(event))
454 cgrp = perf_cgroup_from_task(current);
456 * Do not update time when cgroup is not active
458 if (cgrp == event->cgrp)
459 __update_cgrp_time(event->cgrp);
463 perf_cgroup_set_timestamp(struct task_struct *task,
464 struct perf_event_context *ctx)
466 struct perf_cgroup *cgrp;
467 struct perf_cgroup_info *info;
470 * ctx->lock held by caller
471 * ensure we do not access cgroup data
472 * unless we have the cgroup pinned (css_get)
474 if (!task || !ctx->nr_cgroups)
477 cgrp = perf_cgroup_from_task(task);
478 info = this_cpu_ptr(cgrp->info);
479 info->timestamp = ctx->timestamp;
482 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
483 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
486 * reschedule events based on the cgroup constraint of task.
488 * mode SWOUT : schedule out everything
489 * mode SWIN : schedule in based on cgroup for next
491 void perf_cgroup_switch(struct task_struct *task, int mode)
493 struct perf_cpu_context *cpuctx;
498 * disable interrupts to avoid geting nr_cgroup
499 * changes via __perf_event_disable(). Also
502 local_irq_save(flags);
505 * we reschedule only in the presence of cgroup
506 * constrained events.
510 list_for_each_entry_rcu(pmu, &pmus, entry) {
511 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
512 if (cpuctx->unique_pmu != pmu)
513 continue; /* ensure we process each cpuctx once */
516 * perf_cgroup_events says at least one
517 * context on this CPU has cgroup events.
519 * ctx->nr_cgroups reports the number of cgroup
520 * events for a context.
522 if (cpuctx->ctx.nr_cgroups > 0) {
523 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
524 perf_pmu_disable(cpuctx->ctx.pmu);
526 if (mode & PERF_CGROUP_SWOUT) {
527 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
529 * must not be done before ctxswout due
530 * to event_filter_match() in event_sched_out()
535 if (mode & PERF_CGROUP_SWIN) {
536 WARN_ON_ONCE(cpuctx->cgrp);
538 * set cgrp before ctxsw in to allow
539 * event_filter_match() to not have to pass
542 cpuctx->cgrp = perf_cgroup_from_task(task);
543 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
545 perf_pmu_enable(cpuctx->ctx.pmu);
546 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
552 local_irq_restore(flags);
555 static inline void perf_cgroup_sched_out(struct task_struct *task,
556 struct task_struct *next)
558 struct perf_cgroup *cgrp1;
559 struct perf_cgroup *cgrp2 = NULL;
562 * we come here when we know perf_cgroup_events > 0
564 cgrp1 = perf_cgroup_from_task(task);
567 * next is NULL when called from perf_event_enable_on_exec()
568 * that will systematically cause a cgroup_switch()
571 cgrp2 = perf_cgroup_from_task(next);
574 * only schedule out current cgroup events if we know
575 * that we are switching to a different cgroup. Otherwise,
576 * do no touch the cgroup events.
579 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
582 static inline void perf_cgroup_sched_in(struct task_struct *prev,
583 struct task_struct *task)
585 struct perf_cgroup *cgrp1;
586 struct perf_cgroup *cgrp2 = NULL;
589 * we come here when we know perf_cgroup_events > 0
591 cgrp1 = perf_cgroup_from_task(task);
593 /* prev can never be NULL */
594 cgrp2 = perf_cgroup_from_task(prev);
597 * only need to schedule in cgroup events if we are changing
598 * cgroup during ctxsw. Cgroup events were not scheduled
599 * out of ctxsw out if that was not the case.
602 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
605 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
606 struct perf_event_attr *attr,
607 struct perf_event *group_leader)
609 struct perf_cgroup *cgrp;
610 struct cgroup_subsys_state *css;
611 struct fd f = fdget(fd);
617 css = css_tryget_online_from_dir(f.file->f_dentry,
618 &perf_event_cgrp_subsys);
624 cgrp = container_of(css, struct perf_cgroup, css);
628 * all events in a group must monitor
629 * the same cgroup because a task belongs
630 * to only one perf cgroup at a time
632 if (group_leader && group_leader->cgrp != cgrp) {
633 perf_detach_cgroup(event);
642 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
644 struct perf_cgroup_info *t;
645 t = per_cpu_ptr(event->cgrp->info, event->cpu);
646 event->shadow_ctx_time = now - t->timestamp;
650 perf_cgroup_defer_enabled(struct perf_event *event)
653 * when the current task's perf cgroup does not match
654 * the event's, we need to remember to call the
655 * perf_mark_enable() function the first time a task with
656 * a matching perf cgroup is scheduled in.
658 if (is_cgroup_event(event) && !perf_cgroup_match(event))
659 event->cgrp_defer_enabled = 1;
663 perf_cgroup_mark_enabled(struct perf_event *event,
664 struct perf_event_context *ctx)
666 struct perf_event *sub;
667 u64 tstamp = perf_event_time(event);
669 if (!event->cgrp_defer_enabled)
672 event->cgrp_defer_enabled = 0;
674 event->tstamp_enabled = tstamp - event->total_time_enabled;
675 list_for_each_entry(sub, &event->sibling_list, group_entry) {
676 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
677 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
678 sub->cgrp_defer_enabled = 0;
682 #else /* !CONFIG_CGROUP_PERF */
685 perf_cgroup_match(struct perf_event *event)
690 static inline void perf_detach_cgroup(struct perf_event *event)
693 static inline int is_cgroup_event(struct perf_event *event)
698 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
703 static inline void update_cgrp_time_from_event(struct perf_event *event)
707 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
711 static inline void perf_cgroup_sched_out(struct task_struct *task,
712 struct task_struct *next)
716 static inline void perf_cgroup_sched_in(struct task_struct *prev,
717 struct task_struct *task)
721 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
722 struct perf_event_attr *attr,
723 struct perf_event *group_leader)
729 perf_cgroup_set_timestamp(struct task_struct *task,
730 struct perf_event_context *ctx)
735 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
740 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
744 static inline u64 perf_cgroup_event_time(struct perf_event *event)
750 perf_cgroup_defer_enabled(struct perf_event *event)
755 perf_cgroup_mark_enabled(struct perf_event *event,
756 struct perf_event_context *ctx)
762 * set default to be dependent on timer tick just
765 #define PERF_CPU_HRTIMER (1000 / HZ)
767 * function must be called with interrupts disbled
769 static enum hrtimer_restart perf_cpu_hrtimer_handler(struct hrtimer *hr)
771 struct perf_cpu_context *cpuctx;
772 enum hrtimer_restart ret = HRTIMER_NORESTART;
775 WARN_ON(!irqs_disabled());
777 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
779 rotations = perf_rotate_context(cpuctx);
782 * arm timer if needed
785 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
786 ret = HRTIMER_RESTART;
792 /* CPU is going down */
793 void perf_cpu_hrtimer_cancel(int cpu)
795 struct perf_cpu_context *cpuctx;
799 if (WARN_ON(cpu != smp_processor_id()))
802 local_irq_save(flags);
806 list_for_each_entry_rcu(pmu, &pmus, entry) {
807 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
809 if (pmu->task_ctx_nr == perf_sw_context)
812 hrtimer_cancel(&cpuctx->hrtimer);
817 local_irq_restore(flags);
820 static void __perf_cpu_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
822 struct hrtimer *hr = &cpuctx->hrtimer;
823 struct pmu *pmu = cpuctx->ctx.pmu;
826 /* no multiplexing needed for SW PMU */
827 if (pmu->task_ctx_nr == perf_sw_context)
831 * check default is sane, if not set then force to
832 * default interval (1/tick)
834 timer = pmu->hrtimer_interval_ms;
836 timer = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
838 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
840 hrtimer_init(hr, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
841 hr->function = perf_cpu_hrtimer_handler;
844 static void perf_cpu_hrtimer_restart(struct perf_cpu_context *cpuctx)
846 struct hrtimer *hr = &cpuctx->hrtimer;
847 struct pmu *pmu = cpuctx->ctx.pmu;
850 if (pmu->task_ctx_nr == perf_sw_context)
853 if (hrtimer_active(hr))
856 if (!hrtimer_callback_running(hr))
857 __hrtimer_start_range_ns(hr, cpuctx->hrtimer_interval,
858 0, HRTIMER_MODE_REL_PINNED, 0);
861 void perf_pmu_disable(struct pmu *pmu)
863 int *count = this_cpu_ptr(pmu->pmu_disable_count);
865 pmu->pmu_disable(pmu);
868 void perf_pmu_enable(struct pmu *pmu)
870 int *count = this_cpu_ptr(pmu->pmu_disable_count);
872 pmu->pmu_enable(pmu);
875 static DEFINE_PER_CPU(struct list_head, rotation_list);
878 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
879 * because they're strictly cpu affine and rotate_start is called with IRQs
880 * disabled, while rotate_context is called from IRQ context.
882 static void perf_pmu_rotate_start(struct pmu *pmu)
884 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
885 struct list_head *head = &__get_cpu_var(rotation_list);
887 WARN_ON(!irqs_disabled());
889 if (list_empty(&cpuctx->rotation_list))
890 list_add(&cpuctx->rotation_list, head);
893 static void get_ctx(struct perf_event_context *ctx)
895 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
898 static void put_ctx(struct perf_event_context *ctx)
900 if (atomic_dec_and_test(&ctx->refcount)) {
902 put_ctx(ctx->parent_ctx);
904 put_task_struct(ctx->task);
905 kfree_rcu(ctx, rcu_head);
910 * This must be done under the ctx->lock, such as to serialize against
911 * context_equiv(), therefore we cannot call put_ctx() since that might end up
912 * calling scheduler related locks and ctx->lock nests inside those.
914 static __must_check struct perf_event_context *
915 unclone_ctx(struct perf_event_context *ctx)
917 struct perf_event_context *parent_ctx = ctx->parent_ctx;
919 lockdep_assert_held(&ctx->lock);
922 ctx->parent_ctx = NULL;
928 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
931 * only top level events have the pid namespace they were created in
934 event = event->parent;
936 return task_tgid_nr_ns(p, event->ns);
939 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
942 * only top level events have the pid namespace they were created in
945 event = event->parent;
947 return task_pid_nr_ns(p, event->ns);
951 * If we inherit events we want to return the parent event id
954 static u64 primary_event_id(struct perf_event *event)
959 id = event->parent->id;
965 * Get the perf_event_context for a task and lock it.
966 * This has to cope with with the fact that until it is locked,
967 * the context could get moved to another task.
969 static struct perf_event_context *
970 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
972 struct perf_event_context *ctx;
976 * One of the few rules of preemptible RCU is that one cannot do
977 * rcu_read_unlock() while holding a scheduler (or nested) lock when
978 * part of the read side critical section was preemptible -- see
979 * rcu_read_unlock_special().
981 * Since ctx->lock nests under rq->lock we must ensure the entire read
982 * side critical section is non-preemptible.
986 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
989 * If this context is a clone of another, it might
990 * get swapped for another underneath us by
991 * perf_event_task_sched_out, though the
992 * rcu_read_lock() protects us from any context
993 * getting freed. Lock the context and check if it
994 * got swapped before we could get the lock, and retry
995 * if so. If we locked the right context, then it
996 * can't get swapped on us any more.
998 raw_spin_lock_irqsave(&ctx->lock, *flags);
999 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1000 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
1006 if (!atomic_inc_not_zero(&ctx->refcount)) {
1007 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
1017 * Get the context for a task and increment its pin_count so it
1018 * can't get swapped to another task. This also increments its
1019 * reference count so that the context can't get freed.
1021 static struct perf_event_context *
1022 perf_pin_task_context(struct task_struct *task, int ctxn)
1024 struct perf_event_context *ctx;
1025 unsigned long flags;
1027 ctx = perf_lock_task_context(task, ctxn, &flags);
1030 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1035 static void perf_unpin_context(struct perf_event_context *ctx)
1037 unsigned long flags;
1039 raw_spin_lock_irqsave(&ctx->lock, flags);
1041 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1045 * Update the record of the current time in a context.
1047 static void update_context_time(struct perf_event_context *ctx)
1049 u64 now = perf_clock();
1051 ctx->time += now - ctx->timestamp;
1052 ctx->timestamp = now;
1055 static u64 perf_event_time(struct perf_event *event)
1057 struct perf_event_context *ctx = event->ctx;
1059 if (is_cgroup_event(event))
1060 return perf_cgroup_event_time(event);
1062 return ctx ? ctx->time : 0;
1066 * Update the total_time_enabled and total_time_running fields for a event.
1067 * The caller of this function needs to hold the ctx->lock.
1069 static void update_event_times(struct perf_event *event)
1071 struct perf_event_context *ctx = event->ctx;
1074 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1075 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1078 * in cgroup mode, time_enabled represents
1079 * the time the event was enabled AND active
1080 * tasks were in the monitored cgroup. This is
1081 * independent of the activity of the context as
1082 * there may be a mix of cgroup and non-cgroup events.
1084 * That is why we treat cgroup events differently
1087 if (is_cgroup_event(event))
1088 run_end = perf_cgroup_event_time(event);
1089 else if (ctx->is_active)
1090 run_end = ctx->time;
1092 run_end = event->tstamp_stopped;
1094 event->total_time_enabled = run_end - event->tstamp_enabled;
1096 if (event->state == PERF_EVENT_STATE_INACTIVE)
1097 run_end = event->tstamp_stopped;
1099 run_end = perf_event_time(event);
1101 event->total_time_running = run_end - event->tstamp_running;
1106 * Update total_time_enabled and total_time_running for all events in a group.
1108 static void update_group_times(struct perf_event *leader)
1110 struct perf_event *event;
1112 update_event_times(leader);
1113 list_for_each_entry(event, &leader->sibling_list, group_entry)
1114 update_event_times(event);
1117 static struct list_head *
1118 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1120 if (event->attr.pinned)
1121 return &ctx->pinned_groups;
1123 return &ctx->flexible_groups;
1127 * Add a event from the lists for its context.
1128 * Must be called with ctx->mutex and ctx->lock held.
1131 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1133 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1134 event->attach_state |= PERF_ATTACH_CONTEXT;
1137 * If we're a stand alone event or group leader, we go to the context
1138 * list, group events are kept attached to the group so that
1139 * perf_group_detach can, at all times, locate all siblings.
1141 if (event->group_leader == event) {
1142 struct list_head *list;
1144 if (is_software_event(event))
1145 event->group_flags |= PERF_GROUP_SOFTWARE;
1147 list = ctx_group_list(event, ctx);
1148 list_add_tail(&event->group_entry, list);
1151 if (is_cgroup_event(event))
1154 if (has_branch_stack(event))
1155 ctx->nr_branch_stack++;
1157 list_add_rcu(&event->event_entry, &ctx->event_list);
1158 if (!ctx->nr_events)
1159 perf_pmu_rotate_start(ctx->pmu);
1161 if (event->attr.inherit_stat)
1168 * Initialize event state based on the perf_event_attr::disabled.
1170 static inline void perf_event__state_init(struct perf_event *event)
1172 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1173 PERF_EVENT_STATE_INACTIVE;
1177 * Called at perf_event creation and when events are attached/detached from a
1180 static void perf_event__read_size(struct perf_event *event)
1182 int entry = sizeof(u64); /* value */
1186 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1187 size += sizeof(u64);
1189 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1190 size += sizeof(u64);
1192 if (event->attr.read_format & PERF_FORMAT_ID)
1193 entry += sizeof(u64);
1195 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1196 nr += event->group_leader->nr_siblings;
1197 size += sizeof(u64);
1201 event->read_size = size;
1204 static void perf_event__header_size(struct perf_event *event)
1206 struct perf_sample_data *data;
1207 u64 sample_type = event->attr.sample_type;
1210 perf_event__read_size(event);
1212 if (sample_type & PERF_SAMPLE_IP)
1213 size += sizeof(data->ip);
1215 if (sample_type & PERF_SAMPLE_ADDR)
1216 size += sizeof(data->addr);
1218 if (sample_type & PERF_SAMPLE_PERIOD)
1219 size += sizeof(data->period);
1221 if (sample_type & PERF_SAMPLE_WEIGHT)
1222 size += sizeof(data->weight);
1224 if (sample_type & PERF_SAMPLE_READ)
1225 size += event->read_size;
1227 if (sample_type & PERF_SAMPLE_DATA_SRC)
1228 size += sizeof(data->data_src.val);
1230 if (sample_type & PERF_SAMPLE_TRANSACTION)
1231 size += sizeof(data->txn);
1233 event->header_size = size;
1236 static void perf_event__id_header_size(struct perf_event *event)
1238 struct perf_sample_data *data;
1239 u64 sample_type = event->attr.sample_type;
1242 if (sample_type & PERF_SAMPLE_TID)
1243 size += sizeof(data->tid_entry);
1245 if (sample_type & PERF_SAMPLE_TIME)
1246 size += sizeof(data->time);
1248 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1249 size += sizeof(data->id);
1251 if (sample_type & PERF_SAMPLE_ID)
1252 size += sizeof(data->id);
1254 if (sample_type & PERF_SAMPLE_STREAM_ID)
1255 size += sizeof(data->stream_id);
1257 if (sample_type & PERF_SAMPLE_CPU)
1258 size += sizeof(data->cpu_entry);
1260 event->id_header_size = size;
1263 static void perf_group_attach(struct perf_event *event)
1265 struct perf_event *group_leader = event->group_leader, *pos;
1268 * We can have double attach due to group movement in perf_event_open.
1270 if (event->attach_state & PERF_ATTACH_GROUP)
1273 event->attach_state |= PERF_ATTACH_GROUP;
1275 if (group_leader == event)
1278 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1279 !is_software_event(event))
1280 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1282 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1283 group_leader->nr_siblings++;
1285 perf_event__header_size(group_leader);
1287 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1288 perf_event__header_size(pos);
1292 * Remove a event from the lists for its context.
1293 * Must be called with ctx->mutex and ctx->lock held.
1296 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1298 struct perf_cpu_context *cpuctx;
1300 * We can have double detach due to exit/hot-unplug + close.
1302 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1305 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1307 if (is_cgroup_event(event)) {
1309 cpuctx = __get_cpu_context(ctx);
1311 * if there are no more cgroup events
1312 * then cler cgrp to avoid stale pointer
1313 * in update_cgrp_time_from_cpuctx()
1315 if (!ctx->nr_cgroups)
1316 cpuctx->cgrp = NULL;
1319 if (has_branch_stack(event))
1320 ctx->nr_branch_stack--;
1323 if (event->attr.inherit_stat)
1326 list_del_rcu(&event->event_entry);
1328 if (event->group_leader == event)
1329 list_del_init(&event->group_entry);
1331 update_group_times(event);
1334 * If event was in error state, then keep it
1335 * that way, otherwise bogus counts will be
1336 * returned on read(). The only way to get out
1337 * of error state is by explicit re-enabling
1340 if (event->state > PERF_EVENT_STATE_OFF)
1341 event->state = PERF_EVENT_STATE_OFF;
1346 static void perf_group_detach(struct perf_event *event)
1348 struct perf_event *sibling, *tmp;
1349 struct list_head *list = NULL;
1352 * We can have double detach due to exit/hot-unplug + close.
1354 if (!(event->attach_state & PERF_ATTACH_GROUP))
1357 event->attach_state &= ~PERF_ATTACH_GROUP;
1360 * If this is a sibling, remove it from its group.
1362 if (event->group_leader != event) {
1363 list_del_init(&event->group_entry);
1364 event->group_leader->nr_siblings--;
1368 if (!list_empty(&event->group_entry))
1369 list = &event->group_entry;
1372 * If this was a group event with sibling events then
1373 * upgrade the siblings to singleton events by adding them
1374 * to whatever list we are on.
1376 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1378 list_move_tail(&sibling->group_entry, list);
1379 sibling->group_leader = sibling;
1381 /* Inherit group flags from the previous leader */
1382 sibling->group_flags = event->group_flags;
1386 perf_event__header_size(event->group_leader);
1388 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1389 perf_event__header_size(tmp);
1393 * User event without the task.
1395 static bool is_orphaned_event(struct perf_event *event)
1397 return event && !is_kernel_event(event) && !event->owner;
1401 * Event has a parent but parent's task finished and it's
1402 * alive only because of children holding refference.
1404 static bool is_orphaned_child(struct perf_event *event)
1406 return is_orphaned_event(event->parent);
1409 static void orphans_remove_work(struct work_struct *work);
1411 static void schedule_orphans_remove(struct perf_event_context *ctx)
1413 if (!ctx->task || ctx->orphans_remove_sched || !perf_wq)
1416 if (queue_delayed_work(perf_wq, &ctx->orphans_remove, 1)) {
1418 ctx->orphans_remove_sched = true;
1422 static int __init perf_workqueue_init(void)
1424 perf_wq = create_singlethread_workqueue("perf");
1425 WARN(!perf_wq, "failed to create perf workqueue\n");
1426 return perf_wq ? 0 : -1;
1429 core_initcall(perf_workqueue_init);
1432 event_filter_match(struct perf_event *event)
1434 return (event->cpu == -1 || event->cpu == smp_processor_id())
1435 && perf_cgroup_match(event);
1439 event_sched_out(struct perf_event *event,
1440 struct perf_cpu_context *cpuctx,
1441 struct perf_event_context *ctx)
1443 u64 tstamp = perf_event_time(event);
1446 * An event which could not be activated because of
1447 * filter mismatch still needs to have its timings
1448 * maintained, otherwise bogus information is return
1449 * via read() for time_enabled, time_running:
1451 if (event->state == PERF_EVENT_STATE_INACTIVE
1452 && !event_filter_match(event)) {
1453 delta = tstamp - event->tstamp_stopped;
1454 event->tstamp_running += delta;
1455 event->tstamp_stopped = tstamp;
1458 if (event->state != PERF_EVENT_STATE_ACTIVE)
1461 perf_pmu_disable(event->pmu);
1463 event->state = PERF_EVENT_STATE_INACTIVE;
1464 if (event->pending_disable) {
1465 event->pending_disable = 0;
1466 event->state = PERF_EVENT_STATE_OFF;
1468 event->tstamp_stopped = tstamp;
1469 event->pmu->del(event, 0);
1472 if (!is_software_event(event))
1473 cpuctx->active_oncpu--;
1475 if (event->attr.freq && event->attr.sample_freq)
1477 if (event->attr.exclusive || !cpuctx->active_oncpu)
1478 cpuctx->exclusive = 0;
1480 if (is_orphaned_child(event))
1481 schedule_orphans_remove(ctx);
1483 perf_pmu_enable(event->pmu);
1487 group_sched_out(struct perf_event *group_event,
1488 struct perf_cpu_context *cpuctx,
1489 struct perf_event_context *ctx)
1491 struct perf_event *event;
1492 int state = group_event->state;
1494 event_sched_out(group_event, cpuctx, ctx);
1497 * Schedule out siblings (if any):
1499 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1500 event_sched_out(event, cpuctx, ctx);
1502 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1503 cpuctx->exclusive = 0;
1506 struct remove_event {
1507 struct perf_event *event;
1512 * Cross CPU call to remove a performance event
1514 * We disable the event on the hardware level first. After that we
1515 * remove it from the context list.
1517 static int __perf_remove_from_context(void *info)
1519 struct remove_event *re = info;
1520 struct perf_event *event = re->event;
1521 struct perf_event_context *ctx = event->ctx;
1522 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1524 raw_spin_lock(&ctx->lock);
1525 event_sched_out(event, cpuctx, ctx);
1526 if (re->detach_group)
1527 perf_group_detach(event);
1528 list_del_event(event, ctx);
1529 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1531 cpuctx->task_ctx = NULL;
1533 raw_spin_unlock(&ctx->lock);
1540 * Remove the event from a task's (or a CPU's) list of events.
1542 * CPU events are removed with a smp call. For task events we only
1543 * call when the task is on a CPU.
1545 * If event->ctx is a cloned context, callers must make sure that
1546 * every task struct that event->ctx->task could possibly point to
1547 * remains valid. This is OK when called from perf_release since
1548 * that only calls us on the top-level context, which can't be a clone.
1549 * When called from perf_event_exit_task, it's OK because the
1550 * context has been detached from its task.
1552 static void perf_remove_from_context(struct perf_event *event, bool detach_group)
1554 struct perf_event_context *ctx = event->ctx;
1555 struct task_struct *task = ctx->task;
1556 struct remove_event re = {
1558 .detach_group = detach_group,
1561 lockdep_assert_held(&ctx->mutex);
1565 * Per cpu events are removed via an smp call and
1566 * the removal is always successful.
1568 cpu_function_call(event->cpu, __perf_remove_from_context, &re);
1573 if (!task_function_call(task, __perf_remove_from_context, &re))
1576 raw_spin_lock_irq(&ctx->lock);
1578 * If we failed to find a running task, but find the context active now
1579 * that we've acquired the ctx->lock, retry.
1581 if (ctx->is_active) {
1582 raw_spin_unlock_irq(&ctx->lock);
1584 * Reload the task pointer, it might have been changed by
1585 * a concurrent perf_event_context_sched_out().
1592 * Since the task isn't running, its safe to remove the event, us
1593 * holding the ctx->lock ensures the task won't get scheduled in.
1596 perf_group_detach(event);
1597 list_del_event(event, ctx);
1598 raw_spin_unlock_irq(&ctx->lock);
1602 * Cross CPU call to disable a performance event
1604 int __perf_event_disable(void *info)
1606 struct perf_event *event = info;
1607 struct perf_event_context *ctx = event->ctx;
1608 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1611 * If this is a per-task event, need to check whether this
1612 * event's task is the current task on this cpu.
1614 * Can trigger due to concurrent perf_event_context_sched_out()
1615 * flipping contexts around.
1617 if (ctx->task && cpuctx->task_ctx != ctx)
1620 raw_spin_lock(&ctx->lock);
1623 * If the event is on, turn it off.
1624 * If it is in error state, leave it in error state.
1626 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1627 update_context_time(ctx);
1628 update_cgrp_time_from_event(event);
1629 update_group_times(event);
1630 if (event == event->group_leader)
1631 group_sched_out(event, cpuctx, ctx);
1633 event_sched_out(event, cpuctx, ctx);
1634 event->state = PERF_EVENT_STATE_OFF;
1637 raw_spin_unlock(&ctx->lock);
1645 * If event->ctx is a cloned context, callers must make sure that
1646 * every task struct that event->ctx->task could possibly point to
1647 * remains valid. This condition is satisifed when called through
1648 * perf_event_for_each_child or perf_event_for_each because they
1649 * hold the top-level event's child_mutex, so any descendant that
1650 * goes to exit will block in sync_child_event.
1651 * When called from perf_pending_event it's OK because event->ctx
1652 * is the current context on this CPU and preemption is disabled,
1653 * hence we can't get into perf_event_task_sched_out for this context.
1655 void perf_event_disable(struct perf_event *event)
1657 struct perf_event_context *ctx = event->ctx;
1658 struct task_struct *task = ctx->task;
1662 * Disable the event on the cpu that it's on
1664 cpu_function_call(event->cpu, __perf_event_disable, event);
1669 if (!task_function_call(task, __perf_event_disable, event))
1672 raw_spin_lock_irq(&ctx->lock);
1674 * If the event is still active, we need to retry the cross-call.
1676 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1677 raw_spin_unlock_irq(&ctx->lock);
1679 * Reload the task pointer, it might have been changed by
1680 * a concurrent perf_event_context_sched_out().
1687 * Since we have the lock this context can't be scheduled
1688 * in, so we can change the state safely.
1690 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1691 update_group_times(event);
1692 event->state = PERF_EVENT_STATE_OFF;
1694 raw_spin_unlock_irq(&ctx->lock);
1696 EXPORT_SYMBOL_GPL(perf_event_disable);
1698 static void perf_set_shadow_time(struct perf_event *event,
1699 struct perf_event_context *ctx,
1703 * use the correct time source for the time snapshot
1705 * We could get by without this by leveraging the
1706 * fact that to get to this function, the caller
1707 * has most likely already called update_context_time()
1708 * and update_cgrp_time_xx() and thus both timestamp
1709 * are identical (or very close). Given that tstamp is,
1710 * already adjusted for cgroup, we could say that:
1711 * tstamp - ctx->timestamp
1713 * tstamp - cgrp->timestamp.
1715 * Then, in perf_output_read(), the calculation would
1716 * work with no changes because:
1717 * - event is guaranteed scheduled in
1718 * - no scheduled out in between
1719 * - thus the timestamp would be the same
1721 * But this is a bit hairy.
1723 * So instead, we have an explicit cgroup call to remain
1724 * within the time time source all along. We believe it
1725 * is cleaner and simpler to understand.
1727 if (is_cgroup_event(event))
1728 perf_cgroup_set_shadow_time(event, tstamp);
1730 event->shadow_ctx_time = tstamp - ctx->timestamp;
1733 #define MAX_INTERRUPTS (~0ULL)
1735 static void perf_log_throttle(struct perf_event *event, int enable);
1738 event_sched_in(struct perf_event *event,
1739 struct perf_cpu_context *cpuctx,
1740 struct perf_event_context *ctx)
1742 u64 tstamp = perf_event_time(event);
1745 lockdep_assert_held(&ctx->lock);
1747 if (event->state <= PERF_EVENT_STATE_OFF)
1750 event->state = PERF_EVENT_STATE_ACTIVE;
1751 event->oncpu = smp_processor_id();
1754 * Unthrottle events, since we scheduled we might have missed several
1755 * ticks already, also for a heavily scheduling task there is little
1756 * guarantee it'll get a tick in a timely manner.
1758 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1759 perf_log_throttle(event, 1);
1760 event->hw.interrupts = 0;
1764 * The new state must be visible before we turn it on in the hardware:
1768 perf_pmu_disable(event->pmu);
1770 if (event->pmu->add(event, PERF_EF_START)) {
1771 event->state = PERF_EVENT_STATE_INACTIVE;
1777 event->tstamp_running += tstamp - event->tstamp_stopped;
1779 perf_set_shadow_time(event, ctx, tstamp);
1781 if (!is_software_event(event))
1782 cpuctx->active_oncpu++;
1784 if (event->attr.freq && event->attr.sample_freq)
1787 if (event->attr.exclusive)
1788 cpuctx->exclusive = 1;
1790 if (is_orphaned_child(event))
1791 schedule_orphans_remove(ctx);
1794 perf_pmu_enable(event->pmu);
1800 group_sched_in(struct perf_event *group_event,
1801 struct perf_cpu_context *cpuctx,
1802 struct perf_event_context *ctx)
1804 struct perf_event *event, *partial_group = NULL;
1805 struct pmu *pmu = ctx->pmu;
1806 u64 now = ctx->time;
1807 bool simulate = false;
1809 if (group_event->state == PERF_EVENT_STATE_OFF)
1812 pmu->start_txn(pmu);
1814 if (event_sched_in(group_event, cpuctx, ctx)) {
1815 pmu->cancel_txn(pmu);
1816 perf_cpu_hrtimer_restart(cpuctx);
1821 * Schedule in siblings as one group (if any):
1823 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1824 if (event_sched_in(event, cpuctx, ctx)) {
1825 partial_group = event;
1830 if (!pmu->commit_txn(pmu))
1835 * Groups can be scheduled in as one unit only, so undo any
1836 * partial group before returning:
1837 * The events up to the failed event are scheduled out normally,
1838 * tstamp_stopped will be updated.
1840 * The failed events and the remaining siblings need to have
1841 * their timings updated as if they had gone thru event_sched_in()
1842 * and event_sched_out(). This is required to get consistent timings
1843 * across the group. This also takes care of the case where the group
1844 * could never be scheduled by ensuring tstamp_stopped is set to mark
1845 * the time the event was actually stopped, such that time delta
1846 * calculation in update_event_times() is correct.
1848 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1849 if (event == partial_group)
1853 event->tstamp_running += now - event->tstamp_stopped;
1854 event->tstamp_stopped = now;
1856 event_sched_out(event, cpuctx, ctx);
1859 event_sched_out(group_event, cpuctx, ctx);
1861 pmu->cancel_txn(pmu);
1863 perf_cpu_hrtimer_restart(cpuctx);
1869 * Work out whether we can put this event group on the CPU now.
1871 static int group_can_go_on(struct perf_event *event,
1872 struct perf_cpu_context *cpuctx,
1876 * Groups consisting entirely of software events can always go on.
1878 if (event->group_flags & PERF_GROUP_SOFTWARE)
1881 * If an exclusive group is already on, no other hardware
1884 if (cpuctx->exclusive)
1887 * If this group is exclusive and there are already
1888 * events on the CPU, it can't go on.
1890 if (event->attr.exclusive && cpuctx->active_oncpu)
1893 * Otherwise, try to add it if all previous groups were able
1899 static void add_event_to_ctx(struct perf_event *event,
1900 struct perf_event_context *ctx)
1902 u64 tstamp = perf_event_time(event);
1904 list_add_event(event, ctx);
1905 perf_group_attach(event);
1906 event->tstamp_enabled = tstamp;
1907 event->tstamp_running = tstamp;
1908 event->tstamp_stopped = tstamp;
1911 static void task_ctx_sched_out(struct perf_event_context *ctx);
1913 ctx_sched_in(struct perf_event_context *ctx,
1914 struct perf_cpu_context *cpuctx,
1915 enum event_type_t event_type,
1916 struct task_struct *task);
1918 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
1919 struct perf_event_context *ctx,
1920 struct task_struct *task)
1922 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
1924 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
1925 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
1927 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
1931 * Cross CPU call to install and enable a performance event
1933 * Must be called with ctx->mutex held
1935 static int __perf_install_in_context(void *info)
1937 struct perf_event *event = info;
1938 struct perf_event_context *ctx = event->ctx;
1939 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1940 struct perf_event_context *task_ctx = cpuctx->task_ctx;
1941 struct task_struct *task = current;
1943 perf_ctx_lock(cpuctx, task_ctx);
1944 perf_pmu_disable(cpuctx->ctx.pmu);
1947 * If there was an active task_ctx schedule it out.
1950 task_ctx_sched_out(task_ctx);
1953 * If the context we're installing events in is not the
1954 * active task_ctx, flip them.
1956 if (ctx->task && task_ctx != ctx) {
1958 raw_spin_unlock(&task_ctx->lock);
1959 raw_spin_lock(&ctx->lock);
1964 cpuctx->task_ctx = task_ctx;
1965 task = task_ctx->task;
1968 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
1970 update_context_time(ctx);
1972 * update cgrp time only if current cgrp
1973 * matches event->cgrp. Must be done before
1974 * calling add_event_to_ctx()
1976 update_cgrp_time_from_event(event);
1978 add_event_to_ctx(event, ctx);
1981 * Schedule everything back in
1983 perf_event_sched_in(cpuctx, task_ctx, task);
1985 perf_pmu_enable(cpuctx->ctx.pmu);
1986 perf_ctx_unlock(cpuctx, task_ctx);
1992 * Attach a performance event to a context
1994 * First we add the event to the list with the hardware enable bit
1995 * in event->hw_config cleared.
1997 * If the event is attached to a task which is on a CPU we use a smp
1998 * call to enable it in the task context. The task might have been
1999 * scheduled away, but we check this in the smp call again.
2002 perf_install_in_context(struct perf_event_context *ctx,
2003 struct perf_event *event,
2006 struct task_struct *task = ctx->task;
2008 lockdep_assert_held(&ctx->mutex);
2011 if (event->cpu != -1)
2016 * Per cpu events are installed via an smp call and
2017 * the install is always successful.
2019 cpu_function_call(cpu, __perf_install_in_context, event);
2024 if (!task_function_call(task, __perf_install_in_context, event))
2027 raw_spin_lock_irq(&ctx->lock);
2029 * If we failed to find a running task, but find the context active now
2030 * that we've acquired the ctx->lock, retry.
2032 if (ctx->is_active) {
2033 raw_spin_unlock_irq(&ctx->lock);
2035 * Reload the task pointer, it might have been changed by
2036 * a concurrent perf_event_context_sched_out().
2043 * Since the task isn't running, its safe to add the event, us holding
2044 * the ctx->lock ensures the task won't get scheduled in.
2046 add_event_to_ctx(event, ctx);
2047 raw_spin_unlock_irq(&ctx->lock);
2051 * Put a event into inactive state and update time fields.
2052 * Enabling the leader of a group effectively enables all
2053 * the group members that aren't explicitly disabled, so we
2054 * have to update their ->tstamp_enabled also.
2055 * Note: this works for group members as well as group leaders
2056 * since the non-leader members' sibling_lists will be empty.
2058 static void __perf_event_mark_enabled(struct perf_event *event)
2060 struct perf_event *sub;
2061 u64 tstamp = perf_event_time(event);
2063 event->state = PERF_EVENT_STATE_INACTIVE;
2064 event->tstamp_enabled = tstamp - event->total_time_enabled;
2065 list_for_each_entry(sub, &event->sibling_list, group_entry) {
2066 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2067 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2072 * Cross CPU call to enable a performance event
2074 static int __perf_event_enable(void *info)
2076 struct perf_event *event = info;
2077 struct perf_event_context *ctx = event->ctx;
2078 struct perf_event *leader = event->group_leader;
2079 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2083 * There's a time window between 'ctx->is_active' check
2084 * in perf_event_enable function and this place having:
2086 * - ctx->lock unlocked
2088 * where the task could be killed and 'ctx' deactivated
2089 * by perf_event_exit_task.
2091 if (!ctx->is_active)
2094 raw_spin_lock(&ctx->lock);
2095 update_context_time(ctx);
2097 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2101 * set current task's cgroup time reference point
2103 perf_cgroup_set_timestamp(current, ctx);
2105 __perf_event_mark_enabled(event);
2107 if (!event_filter_match(event)) {
2108 if (is_cgroup_event(event))
2109 perf_cgroup_defer_enabled(event);
2114 * If the event is in a group and isn't the group leader,
2115 * then don't put it on unless the group is on.
2117 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
2120 if (!group_can_go_on(event, cpuctx, 1)) {
2123 if (event == leader)
2124 err = group_sched_in(event, cpuctx, ctx);
2126 err = event_sched_in(event, cpuctx, ctx);
2131 * If this event can't go on and it's part of a
2132 * group, then the whole group has to come off.
2134 if (leader != event) {
2135 group_sched_out(leader, cpuctx, ctx);
2136 perf_cpu_hrtimer_restart(cpuctx);
2138 if (leader->attr.pinned) {
2139 update_group_times(leader);
2140 leader->state = PERF_EVENT_STATE_ERROR;
2145 raw_spin_unlock(&ctx->lock);
2153 * If event->ctx is a cloned context, callers must make sure that
2154 * every task struct that event->ctx->task could possibly point to
2155 * remains valid. This condition is satisfied when called through
2156 * perf_event_for_each_child or perf_event_for_each as described
2157 * for perf_event_disable.
2159 void perf_event_enable(struct perf_event *event)
2161 struct perf_event_context *ctx = event->ctx;
2162 struct task_struct *task = ctx->task;
2166 * Enable the event on the cpu that it's on
2168 cpu_function_call(event->cpu, __perf_event_enable, event);
2172 raw_spin_lock_irq(&ctx->lock);
2173 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2177 * If the event is in error state, clear that first.
2178 * That way, if we see the event in error state below, we
2179 * know that it has gone back into error state, as distinct
2180 * from the task having been scheduled away before the
2181 * cross-call arrived.
2183 if (event->state == PERF_EVENT_STATE_ERROR)
2184 event->state = PERF_EVENT_STATE_OFF;
2187 if (!ctx->is_active) {
2188 __perf_event_mark_enabled(event);
2192 raw_spin_unlock_irq(&ctx->lock);
2194 if (!task_function_call(task, __perf_event_enable, event))
2197 raw_spin_lock_irq(&ctx->lock);
2200 * If the context is active and the event is still off,
2201 * we need to retry the cross-call.
2203 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
2205 * task could have been flipped by a concurrent
2206 * perf_event_context_sched_out()
2213 raw_spin_unlock_irq(&ctx->lock);
2215 EXPORT_SYMBOL_GPL(perf_event_enable);
2217 int perf_event_refresh(struct perf_event *event, int refresh)
2220 * not supported on inherited events
2222 if (event->attr.inherit || !is_sampling_event(event))
2225 atomic_add(refresh, &event->event_limit);
2226 perf_event_enable(event);
2230 EXPORT_SYMBOL_GPL(perf_event_refresh);
2232 static void ctx_sched_out(struct perf_event_context *ctx,
2233 struct perf_cpu_context *cpuctx,
2234 enum event_type_t event_type)
2236 struct perf_event *event;
2237 int is_active = ctx->is_active;
2239 ctx->is_active &= ~event_type;
2240 if (likely(!ctx->nr_events))
2243 update_context_time(ctx);
2244 update_cgrp_time_from_cpuctx(cpuctx);
2245 if (!ctx->nr_active)
2248 perf_pmu_disable(ctx->pmu);
2249 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2250 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2251 group_sched_out(event, cpuctx, ctx);
2254 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2255 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2256 group_sched_out(event, cpuctx, ctx);
2258 perf_pmu_enable(ctx->pmu);
2262 * Test whether two contexts are equivalent, i.e. whether they have both been
2263 * cloned from the same version of the same context.
2265 * Equivalence is measured using a generation number in the context that is
2266 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2267 * and list_del_event().
2269 static int context_equiv(struct perf_event_context *ctx1,
2270 struct perf_event_context *ctx2)
2272 lockdep_assert_held(&ctx1->lock);
2273 lockdep_assert_held(&ctx2->lock);
2275 /* Pinning disables the swap optimization */
2276 if (ctx1->pin_count || ctx2->pin_count)
2279 /* If ctx1 is the parent of ctx2 */
2280 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2283 /* If ctx2 is the parent of ctx1 */
2284 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2288 * If ctx1 and ctx2 have the same parent; we flatten the parent
2289 * hierarchy, see perf_event_init_context().
2291 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2292 ctx1->parent_gen == ctx2->parent_gen)
2299 static void __perf_event_sync_stat(struct perf_event *event,
2300 struct perf_event *next_event)
2304 if (!event->attr.inherit_stat)
2308 * Update the event value, we cannot use perf_event_read()
2309 * because we're in the middle of a context switch and have IRQs
2310 * disabled, which upsets smp_call_function_single(), however
2311 * we know the event must be on the current CPU, therefore we
2312 * don't need to use it.
2314 switch (event->state) {
2315 case PERF_EVENT_STATE_ACTIVE:
2316 event->pmu->read(event);
2319 case PERF_EVENT_STATE_INACTIVE:
2320 update_event_times(event);
2328 * In order to keep per-task stats reliable we need to flip the event
2329 * values when we flip the contexts.
2331 value = local64_read(&next_event->count);
2332 value = local64_xchg(&event->count, value);
2333 local64_set(&next_event->count, value);
2335 swap(event->total_time_enabled, next_event->total_time_enabled);
2336 swap(event->total_time_running, next_event->total_time_running);
2339 * Since we swizzled the values, update the user visible data too.
2341 perf_event_update_userpage(event);
2342 perf_event_update_userpage(next_event);
2345 static void perf_event_sync_stat(struct perf_event_context *ctx,
2346 struct perf_event_context *next_ctx)
2348 struct perf_event *event, *next_event;
2353 update_context_time(ctx);
2355 event = list_first_entry(&ctx->event_list,
2356 struct perf_event, event_entry);
2358 next_event = list_first_entry(&next_ctx->event_list,
2359 struct perf_event, event_entry);
2361 while (&event->event_entry != &ctx->event_list &&
2362 &next_event->event_entry != &next_ctx->event_list) {
2364 __perf_event_sync_stat(event, next_event);
2366 event = list_next_entry(event, event_entry);
2367 next_event = list_next_entry(next_event, event_entry);
2371 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2372 struct task_struct *next)
2374 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2375 struct perf_event_context *next_ctx;
2376 struct perf_event_context *parent, *next_parent;
2377 struct perf_cpu_context *cpuctx;
2383 cpuctx = __get_cpu_context(ctx);
2384 if (!cpuctx->task_ctx)
2388 next_ctx = next->perf_event_ctxp[ctxn];
2392 parent = rcu_dereference(ctx->parent_ctx);
2393 next_parent = rcu_dereference(next_ctx->parent_ctx);
2395 /* If neither context have a parent context; they cannot be clones. */
2396 if (!parent && !next_parent)
2399 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2401 * Looks like the two contexts are clones, so we might be
2402 * able to optimize the context switch. We lock both
2403 * contexts and check that they are clones under the
2404 * lock (including re-checking that neither has been
2405 * uncloned in the meantime). It doesn't matter which
2406 * order we take the locks because no other cpu could
2407 * be trying to lock both of these tasks.
2409 raw_spin_lock(&ctx->lock);
2410 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2411 if (context_equiv(ctx, next_ctx)) {
2413 * XXX do we need a memory barrier of sorts
2414 * wrt to rcu_dereference() of perf_event_ctxp
2416 task->perf_event_ctxp[ctxn] = next_ctx;
2417 next->perf_event_ctxp[ctxn] = ctx;
2419 next_ctx->task = task;
2422 perf_event_sync_stat(ctx, next_ctx);
2424 raw_spin_unlock(&next_ctx->lock);
2425 raw_spin_unlock(&ctx->lock);
2431 raw_spin_lock(&ctx->lock);
2432 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2433 cpuctx->task_ctx = NULL;
2434 raw_spin_unlock(&ctx->lock);
2438 #define for_each_task_context_nr(ctxn) \
2439 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2442 * Called from scheduler to remove the events of the current task,
2443 * with interrupts disabled.
2445 * We stop each event and update the event value in event->count.
2447 * This does not protect us against NMI, but disable()
2448 * sets the disabled bit in the control field of event _before_
2449 * accessing the event control register. If a NMI hits, then it will
2450 * not restart the event.
2452 void __perf_event_task_sched_out(struct task_struct *task,
2453 struct task_struct *next)
2457 for_each_task_context_nr(ctxn)
2458 perf_event_context_sched_out(task, ctxn, next);
2461 * if cgroup events exist on this CPU, then we need
2462 * to check if we have to switch out PMU state.
2463 * cgroup event are system-wide mode only
2465 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2466 perf_cgroup_sched_out(task, next);
2469 static void task_ctx_sched_out(struct perf_event_context *ctx)
2471 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2473 if (!cpuctx->task_ctx)
2476 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2479 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2480 cpuctx->task_ctx = NULL;
2484 * Called with IRQs disabled
2486 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2487 enum event_type_t event_type)
2489 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2493 ctx_pinned_sched_in(struct perf_event_context *ctx,
2494 struct perf_cpu_context *cpuctx)
2496 struct perf_event *event;
2498 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2499 if (event->state <= PERF_EVENT_STATE_OFF)
2501 if (!event_filter_match(event))
2504 /* may need to reset tstamp_enabled */
2505 if (is_cgroup_event(event))
2506 perf_cgroup_mark_enabled(event, ctx);
2508 if (group_can_go_on(event, cpuctx, 1))
2509 group_sched_in(event, cpuctx, ctx);
2512 * If this pinned group hasn't been scheduled,
2513 * put it in error state.
2515 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2516 update_group_times(event);
2517 event->state = PERF_EVENT_STATE_ERROR;
2523 ctx_flexible_sched_in(struct perf_event_context *ctx,
2524 struct perf_cpu_context *cpuctx)
2526 struct perf_event *event;
2529 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2530 /* Ignore events in OFF or ERROR state */
2531 if (event->state <= PERF_EVENT_STATE_OFF)
2534 * Listen to the 'cpu' scheduling filter constraint
2537 if (!event_filter_match(event))
2540 /* may need to reset tstamp_enabled */
2541 if (is_cgroup_event(event))
2542 perf_cgroup_mark_enabled(event, ctx);
2544 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2545 if (group_sched_in(event, cpuctx, ctx))
2552 ctx_sched_in(struct perf_event_context *ctx,
2553 struct perf_cpu_context *cpuctx,
2554 enum event_type_t event_type,
2555 struct task_struct *task)
2558 int is_active = ctx->is_active;
2560 ctx->is_active |= event_type;
2561 if (likely(!ctx->nr_events))
2565 ctx->timestamp = now;
2566 perf_cgroup_set_timestamp(task, ctx);
2568 * First go through the list and put on any pinned groups
2569 * in order to give them the best chance of going on.
2571 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2572 ctx_pinned_sched_in(ctx, cpuctx);
2574 /* Then walk through the lower prio flexible groups */
2575 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2576 ctx_flexible_sched_in(ctx, cpuctx);
2579 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2580 enum event_type_t event_type,
2581 struct task_struct *task)
2583 struct perf_event_context *ctx = &cpuctx->ctx;
2585 ctx_sched_in(ctx, cpuctx, event_type, task);
2588 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2589 struct task_struct *task)
2591 struct perf_cpu_context *cpuctx;
2593 cpuctx = __get_cpu_context(ctx);
2594 if (cpuctx->task_ctx == ctx)
2597 perf_ctx_lock(cpuctx, ctx);
2598 perf_pmu_disable(ctx->pmu);
2600 * We want to keep the following priority order:
2601 * cpu pinned (that don't need to move), task pinned,
2602 * cpu flexible, task flexible.
2604 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2607 cpuctx->task_ctx = ctx;
2609 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2611 perf_pmu_enable(ctx->pmu);
2612 perf_ctx_unlock(cpuctx, ctx);
2615 * Since these rotations are per-cpu, we need to ensure the
2616 * cpu-context we got scheduled on is actually rotating.
2618 perf_pmu_rotate_start(ctx->pmu);
2622 * When sampling the branck stack in system-wide, it may be necessary
2623 * to flush the stack on context switch. This happens when the branch
2624 * stack does not tag its entries with the pid of the current task.
2625 * Otherwise it becomes impossible to associate a branch entry with a
2626 * task. This ambiguity is more likely to appear when the branch stack
2627 * supports priv level filtering and the user sets it to monitor only
2628 * at the user level (which could be a useful measurement in system-wide
2629 * mode). In that case, the risk is high of having a branch stack with
2630 * branch from multiple tasks. Flushing may mean dropping the existing
2631 * entries or stashing them somewhere in the PMU specific code layer.
2633 * This function provides the context switch callback to the lower code
2634 * layer. It is invoked ONLY when there is at least one system-wide context
2635 * with at least one active event using taken branch sampling.
2637 static void perf_branch_stack_sched_in(struct task_struct *prev,
2638 struct task_struct *task)
2640 struct perf_cpu_context *cpuctx;
2642 unsigned long flags;
2644 /* no need to flush branch stack if not changing task */
2648 local_irq_save(flags);
2652 list_for_each_entry_rcu(pmu, &pmus, entry) {
2653 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2656 * check if the context has at least one
2657 * event using PERF_SAMPLE_BRANCH_STACK
2659 if (cpuctx->ctx.nr_branch_stack > 0
2660 && pmu->flush_branch_stack) {
2662 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2664 perf_pmu_disable(pmu);
2666 pmu->flush_branch_stack();
2668 perf_pmu_enable(pmu);
2670 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2676 local_irq_restore(flags);
2680 * Called from scheduler to add the events of the current task
2681 * with interrupts disabled.
2683 * We restore the event value and then enable it.
2685 * This does not protect us against NMI, but enable()
2686 * sets the enabled bit in the control field of event _before_
2687 * accessing the event control register. If a NMI hits, then it will
2688 * keep the event running.
2690 void __perf_event_task_sched_in(struct task_struct *prev,
2691 struct task_struct *task)
2693 struct perf_event_context *ctx;
2696 for_each_task_context_nr(ctxn) {
2697 ctx = task->perf_event_ctxp[ctxn];
2701 perf_event_context_sched_in(ctx, task);
2704 * if cgroup events exist on this CPU, then we need
2705 * to check if we have to switch in PMU state.
2706 * cgroup event are system-wide mode only
2708 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2709 perf_cgroup_sched_in(prev, task);
2711 /* check for system-wide branch_stack events */
2712 if (atomic_read(&__get_cpu_var(perf_branch_stack_events)))
2713 perf_branch_stack_sched_in(prev, task);
2716 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2718 u64 frequency = event->attr.sample_freq;
2719 u64 sec = NSEC_PER_SEC;
2720 u64 divisor, dividend;
2722 int count_fls, nsec_fls, frequency_fls, sec_fls;
2724 count_fls = fls64(count);
2725 nsec_fls = fls64(nsec);
2726 frequency_fls = fls64(frequency);
2730 * We got @count in @nsec, with a target of sample_freq HZ
2731 * the target period becomes:
2734 * period = -------------------
2735 * @nsec * sample_freq
2740 * Reduce accuracy by one bit such that @a and @b converge
2741 * to a similar magnitude.
2743 #define REDUCE_FLS(a, b) \
2745 if (a##_fls > b##_fls) { \
2755 * Reduce accuracy until either term fits in a u64, then proceed with
2756 * the other, so that finally we can do a u64/u64 division.
2758 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2759 REDUCE_FLS(nsec, frequency);
2760 REDUCE_FLS(sec, count);
2763 if (count_fls + sec_fls > 64) {
2764 divisor = nsec * frequency;
2766 while (count_fls + sec_fls > 64) {
2767 REDUCE_FLS(count, sec);
2771 dividend = count * sec;
2773 dividend = count * sec;
2775 while (nsec_fls + frequency_fls > 64) {
2776 REDUCE_FLS(nsec, frequency);
2780 divisor = nsec * frequency;
2786 return div64_u64(dividend, divisor);
2789 static DEFINE_PER_CPU(int, perf_throttled_count);
2790 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2792 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2794 struct hw_perf_event *hwc = &event->hw;
2795 s64 period, sample_period;
2798 period = perf_calculate_period(event, nsec, count);
2800 delta = (s64)(period - hwc->sample_period);
2801 delta = (delta + 7) / 8; /* low pass filter */
2803 sample_period = hwc->sample_period + delta;
2808 hwc->sample_period = sample_period;
2810 if (local64_read(&hwc->period_left) > 8*sample_period) {
2812 event->pmu->stop(event, PERF_EF_UPDATE);
2814 local64_set(&hwc->period_left, 0);
2817 event->pmu->start(event, PERF_EF_RELOAD);
2822 * combine freq adjustment with unthrottling to avoid two passes over the
2823 * events. At the same time, make sure, having freq events does not change
2824 * the rate of unthrottling as that would introduce bias.
2826 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
2829 struct perf_event *event;
2830 struct hw_perf_event *hwc;
2831 u64 now, period = TICK_NSEC;
2835 * only need to iterate over all events iff:
2836 * - context have events in frequency mode (needs freq adjust)
2837 * - there are events to unthrottle on this cpu
2839 if (!(ctx->nr_freq || needs_unthr))
2842 raw_spin_lock(&ctx->lock);
2843 perf_pmu_disable(ctx->pmu);
2845 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
2846 if (event->state != PERF_EVENT_STATE_ACTIVE)
2849 if (!event_filter_match(event))
2852 perf_pmu_disable(event->pmu);
2856 if (hwc->interrupts == MAX_INTERRUPTS) {
2857 hwc->interrupts = 0;
2858 perf_log_throttle(event, 1);
2859 event->pmu->start(event, 0);
2862 if (!event->attr.freq || !event->attr.sample_freq)
2866 * stop the event and update event->count
2868 event->pmu->stop(event, PERF_EF_UPDATE);
2870 now = local64_read(&event->count);
2871 delta = now - hwc->freq_count_stamp;
2872 hwc->freq_count_stamp = now;
2876 * reload only if value has changed
2877 * we have stopped the event so tell that
2878 * to perf_adjust_period() to avoid stopping it
2882 perf_adjust_period(event, period, delta, false);
2884 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
2886 perf_pmu_enable(event->pmu);
2889 perf_pmu_enable(ctx->pmu);
2890 raw_spin_unlock(&ctx->lock);
2894 * Round-robin a context's events:
2896 static void rotate_ctx(struct perf_event_context *ctx)
2899 * Rotate the first entry last of non-pinned groups. Rotation might be
2900 * disabled by the inheritance code.
2902 if (!ctx->rotate_disable)
2903 list_rotate_left(&ctx->flexible_groups);
2907 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
2908 * because they're strictly cpu affine and rotate_start is called with IRQs
2909 * disabled, while rotate_context is called from IRQ context.
2911 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
2913 struct perf_event_context *ctx = NULL;
2914 int rotate = 0, remove = 1;
2916 if (cpuctx->ctx.nr_events) {
2918 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
2922 ctx = cpuctx->task_ctx;
2923 if (ctx && ctx->nr_events) {
2925 if (ctx->nr_events != ctx->nr_active)
2932 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2933 perf_pmu_disable(cpuctx->ctx.pmu);
2935 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2937 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
2939 rotate_ctx(&cpuctx->ctx);
2943 perf_event_sched_in(cpuctx, ctx, current);
2945 perf_pmu_enable(cpuctx->ctx.pmu);
2946 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2949 list_del_init(&cpuctx->rotation_list);
2954 #ifdef CONFIG_NO_HZ_FULL
2955 bool perf_event_can_stop_tick(void)
2957 if (atomic_read(&nr_freq_events) ||
2958 __this_cpu_read(perf_throttled_count))
2965 void perf_event_task_tick(void)
2967 struct list_head *head = &__get_cpu_var(rotation_list);
2968 struct perf_cpu_context *cpuctx, *tmp;
2969 struct perf_event_context *ctx;
2972 WARN_ON(!irqs_disabled());
2974 __this_cpu_inc(perf_throttled_seq);
2975 throttled = __this_cpu_xchg(perf_throttled_count, 0);
2977 list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) {
2979 perf_adjust_freq_unthr_context(ctx, throttled);
2981 ctx = cpuctx->task_ctx;
2983 perf_adjust_freq_unthr_context(ctx, throttled);
2987 static int event_enable_on_exec(struct perf_event *event,
2988 struct perf_event_context *ctx)
2990 if (!event->attr.enable_on_exec)
2993 event->attr.enable_on_exec = 0;
2994 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2997 __perf_event_mark_enabled(event);
3003 * Enable all of a task's events that have been marked enable-on-exec.
3004 * This expects task == current.
3006 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
3008 struct perf_event_context *clone_ctx = NULL;
3009 struct perf_event *event;
3010 unsigned long flags;
3014 local_irq_save(flags);
3015 if (!ctx || !ctx->nr_events)
3019 * We must ctxsw out cgroup events to avoid conflict
3020 * when invoking perf_task_event_sched_in() later on
3021 * in this function. Otherwise we end up trying to
3022 * ctxswin cgroup events which are already scheduled
3025 perf_cgroup_sched_out(current, NULL);
3027 raw_spin_lock(&ctx->lock);
3028 task_ctx_sched_out(ctx);
3030 list_for_each_entry(event, &ctx->event_list, event_entry) {
3031 ret = event_enable_on_exec(event, ctx);
3037 * Unclone this context if we enabled any event.
3040 clone_ctx = unclone_ctx(ctx);
3042 raw_spin_unlock(&ctx->lock);
3045 * Also calls ctxswin for cgroup events, if any:
3047 perf_event_context_sched_in(ctx, ctx->task);
3049 local_irq_restore(flags);
3055 void perf_event_exec(void)
3057 struct perf_event_context *ctx;
3061 for_each_task_context_nr(ctxn) {
3062 ctx = current->perf_event_ctxp[ctxn];
3066 perf_event_enable_on_exec(ctx);
3072 * Cross CPU call to read the hardware event
3074 static void __perf_event_read(void *info)
3076 struct perf_event *event = info;
3077 struct perf_event_context *ctx = event->ctx;
3078 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3081 * If this is a task context, we need to check whether it is
3082 * the current task context of this cpu. If not it has been
3083 * scheduled out before the smp call arrived. In that case
3084 * event->count would have been updated to a recent sample
3085 * when the event was scheduled out.
3087 if (ctx->task && cpuctx->task_ctx != ctx)
3090 raw_spin_lock(&ctx->lock);
3091 if (ctx->is_active) {
3092 update_context_time(ctx);
3093 update_cgrp_time_from_event(event);
3095 update_event_times(event);
3096 if (event->state == PERF_EVENT_STATE_ACTIVE)
3097 event->pmu->read(event);
3098 raw_spin_unlock(&ctx->lock);
3101 static inline u64 perf_event_count(struct perf_event *event)
3103 return local64_read(&event->count) + atomic64_read(&event->child_count);
3106 static u64 perf_event_read(struct perf_event *event)
3109 * If event is enabled and currently active on a CPU, update the
3110 * value in the event structure:
3112 if (event->state == PERF_EVENT_STATE_ACTIVE) {
3113 smp_call_function_single(event->oncpu,
3114 __perf_event_read, event, 1);
3115 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3116 struct perf_event_context *ctx = event->ctx;
3117 unsigned long flags;
3119 raw_spin_lock_irqsave(&ctx->lock, flags);
3121 * may read while context is not active
3122 * (e.g., thread is blocked), in that case
3123 * we cannot update context time
3125 if (ctx->is_active) {
3126 update_context_time(ctx);
3127 update_cgrp_time_from_event(event);
3129 update_event_times(event);
3130 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3133 return perf_event_count(event);
3137 * Initialize the perf_event context in a task_struct:
3139 static void __perf_event_init_context(struct perf_event_context *ctx)
3141 raw_spin_lock_init(&ctx->lock);
3142 mutex_init(&ctx->mutex);
3143 INIT_LIST_HEAD(&ctx->pinned_groups);
3144 INIT_LIST_HEAD(&ctx->flexible_groups);
3145 INIT_LIST_HEAD(&ctx->event_list);
3146 atomic_set(&ctx->refcount, 1);
3147 INIT_DELAYED_WORK(&ctx->orphans_remove, orphans_remove_work);
3150 static struct perf_event_context *
3151 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3153 struct perf_event_context *ctx;
3155 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3159 __perf_event_init_context(ctx);
3162 get_task_struct(task);
3169 static struct task_struct *
3170 find_lively_task_by_vpid(pid_t vpid)
3172 struct task_struct *task;
3179 task = find_task_by_vpid(vpid);
3181 get_task_struct(task);
3185 return ERR_PTR(-ESRCH);
3187 /* Reuse ptrace permission checks for now. */
3189 if (!ptrace_may_access(task, PTRACE_MODE_READ))
3194 put_task_struct(task);
3195 return ERR_PTR(err);
3200 * Returns a matching context with refcount and pincount.
3202 static struct perf_event_context *
3203 find_get_context(struct pmu *pmu, struct task_struct *task, int cpu)
3205 struct perf_event_context *ctx, *clone_ctx = NULL;
3206 struct perf_cpu_context *cpuctx;
3207 unsigned long flags;
3211 /* Must be root to operate on a CPU event: */
3212 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3213 return ERR_PTR(-EACCES);
3216 * We could be clever and allow to attach a event to an
3217 * offline CPU and activate it when the CPU comes up, but
3220 if (!cpu_online(cpu))
3221 return ERR_PTR(-ENODEV);
3223 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3232 ctxn = pmu->task_ctx_nr;
3237 ctx = perf_lock_task_context(task, ctxn, &flags);
3239 clone_ctx = unclone_ctx(ctx);
3241 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3246 ctx = alloc_perf_context(pmu, task);
3252 mutex_lock(&task->perf_event_mutex);
3254 * If it has already passed perf_event_exit_task().
3255 * we must see PF_EXITING, it takes this mutex too.
3257 if (task->flags & PF_EXITING)
3259 else if (task->perf_event_ctxp[ctxn])
3264 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3266 mutex_unlock(&task->perf_event_mutex);
3268 if (unlikely(err)) {
3280 return ERR_PTR(err);
3283 static void perf_event_free_filter(struct perf_event *event);
3285 static void free_event_rcu(struct rcu_head *head)
3287 struct perf_event *event;
3289 event = container_of(head, struct perf_event, rcu_head);
3291 put_pid_ns(event->ns);
3292 perf_event_free_filter(event);
3296 static void ring_buffer_put(struct ring_buffer *rb);
3297 static void ring_buffer_attach(struct perf_event *event,
3298 struct ring_buffer *rb);
3300 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3305 if (has_branch_stack(event)) {
3306 if (!(event->attach_state & PERF_ATTACH_TASK))
3307 atomic_dec(&per_cpu(perf_branch_stack_events, cpu));
3309 if (is_cgroup_event(event))
3310 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3313 static void unaccount_event(struct perf_event *event)
3318 if (event->attach_state & PERF_ATTACH_TASK)
3319 static_key_slow_dec_deferred(&perf_sched_events);
3320 if (event->attr.mmap || event->attr.mmap_data)
3321 atomic_dec(&nr_mmap_events);
3322 if (event->attr.comm)
3323 atomic_dec(&nr_comm_events);
3324 if (event->attr.task)
3325 atomic_dec(&nr_task_events);
3326 if (event->attr.freq)
3327 atomic_dec(&nr_freq_events);
3328 if (is_cgroup_event(event))
3329 static_key_slow_dec_deferred(&perf_sched_events);
3330 if (has_branch_stack(event))
3331 static_key_slow_dec_deferred(&perf_sched_events);
3333 unaccount_event_cpu(event, event->cpu);
3336 static void __free_event(struct perf_event *event)
3338 if (!event->parent) {
3339 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3340 put_callchain_buffers();
3344 event->destroy(event);
3347 put_ctx(event->ctx);
3350 module_put(event->pmu->module);
3352 call_rcu(&event->rcu_head, free_event_rcu);
3355 static void _free_event(struct perf_event *event)
3357 irq_work_sync(&event->pending);
3359 unaccount_event(event);
3363 * Can happen when we close an event with re-directed output.
3365 * Since we have a 0 refcount, perf_mmap_close() will skip
3366 * over us; possibly making our ring_buffer_put() the last.
3368 mutex_lock(&event->mmap_mutex);
3369 ring_buffer_attach(event, NULL);
3370 mutex_unlock(&event->mmap_mutex);
3373 if (is_cgroup_event(event))
3374 perf_detach_cgroup(event);
3376 __free_event(event);
3380 * Used to free events which have a known refcount of 1, such as in error paths
3381 * where the event isn't exposed yet and inherited events.
3383 static void free_event(struct perf_event *event)
3385 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3386 "unexpected event refcount: %ld; ptr=%p\n",
3387 atomic_long_read(&event->refcount), event)) {
3388 /* leak to avoid use-after-free */
3396 * Remove user event from the owner task.
3398 static void perf_remove_from_owner(struct perf_event *event)
3400 struct task_struct *owner;
3403 owner = ACCESS_ONCE(event->owner);
3405 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3406 * !owner it means the list deletion is complete and we can indeed
3407 * free this event, otherwise we need to serialize on
3408 * owner->perf_event_mutex.
3410 smp_read_barrier_depends();
3413 * Since delayed_put_task_struct() also drops the last
3414 * task reference we can safely take a new reference
3415 * while holding the rcu_read_lock().
3417 get_task_struct(owner);
3422 mutex_lock(&owner->perf_event_mutex);
3424 * We have to re-check the event->owner field, if it is cleared
3425 * we raced with perf_event_exit_task(), acquiring the mutex
3426 * ensured they're done, and we can proceed with freeing the