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 = __this_cpu_read(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 = __this_cpu_read(running_sample_length);
275 local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES;
276 local_samples_len += sample_len_ns;
277 __this_cpu_write(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 = this_cpu_ptr(&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(this_cpu_ptr(&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(this_cpu_ptr(&perf_cgroup_events)))
2709 perf_cgroup_sched_in(prev, task);
2711 /* check for system-wide branch_stack events */
2712 if (atomic_read(this_cpu_ptr(&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 = this_cpu_ptr(&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
3430 list_del_init(&event->owner_entry);
3431 mutex_unlock(&owner->perf_event_mutex);
3432 put_task_struct(owner);
3437 * Called when the last reference to the file is gone.
3439 static void put_event(struct perf_event *event)
3441 struct perf_event_context *ctx = event->ctx;
3443 if (!atomic_long_dec_and_test(&event->refcount))
3446 if (!is_kernel_event(event))
3447 perf_remove_from_owner(event);
3449 WARN_ON_ONCE(ctx->parent_ctx);
3451 * There are two ways this annotation is useful:
3453 * 1) there is a lock recursion from perf_event_exit_task
3454 * see the comment there.
3456 * 2) there is a lock-inversion with mmap_sem through
3457 * perf_event_read_group(), which takes faults while
3458 * holding ctx->mutex, however this is called after
3459 * the last filedesc died, so there is no possibility
3460 * to trigger the AB-BA case.
3462 mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
3463 perf_remove_from_context(event, true);
3464 mutex_unlock(&ctx->mutex);
3469 int perf_event_release_kernel(struct perf_event *event)
3474 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3476 static int perf_release(struct inode *inode, struct file *file)
3478 put_event(file->private_data);
3483 * Remove all orphanes events from the context.
3485 static void orphans_remove_work(struct work_struct *work)
3487 struct perf_event_context *ctx;
3488 struct perf_event *event, *tmp;
3490 ctx = container_of(work, struct perf_event_context,
3491 orphans_remove.work);
3493 mutex_lock(&ctx->mutex);
3494 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) {
3495 struct perf_event *parent_event = event->parent;
3497 if (!is_orphaned_child(event))
3500 perf_remove_from_context(event, true);
3502 mutex_lock(&parent_event->child_mutex);
3503 list_del_init(&event->child_list);
3504 mutex_unlock(&parent_event->child_mutex);
3507 put_event(parent_event);
3510 raw_spin_lock_irq(&ctx->lock);
3511 ctx->orphans_remove_sched = false;
3512 raw_spin_unlock_irq(&ctx->lock);
3513 mutex_unlock(&ctx->mutex);
3518 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3520 struct perf_event *child;
3526 mutex_lock(&event->child_mutex);
3527 total += perf_event_read(event);
3528 *enabled += event->total_time_enabled +
3529 atomic64_read(&event->child_total_time_enabled);
3530 *running += event->total_time_running +
3531 atomic64_read(&event->child_total_time_running);
3533 list_for_each_entry(child, &event->child_list, child_list) {
3534 total += perf_event_read(child);
3535 *enabled += child->total_time_enabled;
3536 *running += child->total_time_running;
3538 mutex_unlock(&event->child_mutex);
3542 EXPORT_SYMBOL_GPL(perf_event_read_value);
3544 static int perf_event_read_group(struct perf_event *event,
3545 u64 read_format, char __user *buf)
3547 struct perf_event *leader = event->group_leader, *sub;
3548 int n = 0, size = 0, ret = -EFAULT;
3549 struct perf_event_context *ctx = leader->ctx;
3551 u64 count, enabled, running;
3553 mutex_lock(&ctx->mutex);
3554 count = perf_event_read_value(leader, &enabled, &running);
3556 values[n++] = 1 + leader->nr_siblings;
3557 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3558 values[n++] = enabled;
3559 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3560 values[n++] = running;
3561 values[n++] = count;
3562 if (read_format & PERF_FORMAT_ID)
3563 values[n++] = primary_event_id(leader);
3565 size = n * sizeof(u64);
3567 if (copy_to_user(buf, values, size))
3572 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3575 values[n++] = perf_event_read_value(sub, &enabled, &running);
3576 if (read_format & PERF_FORMAT_ID)
3577 values[n++] = primary_event_id(sub);
3579 size = n * sizeof(u64);
3581 if (copy_to_user(buf + ret, values, size)) {
3589 mutex_unlock(&ctx->mutex);
3594 static int perf_event_read_one(struct perf_event *event,
3595 u64 read_format, char __user *buf)
3597 u64 enabled, running;
3601 values[n++] = perf_event_read_value(event, &enabled, &running);
3602 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3603 values[n++] = enabled;
3604 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3605 values[n++] = running;
3606 if (read_format & PERF_FORMAT_ID)
3607 values[n++] = primary_event_id(event);
3609 if (copy_to_user(buf, values, n * sizeof(u64)))
3612 return n * sizeof(u64);
3615 static bool is_event_hup(struct perf_event *event)
3619 if (event->state != PERF_EVENT_STATE_EXIT)
3622 mutex_lock(&event->child_mutex);
3623 no_children = list_empty(&event->child_list);
3624 mutex_unlock(&event->child_mutex);
3629 * Read the performance event - simple non blocking version for now
3632 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
3634 u64 read_format = event->attr.read_format;
3638 * Return end-of-file for a read on a event that is in
3639 * error state (i.e. because it was pinned but it couldn't be
3640 * scheduled on to the CPU at some point).
3642 if (event->state == PERF_EVENT_STATE_ERROR)
3645 if (count < event->read_size)
3648 WARN_ON_ONCE(event->ctx->parent_ctx);
3649 if (read_format & PERF_FORMAT_GROUP)
3650 ret = perf_event_read_group(event, read_format, buf);
3652 ret = perf_event_read_one(event, read_format, buf);
3658 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
3660 struct perf_event *event = file->private_data;
3662 return perf_read_hw(event, buf, count);
3665 static unsigned int perf_poll(struct file *file, poll_table *wait)
3667 struct perf_event *event = file->private_data;
3668 struct ring_buffer *rb;
3669 unsigned int events = POLLHUP;
3671 poll_wait(file, &event->waitq, wait);
3673 if (is_event_hup(event))
3677 * Pin the event->rb by taking event->mmap_mutex; otherwise
3678 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
3680 mutex_lock(&event->mmap_mutex);
3683 events = atomic_xchg(&rb->poll, 0);
3684 mutex_unlock(&event->mmap_mutex);
3688 static void perf_event_reset(struct perf_event *event)
3690 (void)perf_event_read(event);
3691 local64_set(&event->count, 0);
3692 perf_event_update_userpage(event);
3696 * Holding the top-level event's child_mutex means that any
3697 * descendant process that has inherited this event will block
3698 * in sync_child_event if it goes to exit, thus satisfying the
3699 * task existence requirements of perf_event_enable/disable.
3701 static void perf_event_for_each_child(struct perf_event *event,
3702 void (*func)(struct perf_event *))
3704 struct perf_event *child;
3706 WARN_ON_ONCE(event->ctx->parent_ctx);
3707 mutex_lock(&event->child_mutex);
3709 list_for_each_entry(child, &event->child_list, child_list)
3711 mutex_unlock(&event->child_mutex);
3714 static void perf_event_for_each(struct perf_event *event,
3715 void (*func)(struct perf_event *))
3717 struct perf_event_context *ctx = event->ctx;
3718 struct perf_event *sibling;
3720 WARN_ON_ONCE(ctx->parent_ctx);
3721 mutex_lock(&ctx->mutex);
3722 event = event->group_leader;
3724 perf_event_for_each_child(event, func);
3725 list_for_each_entry(sibling, &event->sibling_list, group_entry)
3726 perf_event_for_each_child(sibling, func);
3727 mutex_unlock(&ctx->mutex);
3730 static int perf_event_period(struct perf_event *event, u64 __user *arg)
3732 struct perf_event_context *ctx = event->ctx;
3733 int ret = 0, active;
3736 if (!is_sampling_event(event))
3739 if (copy_from_user(&value, arg, sizeof(value)))
3745 raw_spin_lock_irq(&ctx->lock);
3746 if (event->attr.freq) {
3747 if (value > sysctl_perf_event_sample_rate) {
3752 event->attr.sample_freq = value;
3754 event->attr.sample_period = value;
3755 event->hw.sample_period = value;
3758 active = (event->state == PERF_EVENT_STATE_ACTIVE);
3760 perf_pmu_disable(ctx->pmu);
3761 event->pmu->stop(event, PERF_EF_UPDATE);
3764 local64_set(&event->hw.period_left, 0);
3767 event->pmu->start(event, PERF_EF_RELOAD);
3768 perf_pmu_enable(ctx->pmu);
3772 raw_spin_unlock_irq(&ctx->lock);
3777 static const struct file_operations perf_fops;
3779 static inline int perf_fget_light(int fd, struct fd *p)
3781 struct fd f = fdget(fd);
3785 if (f.file->f_op != &perf_fops) {
3793 static int perf_event_set_output(struct perf_event *event,
3794 struct perf_event *output_event);
3795 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
3797 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
3799 struct perf_event *event = file->private_data;
3800 void (*func)(struct perf_event *);
3804 case PERF_EVENT_IOC_ENABLE:
3805 func = perf_event_enable;
3807 case PERF_EVENT_IOC_DISABLE:
3808 func = perf_event_disable;
3810 case PERF_EVENT_IOC_RESET:
3811 func = perf_event_reset;
3814 case PERF_EVENT_IOC_REFRESH:
3815 return perf_event_refresh(event, arg);
3817 case PERF_EVENT_IOC_PERIOD:
3818 return perf_event_period(event, (u64 __user *)arg);
3820 case PERF_EVENT_IOC_ID:
3822 u64 id = primary_event_id(event);
3824 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
3829 case PERF_EVENT_IOC_SET_OUTPUT:
3833 struct perf_event *output_event;
3835 ret = perf_fget_light(arg, &output);
3838 output_event = output.file->private_data;
3839 ret = perf_event_set_output(event, output_event);
3842 ret = perf_event_set_output(event, NULL);
3847 case PERF_EVENT_IOC_SET_FILTER:
3848 return perf_event_set_filter(event, (void __user *)arg);
3854 if (flags & PERF_IOC_FLAG_GROUP)
3855 perf_event_for_each(event, func);
3857 perf_event_for_each_child(event, func);
3862 #ifdef CONFIG_COMPAT
3863 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
3866 switch (_IOC_NR(cmd)) {
3867 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
3868 case _IOC_NR(PERF_EVENT_IOC_ID):
3869 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
3870 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
3871 cmd &= ~IOCSIZE_MASK;
3872 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
3876 return perf_ioctl(file, cmd, arg);
3879 # define perf_compat_ioctl NULL
3882 int perf_event_task_enable(void)
3884 struct perf_event *event;
3886 mutex_lock(¤t->perf_event_mutex);
3887 list_for_each_entry(event, ¤t->perf_event_list, owner_entry)
3888 perf_event_for_each_child(event, perf_event_enable);
3889 mutex_unlock(¤t->perf_event_mutex);
3894 int perf_event_task_disable(void)
3896 struct perf_event *event;
3898 mutex_lock(¤t->perf_event_mutex);
3899 list_for_each_entry(event, ¤t->perf_event_list, owner_entry)
3900 perf_event_for_each_child(event, perf_event_disable);
3901 mutex_unlock(¤t->perf_event_mutex);
3906 static int perf_event_index(struct perf_event *event)
3908 if (event->hw.state & PERF_HES_STOPPED)
3911 if (event->state != PERF_EVENT_STATE_ACTIVE)
3914 return event->pmu->event_idx(event);
3917 static void calc_timer_values(struct perf_event *event,
3924 *now = perf_clock();
3925 ctx_time = event->shadow_ctx_time + *now;
3926 *enabled = ctx_time - event->tstamp_enabled;
3927 *running = ctx_time - event->tstamp_running;
3930 static void perf_event_init_userpage(struct perf_event *event)
3932 struct perf_event_mmap_page *userpg;
3933 struct ring_buffer *rb;
3936 rb = rcu_dereference(event->rb);
3940 userpg = rb->user_page;
3942 /* Allow new userspace to detect that bit 0 is deprecated */
3943 userpg->cap_bit0_is_deprecated = 1;
3944 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
3950 void __weak arch_perf_update_userpage(struct perf_event_mmap_page *userpg, u64 now)
3955 * Callers need to ensure there can be no nesting of this function, otherwise
3956 * the seqlock logic goes bad. We can not serialize this because the arch
3957 * code calls this from NMI context.
3959 void perf_event_update_userpage(struct perf_event *event)
3961 struct perf_event_mmap_page *userpg;
3962 struct ring_buffer *rb;
3963 u64 enabled, running, now;
3966 rb = rcu_dereference(event->rb);
3971 * compute total_time_enabled, total_time_running
3972 * based on snapshot values taken when the event
3973 * was last scheduled in.
3975 * we cannot simply called update_context_time()
3976 * because of locking issue as we can be called in
3979 calc_timer_values(event, &now, &enabled, &running);
3981 userpg = rb->user_page;
3983 * Disable preemption so as to not let the corresponding user-space
3984 * spin too long if we get preempted.
3989 userpg->index = perf_event_index(event);
3990 userpg->offset = perf_event_count(event);
3992 userpg->offset -= local64_read(&event->hw.prev_count);
3994 userpg->time_enabled = enabled +
3995 atomic64_read(&event->child_total_time_enabled);
3997 userpg->time_running = running +
3998 atomic64_read(&event->child_total_time_running);
4000 arch_perf_update_userpage(userpg, now);
4009 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
4011 struct perf_event *event = vma->vm_file->private_data;
4012 struct ring_buffer *rb;
4013 int ret = VM_FAULT_SIGBUS;
4015 if (vmf->flags & FAULT_FLAG_MKWRITE) {
4016 if (vmf->pgoff == 0)
4022 rb = rcu_dereference(event->rb);
4026 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
4029 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
4033 get_page(vmf->page);
4034 vmf->page->mapping = vma->vm_file->f_mapping;
4035 vmf->page->index = vmf->pgoff;
4044 static void ring_buffer_attach(struct perf_event *event,
4045 struct ring_buffer *rb)
4047 struct ring_buffer *old_rb = NULL;
4048 unsigned long flags;
4052 * Should be impossible, we set this when removing
4053 * event->rb_entry and wait/clear when adding event->rb_entry.
4055 WARN_ON_ONCE(event->rcu_pending);
4058 event->rcu_batches = get_state_synchronize_rcu();
4059 event->rcu_pending = 1;
4061 spin_lock_irqsave(&old_rb->event_lock, flags);
4062 list_del_rcu(&event->rb_entry);
4063 spin_unlock_irqrestore(&old_rb->event_lock, flags);
4066 if (event->rcu_pending && rb) {
4067 cond_synchronize_rcu(event->rcu_batches);
4068 event->rcu_pending = 0;
4072 spin_lock_irqsave(&rb->event_lock, flags);
4073 list_add_rcu(&event->rb_entry, &rb->event_list);
4074 spin_unlock_irqrestore(&rb->event_lock, flags);
4077 rcu_assign_pointer(event->rb, rb);
4080 ring_buffer_put(old_rb);
4082 * Since we detached before setting the new rb, so that we
4083 * could attach the new rb, we could have missed a wakeup.
4086 wake_up_all(&event->waitq);
4090 static void ring_buffer_wakeup(struct perf_event *event)
4092 struct ring_buffer *rb;
4095 rb = rcu_dereference(event->rb);
4097 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
4098 wake_up_all(&event->waitq);
4103 static void rb_free_rcu(struct rcu_head *rcu_head)
4105 struct ring_buffer *rb;
4107 rb = container_of(rcu_head, struct ring_buffer, rcu_head);
4111 static struct ring_buffer *ring_buffer_get(struct perf_event *event)
4113 struct ring_buffer *rb;
4116 rb = rcu_dereference(event->rb);
4118 if (!atomic_inc_not_zero(&rb->refcount))
4126 static void ring_buffer_put(struct ring_buffer *rb)
4128 if (!atomic_dec_and_test(&rb->refcount))
4131 WARN_ON_ONCE(!list_empty(&rb->event_list));
4133 call_rcu(&rb->rcu_head, rb_free_rcu);
4136 static void perf_mmap_open(struct vm_area_struct *vma)
4138 struct perf_event *event = vma->vm_file->private_data;
4140 atomic_inc(&event->mmap_count);
4141 atomic_inc(&event->rb->mmap_count);
4145 * A buffer can be mmap()ed multiple times; either directly through the same
4146 * event, or through other events by use of perf_event_set_output().
4148 * In order to undo the VM accounting done by perf_mmap() we need to destroy
4149 * the buffer here, where we still have a VM context. This means we need
4150 * to detach all events redirecting to us.
4152 static void perf_mmap_close(struct vm_area_struct *vma)
4154 struct perf_event *event = vma->vm_file->private_data;
4156 struct ring_buffer *rb = ring_buffer_get(event);
4157 struct user_struct *mmap_user = rb->mmap_user;
4158 int mmap_locked = rb->mmap_locked;
4159 unsigned long size = perf_data_size(rb);
4161 atomic_dec(&rb->mmap_count);
4163 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
4166 ring_buffer_attach(event, NULL);
4167 mutex_unlock(&event->mmap_mutex);
4169 /* If there's still other mmap()s of this buffer, we're done. */
4170 if (atomic_read(&rb->mmap_count))
4174 * No other mmap()s, detach from all other events that might redirect
4175 * into the now unreachable buffer. Somewhat complicated by the
4176 * fact that rb::event_lock otherwise nests inside mmap_mutex.
4180 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4181 if (!atomic_long_inc_not_zero(&event->refcount)) {
4183 * This event is en-route to free_event() which will
4184 * detach it and remove it from the list.
4190 mutex_lock(&event->mmap_mutex);
4192 * Check we didn't race with perf_event_set_output() which can
4193 * swizzle the rb from under us while we were waiting to
4194 * acquire mmap_mutex.
4196 * If we find a different rb; ignore this event, a next
4197 * iteration will no longer find it on the list. We have to
4198 * still restart the iteration to make sure we're not now
4199 * iterating the wrong list.
4201 if (event->rb == rb)
4202 ring_buffer_attach(event, NULL);
4204 mutex_unlock(&event->mmap_mutex);
4208 * Restart the iteration; either we're on the wrong list or
4209 * destroyed its integrity by doing a deletion.
4216 * It could be there's still a few 0-ref events on the list; they'll
4217 * get cleaned up by free_event() -- they'll also still have their
4218 * ref on the rb and will free it whenever they are done with it.
4220 * Aside from that, this buffer is 'fully' detached and unmapped,
4221 * undo the VM accounting.
4224 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4225 vma->vm_mm->pinned_vm -= mmap_locked;
4226 free_uid(mmap_user);
4229 ring_buffer_put(rb); /* could be last */
4232 static const struct vm_operations_struct perf_mmap_vmops = {
4233 .open = perf_mmap_open,
4234 .close = perf_mmap_close,
4235 .fault = perf_mmap_fault,
4236 .page_mkwrite = perf_mmap_fault,
4239 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
4241 struct perf_event *event = file->private_data;
4242 unsigned long user_locked, user_lock_limit;
4243 struct user_struct *user = current_user();
4244 unsigned long locked, lock_limit;
4245 struct ring_buffer *rb;
4246 unsigned long vma_size;
4247 unsigned long nr_pages;
4248 long user_extra, extra;
4249 int ret = 0, flags = 0;
4252 * Don't allow mmap() of inherited per-task counters. This would
4253 * create a performance issue due to all children writing to the
4256 if (event->cpu == -1 && event->attr.inherit)
4259 if (!(vma->vm_flags & VM_SHARED))
4262 vma_size = vma->vm_end - vma->vm_start;
4263 nr_pages = (vma_size / PAGE_SIZE) - 1;
4266 * If we have rb pages ensure they're a power-of-two number, so we
4267 * can do bitmasks instead of modulo.
4269 if (nr_pages != 0 && !is_power_of_2(nr_pages))
4272 if (vma_size != PAGE_SIZE * (1 + nr_pages))
4275 if (vma->vm_pgoff != 0)
4278 WARN_ON_ONCE(event->ctx->parent_ctx);
4280 mutex_lock(&event->mmap_mutex);
4282 if (event->rb->nr_pages != nr_pages) {
4287 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4289 * Raced against perf_mmap_close() through
4290 * perf_event_set_output(). Try again, hope for better
4293 mutex_unlock(&event->mmap_mutex);
4300 user_extra = nr_pages + 1;
4301 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
4304 * Increase the limit linearly with more CPUs:
4306 user_lock_limit *= num_online_cpus();
4308 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
4311 if (user_locked > user_lock_limit)
4312 extra = user_locked - user_lock_limit;
4314 lock_limit = rlimit(RLIMIT_MEMLOCK);
4315 lock_limit >>= PAGE_SHIFT;
4316 locked = vma->vm_mm->pinned_vm + extra;
4318 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
4319 !capable(CAP_IPC_LOCK)) {
4326 if (vma->vm_flags & VM_WRITE)
4327 flags |= RING_BUFFER_WRITABLE;
4329 rb = rb_alloc(nr_pages,
4330 event->attr.watermark ? event->attr.wakeup_watermark : 0,
4338 atomic_set(&rb->mmap_count, 1);
4339 rb->mmap_locked = extra;
4340 rb->mmap_user = get_current_user();
4342 atomic_long_add(user_extra, &user->locked_vm);
4343 vma->vm_mm->pinned_vm += extra;
4345 ring_buffer_attach(event, rb);
4347 perf_event_init_userpage(event);
4348 perf_event_update_userpage(event);
4352 atomic_inc(&event->mmap_count);
4353 mutex_unlock(&event->mmap_mutex);
4356 * Since pinned accounting is per vm we cannot allow fork() to copy our
4359 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
4360 vma->vm_ops = &perf_mmap_vmops;
4365 static int perf_fasync(int fd, struct file *filp, int on)
4367 struct inode *inode = file_inode(filp);
4368 struct perf_event *event = filp->private_data;
4371 mutex_lock(&inode->i_mutex);
4372 retval = fasync_helper(fd, filp, on, &event->fasync);
4373 mutex_unlock(&inode->i_mutex);
4381 static const struct file_operations perf_fops = {
4382 .llseek = no_llseek,
4383 .release = perf_release,
4386 .unlocked_ioctl = perf_ioctl,
4387 .compat_ioctl = perf_compat_ioctl,
4389 .fasync = perf_fasync,
4395 * If there's data, ensure we set the poll() state and publish everything
4396 * to user-space before waking everybody up.
4399 void perf_event_wakeup(struct perf_event *event)
4401 ring_buffer_wakeup(event);
4403 if (event->pending_kill) {
4404 kill_fasync(&event->fasync, SIGIO, event->pending_kill);
4405 event->pending_kill = 0;
4409 static void perf_pending_event(struct irq_work *entry)
4411 struct perf_event *event = container_of(entry,
4412 struct perf_event, pending);
4414 if (event->pending_disable) {
4415 event->pending_disable = 0;
4416 __perf_event_disable(event);
4419 if (event->pending_wakeup) {
4420 event->pending_wakeup = 0;
4421 perf_event_wakeup(event);
4426 * We assume there is only KVM supporting the callbacks.
4427 * Later on, we might change it to a list if there is
4428 * another virtualization implementation supporting the callbacks.
4430 struct perf_guest_info_callbacks *perf_guest_cbs;
4432 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4434 perf_guest_cbs = cbs;
4437 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
4439 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4441 perf_guest_cbs = NULL;
4444 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
4447 perf_output_sample_regs(struct perf_output_handle *handle,
4448 struct pt_regs *regs, u64 mask)
4452 for_each_set_bit(bit, (const unsigned long *) &mask,
4453 sizeof(mask) * BITS_PER_BYTE) {
4456 val = perf_reg_value(regs, bit);
4457 perf_output_put(handle, val);
4461 static void perf_sample_regs_user(struct perf_regs_user *regs_user,
4462 struct pt_regs *regs)
4464 if (!user_mode(regs)) {
4466 regs = task_pt_regs(current);
4472 regs_user->regs = regs;
4473 regs_user->abi = perf_reg_abi(current);
4478 * Get remaining task size from user stack pointer.
4480 * It'd be better to take stack vma map and limit this more
4481 * precisly, but there's no way to get it safely under interrupt,
4482 * so using TASK_SIZE as limit.
4484 static u64 perf_ustack_task_size(struct pt_regs *regs)
4486 unsigned long addr = perf_user_stack_pointer(regs);
4488 if (!addr || addr >= TASK_SIZE)
4491 return TASK_SIZE - addr;
4495 perf_sample_ustack_size(u16 stack_size, u16 header_size,
4496 struct pt_regs *regs)
4500 /* No regs, no stack pointer, no dump. */
4505 * Check if we fit in with the requested stack size into the:
4507 * If we don't, we limit the size to the TASK_SIZE.
4509 * - remaining sample size
4510 * If we don't, we customize the stack size to
4511 * fit in to the remaining sample size.
4514 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
4515 stack_size = min(stack_size, (u16) task_size);
4517 /* Current header size plus static size and dynamic size. */
4518 header_size += 2 * sizeof(u64);
4520 /* Do we fit in with the current stack dump size? */
4521 if ((u16) (header_size + stack_size) < header_size) {
4523 * If we overflow the maximum size for the sample,
4524 * we customize the stack dump size to fit in.
4526 stack_size = USHRT_MAX - header_size - sizeof(u64);
4527 stack_size = round_up(stack_size, sizeof(u64));
4534 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
4535 struct pt_regs *regs)
4537 /* Case of a kernel thread, nothing to dump */
4540 perf_output_put(handle, size);
4549 * - the size requested by user or the best one we can fit
4550 * in to the sample max size
4552 * - user stack dump data
4554 * - the actual dumped size
4558 perf_output_put(handle, dump_size);
4561 sp = perf_user_stack_pointer(regs);
4562 rem = __output_copy_user(handle, (void *) sp, dump_size);
4563 dyn_size = dump_size - rem;
4565 perf_output_skip(handle, rem);
4568 perf_output_put(handle, dyn_size);
4572 static void __perf_event_header__init_id(struct perf_event_header *header,
4573 struct perf_sample_data *data,
4574 struct perf_event *event)
4576 u64 sample_type = event->attr.sample_type;
4578 data->type = sample_type;
4579 header->size += event->id_header_size;
4581 if (sample_type & PERF_SAMPLE_TID) {
4582 /* namespace issues */
4583 data->tid_entry.pid = perf_event_pid(event, current);
4584 data->tid_entry.tid = perf_event_tid(event, current);
4587 if (sample_type & PERF_SAMPLE_TIME)
4588 data->time = perf_clock();
4590 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
4591 data->id = primary_event_id(event);
4593 if (sample_type & PERF_SAMPLE_STREAM_ID)
4594 data->stream_id = event->id;
4596 if (sample_type & PERF_SAMPLE_CPU) {
4597 data->cpu_entry.cpu = raw_smp_processor_id();
4598 data->cpu_entry.reserved = 0;
4602 void perf_event_header__init_id(struct perf_event_header *header,
4603 struct perf_sample_data *data,
4604 struct perf_event *event)
4606 if (event->attr.sample_id_all)
4607 __perf_event_header__init_id(header, data, event);
4610 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
4611 struct perf_sample_data *data)
4613 u64 sample_type = data->type;
4615 if (sample_type & PERF_SAMPLE_TID)
4616 perf_output_put(handle, data->tid_entry);
4618 if (sample_type & PERF_SAMPLE_TIME)
4619 perf_output_put(handle, data->time);
4621 if (sample_type & PERF_SAMPLE_ID)
4622 perf_output_put(handle, data->id);
4624 if (sample_type & PERF_SAMPLE_STREAM_ID)
4625 perf_output_put(handle, data->stream_id);
4627 if (sample_type & PERF_SAMPLE_CPU)
4628 perf_output_put(handle, data->cpu_entry);
4630 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4631 perf_output_put(handle, data->id);
4634 void perf_event__output_id_sample(struct perf_event *event,
4635 struct perf_output_handle *handle,
4636 struct perf_sample_data *sample)
4638 if (event->attr.sample_id_all)
4639 __perf_event__output_id_sample(handle, sample);
4642 static void perf_output_read_one(struct perf_output_handle *handle,
4643 struct perf_event *event,
4644 u64 enabled, u64 running)
4646 u64 read_format = event->attr.read_format;
4650 values[n++] = perf_event_count(event);
4651 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4652 values[n++] = enabled +
4653 atomic64_read(&event->child_total_time_enabled);
4655 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4656 values[n++] = running +
4657 atomic64_read(&event->child_total_time_running);
4659 if (read_format & PERF_FORMAT_ID)
4660 values[n++] = primary_event_id(event);
4662 __output_copy(handle, values, n * sizeof(u64));
4666 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
4668 static void perf_output_read_group(struct perf_output_handle *handle,
4669 struct perf_event *event,
4670 u64 enabled, u64 running)
4672 struct perf_event *leader = event->group_leader, *sub;
4673 u64 read_format = event->attr.read_format;
4677 values[n++] = 1 + leader->nr_siblings;
4679 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4680 values[n++] = enabled;
4682 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4683 values[n++] = running;
4685 if (leader != event)
4686 leader->pmu->read(leader);
4688 values[n++] = perf_event_count(leader);
4689 if (read_format & PERF_FORMAT_ID)
4690 values[n++] = primary_event_id(leader);
4692 __output_copy(handle, values, n * sizeof(u64));
4694 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4697 if ((sub != event) &&
4698 (sub->state == PERF_EVENT_STATE_ACTIVE))
4699 sub->pmu->read(sub);
4701 values[n++] = perf_event_count(sub);
4702 if (read_format & PERF_FORMAT_ID)
4703 values[n++] = primary_event_id(sub);
4705 __output_copy(handle, values, n * sizeof(u64));
4709 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
4710 PERF_FORMAT_TOTAL_TIME_RUNNING)
4712 static void perf_output_read(struct perf_output_handle *handle,
4713 struct perf_event *event)
4715 u64 enabled = 0, running = 0, now;
4716 u64 read_format = event->attr.read_format;
4719 * compute total_time_enabled, total_time_running
4720 * based on snapshot values taken when the event
4721 * was last scheduled in.
4723 * we cannot simply called update_context_time()
4724 * because of locking issue as we are called in
4727 if (read_format & PERF_FORMAT_TOTAL_TIMES)
4728 calc_timer_values(event, &now, &enabled, &running);
4730 if (event->attr.read_format & PERF_FORMAT_GROUP)
4731 perf_output_read_group(handle, event, enabled, running);
4733 perf_output_read_one(handle, event, enabled, running);
4736 void perf_output_sample(struct perf_output_handle *handle,
4737 struct perf_event_header *header,
4738 struct perf_sample_data *data,
4739 struct perf_event *event)
4741 u64 sample_type = data->type;
4743 perf_output_put(handle, *header);
4745 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4746 perf_output_put(handle, data->id);
4748 if (sample_type & PERF_SAMPLE_IP)
4749 perf_output_put(handle, data->ip);
4751 if (sample_type & PERF_SAMPLE_TID)
4752 perf_output_put(handle, data->tid_entry);
4754 if (sample_type & PERF_SAMPLE_TIME)
4755 perf_output_put(handle, data->time);
4757 if (sample_type & PERF_SAMPLE_ADDR)
4758 perf_output_put(handle, data->addr);
4760 if (sample_type & PERF_SAMPLE_ID)
4761 perf_output_put(handle, data->id);
4763 if (sample_type & PERF_SAMPLE_STREAM_ID)
4764 perf_output_put(handle, data->stream_id);
4766 if (sample_type & PERF_SAMPLE_CPU)
4767 perf_output_put(handle, data->cpu_entry);
4769 if (sample_type & PERF_SAMPLE_PERIOD)
4770 perf_output_put(handle, data->period);
4772 if (sample_type & PERF_SAMPLE_READ)
4773 perf_output_read(handle, event);
4775 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4776 if (data->callchain) {
4779 if (data->callchain)
4780 size += data->callchain->nr;
4782 size *= sizeof(u64);
4784 __output_copy(handle, data->callchain, size);
4787 perf_output_put(handle, nr);
4791 if (sample_type & PERF_SAMPLE_RAW) {
4793 perf_output_put(handle, data->raw->size);
4794 __output_copy(handle, data->raw->data,
4801 .size = sizeof(u32),
4804 perf_output_put(handle, raw);
4808 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4809 if (data->br_stack) {
4812 size = data->br_stack->nr
4813 * sizeof(struct perf_branch_entry);
4815 perf_output_put(handle, data->br_stack->nr);
4816 perf_output_copy(handle, data->br_stack->entries, size);
4819 * we always store at least the value of nr
4822 perf_output_put(handle, nr);
4826 if (sample_type & PERF_SAMPLE_REGS_USER) {
4827 u64 abi = data->regs_user.abi;
4830 * If there are no regs to dump, notice it through
4831 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
4833 perf_output_put(handle, abi);
4836 u64 mask = event->attr.sample_regs_user;
4837 perf_output_sample_regs(handle,
4838 data->regs_user.regs,
4843 if (sample_type & PERF_SAMPLE_STACK_USER) {
4844 perf_output_sample_ustack(handle,
4845 data->stack_user_size,
4846 data->regs_user.regs);
4849 if (sample_type & PERF_SAMPLE_WEIGHT)
4850 perf_output_put(handle, data->weight);
4852 if (sample_type & PERF_SAMPLE_DATA_SRC)
4853 perf_output_put(handle, data->data_src.val);
4855 if (sample_type & PERF_SAMPLE_TRANSACTION)
4856 perf_output_put(handle, data->txn);
4858 if (!event->attr.watermark) {
4859 int wakeup_events = event->attr.wakeup_events;
4861 if (wakeup_events) {
4862 struct ring_buffer *rb = handle->rb;
4863 int events = local_inc_return(&rb->events);
4865 if (events >= wakeup_events) {
4866 local_sub(wakeup_events, &rb->events);
4867 local_inc(&rb->wakeup);
4873 void perf_prepare_sample(struct perf_event_header *header,
4874 struct perf_sample_data *data,
4875 struct perf_event *event,
4876 struct pt_regs *regs)
4878 u64 sample_type = event->attr.sample_type;
4880 header->type = PERF_RECORD_SAMPLE;
4881 header->size = sizeof(*header) + event->header_size;
4884 header->misc |= perf_misc_flags(regs);
4886 __perf_event_header__init_id(header, data, event);
4888 if (sample_type & PERF_SAMPLE_IP)
4889 data->ip = perf_instruction_pointer(regs);
4891 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4894 data->callchain = perf_callchain(event, regs);
4896 if (data->callchain)
4897 size += data->callchain->nr;
4899 header->size += size * sizeof(u64);
4902 if (sample_type & PERF_SAMPLE_RAW) {
4903 int size = sizeof(u32);
4906 size += data->raw->size;
4908 size += sizeof(u32);
4910 WARN_ON_ONCE(size & (sizeof(u64)-1));
4911 header->size += size;
4914 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4915 int size = sizeof(u64); /* nr */
4916 if (data->br_stack) {
4917 size += data->br_stack->nr
4918 * sizeof(struct perf_branch_entry);
4920 header->size += size;
4923 if (sample_type & PERF_SAMPLE_REGS_USER) {
4924 /* regs dump ABI info */
4925 int size = sizeof(u64);
4927 perf_sample_regs_user(&data->regs_user, regs);
4929 if (data->regs_user.regs) {
4930 u64 mask = event->attr.sample_regs_user;
4931 size += hweight64(mask) * sizeof(u64);
4934 header->size += size;
4937 if (sample_type & PERF_SAMPLE_STACK_USER) {
4939 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
4940 * processed as the last one or have additional check added
4941 * in case new sample type is added, because we could eat
4942 * up the rest of the sample size.
4944 struct perf_regs_user *uregs = &data->regs_user;
4945 u16 stack_size = event->attr.sample_stack_user;
4946 u16 size = sizeof(u64);
4949 perf_sample_regs_user(uregs, regs);
4951 stack_size = perf_sample_ustack_size(stack_size, header->size,
4955 * If there is something to dump, add space for the dump
4956 * itself and for the field that tells the dynamic size,
4957 * which is how many have been actually dumped.
4960 size += sizeof(u64) + stack_size;
4962 data->stack_user_size = stack_size;
4963 header->size += size;
4967 static void perf_event_output(struct perf_event *event,
4968 struct perf_sample_data *data,
4969 struct pt_regs *regs)
4971 struct perf_output_handle handle;
4972 struct perf_event_header header;
4974 /* protect the callchain buffers */
4977 perf_prepare_sample(&header, data, event, regs);
4979 if (perf_output_begin(&handle, event, header.size))
4982 perf_output_sample(&handle, &header, data, event);
4984 perf_output_end(&handle);
4994 struct perf_read_event {
4995 struct perf_event_header header;
5002 perf_event_read_event(struct perf_event *event,
5003 struct task_struct *task)
5005 struct perf_output_handle handle;
5006 struct perf_sample_data sample;
5007 struct perf_read_event read_event = {
5009 .type = PERF_RECORD_READ,
5011 .size = sizeof(read_event) + event->read_size,
5013 .pid = perf_event_pid(event, task),
5014 .tid = perf_event_tid(event, task),
5018 perf_event_header__init_id(&read_event.header, &sample, event);
5019 ret = perf_output_begin(&handle, event, read_event.header.size);
5023 perf_output_put(&handle, read_event);
5024 perf_output_read(&handle, event);
5025 perf_event__output_id_sample(event, &handle, &sample);
5027 perf_output_end(&handle);
5030 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
5033 perf_event_aux_ctx(struct perf_event_context *ctx,
5034 perf_event_aux_output_cb output,
5037 struct perf_event *event;
5039 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5040 if (event->state < PERF_EVENT_STATE_INACTIVE)
5042 if (!event_filter_match(event))
5044 output(event, data);
5049 perf_event_aux(perf_event_aux_output_cb output, void *data,
5050 struct perf_event_context *task_ctx)
5052 struct perf_cpu_context *cpuctx;
5053 struct perf_event_context *ctx;
5058 list_for_each_entry_rcu(pmu, &pmus, entry) {
5059 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
5060 if (cpuctx->unique_pmu != pmu)
5062 perf_event_aux_ctx(&cpuctx->ctx, output, data);
5065 ctxn = pmu->task_ctx_nr;
5068 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
5070 perf_event_aux_ctx(ctx, output, data);
5072 put_cpu_ptr(pmu->pmu_cpu_context);
5077 perf_event_aux_ctx(task_ctx, output, data);
5084 * task tracking -- fork/exit
5086 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
5089 struct perf_task_event {
5090 struct task_struct *task;
5091 struct perf_event_context *task_ctx;
5094 struct perf_event_header header;
5104 static int perf_event_task_match(struct perf_event *event)
5106 return event->attr.comm || event->attr.mmap ||
5107 event->attr.mmap2 || event->attr.mmap_data ||
5111 static void perf_event_task_output(struct perf_event *event,
5114 struct perf_task_event *task_event = data;
5115 struct perf_output_handle handle;
5116 struct perf_sample_data sample;
5117 struct task_struct *task = task_event->task;
5118 int ret, size = task_event->event_id.header.size;
5120 if (!perf_event_task_match(event))
5123 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
5125 ret = perf_output_begin(&handle, event,
5126 task_event->event_id.header.size);
5130 task_event->event_id.pid = perf_event_pid(event, task);
5131 task_event->event_id.ppid = perf_event_pid(event, current);
5133 task_event->event_id.tid = perf_event_tid(event, task);
5134 task_event->event_id.ptid = perf_event_tid(event, current);
5136 perf_output_put(&handle, task_event->event_id);
5138 perf_event__output_id_sample(event, &handle, &sample);
5140 perf_output_end(&handle);
5142 task_event->event_id.header.size = size;
5145 static void perf_event_task(struct task_struct *task,
5146 struct perf_event_context *task_ctx,
5149 struct perf_task_event task_event;
5151 if (!atomic_read(&nr_comm_events) &&
5152 !atomic_read(&nr_mmap_events) &&
5153 !atomic_read(&nr_task_events))
5156 task_event = (struct perf_task_event){
5158 .task_ctx = task_ctx,
5161 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
5163 .size = sizeof(task_event.event_id),
5169 .time = perf_clock(),
5173 perf_event_aux(perf_event_task_output,
5178 void perf_event_fork(struct task_struct *task)
5180 perf_event_task(task, NULL, 1);
5187 struct perf_comm_event {
5188 struct task_struct *task;
5193 struct perf_event_header header;
5200 static int perf_event_comm_match(struct perf_event *event)
5202 return event->attr.comm;
5205 static void perf_event_comm_output(struct perf_event *event,
5208 struct perf_comm_event *comm_event = data;
5209 struct perf_output_handle handle;
5210 struct perf_sample_data sample;
5211 int size = comm_event->event_id.header.size;
5214 if (!perf_event_comm_match(event))
5217 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
5218 ret = perf_output_begin(&handle, event,
5219 comm_event->event_id.header.size);
5224 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
5225 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
5227 perf_output_put(&handle, comm_event->event_id);
5228 __output_copy(&handle, comm_event->comm,
5229 comm_event->comm_size);
5231 perf_event__output_id_sample(event, &handle, &sample);
5233 perf_output_end(&handle);
5235 comm_event->event_id.header.size = size;
5238 static void perf_event_comm_event(struct perf_comm_event *comm_event)
5240 char comm[TASK_COMM_LEN];
5243 memset(comm, 0, sizeof(comm));
5244 strlcpy(comm, comm_event->task->comm, sizeof(comm));
5245 size = ALIGN(strlen(comm)+1, sizeof(u64));
5247 comm_event->comm = comm;
5248 comm_event->comm_size = size;
5250 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
5252 perf_event_aux(perf_event_comm_output,
5257 void perf_event_comm(struct task_struct *task, bool exec)
5259 struct perf_comm_event comm_event;
5261 if (!atomic_read(&nr_comm_events))
5264 comm_event = (struct perf_comm_event){
5270 .type = PERF_RECORD_COMM,
5271 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
5279 perf_event_comm_event(&comm_event);
5286 struct perf_mmap_event {
5287 struct vm_area_struct *vma;
5289 const char *file_name;
5297 struct perf_event_header header;
5307 static int perf_event_mmap_match(struct perf_event *event,
5310 struct perf_mmap_event *mmap_event = data;
5311 struct vm_area_struct *vma = mmap_event->vma;
5312 int executable = vma->vm_flags & VM_EXEC;
5314 return (!executable && event->attr.mmap_data) ||
5315 (executable && (event->attr.mmap || event->attr.mmap2));
5318 static void perf_event_mmap_output(struct perf_event *event,
5321 struct perf_mmap_event *mmap_event = data;
5322 struct perf_output_handle handle;
5323 struct perf_sample_data sample;
5324 int size = mmap_event->event_id.header.size;
5327 if (!perf_event_mmap_match(event, data))
5330 if (event->attr.mmap2) {
5331 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
5332 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
5333 mmap_event->event_id.header.size += sizeof(mmap_event->min);
5334 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
5335 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
5336 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
5337 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
5340 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
5341 ret = perf_output_begin(&handle, event,
5342 mmap_event->event_id.header.size);
5346 mmap_event->event_id.pid = perf_event_pid(event, current);
5347 mmap_event->event_id.tid = perf_event_tid(event, current);
5349 perf_output_put(&handle, mmap_event->event_id);
5351 if (event->attr.mmap2) {
5352 perf_output_put(&handle, mmap_event->maj);
5353 perf_output_put(&handle, mmap_event->min);
5354 perf_output_put(&handle, mmap_event->ino);
5355 perf_output_put(&handle, mmap_event->ino_generation);
5356 perf_output_put(&handle, mmap_event->prot);
5357 perf_output_put(&handle, mmap_event->flags);
5360 __output_copy(&handle, mmap_event->file_name,
5361 mmap_event->file_size);
5363 perf_event__output_id_sample(event, &handle, &sample);
5365 perf_output_end(&handle);
5367 mmap_event->event_id.header.size = size;
5370 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
5372 struct vm_area_struct *vma = mmap_event->vma;
5373 struct file *file = vma->vm_file;
5374 int maj = 0, min = 0;
5375 u64 ino = 0, gen = 0;
5376 u32 prot = 0, flags = 0;
5383 struct inode *inode;
5386 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5392 * d_path() works from the end of the rb backwards, so we
5393 * need to add enough zero bytes after the string to handle
5394 * the 64bit alignment we do later.
5396 name = d_path(&file->f_path, buf, PATH_MAX - sizeof(u64));
5401 inode = file_inode(vma->vm_file);
5402 dev = inode->i_sb->s_dev;
5404 gen = inode->i_generation;
5408 if (vma->vm_flags & VM_READ)
5410 if (vma->vm_flags & VM_WRITE)
5412 if (vma->vm_flags & VM_EXEC)
5415 if (vma->vm_flags & VM_MAYSHARE)
5418 flags = MAP_PRIVATE;
5420 if (vma->vm_flags & VM_DENYWRITE)
5421 flags |= MAP_DENYWRITE;
5422 if (vma->vm_flags & VM_MAYEXEC)
5423 flags |= MAP_EXECUTABLE;
5424 if (vma->vm_flags & VM_LOCKED)
5425 flags |= MAP_LOCKED;
5426 if (vma->vm_flags & VM_HUGETLB)
5427 flags |= MAP_HUGETLB;
5431 if (vma->vm_ops && vma->vm_ops->name) {
5432 name = (char *) vma->vm_ops->name(vma);
5437 name = (char *)arch_vma_name(vma);
5441 if (vma->vm_start <= vma->vm_mm->start_brk &&
5442 vma->vm_end >= vma->vm_mm->brk) {
5446 if (vma->vm_start <= vma->vm_mm->start_stack &&
5447 vma->vm_end >= vma->vm_mm->start_stack) {
5457 strlcpy(tmp, name, sizeof(tmp));
5461 * Since our buffer works in 8 byte units we need to align our string
5462 * size to a multiple of 8. However, we must guarantee the tail end is
5463 * zero'd out to avoid leaking random bits to userspace.
5465 size = strlen(name)+1;
5466 while (!IS_ALIGNED(size, sizeof(u64)))
5467 name[size++] = '\0';
5469 mmap_event->file_name = name;
5470 mmap_event->file_size = size;
5471 mmap_event->maj = maj;
5472 mmap_event->min = min;
5473 mmap_event->ino = ino;
5474 mmap_event->ino_generation = gen;
5475 mmap_event->prot = prot;
5476 mmap_event->flags = flags;
5478 if (!(vma->vm_flags & VM_EXEC))
5479 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
5481 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
5483 perf_event_aux(perf_event_mmap_output,
5490 void perf_event_mmap(struct vm_area_struct *vma)
5492 struct perf_mmap_event mmap_event;
5494 if (!atomic_read(&nr_mmap_events))
5497 mmap_event = (struct perf_mmap_event){
5503 .type = PERF_RECORD_MMAP,
5504 .misc = PERF_RECORD_MISC_USER,
5509 .start = vma->vm_start,
5510 .len = vma->vm_end - vma->vm_start,
5511 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
5513 /* .maj (attr_mmap2 only) */
5514 /* .min (attr_mmap2 only) */
5515 /* .ino (attr_mmap2 only) */
5516 /* .ino_generation (attr_mmap2 only) */
5517 /* .prot (attr_mmap2 only) */
5518 /* .flags (attr_mmap2 only) */
5521 perf_event_mmap_event(&mmap_event);
5525 * IRQ throttle logging
5528 static void perf_log_throttle(struct perf_event *event, int enable)
5530 struct perf_output_handle handle;
5531 struct perf_sample_data sample;
5535 struct perf_event_header header;
5539 } throttle_event = {
5541 .type = PERF_RECORD_THROTTLE,
5543 .size = sizeof(throttle_event),
5545 .time = perf_clock(),
5546 .id = primary_event_id(event),
5547 .stream_id = event->id,
5551 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
5553 perf_event_header__init_id(&throttle_event.header, &sample, event);
5555 ret = perf_output_begin(&handle, event,
5556 throttle_event.header.size);
5560 perf_output_put(&handle, throttle_event);
5561 perf_event__output_id_sample(event, &handle, &sample);
5562 perf_output_end(&handle);
5566 * Generic event overflow handling, sampling.
5569 static int __perf_event_overflow(struct perf_event *event,
5570 int throttle, struct perf_sample_data *data,
5571 struct pt_regs *regs)
5573 int events = atomic_read(&event->event_limit);
5574 struct hw_perf_event *hwc = &event->hw;
5579 * Non-sampling counters might still use the PMI to fold short
5580 * hardware counters, ignore those.
5582 if (unlikely(!is_sampling_event(event)))
5585 seq = __this_cpu_read(perf_throttled_seq);
5586 if (seq != hwc->interrupts_seq) {
5587 hwc->interrupts_seq = seq;
5588 hwc->interrupts = 1;
5591 if (unlikely(throttle
5592 && hwc->interrupts >= max_samples_per_tick)) {
5593 __this_cpu_inc(perf_throttled_count);
5594 hwc->interrupts = MAX_INTERRUPTS;
5595 perf_log_throttle(event, 0);
5596 tick_nohz_full_kick();
5601 if (event->attr.freq) {
5602 u64 now = perf_clock();
5603 s64 delta = now - hwc->freq_time_stamp;
5605 hwc->freq_time_stamp = now;
5607 if (delta > 0 && delta < 2*TICK_NSEC)
5608 perf_adjust_period(event, delta, hwc->last_period, true);
5612 * XXX event_limit might not quite work as expected on inherited
5616 event->pending_kill = POLL_IN;
5617 if (events && atomic_dec_and_test(&event->event_limit)) {
5619 event->pending_kill = POLL_HUP;
5620 event->pending_disable = 1;
5621 irq_work_queue(&event->pending);
5624 if (event->overflow_handler)
5625 event->overflow_handler(event, data, regs);
5627 perf_event_output(event, data, regs);
5629 if (event->fasync && event->pending_kill) {
5630 event->pending_wakeup = 1;
5631 irq_work_queue(&event->pending);
5637 int perf_event_overflow(struct perf_event *event,
5638 struct perf_sample_data *data,
5639 struct pt_regs *regs)
5641 return __perf_event_overflow(event, 1, data, regs);
5645 * Generic software event infrastructure
5648 struct swevent_htable {
5649 struct swevent_hlist *swevent_hlist;
5650 struct mutex hlist_mutex;
5653 /* Recursion avoidance in each contexts */
5654 int recursion[PERF_NR_CONTEXTS];
5656 /* Keeps track of cpu being initialized/exited */
5660 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
5663 * We directly increment event->count and keep a second value in
5664 * event->hw.period_left to count intervals. This period event
5665 * is kept in the range [-sample_period, 0] so that we can use the
5669 u64 perf_swevent_set_period(struct perf_event *event)
5671 struct hw_perf_event *hwc = &event->hw;
5672 u64 period = hwc->last_period;
5676 hwc->last_period = hwc->sample_period;
5679 old = val = local64_read(&hwc->period_left);
5683 nr = div64_u64(period + val, period);
5684 offset = nr * period;
5686 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
5692 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
5693 struct perf_sample_data *data,
5694 struct pt_regs *regs)
5696 struct hw_perf_event *hwc = &event->hw;
5700 overflow = perf_swevent_set_period(event);
5702 if (hwc->interrupts == MAX_INTERRUPTS)
5705 for (; overflow; overflow--) {
5706 if (__perf_event_overflow(event, throttle,
5709 * We inhibit the overflow from happening when
5710 * hwc->interrupts == MAX_INTERRUPTS.
5718 static void perf_swevent_event(struct perf_event *event, u64 nr,
5719 struct perf_sample_data *data,
5720 struct pt_regs *regs)
5722 struct hw_perf_event *hwc = &event->hw;
5724 local64_add(nr, &event->count);
5729 if (!is_sampling_event(event))
5732 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
5734 return perf_swevent_overflow(event, 1, data, regs);
5736 data->period = event->hw.last_period;
5738 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
5739 return perf_swevent_overflow(event, 1, data, regs);
5741 if (local64_add_negative(nr, &hwc->period_left))
5744 perf_swevent_overflow(event, 0, data, regs);
5747 static int perf_exclude_event(struct perf_event *event,
5748 struct pt_regs *regs)
5750 if (event->hw.state & PERF_HES_STOPPED)
5754 if (event->attr.exclude_user && user_mode(regs))
5757 if (event->attr.exclude_kernel && !user_mode(regs))
5764 static int perf_swevent_match(struct perf_event *event,
5765 enum perf_type_id type,
5767 struct perf_sample_data *data,
5768 struct pt_regs *regs)
5770 if (event->attr.type != type)
5773 if (event->attr.config != event_id)
5776 if (perf_exclude_event(event, regs))
5782 static inline u64 swevent_hash(u64 type, u32 event_id)
5784 u64 val = event_id | (type << 32);
5786 return hash_64(val, SWEVENT_HLIST_BITS);
5789 static inline struct hlist_head *
5790 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
5792 u64 hash = swevent_hash(type, event_id);
5794 return &hlist->heads[hash];
5797 /* For the read side: events when they trigger */
5798 static inline struct hlist_head *
5799 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
5801 struct swevent_hlist *hlist;
5803 hlist = rcu_dereference(swhash->swevent_hlist);
5807 return __find_swevent_head(hlist, type, event_id);
5810 /* For the event head insertion and removal in the hlist */
5811 static inline struct hlist_head *
5812 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
5814 struct swevent_hlist *hlist;
5815 u32 event_id = event->attr.config;
5816 u64 type = event->attr.type;
5819 * Event scheduling is always serialized against hlist allocation
5820 * and release. Which makes the protected version suitable here.
5821 * The context lock guarantees that.
5823 hlist = rcu_dereference_protected(swhash->swevent_hlist,
5824 lockdep_is_held(&event->ctx->lock));
5828 return __find_swevent_head(hlist, type, event_id);
5831 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
5833 struct perf_sample_data *data,
5834 struct pt_regs *regs)
5836 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
5837 struct perf_event *event;
5838 struct hlist_head *head;
5841 head = find_swevent_head_rcu(swhash, type, event_id);
5845 hlist_for_each_entry_rcu(event, head, hlist_entry) {
5846 if (perf_swevent_match(event, type, event_id, data, regs))
5847 perf_swevent_event(event, nr, data, regs);
5853 int perf_swevent_get_recursion_context(void)
5855 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
5857 return get_recursion_context(swhash->recursion);
5859 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
5861 inline void perf_swevent_put_recursion_context(int rctx)
5863 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
5865 put_recursion_context(swhash->recursion, rctx);
5868 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
5870 struct perf_sample_data data;
5873 preempt_disable_notrace();
5874 rctx = perf_swevent_get_recursion_context();
5878 perf_sample_data_init(&data, addr, 0);
5880 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
5882 perf_swevent_put_recursion_context(rctx);
5883 preempt_enable_notrace();
5886 static void perf_swevent_read(struct perf_event *event)
5890 static int perf_swevent_add(struct perf_event *event, int flags)
5892 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
5893 struct hw_perf_event *hwc = &event->hw;
5894 struct hlist_head *head;
5896 if (is_sampling_event(event)) {
5897 hwc->last_period = hwc->sample_period;
5898 perf_swevent_set_period(event);
5901 hwc->state = !(flags & PERF_EF_START);
5903 head = find_swevent_head(swhash, event);
5906 * We can race with cpu hotplug code. Do not
5907 * WARN if the cpu just got unplugged.
5909 WARN_ON_ONCE(swhash->online);
5913 hlist_add_head_rcu(&event->hlist_entry, head);
5918 static void perf_swevent_del(struct perf_event *event, int flags)
5920 hlist_del_rcu(&event->hlist_entry);
5923 static void perf_swevent_start(struct perf_event *event, int flags)
5925 event->hw.state = 0;
5928 static void perf_swevent_stop(struct perf_event *event, int flags)
5930 event->hw.state = PERF_HES_STOPPED;
5933 /* Deref the hlist from the update side */
5934 static inline struct swevent_hlist *
5935 swevent_hlist_deref(struct swevent_htable *swhash)
5937 return rcu_dereference_protected(swhash->swevent_hlist,
5938 lockdep_is_held(&swhash->hlist_mutex));
5941 static void swevent_hlist_release(struct swevent_htable *swhash)
5943 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
5948 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
5949 kfree_rcu(hlist, rcu_head);
5952 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
5954 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5956 mutex_lock(&swhash->hlist_mutex);
5958 if (!--swhash->hlist_refcount)
5959 swevent_hlist_release(swhash);
5961 mutex_unlock(&swhash->hlist_mutex);
5964 static void swevent_hlist_put(struct perf_event *event)
5968 for_each_possible_cpu(cpu)
5969 swevent_hlist_put_cpu(event, cpu);
5972 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
5974 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5977 mutex_lock(&swhash->hlist_mutex);
5979 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
5980 struct swevent_hlist *hlist;
5982 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
5987 rcu_assign_pointer(swhash->swevent_hlist, hlist);
5989 swhash->hlist_refcount++;
5991 mutex_unlock(&swhash->hlist_mutex);
5996 static int swevent_hlist_get(struct perf_event *event)
5999 int cpu, failed_cpu;
6002 for_each_possible_cpu(cpu) {
6003 err = swevent_hlist_get_cpu(event, cpu);
6013 for_each_possible_cpu(cpu) {
6014 if (cpu == failed_cpu)
6016 swevent_hlist_put_cpu(event, cpu);
6023 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
6025 static void sw_perf_event_destroy(struct perf_event *event)
6027 u64 event_id = event->attr.config;
6029 WARN_ON(event->parent);
6031 static_key_slow_dec(&perf_swevent_enabled[event_id]);
6032 swevent_hlist_put(event);
6035 static int perf_swevent_init(struct perf_event *event)
6037 u64 event_id = event->attr.config;
6039 if (event->attr.type != PERF_TYPE_SOFTWARE)
6043 * no branch sampling for software events
6045 if (has_branch_stack(event))
6049 case PERF_COUNT_SW_CPU_CLOCK:
6050 case PERF_COUNT_SW_TASK_CLOCK:
6057 if (event_id >= PERF_COUNT_SW_MAX)
6060 if (!event->parent) {
6063 err = swevent_hlist_get(event);
6067 static_key_slow_inc(&perf_swevent_enabled[event_id]);
6068 event->destroy = sw_perf_event_destroy;
6074 static int perf_swevent_event_idx(struct perf_event *event)
6079 static struct pmu perf_swevent = {
6080 .task_ctx_nr = perf_sw_context,
6082 .event_init = perf_swevent_init,
6083 .add = perf_swevent_add,
6084 .del = perf_swevent_del,
6085 .start = perf_swevent_start,
6086 .stop = perf_swevent_stop,
6087 .read = perf_swevent_read,
6089 .event_idx = perf_swevent_event_idx,
6092 #ifdef CONFIG_EVENT_TRACING
6094 static int perf_tp_filter_match(struct perf_event *event,
6095 struct perf_sample_data *data)
6097 void *record = data->raw->data;
6099 if (likely(!event->filter) || filter_match_preds(event->filter, record))
6104 static int perf_tp_event_match(struct perf_event *event,
6105 struct perf_sample_data *data,
6106 struct pt_regs *regs)
6108 if (event->hw.state & PERF_HES_STOPPED)
6111 * All tracepoints are from kernel-space.
6113 if (event->attr.exclude_kernel)
6116 if (!perf_tp_filter_match(event, data))
6122 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
6123 struct pt_regs *regs, struct hlist_head *head, int rctx,
6124 struct task_struct *task)
6126 struct perf_sample_data data;
6127 struct perf_event *event;
6129 struct perf_raw_record raw = {
6134 perf_sample_data_init(&data, addr, 0);
6137 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6138 if (perf_tp_event_match(event, &data, regs))
6139 perf_swevent_event(event, count, &data, regs);
6143 * If we got specified a target task, also iterate its context and
6144 * deliver this event there too.
6146 if (task && task != current) {
6147 struct perf_event_context *ctx;
6148 struct trace_entry *entry = record;
6151 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
6155 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
6156 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6158 if (event->attr.config != entry->type)
6160 if (perf_tp_event_match(event, &data, regs))
6161 perf_swevent_event(event, count, &data, regs);
6167 perf_swevent_put_recursion_context(rctx);
6169 EXPORT_SYMBOL_GPL(perf_tp_event);
6171 static void tp_perf_event_destroy(struct perf_event *event)
6173 perf_trace_destroy(event);
6176 static int perf_tp_event_init(struct perf_event *event)
6180 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6184 * no branch sampling for tracepoint events
6186 if (has_branch_stack(event))
6189 err = perf_trace_init(event);
6193 event->destroy = tp_perf_event_destroy;
6198 static struct pmu perf_tracepoint = {
6199 .task_ctx_nr = perf_sw_context,
6201 .event_init = perf_tp_event_init,
6202 .add = perf_trace_add,
6203 .del = perf_trace_del,
6204 .start = perf_swevent_start,
6205 .stop = perf_swevent_stop,
6206 .read = perf_swevent_read,
6208 .event_idx = perf_swevent_event_idx,
6211 static inline void perf_tp_register(void)
6213 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
6216 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
6221 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6224 filter_str = strndup_user(arg, PAGE_SIZE);
6225 if (IS_ERR(filter_str))
6226 return PTR_ERR(filter_str);
6228 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
6234 static void perf_event_free_filter(struct perf_event *event)
6236 ftrace_profile_free_filter(event);
6241 static inline void perf_tp_register(void)
6245 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
6250 static void perf_event_free_filter(struct perf_event *event)
6254 #endif /* CONFIG_EVENT_TRACING */
6256 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6257 void perf_bp_event(struct perf_event *bp, void *data)
6259 struct perf_sample_data sample;
6260 struct pt_regs *regs = data;
6262 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
6264 if (!bp->hw.state && !perf_exclude_event(bp, regs))
6265 perf_swevent_event(bp, 1, &sample, regs);
6270 * hrtimer based swevent callback
6273 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
6275 enum hrtimer_restart ret = HRTIMER_RESTART;
6276 struct perf_sample_data data;
6277 struct pt_regs *regs;
6278 struct perf_event *event;
6281 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
6283 if (event->state != PERF_EVENT_STATE_ACTIVE)
6284 return HRTIMER_NORESTART;
6286 event->pmu->read(event);
6288 perf_sample_data_init(&data, 0, event->hw.last_period);
6289 regs = get_irq_regs();
6291 if (regs && !perf_exclude_event(event, regs)) {
6292 if (!(event->attr.exclude_idle && is_idle_task(current)))
6293 if (__perf_event_overflow(event, 1, &data, regs))
6294 ret = HRTIMER_NORESTART;
6297 period = max_t(u64, 10000, event->hw.sample_period);
6298 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
6303 static void perf_swevent_start_hrtimer(struct perf_event *event)
6305 struct hw_perf_event *hwc = &event->hw;
6308 if (!is_sampling_event(event))
6311 period = local64_read(&hwc->period_left);
6316 local64_set(&hwc->period_left, 0);
6318 period = max_t(u64, 10000, hwc->sample_period);
6320 __hrtimer_start_range_ns(&hwc->hrtimer,
6321 ns_to_ktime(period), 0,
6322 HRTIMER_MODE_REL_PINNED, 0);
6325 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
6327 struct hw_perf_event *hwc = &event->hw;
6329 if (is_sampling_event(event)) {
6330 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
6331 local64_set(&hwc->period_left, ktime_to_ns(remaining));
6333 hrtimer_cancel(&hwc->hrtimer);
6337 static void perf_swevent_init_hrtimer(struct perf_event *event)
6339 struct hw_perf_event *hwc = &event->hw;
6341 if (!is_sampling_event(event))
6344 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6345 hwc->hrtimer.function = perf_swevent_hrtimer;
6348 * Since hrtimers have a fixed rate, we can do a static freq->period
6349 * mapping and avoid the whole period adjust feedback stuff.
6351 if (event->attr.freq) {
6352 long freq = event->attr.sample_freq;
6354 event->attr.sample_period = NSEC_PER_SEC / freq;
6355 hwc->sample_period = event->attr.sample_period;
6356 local64_set(&hwc->period_left, hwc->sample_period);
6357 hwc->last_period = hwc->sample_period;
6358 event->attr.freq = 0;
6363 * Software event: cpu wall time clock
6366 static void cpu_clock_event_update(struct perf_event *event)
6371 now = local_clock();
6372 prev = local64_xchg(&event->hw.prev_count, now);
6373 local64_add(now - prev, &event->count);
6376 static void cpu_clock_event_start(struct perf_event *event, int flags)
6378 local64_set(&event->hw.prev_count, local_clock());
6379 perf_swevent_start_hrtimer(event);
6382 static void cpu_clock_event_stop(struct perf_event *event, int flags)
6384 perf_swevent_cancel_hrtimer(event);
6385 cpu_clock_event_update(event);
6388 static int cpu_clock_event_add(struct perf_event *event, int flags)
6390 if (flags & PERF_EF_START)
6391 cpu_clock_event_start(event, flags);
6396 static void cpu_clock_event_del(struct perf_event *event, int flags)
6398 cpu_clock_event_stop(event, flags);
6401 static void cpu_clock_event_read(struct perf_event *event)
6403 cpu_clock_event_update(event);
6406 static int cpu_clock_event_init(struct perf_event *event)
6408 if (event->attr.type != PERF_TYPE_SOFTWARE)
6411 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
6415 * no branch sampling for software events
6417 if (has_branch_stack(event))
6420 perf_swevent_init_hrtimer(event);
6425 static struct pmu perf_cpu_clock = {
6426 .task_ctx_nr = perf_sw_context,
6428 .event_init = cpu_clock_event_init,
6429 .add = cpu_clock_event_add,
6430 .del = cpu_clock_event_del,
6431 .start = cpu_clock_event_start,
6432 .stop = cpu_clock_event_stop,
6433 .read = cpu_clock_event_read,
6435 .event_idx = perf_swevent_event_idx,
6439 * Software event: task time clock
6442 static void task_clock_event_update(struct perf_event *event, u64 now)
6447 prev = local64_xchg(&event->hw.prev_count, now);
6449 local64_add(delta, &event->count);
6452 static void task_clock_event_start(struct perf_event *event, int flags)
6454 local64_set(&event->hw.prev_count, event->ctx->time);
6455 perf_swevent_start_hrtimer(event);
6458 static void task_clock_event_stop(struct perf_event *event, int flags)
6460 perf_swevent_cancel_hrtimer(event);
6461 task_clock_event_update(event, event->ctx->time);
6464 static int task_clock_event_add(struct perf_event *event, int flags)
6466 if (flags & PERF_EF_START)
6467 task_clock_event_start(event, flags);
6472 static void task_clock_event_del(struct perf_event *event, int flags)
6474 task_clock_event_stop(event, PERF_EF_UPDATE);
6477 static void task_clock_event_read(struct perf_event *event)
6479 u64 now = perf_clock();
6480 u64 delta = now - event->ctx->timestamp;
6481 u64 time = event->ctx->time + delta;
6483 task_clock_event_update(event, time);
6486 static int task_clock_event_init(struct perf_event *event)
6488 if (event->attr.type != PERF_TYPE_SOFTWARE)
6491 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
6495 * no branch sampling for software events
6497 if (has_branch_stack(event))
6500 perf_swevent_init_hrtimer(event);
6505 static struct pmu perf_task_clock = {
6506 .task_ctx_nr = perf_sw_context,
6508 .event_init = task_clock_event_init,
6509 .add = task_clock_event_add,
6510 .del = task_clock_event_del,
6511 .start = task_clock_event_start,
6512 .stop = task_clock_event_stop,
6513 .read = task_clock_event_read,
6515 .event_idx = perf_swevent_event_idx,
6518 static void perf_pmu_nop_void(struct pmu *pmu)
6522 static int perf_pmu_nop_int(struct pmu *pmu)
6527 static void perf_pmu_start_txn(struct pmu *pmu)
6529 perf_pmu_disable(pmu);
6532 static int perf_pmu_commit_txn(struct pmu *pmu)
6534 perf_pmu_enable(pmu);
6538 static void perf_pmu_cancel_txn(struct pmu *pmu)
6540 perf_pmu_enable(pmu);
6543 static int perf_event_idx_default(struct perf_event *event)
6545 return event->hw.idx + 1;
6549 * Ensures all contexts with the same task_ctx_nr have the same
6550 * pmu_cpu_context too.
6552 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
6559 list_for_each_entry(pmu, &pmus, entry) {
6560 if (pmu->task_ctx_nr == ctxn)
6561 return pmu->pmu_cpu_context;
6567 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
6571 for_each_possible_cpu(cpu) {
6572 struct perf_cpu_context *cpuctx;
6574 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6576 if (cpuctx->unique_pmu == old_pmu)
6577 cpuctx->unique_pmu = pmu;
6581 static void free_pmu_context(struct pmu *pmu)
6585 mutex_lock(&pmus_lock);
6587 * Like a real lame refcount.
6589 list_for_each_entry(i, &pmus, entry) {
6590 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
6591 update_pmu_context(i, pmu);
6596 free_percpu(pmu->pmu_cpu_context);
6598 mutex_unlock(&pmus_lock);
6600 static struct idr pmu_idr;
6603 type_show(struct device *dev, struct device_attribute *attr, char *page)
6605 struct pmu *pmu = dev_get_drvdata(dev);
6607 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
6609 static DEVICE_ATTR_RO(type);
6612 perf_event_mux_interval_ms_show(struct device *dev,
6613 struct device_attribute *attr,
6616 struct pmu *pmu = dev_get_drvdata(dev);
6618 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
6622 perf_event_mux_interval_ms_store(struct device *dev,
6623 struct device_attribute *attr,
6624 const char *buf, size_t count)
6626 struct pmu *pmu = dev_get_drvdata(dev);
6627 int timer, cpu, ret;
6629 ret = kstrtoint(buf, 0, &timer);
6636 /* same value, noting to do */
6637 if (timer == pmu->hrtimer_interval_ms)
6640 pmu->hrtimer_interval_ms = timer;
6642 /* update all cpuctx for this PMU */
6643 for_each_possible_cpu(cpu) {
6644 struct perf_cpu_context *cpuctx;
6645 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6646 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
6648 if (hrtimer_active(&cpuctx->hrtimer))
6649 hrtimer_forward_now(&cpuctx->hrtimer, cpuctx->hrtimer_interval);
6654 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
6656 static struct attribute *pmu_dev_attrs[] = {
6657 &dev_attr_type.attr,
6658 &dev_attr_perf_event_mux_interval_ms.attr,
6661 ATTRIBUTE_GROUPS(pmu_dev);
6663 static int pmu_bus_running;
6664 static struct bus_type pmu_bus = {
6665 .name = "event_source",
6666 .dev_groups = pmu_dev_groups,
6669 static void pmu_dev_release(struct device *dev)
6674 static int pmu_dev_alloc(struct pmu *pmu)
6678 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
6682 pmu->dev->groups = pmu->attr_groups;
6683 device_initialize(pmu->dev);
6684 ret = dev_set_name(pmu->dev, "%s", pmu->name);
6688 dev_set_drvdata(pmu->dev, pmu);
6689 pmu->dev->bus = &pmu_bus;
6690 pmu->dev->release = pmu_dev_release;
6691 ret = device_add(pmu->dev);
6699 put_device(pmu->dev);
6703 static struct lock_class_key cpuctx_mutex;
6704 static struct lock_class_key cpuctx_lock;
6706 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
6710 mutex_lock(&pmus_lock);
6712 pmu->pmu_disable_count = alloc_percpu(int);
6713 if (!pmu->pmu_disable_count)
6722 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
6730 if (pmu_bus_running) {
6731 ret = pmu_dev_alloc(pmu);
6737 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
6738 if (pmu->pmu_cpu_context)
6739 goto got_cpu_context;
6742 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
6743 if (!pmu->pmu_cpu_context)
6746 for_each_possible_cpu(cpu) {
6747 struct perf_cpu_context *cpuctx;
6749 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6750 __perf_event_init_context(&cpuctx->ctx);
6751 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
6752 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
6753 cpuctx->ctx.type = cpu_context;
6754 cpuctx->ctx.pmu = pmu;
6756 __perf_cpu_hrtimer_init(cpuctx, cpu);
6758 INIT_LIST_HEAD(&cpuctx->rotation_list);
6759 cpuctx->unique_pmu = pmu;
6763 if (!pmu->start_txn) {
6764 if (pmu->pmu_enable) {
6766 * If we have pmu_enable/pmu_disable calls, install
6767 * transaction stubs that use that to try and batch
6768 * hardware accesses.
6770 pmu->start_txn = perf_pmu_start_txn;
6771 pmu->commit_txn = perf_pmu_commit_txn;
6772 pmu->cancel_txn = perf_pmu_cancel_txn;
6774 pmu->start_txn = perf_pmu_nop_void;
6775 pmu->commit_txn = perf_pmu_nop_int;
6776 pmu->cancel_txn = perf_pmu_nop_void;
6780 if (!pmu->pmu_enable) {
6781 pmu->pmu_enable = perf_pmu_nop_void;
6782 pmu->pmu_disable = perf_pmu_nop_void;
6785 if (!pmu->event_idx)
6786 pmu->event_idx = perf_event_idx_default;
6788 list_add_rcu(&pmu->entry, &pmus);
6791 mutex_unlock(&pmus_lock);
6796 device_del(pmu->dev);
6797 put_device(pmu->dev);
6800 if (pmu->type >= PERF_TYPE_MAX)
6801 idr_remove(&pmu_idr, pmu->type);
6804 free_percpu(pmu->pmu_disable_count);
6807 EXPORT_SYMBOL_GPL(perf_pmu_register);
6809 void perf_pmu_unregister(struct pmu *pmu)
6811 mutex_lock(&pmus_lock);
6812 list_del_rcu(&pmu->entry);
6813 mutex_unlock(&pmus_lock);
6816 * We dereference the pmu list under both SRCU and regular RCU, so
6817 * synchronize against both of those.
6819 synchronize_srcu(&pmus_srcu);
6822 free_percpu(pmu->pmu_disable_count);
6823 if (pmu->type >= PERF_TYPE_MAX)
6824 idr_remove(&pmu_idr, pmu->type);
6825 device_del(pmu->dev);
6826 put_device(pmu->dev);
6827 free_pmu_context(pmu);
6829 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
6831 struct pmu *perf_init_event(struct perf_event *event)
6833 struct pmu *pmu = NULL;
6837 idx = srcu_read_lock(&pmus_srcu);
6840 pmu = idr_find(&pmu_idr, event->attr.type);
6843 if (!try_module_get(pmu->module)) {
6844 pmu = ERR_PTR(-ENODEV);
6848 ret = pmu->event_init(event);
6854 list_for_each_entry_rcu(pmu, &pmus, entry) {
6855 if (!try_module_get(pmu->module)) {
6856 pmu = ERR_PTR(-ENODEV);
6860 ret = pmu->event_init(event);
6864 if (ret != -ENOENT) {
6869 pmu = ERR_PTR(-ENOENT);
6871 srcu_read_unlock(&pmus_srcu, idx);
6876 static void account_event_cpu(struct perf_event *event, int cpu)
6881 if (has_branch_stack(event)) {
6882 if (!(event->attach_state & PERF_ATTACH_TASK))
6883 atomic_inc(&per_cpu(perf_branch_stack_events, cpu));
6885 if (is_cgroup_event(event))
6886 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
6889 static void account_event(struct perf_event *event)
6894 if (event->attach_state & PERF_ATTACH_TASK)
6895 static_key_slow_inc(&perf_sched_events.key);
6896 if (event->attr.mmap || event->attr.mmap_data)
6897 atomic_inc(&nr_mmap_events);
6898 if (event->attr.comm)
6899 atomic_inc(&nr_comm_events);
6900 if (event->attr.task)
6901 atomic_inc(&nr_task_events);
6902 if (event->attr.freq) {
6903 if (atomic_inc_return(&nr_freq_events) == 1)
6904 tick_nohz_full_kick_all();
6906 if (has_branch_stack(event))
6907 static_key_slow_inc(&perf_sched_events.key);
6908 if (is_cgroup_event(event))
6909 static_key_slow_inc(&perf_sched_events.key);
6911 account_event_cpu(event, event->cpu);
6915 * Allocate and initialize a event structure
6917 static struct perf_event *
6918 perf_event_alloc(struct perf_event_attr *attr, int cpu,
6919 struct task_struct *task,
6920 struct perf_event *group_leader,
6921 struct perf_event *parent_event,
6922 perf_overflow_handler_t overflow_handler,
6926 struct perf_event *event;
6927 struct hw_perf_event *hwc;
6930 if ((unsigned)cpu >= nr_cpu_ids) {
6931 if (!task || cpu != -1)
6932 return ERR_PTR(-EINVAL);
6935 event = kzalloc(sizeof(*event), GFP_KERNEL);
6937 return ERR_PTR(-ENOMEM);
6940 * Single events are their own group leaders, with an
6941 * empty sibling list:
6944 group_leader = event;
6946 mutex_init(&event->child_mutex);
6947 INIT_LIST_HEAD(&event->child_list);
6949 INIT_LIST_HEAD(&event->group_entry);
6950 INIT_LIST_HEAD(&event->event_entry);
6951 INIT_LIST_HEAD(&event->sibling_list);
6952 INIT_LIST_HEAD(&event->rb_entry);
6953 INIT_LIST_HEAD(&event->active_entry);
6954 INIT_HLIST_NODE(&event->hlist_entry);
6957 init_waitqueue_head(&event->waitq);
6958 init_irq_work(&event->pending, perf_pending_event);
6960 mutex_init(&event->mmap_mutex);
6962 atomic_long_set(&event->refcount, 1);
6964 event->attr = *attr;
6965 event->group_leader = group_leader;
6969 event->parent = parent_event;
6971 event->ns = get_pid_ns(task_active_pid_ns(current));
6972 event->id = atomic64_inc_return(&perf_event_id);
6974 event->state = PERF_EVENT_STATE_INACTIVE;
6977 event->attach_state = PERF_ATTACH_TASK;
6979 if (attr->type == PERF_TYPE_TRACEPOINT)
6980 event->hw.tp_target = task;
6981 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6983 * hw_breakpoint is a bit difficult here..
6985 else if (attr->type == PERF_TYPE_BREAKPOINT)
6986 event->hw.bp_target = task;
6990 if (!overflow_handler && parent_event) {
6991 overflow_handler = parent_event->overflow_handler;
6992 context = parent_event->overflow_handler_context;
6995 event->overflow_handler = overflow_handler;
6996 event->overflow_handler_context = context;
6998 perf_event__state_init(event);
7003 hwc->sample_period = attr->sample_period;
7004 if (attr->freq && attr->sample_freq)
7005 hwc->sample_period = 1;
7006 hwc->last_period = hwc->sample_period;
7008 local64_set(&hwc->period_left, hwc->sample_period);
7011 * we currently do not support PERF_FORMAT_GROUP on inherited events
7013 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
7016 pmu = perf_init_event(event);
7019 else if (IS_ERR(pmu)) {
7024 if (!event->parent) {
7025 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
7026 err = get_callchain_buffers();
7036 event->destroy(event);
7037 module_put(pmu->module);
7040 put_pid_ns(event->ns);
7043 return ERR_PTR(err);
7046 static int perf_copy_attr(struct perf_event_attr __user *uattr,
7047 struct perf_event_attr *attr)
7052 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
7056 * zero the full structure, so that a short copy will be nice.
7058 memset(attr, 0, sizeof(*attr));
7060 ret = get_user(size, &uattr->size);
7064 if (size > PAGE_SIZE) /* silly large */
7067 if (!size) /* abi compat */
7068 size = PERF_ATTR_SIZE_VER0;
7070 if (size < PERF_ATTR_SIZE_VER0)
7074 * If we're handed a bigger struct than we know of,
7075 * ensure all the unknown bits are 0 - i.e. new
7076 * user-space does not rely on any kernel feature
7077 * extensions we dont know about yet.
7079 if (size > sizeof(*attr)) {
7080 unsigned char __user *addr;
7081 unsigned char __user *end;
7084 addr = (void __user *)uattr + sizeof(*attr);
7085 end = (void __user *)uattr + size;
7087 for (; addr < end; addr++) {
7088 ret = get_user(val, addr);
7094 size = sizeof(*attr);
7097 ret = copy_from_user(attr, uattr, size);
7101 if (attr->__reserved_1)
7104 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
7107 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
7110 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
7111 u64 mask = attr->branch_sample_type;
7113 /* only using defined bits */
7114 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
7117 /* at least one branch bit must be set */
7118 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
7121 /* propagate priv level, when not set for branch */
7122 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
7124 /* exclude_kernel checked on syscall entry */
7125 if (!attr->exclude_kernel)
7126 mask |= PERF_SAMPLE_BRANCH_KERNEL;
7128 if (!attr->exclude_user)
7129 mask |= PERF_SAMPLE_BRANCH_USER;
7131 if (!attr->exclude_hv)
7132 mask |= PERF_SAMPLE_BRANCH_HV;
7134 * adjust user setting (for HW filter setup)
7136 attr->branch_sample_type = mask;
7138 /* privileged levels capture (kernel, hv): check permissions */
7139 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
7140 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
7144 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
7145 ret = perf_reg_validate(attr->sample_regs_user);
7150 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
7151 if (!arch_perf_have_user_stack_dump())
7155 * We have __u32 type for the size, but so far
7156 * we can only use __u16 as maximum due to the
7157 * __u16 sample size limit.
7159 if (attr->sample_stack_user >= USHRT_MAX)
7161 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
7169 put_user(sizeof(*attr), &uattr->size);
7175 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
7177 struct ring_buffer *rb = NULL;
7183 /* don't allow circular references */
7184 if (event == output_event)
7188 * Don't allow cross-cpu buffers
7190 if (output_event->cpu != event->cpu)
7194 * If its not a per-cpu rb, it must be the same task.
7196 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
7200 mutex_lock(&event->mmap_mutex);
7201 /* Can't redirect output if we've got an active mmap() */
7202 if (atomic_read(&event->mmap_count))
7206 /* get the rb we want to redirect to */
7207 rb = ring_buffer_get(output_event);
7212 ring_buffer_attach(event, rb);
7216 mutex_unlock(&event->mmap_mutex);
7223 * sys_perf_event_open - open a performance event, associate it to a task/cpu
7225 * @attr_uptr: event_id type attributes for monitoring/sampling
7228 * @group_fd: group leader event fd
7230 SYSCALL_DEFINE5(perf_event_open,
7231 struct perf_event_attr __user *, attr_uptr,
7232 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
7234 struct perf_event *group_leader = NULL, *output_event = NULL;
7235 struct perf_event *event, *sibling;
7236 struct perf_event_attr attr;
7237 struct perf_event_context *ctx;
7238 struct file *event_file = NULL;
7239 struct fd group = {NULL, 0};
7240 struct task_struct *task = NULL;
7245 int f_flags = O_RDWR;
7247 /* for future expandability... */
7248 if (flags & ~PERF_FLAG_ALL)
7251 err = perf_copy_attr(attr_uptr, &attr);
7255 if (!attr.exclude_kernel) {
7256 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
7261 if (attr.sample_freq > sysctl_perf_event_sample_rate)
7264 if (attr.sample_period & (1ULL << 63))
7269 * In cgroup mode, the pid argument is used to pass the fd
7270 * opened to the cgroup directory in cgroupfs. The cpu argument
7271 * designates the cpu on which to monitor threads from that
7274 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
7277 if (flags & PERF_FLAG_FD_CLOEXEC)
7278 f_flags |= O_CLOEXEC;
7280 event_fd = get_unused_fd_flags(f_flags);
7284 if (group_fd != -1) {
7285 err = perf_fget_light(group_fd, &group);
7288 group_leader = group.file->private_data;
7289 if (flags & PERF_FLAG_FD_OUTPUT)
7290 output_event = group_leader;
7291 if (flags & PERF_FLAG_FD_NO_GROUP)
7292 group_leader = NULL;
7295 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
7296 task = find_lively_task_by_vpid(pid);
7298 err = PTR_ERR(task);
7303 if (task && group_leader &&
7304 group_leader->attr.inherit != attr.inherit) {
7311 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
7313 if (IS_ERR(event)) {
7314 err = PTR_ERR(event);
7318 if (flags & PERF_FLAG_PID_CGROUP) {
7319 err = perf_cgroup_connect(pid, event, &attr, group_leader);
7321 __free_event(event);
7326 if (is_sampling_event(event)) {
7327 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
7333 account_event(event);
7336 * Special case software events and allow them to be part of
7337 * any hardware group.
7342 (is_software_event(event) != is_software_event(group_leader))) {
7343 if (is_software_event(event)) {
7345 * If event and group_leader are not both a software
7346 * event, and event is, then group leader is not.
7348 * Allow the addition of software events to !software
7349 * groups, this is safe because software events never
7352 pmu = group_leader->pmu;
7353 } else if (is_software_event(group_leader) &&
7354 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
7356 * In case the group is a pure software group, and we
7357 * try to add a hardware event, move the whole group to
7358 * the hardware context.
7365 * Get the target context (task or percpu):
7367 ctx = find_get_context(pmu, task, event->cpu);
7374 put_task_struct(task);
7379 * Look up the group leader (we will attach this event to it):
7385 * Do not allow a recursive hierarchy (this new sibling
7386 * becoming part of another group-sibling):
7388 if (group_leader->group_leader != group_leader)
7391 * Do not allow to attach to a group in a different
7392 * task or CPU context:
7395 if (group_leader->ctx->type != ctx->type)
7398 if (group_leader->ctx != ctx)
7403 * Only a group leader can be exclusive or pinned
7405 if (attr.exclusive || attr.pinned)
7410 err = perf_event_set_output(event, output_event);
7415 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
7417 if (IS_ERR(event_file)) {
7418 err = PTR_ERR(event_file);
7423 struct perf_event_context *gctx = group_leader->ctx;
7425 mutex_lock(&gctx->mutex);
7426 perf_remove_from_context(group_leader, false);
7429 * Removing from the context ends up with disabled
7430 * event. What we want here is event in the initial
7431 * startup state, ready to be add into new context.
7433 perf_event__state_init(group_leader);
7434 list_for_each_entry(sibling, &group_leader->sibling_list,
7436 perf_remove_from_context(sibling, false);
7437 perf_event__state_init(sibling);
7440 mutex_unlock(&gctx->mutex);
7444 WARN_ON_ONCE(ctx->parent_ctx);
7445 mutex_lock(&ctx->mutex);
7449 perf_install_in_context(ctx, group_leader, event->cpu);
7451 list_for_each_entry(sibling, &group_leader->sibling_list,
7453 perf_install_in_context(ctx, sibling, event->cpu);
7458 perf_install_in_context(ctx, event, event->cpu);
7459 perf_unpin_context(ctx);
7460 mutex_unlock(&ctx->mutex);
7464 event->owner = current;
7466 mutex_lock(¤t->perf_event_mutex);
7467 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
7468 mutex_unlock(¤t->perf_event_mutex);
7471 * Precalculate sample_data sizes
7473 perf_event__header_size(event);
7474 perf_event__id_header_size(event);
7477 * Drop the reference on the group_event after placing the
7478 * new event on the sibling_list. This ensures destruction
7479 * of the group leader will find the pointer to itself in
7480 * perf_group_detach().
7483 fd_install(event_fd, event_file);
7487 perf_unpin_context(ctx);
7495 put_task_struct(task);
7499 put_unused_fd(event_fd);
7504 * perf_event_create_kernel_counter
7506 * @attr: attributes of the counter to create
7507 * @cpu: cpu in which the counter is bound
7508 * @task: task to profile (NULL for percpu)
7511 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
7512 struct task_struct *task,
7513 perf_overflow_handler_t overflow_handler,
7516 struct perf_event_context *ctx;
7517 struct perf_event *event;
7521 * Get the target context (task or percpu):
7524 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
7525 overflow_handler, context);
7526 if (IS_ERR(event)) {
7527 err = PTR_ERR(event);
7531 /* Mark owner so we could distinguish it from user events. */
7532 event->owner = EVENT_OWNER_KERNEL;
7534 account_event(event);
7536 ctx = find_get_context(event->pmu, task, cpu);
7542 WARN_ON_ONCE(ctx->parent_ctx);
7543 mutex_lock(&ctx->mutex);
7544 perf_install_in_context(ctx, event, cpu);
7545 perf_unpin_context(ctx);
7546 mutex_unlock(&ctx->mutex);
7553 return ERR_PTR(err);
7555 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
7557 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
7559 struct perf_event_context *src_ctx;
7560 struct perf_event_context *dst_ctx;
7561 struct perf_event *event, *tmp;
7564 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
7565 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
7567 mutex_lock(&src_ctx->mutex);
7568 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
7570 perf_remove_from_context(event, false);
7571 unaccount_event_cpu(event, src_cpu);
7573 list_add(&event->migrate_entry, &events);
7575 mutex_unlock(&src_ctx->mutex);
7579 mutex_lock(&dst_ctx->mutex);
7580 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
7581 list_del(&event->migrate_entry);
7582 if (event->state >= PERF_EVENT_STATE_OFF)
7583 event->state = PERF_EVENT_STATE_INACTIVE;
7584 account_event_cpu(event, dst_cpu);
7585 perf_install_in_context(dst_ctx, event, dst_cpu);
7588 mutex_unlock(&dst_ctx->mutex);
7590 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
7592 static void sync_child_event(struct perf_event *child_event,
7593 struct task_struct *child)
7595 struct perf_event *parent_event = child_event->parent;
7598 if (child_event->attr.inherit_stat)
7599 perf_event_read_event(child_event, child);
7601 child_val = perf_event_count(child_event);
7604 * Add back the child's count to the parent's count:
7606 atomic64_add(child_val, &parent_event->child_count);
7607 atomic64_add(child_event->total_time_enabled,
7608 &parent_event->child_total_time_enabled);
7609 atomic64_add(child_event->total_time_running,
7610 &parent_event->child_total_time_running);
7613 * Remove this event from the parent's list
7615 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7616 mutex_lock(&parent_event->child_mutex);
7617 list_del_init(&child_event->child_list);
7618 mutex_unlock(&parent_event->child_mutex);
7621 * Make sure user/parent get notified, that we just
7624 perf_event_wakeup(parent_event);
7627 * Release the parent event, if this was the last
7630 put_event(parent_event);
7634 __perf_event_exit_task(struct perf_event *child_event,
7635 struct perf_event_context *child_ctx,
7636 struct task_struct *child)
7639 * Do not destroy the 'original' grouping; because of the context
7640 * switch optimization the original events could've ended up in a
7641 * random child task.
7643 * If we were to destroy the original group, all group related
7644 * operations would cease to function properly after this random
7647 * Do destroy all inherited groups, we don't care about those
7648 * and being thorough is better.
7650 perf_remove_from_context(child_event, !!child_event->parent);
7653 * It can happen that the parent exits first, and has events
7654 * that are still around due to the child reference. These
7655 * events need to be zapped.
7657 if (child_event->parent) {
7658 sync_child_event(child_event, child);
7659 free_event(child_event);
7661 child_event->state = PERF_EVENT_STATE_EXIT;
7662 perf_event_wakeup(child_event);
7666 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
7668 struct perf_event *child_event, *next;
7669 struct perf_event_context *child_ctx, *clone_ctx = NULL;
7670 unsigned long flags;
7672 if (likely(!child->perf_event_ctxp[ctxn])) {
7673 perf_event_task(child, NULL, 0);
7677 local_irq_save(flags);
7679 * We can't reschedule here because interrupts are disabled,
7680 * and either child is current or it is a task that can't be
7681 * scheduled, so we are now safe from rescheduling changing
7684 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
7687 * Take the context lock here so that if find_get_context is
7688 * reading child->perf_event_ctxp, we wait until it has
7689 * incremented the context's refcount before we do put_ctx below.
7691 raw_spin_lock(&child_ctx->lock);
7692 task_ctx_sched_out(child_ctx);
7693 child->perf_event_ctxp[ctxn] = NULL;
7696 * If this context is a clone; unclone it so it can't get
7697 * swapped to another process while we're removing all
7698 * the events from it.
7700 clone_ctx = unclone_ctx(child_ctx);
7701 update_context_time(child_ctx);
7702 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7708 * Report the task dead after unscheduling the events so that we
7709 * won't get any samples after PERF_RECORD_EXIT. We can however still
7710 * get a few PERF_RECORD_READ events.
7712 perf_event_task(child, child_ctx, 0);
7715 * We can recurse on the same lock type through:
7717 * __perf_event_exit_task()
7718 * sync_child_event()
7720 * mutex_lock(&ctx->mutex)
7722 * But since its the parent context it won't be the same instance.
7724 mutex_lock(&child_ctx->mutex);
7726 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
7727 __perf_event_exit_task(child_event, child_ctx, child);
7729 mutex_unlock(&child_ctx->mutex);
7735 * When a child task exits, feed back event values to parent events.
7737 void perf_event_exit_task(struct task_struct *child)
7739 struct perf_event *event, *tmp;
7742 mutex_lock(&child->perf_event_mutex);
7743 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
7745 list_del_init(&event->owner_entry);
7748 * Ensure the list deletion is visible before we clear
7749 * the owner, closes a race against perf_release() where
7750 * we need to serialize on the owner->perf_event_mutex.
7753 event->owner = NULL;
7755 mutex_unlock(&child->perf_event_mutex);
7757 for_each_task_context_nr(ctxn)
7758 perf_event_exit_task_context(child, ctxn);
7761 static void perf_free_event(struct perf_event *event,
7762 struct perf_event_context *ctx)
7764 struct perf_event *parent = event->parent;
7766 if (WARN_ON_ONCE(!parent))
7769 mutex_lock(&parent->child_mutex);
7770 list_del_init(&event->child_list);
7771 mutex_unlock(&parent->child_mutex);
7775 perf_group_detach(event);
7776 list_del_event(event, ctx);
7781 * free an unexposed, unused context as created by inheritance by
7782 * perf_event_init_task below, used by fork() in case of fail.
7784 void perf_event_free_task(struct task_struct *task)
7786 struct perf_event_context *ctx;
7787 struct perf_event *event, *tmp;
7790 for_each_task_context_nr(ctxn) {
7791 ctx = task->perf_event_ctxp[ctxn];
7795 mutex_lock(&ctx->mutex);
7797 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
7799 perf_free_event(event, ctx);
7801 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
7803 perf_free_event(event, ctx);
7805 if (!list_empty(&ctx->pinned_groups) ||
7806 !list_empty(&ctx->flexible_groups))
7809 mutex_unlock(&ctx->mutex);
7815 void perf_event_delayed_put(struct task_struct *task)
7819 for_each_task_context_nr(ctxn)
7820 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
7824 * inherit a event from parent task to child task:
7826 static struct perf_event *
7827 inherit_event(struct perf_event *parent_event,
7828 struct task_struct *parent,
7829 struct perf_event_context *parent_ctx,
7830 struct task_struct *child,
7831 struct perf_event *group_leader,
7832 struct perf_event_context *child_ctx)
7834 enum perf_event_active_state parent_state = parent_event->state;
7835 struct perf_event *child_event;
7836 unsigned long flags;
7839 * Instead of creating recursive hierarchies of events,
7840 * we link inherited events back to the original parent,
7841 * which has a filp for sure, which we use as the reference
7844 if (parent_event->parent)
7845 parent_event = parent_event->parent;
7847 child_event = perf_event_alloc(&parent_event->attr,
7850 group_leader, parent_event,
7852 if (IS_ERR(child_event))
7855 if (is_orphaned_event(parent_event) ||
7856 !atomic_long_inc_not_zero(&parent_event->refcount)) {
7857 free_event(child_event);
7864 * Make the child state follow the state of the parent event,
7865 * not its attr.disabled bit. We hold the parent's mutex,
7866 * so we won't race with perf_event_{en, dis}able_family.
7868 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
7869 child_event->state = PERF_EVENT_STATE_INACTIVE;
7871 child_event->state = PERF_EVENT_STATE_OFF;
7873 if (parent_event->attr.freq) {
7874 u64 sample_period = parent_event->hw.sample_period;
7875 struct hw_perf_event *hwc = &child_event->hw;
7877 hwc->sample_period = sample_period;
7878 hwc->last_period = sample_period;
7880 local64_set(&hwc->period_left, sample_period);
7883 child_event->ctx = child_ctx;
7884 child_event->overflow_handler = parent_event->overflow_handler;
7885 child_event->overflow_handler_context
7886 = parent_event->overflow_handler_context;
7889 * Precalculate sample_data sizes
7891 perf_event__header_size(child_event);
7892 perf_event__id_header_size(child_event);
7895 * Link it up in the child's context:
7897 raw_spin_lock_irqsave(&child_ctx->lock, flags);
7898 add_event_to_ctx(child_event, child_ctx);
7899 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7902 * Link this into the parent event's child list
7904 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7905 mutex_lock(&parent_event->child_mutex);
7906 list_add_tail(&child_event->child_list, &parent_event->child_list);
7907 mutex_unlock(&parent_event->child_mutex);
7912 static int inherit_group(struct perf_event *parent_event,
7913 struct task_struct *parent,
7914 struct perf_event_context *parent_ctx,
7915 struct task_struct *child,
7916 struct perf_event_context *child_ctx)
7918 struct perf_event *leader;
7919 struct perf_event *sub;
7920 struct perf_event *child_ctr;
7922 leader = inherit_event(parent_event, parent, parent_ctx,
7923 child, NULL, child_ctx);
7925 return PTR_ERR(leader);
7926 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
7927 child_ctr = inherit_event(sub, parent, parent_ctx,
7928 child, leader, child_ctx);
7929 if (IS_ERR(child_ctr))
7930 return PTR_ERR(child_ctr);
7936 inherit_task_group(struct perf_event *event, struct task_struct *parent,
7937 struct perf_event_context *parent_ctx,
7938 struct task_struct *child, int ctxn,
7942 struct perf_event_context *child_ctx;
7944 if (!event->attr.inherit) {
7949 child_ctx = child->perf_event_ctxp[ctxn];
7952 * This is executed from the parent task context, so
7953 * inherit events that have been marked for cloning.
7954 * First allocate and initialize a context for the
7958 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
7962 child->perf_event_ctxp[ctxn] = child_ctx;
7965 ret = inherit_group(event, parent, parent_ctx,
7975 * Initialize the perf_event context in task_struct
7977 static int perf_event_init_context(struct task_struct *child, int ctxn)
7979 struct perf_event_context *child_ctx, *parent_ctx;
7980 struct perf_event_context *cloned_ctx;
7981 struct perf_event *event;
7982 struct task_struct *parent = current;
7983 int inherited_all = 1;
7984 unsigned long flags;
7987 if (likely(!parent->perf_event_ctxp[ctxn]))
7991 * If the parent's context is a clone, pin it so it won't get
7994 parent_ctx = perf_pin_task_context(parent, ctxn);
7999 * No need to check if parent_ctx != NULL here; since we saw
8000 * it non-NULL earlier, the only reason for it to become NULL
8001 * is if we exit, and since we're currently in the middle of
8002 * a fork we can't be exiting at the same time.
8006 * Lock the parent list. No need to lock the child - not PID
8007 * hashed yet and not running, so nobody can access it.
8009 mutex_lock(&parent_ctx->mutex);
8012 * We dont have to disable NMIs - we are only looking at
8013 * the list, not manipulating it:
8015 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
8016 ret = inherit_task_group(event, parent, parent_ctx,
8017 child, ctxn, &inherited_all);
8023 * We can't hold ctx->lock when iterating the ->flexible_group list due
8024 * to allocations, but we need to prevent rotation because
8025 * rotate_ctx() will change the list from interrupt context.
8027 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
8028 parent_ctx->rotate_disable = 1;
8029 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
8031 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
8032 ret = inherit_task_group(event, parent, parent_ctx,
8033 child, ctxn, &inherited_all);
8038 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
8039 parent_ctx->rotate_disable = 0;
8041 child_ctx = child->perf_event_ctxp[ctxn];
8043 if (child_ctx && inherited_all) {
8045 * Mark the child context as a clone of the parent
8046 * context, or of whatever the parent is a clone of.
8048 * Note that if the parent is a clone, the holding of
8049 * parent_ctx->lock avoids it from being uncloned.
8051 cloned_ctx = parent_ctx->parent_ctx;
8053 child_ctx->parent_ctx = cloned_ctx;
8054 child_ctx->parent_gen = parent_ctx->parent_gen;
8056 child_ctx->parent_ctx = parent_ctx;
8057 child_ctx->parent_gen = parent_ctx->generation;
8059 get_ctx(child_ctx->parent_ctx);
8062 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
8063 mutex_unlock(&parent_ctx->mutex);
8065 perf_unpin_context(parent_ctx);
8066 put_ctx(parent_ctx);
8072 * Initialize the perf_event context in task_struct
8074 int perf_event_init_task(struct task_struct *child)
8078 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
8079 mutex_init(&child->perf_event_mutex);
8080 INIT_LIST_HEAD(&child->perf_event_list);
8082 for_each_task_context_nr(ctxn) {
8083 ret = perf_event_init_context(child, ctxn);
8085 perf_event_free_task(child);
8093 static void __init perf_event_init_all_cpus(void)
8095 struct swevent_htable *swhash;
8098 for_each_possible_cpu(cpu) {
8099 swhash = &per_cpu(swevent_htable, cpu);
8100 mutex_init(&swhash->hlist_mutex);
8101 INIT_LIST_HEAD(&per_cpu(rotation_list, cpu));
8105 static void perf_event_init_cpu(int cpu)
8107 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
8109 mutex_lock(&swhash->hlist_mutex);
8110 swhash->online = true;
8111 if (swhash->hlist_refcount > 0) {
8112 struct swevent_hlist *hlist;
8114 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
8116 rcu_assign_pointer(swhash->swevent_hlist, hlist);
8118 mutex_unlock(&swhash->hlist_mutex);
8121 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC
8122 static void perf_pmu_rotate_stop(struct pmu *pmu)
8124 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
8126 WARN_ON(!irqs_disabled());
8128 list_del_init(&cpuctx->rotation_list);
8131 static void __perf_event_exit_context(void *__info)
8133 struct remove_event re = { .detach_group = false };
8134 struct perf_event_context *ctx = __info;
8136 perf_pmu_rotate_stop(ctx->pmu);
8139 list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
8140 __perf_remove_from_context(&re);
8144 static void perf_event_exit_cpu_context(int cpu)
8146 struct perf_event_context *ctx;
8150 idx = srcu_read_lock(&pmus_srcu);
8151 list_for_each_entry_rcu(pmu, &pmus, entry) {
8152 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
8154 mutex_lock(&ctx->mutex);
8155 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
8156 mutex_unlock(&ctx->mutex);
8158 srcu_read_unlock(&pmus_srcu, idx);
8161 static void perf_event_exit_cpu(int cpu)
8163 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
8165 perf_event_exit_cpu_context(cpu);
8167 mutex_lock(&swhash->hlist_mutex);
8168 swhash->online = false;
8169 swevent_hlist_release(swhash);
8170 mutex_unlock(&swhash->hlist_mutex);
8173 static inline void perf_event_exit_cpu(int cpu) { }
8177 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
8181 for_each_online_cpu(cpu)
8182 perf_event_exit_cpu(cpu);
8188 * Run the perf reboot notifier at the very last possible moment so that
8189 * the generic watchdog code runs as long as possible.
8191 static struct notifier_block perf_reboot_notifier = {
8192 .notifier_call = perf_reboot,
8193 .priority = INT_MIN,
8197 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
8199 unsigned int cpu = (long)hcpu;
8201 switch (action & ~CPU_TASKS_FROZEN) {
8203 case CPU_UP_PREPARE:
8204 case CPU_DOWN_FAILED:
8205 perf_event_init_cpu(cpu);
8208 case CPU_UP_CANCELED:
8209 case CPU_DOWN_PREPARE:
8210 perf_event_exit_cpu(cpu);
8219 void __init perf_event_init(void)
8225 perf_event_init_all_cpus();
8226 init_srcu_struct(&pmus_srcu);
8227 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
8228 perf_pmu_register(&perf_cpu_clock, NULL, -1);
8229 perf_pmu_register(&perf_task_clock, NULL, -1);
8231 perf_cpu_notifier(perf_cpu_notify);
8232 register_reboot_notifier(&perf_reboot_notifier);
8234 ret = init_hw_breakpoint();
8235 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
8237 /* do not patch jump label more than once per second */
8238 jump_label_rate_limit(&perf_sched_events, HZ);
8241 * Build time assertion that we keep the data_head at the intended
8242 * location. IOW, validation we got the __reserved[] size right.
8244 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
8248 static int __init perf_event_sysfs_init(void)
8253 mutex_lock(&pmus_lock);
8255 ret = bus_register(&pmu_bus);
8259 list_for_each_entry(pmu, &pmus, entry) {
8260 if (!pmu->name || pmu->type < 0)
8263 ret = pmu_dev_alloc(pmu);
8264 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
8266 pmu_bus_running = 1;
8270 mutex_unlock(&pmus_lock);
8274 device_initcall(perf_event_sysfs_init);
8276 #ifdef CONFIG_CGROUP_PERF
8277 static struct cgroup_subsys_state *
8278 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
8280 struct perf_cgroup *jc;
8282 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
8284 return ERR_PTR(-ENOMEM);
8286 jc->info = alloc_percpu(struct perf_cgroup_info);
8289 return ERR_PTR(-ENOMEM);
8295 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
8297 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
8299 free_percpu(jc->info);
8303 static int __perf_cgroup_move(void *info)
8305 struct task_struct *task = info;
8306 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
8310 static void perf_cgroup_attach(struct cgroup_subsys_state *css,
8311 struct cgroup_taskset *tset)
8313 struct task_struct *task;
8315 cgroup_taskset_for_each(task, tset)
8316 task_function_call(task, __perf_cgroup_move, task);
8319 static void perf_cgroup_exit(struct cgroup_subsys_state *css,
8320 struct cgroup_subsys_state *old_css,
8321 struct task_struct *task)
8324 * cgroup_exit() is called in the copy_process() failure path.
8325 * Ignore this case since the task hasn't ran yet, this avoids
8326 * trying to poke a half freed task state from generic code.
8328 if (!(task->flags & PF_EXITING))
8331 task_function_call(task, __perf_cgroup_move, task);
8334 struct cgroup_subsys perf_event_cgrp_subsys = {
8335 .css_alloc = perf_cgroup_css_alloc,
8336 .css_free = perf_cgroup_css_free,
8337 .exit = perf_cgroup_exit,
8338 .attach = perf_cgroup_attach,
8340 #endif /* CONFIG_CGROUP_PERF */