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/compat.h>
46 #include <asm/irq_regs.h>
48 struct remote_function_call {
49 struct task_struct *p;
50 int (*func)(void *info);
55 static void remote_function(void *data)
57 struct remote_function_call *tfc = data;
58 struct task_struct *p = tfc->p;
62 if (task_cpu(p) != smp_processor_id() || !task_curr(p))
66 tfc->ret = tfc->func(tfc->info);
70 * task_function_call - call a function on the cpu on which a task runs
71 * @p: the task to evaluate
72 * @func: the function to be called
73 * @info: the function call argument
75 * Calls the function @func when the task is currently running. This might
76 * be on the current CPU, which just calls the function directly
78 * returns: @func return value, or
79 * -ESRCH - when the process isn't running
80 * -EAGAIN - when the process moved away
83 task_function_call(struct task_struct *p, int (*func) (void *info), void *info)
85 struct remote_function_call data = {
89 .ret = -ESRCH, /* No such (running) process */
93 smp_call_function_single(task_cpu(p), remote_function, &data, 1);
99 * cpu_function_call - call a function on the cpu
100 * @func: the function to be called
101 * @info: the function call argument
103 * Calls the function @func on the remote cpu.
105 * returns: @func return value or -ENXIO when the cpu is offline
107 static int cpu_function_call(int cpu, int (*func) (void *info), void *info)
109 struct remote_function_call data = {
113 .ret = -ENXIO, /* No such CPU */
116 smp_call_function_single(cpu, remote_function, &data, 1);
121 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
122 PERF_FLAG_FD_OUTPUT |\
123 PERF_FLAG_PID_CGROUP |\
124 PERF_FLAG_FD_CLOEXEC)
127 * branch priv levels that need permission checks
129 #define PERF_SAMPLE_BRANCH_PERM_PLM \
130 (PERF_SAMPLE_BRANCH_KERNEL |\
131 PERF_SAMPLE_BRANCH_HV)
134 EVENT_FLEXIBLE = 0x1,
136 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
140 * perf_sched_events : >0 events exist
141 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
143 struct static_key_deferred perf_sched_events __read_mostly;
144 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
145 static DEFINE_PER_CPU(atomic_t, perf_branch_stack_events);
147 static atomic_t nr_mmap_events __read_mostly;
148 static atomic_t nr_comm_events __read_mostly;
149 static atomic_t nr_task_events __read_mostly;
150 static atomic_t nr_freq_events __read_mostly;
152 static LIST_HEAD(pmus);
153 static DEFINE_MUTEX(pmus_lock);
154 static struct srcu_struct pmus_srcu;
157 * perf event paranoia level:
158 * -1 - not paranoid at all
159 * 0 - disallow raw tracepoint access for unpriv
160 * 1 - disallow cpu events for unpriv
161 * 2 - disallow kernel profiling for unpriv
163 int sysctl_perf_event_paranoid __read_mostly = 1;
165 /* Minimum for 512 kiB + 1 user control page */
166 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
169 * max perf event sample rate
171 #define DEFAULT_MAX_SAMPLE_RATE 100000
172 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
173 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
175 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
177 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
178 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
180 static int perf_sample_allowed_ns __read_mostly =
181 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
183 void update_perf_cpu_limits(void)
185 u64 tmp = perf_sample_period_ns;
187 tmp *= sysctl_perf_cpu_time_max_percent;
189 ACCESS_ONCE(perf_sample_allowed_ns) = tmp;
192 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
194 int perf_proc_update_handler(struct ctl_table *table, int write,
195 void __user *buffer, size_t *lenp,
198 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
203 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
204 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
205 update_perf_cpu_limits();
210 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
212 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
213 void __user *buffer, size_t *lenp,
216 int ret = proc_dointvec(table, write, buffer, lenp, ppos);
221 update_perf_cpu_limits();
227 * perf samples are done in some very critical code paths (NMIs).
228 * If they take too much CPU time, the system can lock up and not
229 * get any real work done. This will drop the sample rate when
230 * we detect that events are taking too long.
232 #define NR_ACCUMULATED_SAMPLES 128
233 static DEFINE_PER_CPU(u64, running_sample_length);
235 void perf_sample_event_took(u64 sample_len_ns)
237 u64 avg_local_sample_len;
238 u64 local_samples_len;
239 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
244 /* decay the counter by 1 average sample */
245 local_samples_len = __get_cpu_var(running_sample_length);
246 local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES;
247 local_samples_len += sample_len_ns;
248 __get_cpu_var(running_sample_length) = local_samples_len;
251 * note: this will be biased artifically low until we have
252 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
253 * from having to maintain a count.
255 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
257 if (avg_local_sample_len <= allowed_ns)
260 if (max_samples_per_tick <= 1)
263 max_samples_per_tick = DIV_ROUND_UP(max_samples_per_tick, 2);
264 sysctl_perf_event_sample_rate = max_samples_per_tick * HZ;
265 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
267 printk_ratelimited(KERN_WARNING
268 "perf samples too long (%lld > %lld), lowering "
269 "kernel.perf_event_max_sample_rate to %d\n",
270 avg_local_sample_len, allowed_ns,
271 sysctl_perf_event_sample_rate);
273 update_perf_cpu_limits();
276 static atomic64_t perf_event_id;
278 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
279 enum event_type_t event_type);
281 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
282 enum event_type_t event_type,
283 struct task_struct *task);
285 static void update_context_time(struct perf_event_context *ctx);
286 static u64 perf_event_time(struct perf_event *event);
288 void __weak perf_event_print_debug(void) { }
290 extern __weak const char *perf_pmu_name(void)
295 static inline u64 perf_clock(void)
297 return local_clock();
300 static inline struct perf_cpu_context *
301 __get_cpu_context(struct perf_event_context *ctx)
303 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
306 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
307 struct perf_event_context *ctx)
309 raw_spin_lock(&cpuctx->ctx.lock);
311 raw_spin_lock(&ctx->lock);
314 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
315 struct perf_event_context *ctx)
318 raw_spin_unlock(&ctx->lock);
319 raw_spin_unlock(&cpuctx->ctx.lock);
322 #ifdef CONFIG_CGROUP_PERF
325 * perf_cgroup_info keeps track of time_enabled for a cgroup.
326 * This is a per-cpu dynamically allocated data structure.
328 struct perf_cgroup_info {
334 struct cgroup_subsys_state css;
335 struct perf_cgroup_info __percpu *info;
339 * Must ensure cgroup is pinned (css_get) before calling
340 * this function. In other words, we cannot call this function
341 * if there is no cgroup event for the current CPU context.
343 static inline struct perf_cgroup *
344 perf_cgroup_from_task(struct task_struct *task)
346 return container_of(task_css(task, perf_subsys_id),
347 struct perf_cgroup, css);
351 perf_cgroup_match(struct perf_event *event)
353 struct perf_event_context *ctx = event->ctx;
354 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
356 /* @event doesn't care about cgroup */
360 /* wants specific cgroup scope but @cpuctx isn't associated with any */
365 * Cgroup scoping is recursive. An event enabled for a cgroup is
366 * also enabled for all its descendant cgroups. If @cpuctx's
367 * cgroup is a descendant of @event's (the test covers identity
368 * case), it's a match.
370 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
371 event->cgrp->css.cgroup);
374 static inline bool perf_tryget_cgroup(struct perf_event *event)
376 return css_tryget(&event->cgrp->css);
379 static inline void perf_put_cgroup(struct perf_event *event)
381 css_put(&event->cgrp->css);
384 static inline void perf_detach_cgroup(struct perf_event *event)
386 perf_put_cgroup(event);
390 static inline int is_cgroup_event(struct perf_event *event)
392 return event->cgrp != NULL;
395 static inline u64 perf_cgroup_event_time(struct perf_event *event)
397 struct perf_cgroup_info *t;
399 t = per_cpu_ptr(event->cgrp->info, event->cpu);
403 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
405 struct perf_cgroup_info *info;
410 info = this_cpu_ptr(cgrp->info);
412 info->time += now - info->timestamp;
413 info->timestamp = now;
416 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
418 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
420 __update_cgrp_time(cgrp_out);
423 static inline void update_cgrp_time_from_event(struct perf_event *event)
425 struct perf_cgroup *cgrp;
428 * ensure we access cgroup data only when needed and
429 * when we know the cgroup is pinned (css_get)
431 if (!is_cgroup_event(event))
434 cgrp = perf_cgroup_from_task(current);
436 * Do not update time when cgroup is not active
438 if (cgrp == event->cgrp)
439 __update_cgrp_time(event->cgrp);
443 perf_cgroup_set_timestamp(struct task_struct *task,
444 struct perf_event_context *ctx)
446 struct perf_cgroup *cgrp;
447 struct perf_cgroup_info *info;
450 * ctx->lock held by caller
451 * ensure we do not access cgroup data
452 * unless we have the cgroup pinned (css_get)
454 if (!task || !ctx->nr_cgroups)
457 cgrp = perf_cgroup_from_task(task);
458 info = this_cpu_ptr(cgrp->info);
459 info->timestamp = ctx->timestamp;
462 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
463 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
466 * reschedule events based on the cgroup constraint of task.
468 * mode SWOUT : schedule out everything
469 * mode SWIN : schedule in based on cgroup for next
471 void perf_cgroup_switch(struct task_struct *task, int mode)
473 struct perf_cpu_context *cpuctx;
478 * disable interrupts to avoid geting nr_cgroup
479 * changes via __perf_event_disable(). Also
482 local_irq_save(flags);
485 * we reschedule only in the presence of cgroup
486 * constrained events.
490 list_for_each_entry_rcu(pmu, &pmus, entry) {
491 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
492 if (cpuctx->unique_pmu != pmu)
493 continue; /* ensure we process each cpuctx once */
496 * perf_cgroup_events says at least one
497 * context on this CPU has cgroup events.
499 * ctx->nr_cgroups reports the number of cgroup
500 * events for a context.
502 if (cpuctx->ctx.nr_cgroups > 0) {
503 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
504 perf_pmu_disable(cpuctx->ctx.pmu);
506 if (mode & PERF_CGROUP_SWOUT) {
507 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
509 * must not be done before ctxswout due
510 * to event_filter_match() in event_sched_out()
515 if (mode & PERF_CGROUP_SWIN) {
516 WARN_ON_ONCE(cpuctx->cgrp);
518 * set cgrp before ctxsw in to allow
519 * event_filter_match() to not have to pass
522 cpuctx->cgrp = perf_cgroup_from_task(task);
523 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
525 perf_pmu_enable(cpuctx->ctx.pmu);
526 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
532 local_irq_restore(flags);
535 static inline void perf_cgroup_sched_out(struct task_struct *task,
536 struct task_struct *next)
538 struct perf_cgroup *cgrp1;
539 struct perf_cgroup *cgrp2 = NULL;
542 * we come here when we know perf_cgroup_events > 0
544 cgrp1 = perf_cgroup_from_task(task);
547 * next is NULL when called from perf_event_enable_on_exec()
548 * that will systematically cause a cgroup_switch()
551 cgrp2 = perf_cgroup_from_task(next);
554 * only schedule out current cgroup events if we know
555 * that we are switching to a different cgroup. Otherwise,
556 * do no touch the cgroup events.
559 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
562 static inline void perf_cgroup_sched_in(struct task_struct *prev,
563 struct task_struct *task)
565 struct perf_cgroup *cgrp1;
566 struct perf_cgroup *cgrp2 = NULL;
569 * we come here when we know perf_cgroup_events > 0
571 cgrp1 = perf_cgroup_from_task(task);
573 /* prev can never be NULL */
574 cgrp2 = perf_cgroup_from_task(prev);
577 * only need to schedule in cgroup events if we are changing
578 * cgroup during ctxsw. Cgroup events were not scheduled
579 * out of ctxsw out if that was not the case.
582 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
585 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
586 struct perf_event_attr *attr,
587 struct perf_event *group_leader)
589 struct perf_cgroup *cgrp;
590 struct cgroup_subsys_state *css;
591 struct fd f = fdget(fd);
599 css = css_from_dir(f.file->f_dentry, &perf_subsys);
605 cgrp = container_of(css, struct perf_cgroup, css);
608 /* must be done before we fput() the file */
609 if (!perf_tryget_cgroup(event)) {
616 * all events in a group must monitor
617 * the same cgroup because a task belongs
618 * to only one perf cgroup at a time
620 if (group_leader && group_leader->cgrp != cgrp) {
621 perf_detach_cgroup(event);
631 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
633 struct perf_cgroup_info *t;
634 t = per_cpu_ptr(event->cgrp->info, event->cpu);
635 event->shadow_ctx_time = now - t->timestamp;
639 perf_cgroup_defer_enabled(struct perf_event *event)
642 * when the current task's perf cgroup does not match
643 * the event's, we need to remember to call the
644 * perf_mark_enable() function the first time a task with
645 * a matching perf cgroup is scheduled in.
647 if (is_cgroup_event(event) && !perf_cgroup_match(event))
648 event->cgrp_defer_enabled = 1;
652 perf_cgroup_mark_enabled(struct perf_event *event,
653 struct perf_event_context *ctx)
655 struct perf_event *sub;
656 u64 tstamp = perf_event_time(event);
658 if (!event->cgrp_defer_enabled)
661 event->cgrp_defer_enabled = 0;
663 event->tstamp_enabled = tstamp - event->total_time_enabled;
664 list_for_each_entry(sub, &event->sibling_list, group_entry) {
665 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
666 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
667 sub->cgrp_defer_enabled = 0;
671 #else /* !CONFIG_CGROUP_PERF */
674 perf_cgroup_match(struct perf_event *event)
679 static inline void perf_detach_cgroup(struct perf_event *event)
682 static inline int is_cgroup_event(struct perf_event *event)
687 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
692 static inline void update_cgrp_time_from_event(struct perf_event *event)
696 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
700 static inline void perf_cgroup_sched_out(struct task_struct *task,
701 struct task_struct *next)
705 static inline void perf_cgroup_sched_in(struct task_struct *prev,
706 struct task_struct *task)
710 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
711 struct perf_event_attr *attr,
712 struct perf_event *group_leader)
718 perf_cgroup_set_timestamp(struct task_struct *task,
719 struct perf_event_context *ctx)
724 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
729 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
733 static inline u64 perf_cgroup_event_time(struct perf_event *event)
739 perf_cgroup_defer_enabled(struct perf_event *event)
744 perf_cgroup_mark_enabled(struct perf_event *event,
745 struct perf_event_context *ctx)
751 * set default to be dependent on timer tick just
754 #define PERF_CPU_HRTIMER (1000 / HZ)
756 * function must be called with interrupts disbled
758 static enum hrtimer_restart perf_cpu_hrtimer_handler(struct hrtimer *hr)
760 struct perf_cpu_context *cpuctx;
761 enum hrtimer_restart ret = HRTIMER_NORESTART;
764 WARN_ON(!irqs_disabled());
766 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
768 rotations = perf_rotate_context(cpuctx);
771 * arm timer if needed
774 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
775 ret = HRTIMER_RESTART;
781 /* CPU is going down */
782 void perf_cpu_hrtimer_cancel(int cpu)
784 struct perf_cpu_context *cpuctx;
788 if (WARN_ON(cpu != smp_processor_id()))
791 local_irq_save(flags);
795 list_for_each_entry_rcu(pmu, &pmus, entry) {
796 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
798 if (pmu->task_ctx_nr == perf_sw_context)
801 hrtimer_cancel(&cpuctx->hrtimer);
806 local_irq_restore(flags);
809 static void __perf_cpu_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
811 struct hrtimer *hr = &cpuctx->hrtimer;
812 struct pmu *pmu = cpuctx->ctx.pmu;
815 /* no multiplexing needed for SW PMU */
816 if (pmu->task_ctx_nr == perf_sw_context)
820 * check default is sane, if not set then force to
821 * default interval (1/tick)
823 timer = pmu->hrtimer_interval_ms;
825 timer = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
827 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
829 hrtimer_init(hr, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
830 hr->function = perf_cpu_hrtimer_handler;
833 static void perf_cpu_hrtimer_restart(struct perf_cpu_context *cpuctx)
835 struct hrtimer *hr = &cpuctx->hrtimer;
836 struct pmu *pmu = cpuctx->ctx.pmu;
839 if (pmu->task_ctx_nr == perf_sw_context)
842 if (hrtimer_active(hr))
845 if (!hrtimer_callback_running(hr))
846 __hrtimer_start_range_ns(hr, cpuctx->hrtimer_interval,
847 0, HRTIMER_MODE_REL_PINNED, 0);
850 void perf_pmu_disable(struct pmu *pmu)
852 int *count = this_cpu_ptr(pmu->pmu_disable_count);
854 pmu->pmu_disable(pmu);
857 void perf_pmu_enable(struct pmu *pmu)
859 int *count = this_cpu_ptr(pmu->pmu_disable_count);
861 pmu->pmu_enable(pmu);
864 static DEFINE_PER_CPU(struct list_head, rotation_list);
867 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
868 * because they're strictly cpu affine and rotate_start is called with IRQs
869 * disabled, while rotate_context is called from IRQ context.
871 static void perf_pmu_rotate_start(struct pmu *pmu)
873 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
874 struct list_head *head = &__get_cpu_var(rotation_list);
876 WARN_ON(!irqs_disabled());
878 if (list_empty(&cpuctx->rotation_list))
879 list_add(&cpuctx->rotation_list, head);
882 static void get_ctx(struct perf_event_context *ctx)
884 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
887 static void put_ctx(struct perf_event_context *ctx)
889 if (atomic_dec_and_test(&ctx->refcount)) {
891 put_ctx(ctx->parent_ctx);
893 put_task_struct(ctx->task);
894 kfree_rcu(ctx, rcu_head);
898 static void unclone_ctx(struct perf_event_context *ctx)
900 if (ctx->parent_ctx) {
901 put_ctx(ctx->parent_ctx);
902 ctx->parent_ctx = NULL;
907 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
910 * only top level events have the pid namespace they were created in
913 event = event->parent;
915 return task_tgid_nr_ns(p, event->ns);
918 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
921 * only top level events have the pid namespace they were created in
924 event = event->parent;
926 return task_pid_nr_ns(p, event->ns);
930 * If we inherit events we want to return the parent event id
933 static u64 primary_event_id(struct perf_event *event)
938 id = event->parent->id;
944 * Get the perf_event_context for a task and lock it.
945 * This has to cope with with the fact that until it is locked,
946 * the context could get moved to another task.
948 static struct perf_event_context *
949 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
951 struct perf_event_context *ctx;
955 * One of the few rules of preemptible RCU is that one cannot do
956 * rcu_read_unlock() while holding a scheduler (or nested) lock when
957 * part of the read side critical section was preemptible -- see
958 * rcu_read_unlock_special().
960 * Since ctx->lock nests under rq->lock we must ensure the entire read
961 * side critical section is non-preemptible.
965 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
968 * If this context is a clone of another, it might
969 * get swapped for another underneath us by
970 * perf_event_task_sched_out, though the
971 * rcu_read_lock() protects us from any context
972 * getting freed. Lock the context and check if it
973 * got swapped before we could get the lock, and retry
974 * if so. If we locked the right context, then it
975 * can't get swapped on us any more.
977 raw_spin_lock_irqsave(&ctx->lock, *flags);
978 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
979 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
985 if (!atomic_inc_not_zero(&ctx->refcount)) {
986 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
996 * Get the context for a task and increment its pin_count so it
997 * can't get swapped to another task. This also increments its
998 * reference count so that the context can't get freed.
1000 static struct perf_event_context *
1001 perf_pin_task_context(struct task_struct *task, int ctxn)
1003 struct perf_event_context *ctx;
1004 unsigned long flags;
1006 ctx = perf_lock_task_context(task, ctxn, &flags);
1009 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1014 static void perf_unpin_context(struct perf_event_context *ctx)
1016 unsigned long flags;
1018 raw_spin_lock_irqsave(&ctx->lock, flags);
1020 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1024 * Update the record of the current time in a context.
1026 static void update_context_time(struct perf_event_context *ctx)
1028 u64 now = perf_clock();
1030 ctx->time += now - ctx->timestamp;
1031 ctx->timestamp = now;
1034 static u64 perf_event_time(struct perf_event *event)
1036 struct perf_event_context *ctx = event->ctx;
1038 if (is_cgroup_event(event))
1039 return perf_cgroup_event_time(event);
1041 return ctx ? ctx->time : 0;
1045 * Update the total_time_enabled and total_time_running fields for a event.
1046 * The caller of this function needs to hold the ctx->lock.
1048 static void update_event_times(struct perf_event *event)
1050 struct perf_event_context *ctx = event->ctx;
1053 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1054 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1057 * in cgroup mode, time_enabled represents
1058 * the time the event was enabled AND active
1059 * tasks were in the monitored cgroup. This is
1060 * independent of the activity of the context as
1061 * there may be a mix of cgroup and non-cgroup events.
1063 * That is why we treat cgroup events differently
1066 if (is_cgroup_event(event))
1067 run_end = perf_cgroup_event_time(event);
1068 else if (ctx->is_active)
1069 run_end = ctx->time;
1071 run_end = event->tstamp_stopped;
1073 event->total_time_enabled = run_end - event->tstamp_enabled;
1075 if (event->state == PERF_EVENT_STATE_INACTIVE)
1076 run_end = event->tstamp_stopped;
1078 run_end = perf_event_time(event);
1080 event->total_time_running = run_end - event->tstamp_running;
1085 * Update total_time_enabled and total_time_running for all events in a group.
1087 static void update_group_times(struct perf_event *leader)
1089 struct perf_event *event;
1091 update_event_times(leader);
1092 list_for_each_entry(event, &leader->sibling_list, group_entry)
1093 update_event_times(event);
1096 static struct list_head *
1097 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1099 if (event->attr.pinned)
1100 return &ctx->pinned_groups;
1102 return &ctx->flexible_groups;
1106 * Add a event from the lists for its context.
1107 * Must be called with ctx->mutex and ctx->lock held.
1110 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1112 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1113 event->attach_state |= PERF_ATTACH_CONTEXT;
1116 * If we're a stand alone event or group leader, we go to the context
1117 * list, group events are kept attached to the group so that
1118 * perf_group_detach can, at all times, locate all siblings.
1120 if (event->group_leader == event) {
1121 struct list_head *list;
1123 if (is_software_event(event))
1124 event->group_flags |= PERF_GROUP_SOFTWARE;
1126 list = ctx_group_list(event, ctx);
1127 list_add_tail(&event->group_entry, list);
1130 if (is_cgroup_event(event))
1133 if (has_branch_stack(event))
1134 ctx->nr_branch_stack++;
1136 list_add_rcu(&event->event_entry, &ctx->event_list);
1137 if (!ctx->nr_events)
1138 perf_pmu_rotate_start(ctx->pmu);
1140 if (event->attr.inherit_stat)
1147 * Initialize event state based on the perf_event_attr::disabled.
1149 static inline void perf_event__state_init(struct perf_event *event)
1151 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1152 PERF_EVENT_STATE_INACTIVE;
1156 * Called at perf_event creation and when events are attached/detached from a
1159 static void perf_event__read_size(struct perf_event *event)
1161 int entry = sizeof(u64); /* value */
1165 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1166 size += sizeof(u64);
1168 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1169 size += sizeof(u64);
1171 if (event->attr.read_format & PERF_FORMAT_ID)
1172 entry += sizeof(u64);
1174 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1175 nr += event->group_leader->nr_siblings;
1176 size += sizeof(u64);
1180 event->read_size = size;
1183 static void perf_event__header_size(struct perf_event *event)
1185 struct perf_sample_data *data;
1186 u64 sample_type = event->attr.sample_type;
1189 perf_event__read_size(event);
1191 if (sample_type & PERF_SAMPLE_IP)
1192 size += sizeof(data->ip);
1194 if (sample_type & PERF_SAMPLE_ADDR)
1195 size += sizeof(data->addr);
1197 if (sample_type & PERF_SAMPLE_PERIOD)
1198 size += sizeof(data->period);
1200 if (sample_type & PERF_SAMPLE_WEIGHT)
1201 size += sizeof(data->weight);
1203 if (sample_type & PERF_SAMPLE_READ)
1204 size += event->read_size;
1206 if (sample_type & PERF_SAMPLE_DATA_SRC)
1207 size += sizeof(data->data_src.val);
1209 if (sample_type & PERF_SAMPLE_TRANSACTION)
1210 size += sizeof(data->txn);
1212 event->header_size = size;
1215 static void perf_event__id_header_size(struct perf_event *event)
1217 struct perf_sample_data *data;
1218 u64 sample_type = event->attr.sample_type;
1221 if (sample_type & PERF_SAMPLE_TID)
1222 size += sizeof(data->tid_entry);
1224 if (sample_type & PERF_SAMPLE_TIME)
1225 size += sizeof(data->time);
1227 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1228 size += sizeof(data->id);
1230 if (sample_type & PERF_SAMPLE_ID)
1231 size += sizeof(data->id);
1233 if (sample_type & PERF_SAMPLE_STREAM_ID)
1234 size += sizeof(data->stream_id);
1236 if (sample_type & PERF_SAMPLE_CPU)
1237 size += sizeof(data->cpu_entry);
1239 event->id_header_size = size;
1242 static void perf_group_attach(struct perf_event *event)
1244 struct perf_event *group_leader = event->group_leader, *pos;
1247 * We can have double attach due to group movement in perf_event_open.
1249 if (event->attach_state & PERF_ATTACH_GROUP)
1252 event->attach_state |= PERF_ATTACH_GROUP;
1254 if (group_leader == event)
1257 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1258 !is_software_event(event))
1259 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1261 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1262 group_leader->nr_siblings++;
1264 perf_event__header_size(group_leader);
1266 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1267 perf_event__header_size(pos);
1271 * Remove a event from the lists for its context.
1272 * Must be called with ctx->mutex and ctx->lock held.
1275 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1277 struct perf_cpu_context *cpuctx;
1279 * We can have double detach due to exit/hot-unplug + close.
1281 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1284 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1286 if (is_cgroup_event(event)) {
1288 cpuctx = __get_cpu_context(ctx);
1290 * if there are no more cgroup events
1291 * then cler cgrp to avoid stale pointer
1292 * in update_cgrp_time_from_cpuctx()
1294 if (!ctx->nr_cgroups)
1295 cpuctx->cgrp = NULL;
1298 if (has_branch_stack(event))
1299 ctx->nr_branch_stack--;
1302 if (event->attr.inherit_stat)
1305 list_del_rcu(&event->event_entry);
1307 if (event->group_leader == event)
1308 list_del_init(&event->group_entry);
1310 update_group_times(event);
1313 * If event was in error state, then keep it
1314 * that way, otherwise bogus counts will be
1315 * returned on read(). The only way to get out
1316 * of error state is by explicit re-enabling
1319 if (event->state > PERF_EVENT_STATE_OFF)
1320 event->state = PERF_EVENT_STATE_OFF;
1325 static void perf_group_detach(struct perf_event *event)
1327 struct perf_event *sibling, *tmp;
1328 struct list_head *list = NULL;
1331 * We can have double detach due to exit/hot-unplug + close.
1333 if (!(event->attach_state & PERF_ATTACH_GROUP))
1336 event->attach_state &= ~PERF_ATTACH_GROUP;
1339 * If this is a sibling, remove it from its group.
1341 if (event->group_leader != event) {
1342 list_del_init(&event->group_entry);
1343 event->group_leader->nr_siblings--;
1347 if (!list_empty(&event->group_entry))
1348 list = &event->group_entry;
1351 * If this was a group event with sibling events then
1352 * upgrade the siblings to singleton events by adding them
1353 * to whatever list we are on.
1355 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1357 list_move_tail(&sibling->group_entry, list);
1358 sibling->group_leader = sibling;
1360 /* Inherit group flags from the previous leader */
1361 sibling->group_flags = event->group_flags;
1365 perf_event__header_size(event->group_leader);
1367 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1368 perf_event__header_size(tmp);
1372 event_filter_match(struct perf_event *event)
1374 return (event->cpu == -1 || event->cpu == smp_processor_id())
1375 && perf_cgroup_match(event);
1379 event_sched_out(struct perf_event *event,
1380 struct perf_cpu_context *cpuctx,
1381 struct perf_event_context *ctx)
1383 u64 tstamp = perf_event_time(event);
1386 * An event which could not be activated because of
1387 * filter mismatch still needs to have its timings
1388 * maintained, otherwise bogus information is return
1389 * via read() for time_enabled, time_running:
1391 if (event->state == PERF_EVENT_STATE_INACTIVE
1392 && !event_filter_match(event)) {
1393 delta = tstamp - event->tstamp_stopped;
1394 event->tstamp_running += delta;
1395 event->tstamp_stopped = tstamp;
1398 if (event->state != PERF_EVENT_STATE_ACTIVE)
1401 perf_pmu_disable(event->pmu);
1403 event->state = PERF_EVENT_STATE_INACTIVE;
1404 if (event->pending_disable) {
1405 event->pending_disable = 0;
1406 event->state = PERF_EVENT_STATE_OFF;
1408 event->tstamp_stopped = tstamp;
1409 event->pmu->del(event, 0);
1412 if (!is_software_event(event))
1413 cpuctx->active_oncpu--;
1415 if (event->attr.freq && event->attr.sample_freq)
1417 if (event->attr.exclusive || !cpuctx->active_oncpu)
1418 cpuctx->exclusive = 0;
1420 perf_pmu_enable(event->pmu);
1424 group_sched_out(struct perf_event *group_event,
1425 struct perf_cpu_context *cpuctx,
1426 struct perf_event_context *ctx)
1428 struct perf_event *event;
1429 int state = group_event->state;
1431 event_sched_out(group_event, cpuctx, ctx);
1434 * Schedule out siblings (if any):
1436 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1437 event_sched_out(event, cpuctx, ctx);
1439 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1440 cpuctx->exclusive = 0;
1443 struct remove_event {
1444 struct perf_event *event;
1449 * Cross CPU call to remove a performance event
1451 * We disable the event on the hardware level first. After that we
1452 * remove it from the context list.
1454 static int __perf_remove_from_context(void *info)
1456 struct remove_event *re = info;
1457 struct perf_event *event = re->event;
1458 struct perf_event_context *ctx = event->ctx;
1459 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1461 raw_spin_lock(&ctx->lock);
1462 event_sched_out(event, cpuctx, ctx);
1463 if (re->detach_group)
1464 perf_group_detach(event);
1465 list_del_event(event, ctx);
1466 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1468 cpuctx->task_ctx = NULL;
1470 raw_spin_unlock(&ctx->lock);
1477 * Remove the event from a task's (or a CPU's) list of events.
1479 * CPU events are removed with a smp call. For task events we only
1480 * call when the task is on a CPU.
1482 * If event->ctx is a cloned context, callers must make sure that
1483 * every task struct that event->ctx->task could possibly point to
1484 * remains valid. This is OK when called from perf_release since
1485 * that only calls us on the top-level context, which can't be a clone.
1486 * When called from perf_event_exit_task, it's OK because the
1487 * context has been detached from its task.
1489 static void perf_remove_from_context(struct perf_event *event, bool detach_group)
1491 struct perf_event_context *ctx = event->ctx;
1492 struct task_struct *task = ctx->task;
1493 struct remove_event re = {
1495 .detach_group = detach_group,
1498 lockdep_assert_held(&ctx->mutex);
1502 * Per cpu events are removed via an smp call and
1503 * the removal is always successful.
1505 cpu_function_call(event->cpu, __perf_remove_from_context, &re);
1510 if (!task_function_call(task, __perf_remove_from_context, &re))
1513 raw_spin_lock_irq(&ctx->lock);
1515 * If we failed to find a running task, but find the context active now
1516 * that we've acquired the ctx->lock, retry.
1518 if (ctx->is_active) {
1519 raw_spin_unlock_irq(&ctx->lock);
1521 * Reload the task pointer, it might have been changed by
1522 * a concurrent perf_event_context_sched_out().
1529 * Since the task isn't running, its safe to remove the event, us
1530 * holding the ctx->lock ensures the task won't get scheduled in.
1533 perf_group_detach(event);
1534 list_del_event(event, ctx);
1535 raw_spin_unlock_irq(&ctx->lock);
1539 * Cross CPU call to disable a performance event
1541 int __perf_event_disable(void *info)
1543 struct perf_event *event = info;
1544 struct perf_event_context *ctx = event->ctx;
1545 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1548 * If this is a per-task event, need to check whether this
1549 * event's task is the current task on this cpu.
1551 * Can trigger due to concurrent perf_event_context_sched_out()
1552 * flipping contexts around.
1554 if (ctx->task && cpuctx->task_ctx != ctx)
1557 raw_spin_lock(&ctx->lock);
1560 * If the event is on, turn it off.
1561 * If it is in error state, leave it in error state.
1563 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1564 update_context_time(ctx);
1565 update_cgrp_time_from_event(event);
1566 update_group_times(event);
1567 if (event == event->group_leader)
1568 group_sched_out(event, cpuctx, ctx);
1570 event_sched_out(event, cpuctx, ctx);
1571 event->state = PERF_EVENT_STATE_OFF;
1574 raw_spin_unlock(&ctx->lock);
1582 * If event->ctx is a cloned context, callers must make sure that
1583 * every task struct that event->ctx->task could possibly point to
1584 * remains valid. This condition is satisifed when called through
1585 * perf_event_for_each_child or perf_event_for_each because they
1586 * hold the top-level event's child_mutex, so any descendant that
1587 * goes to exit will block in sync_child_event.
1588 * When called from perf_pending_event it's OK because event->ctx
1589 * is the current context on this CPU and preemption is disabled,
1590 * hence we can't get into perf_event_task_sched_out for this context.
1592 void perf_event_disable(struct perf_event *event)
1594 struct perf_event_context *ctx = event->ctx;
1595 struct task_struct *task = ctx->task;
1599 * Disable the event on the cpu that it's on
1601 cpu_function_call(event->cpu, __perf_event_disable, event);
1606 if (!task_function_call(task, __perf_event_disable, event))
1609 raw_spin_lock_irq(&ctx->lock);
1611 * If the event is still active, we need to retry the cross-call.
1613 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1614 raw_spin_unlock_irq(&ctx->lock);
1616 * Reload the task pointer, it might have been changed by
1617 * a concurrent perf_event_context_sched_out().
1624 * Since we have the lock this context can't be scheduled
1625 * in, so we can change the state safely.
1627 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1628 update_group_times(event);
1629 event->state = PERF_EVENT_STATE_OFF;
1631 raw_spin_unlock_irq(&ctx->lock);
1633 EXPORT_SYMBOL_GPL(perf_event_disable);
1635 static void perf_set_shadow_time(struct perf_event *event,
1636 struct perf_event_context *ctx,
1640 * use the correct time source for the time snapshot
1642 * We could get by without this by leveraging the
1643 * fact that to get to this function, the caller
1644 * has most likely already called update_context_time()
1645 * and update_cgrp_time_xx() and thus both timestamp
1646 * are identical (or very close). Given that tstamp is,
1647 * already adjusted for cgroup, we could say that:
1648 * tstamp - ctx->timestamp
1650 * tstamp - cgrp->timestamp.
1652 * Then, in perf_output_read(), the calculation would
1653 * work with no changes because:
1654 * - event is guaranteed scheduled in
1655 * - no scheduled out in between
1656 * - thus the timestamp would be the same
1658 * But this is a bit hairy.
1660 * So instead, we have an explicit cgroup call to remain
1661 * within the time time source all along. We believe it
1662 * is cleaner and simpler to understand.
1664 if (is_cgroup_event(event))
1665 perf_cgroup_set_shadow_time(event, tstamp);
1667 event->shadow_ctx_time = tstamp - ctx->timestamp;
1670 #define MAX_INTERRUPTS (~0ULL)
1672 static void perf_log_throttle(struct perf_event *event, int enable);
1675 event_sched_in(struct perf_event *event,
1676 struct perf_cpu_context *cpuctx,
1677 struct perf_event_context *ctx)
1679 u64 tstamp = perf_event_time(event);
1682 if (event->state <= PERF_EVENT_STATE_OFF)
1685 event->state = PERF_EVENT_STATE_ACTIVE;
1686 event->oncpu = smp_processor_id();
1689 * Unthrottle events, since we scheduled we might have missed several
1690 * ticks already, also for a heavily scheduling task there is little
1691 * guarantee it'll get a tick in a timely manner.
1693 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1694 perf_log_throttle(event, 1);
1695 event->hw.interrupts = 0;
1699 * The new state must be visible before we turn it on in the hardware:
1703 perf_pmu_disable(event->pmu);
1705 if (event->pmu->add(event, PERF_EF_START)) {
1706 event->state = PERF_EVENT_STATE_INACTIVE;
1712 event->tstamp_running += tstamp - event->tstamp_stopped;
1714 perf_set_shadow_time(event, ctx, tstamp);
1716 if (!is_software_event(event))
1717 cpuctx->active_oncpu++;
1719 if (event->attr.freq && event->attr.sample_freq)
1722 if (event->attr.exclusive)
1723 cpuctx->exclusive = 1;
1726 perf_pmu_enable(event->pmu);
1732 group_sched_in(struct perf_event *group_event,
1733 struct perf_cpu_context *cpuctx,
1734 struct perf_event_context *ctx)
1736 struct perf_event *event, *partial_group = NULL;
1737 struct pmu *pmu = group_event->pmu;
1738 u64 now = ctx->time;
1739 bool simulate = false;
1741 if (group_event->state == PERF_EVENT_STATE_OFF)
1744 pmu->start_txn(pmu);
1746 if (event_sched_in(group_event, cpuctx, ctx)) {
1747 pmu->cancel_txn(pmu);
1748 perf_cpu_hrtimer_restart(cpuctx);
1753 * Schedule in siblings as one group (if any):
1755 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1756 if (event_sched_in(event, cpuctx, ctx)) {
1757 partial_group = event;
1762 if (!pmu->commit_txn(pmu))
1767 * Groups can be scheduled in as one unit only, so undo any
1768 * partial group before returning:
1769 * The events up to the failed event are scheduled out normally,
1770 * tstamp_stopped will be updated.
1772 * The failed events and the remaining siblings need to have
1773 * their timings updated as if they had gone thru event_sched_in()
1774 * and event_sched_out(). This is required to get consistent timings
1775 * across the group. This also takes care of the case where the group
1776 * could never be scheduled by ensuring tstamp_stopped is set to mark
1777 * the time the event was actually stopped, such that time delta
1778 * calculation in update_event_times() is correct.
1780 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1781 if (event == partial_group)
1785 event->tstamp_running += now - event->tstamp_stopped;
1786 event->tstamp_stopped = now;
1788 event_sched_out(event, cpuctx, ctx);
1791 event_sched_out(group_event, cpuctx, ctx);
1793 pmu->cancel_txn(pmu);
1795 perf_cpu_hrtimer_restart(cpuctx);
1801 * Work out whether we can put this event group on the CPU now.
1803 static int group_can_go_on(struct perf_event *event,
1804 struct perf_cpu_context *cpuctx,
1808 * Groups consisting entirely of software events can always go on.
1810 if (event->group_flags & PERF_GROUP_SOFTWARE)
1813 * If an exclusive group is already on, no other hardware
1816 if (cpuctx->exclusive)
1819 * If this group is exclusive and there are already
1820 * events on the CPU, it can't go on.
1822 if (event->attr.exclusive && cpuctx->active_oncpu)
1825 * Otherwise, try to add it if all previous groups were able
1831 static void add_event_to_ctx(struct perf_event *event,
1832 struct perf_event_context *ctx)
1834 u64 tstamp = perf_event_time(event);
1836 list_add_event(event, ctx);
1837 perf_group_attach(event);
1838 event->tstamp_enabled = tstamp;
1839 event->tstamp_running = tstamp;
1840 event->tstamp_stopped = tstamp;
1843 static void task_ctx_sched_out(struct perf_event_context *ctx);
1845 ctx_sched_in(struct perf_event_context *ctx,
1846 struct perf_cpu_context *cpuctx,
1847 enum event_type_t event_type,
1848 struct task_struct *task);
1850 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
1851 struct perf_event_context *ctx,
1852 struct task_struct *task)
1854 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
1856 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
1857 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
1859 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
1863 * Cross CPU call to install and enable a performance event
1865 * Must be called with ctx->mutex held
1867 static int __perf_install_in_context(void *info)
1869 struct perf_event *event = info;
1870 struct perf_event_context *ctx = event->ctx;
1871 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1872 struct perf_event_context *task_ctx = cpuctx->task_ctx;
1873 struct task_struct *task = current;
1875 perf_ctx_lock(cpuctx, task_ctx);
1876 perf_pmu_disable(cpuctx->ctx.pmu);
1879 * If there was an active task_ctx schedule it out.
1882 task_ctx_sched_out(task_ctx);
1885 * If the context we're installing events in is not the
1886 * active task_ctx, flip them.
1888 if (ctx->task && task_ctx != ctx) {
1890 raw_spin_unlock(&task_ctx->lock);
1891 raw_spin_lock(&ctx->lock);
1896 cpuctx->task_ctx = task_ctx;
1897 task = task_ctx->task;
1900 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
1902 update_context_time(ctx);
1904 * update cgrp time only if current cgrp
1905 * matches event->cgrp. Must be done before
1906 * calling add_event_to_ctx()
1908 update_cgrp_time_from_event(event);
1910 add_event_to_ctx(event, ctx);
1913 * Schedule everything back in
1915 perf_event_sched_in(cpuctx, task_ctx, task);
1917 perf_pmu_enable(cpuctx->ctx.pmu);
1918 perf_ctx_unlock(cpuctx, task_ctx);
1924 * Attach a performance event to a context
1926 * First we add the event to the list with the hardware enable bit
1927 * in event->hw_config cleared.
1929 * If the event is attached to a task which is on a CPU we use a smp
1930 * call to enable it in the task context. The task might have been
1931 * scheduled away, but we check this in the smp call again.
1934 perf_install_in_context(struct perf_event_context *ctx,
1935 struct perf_event *event,
1938 struct task_struct *task = ctx->task;
1940 lockdep_assert_held(&ctx->mutex);
1943 if (event->cpu != -1)
1948 * Per cpu events are installed via an smp call and
1949 * the install is always successful.
1951 cpu_function_call(cpu, __perf_install_in_context, event);
1956 if (!task_function_call(task, __perf_install_in_context, event))
1959 raw_spin_lock_irq(&ctx->lock);
1961 * If we failed to find a running task, but find the context active now
1962 * that we've acquired the ctx->lock, retry.
1964 if (ctx->is_active) {
1965 raw_spin_unlock_irq(&ctx->lock);
1967 * Reload the task pointer, it might have been changed by
1968 * a concurrent perf_event_context_sched_out().
1975 * Since the task isn't running, its safe to add the event, us holding
1976 * the ctx->lock ensures the task won't get scheduled in.
1978 add_event_to_ctx(event, ctx);
1979 raw_spin_unlock_irq(&ctx->lock);
1983 * Put a event into inactive state and update time fields.
1984 * Enabling the leader of a group effectively enables all
1985 * the group members that aren't explicitly disabled, so we
1986 * have to update their ->tstamp_enabled also.
1987 * Note: this works for group members as well as group leaders
1988 * since the non-leader members' sibling_lists will be empty.
1990 static void __perf_event_mark_enabled(struct perf_event *event)
1992 struct perf_event *sub;
1993 u64 tstamp = perf_event_time(event);
1995 event->state = PERF_EVENT_STATE_INACTIVE;
1996 event->tstamp_enabled = tstamp - event->total_time_enabled;
1997 list_for_each_entry(sub, &event->sibling_list, group_entry) {
1998 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
1999 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2004 * Cross CPU call to enable a performance event
2006 static int __perf_event_enable(void *info)
2008 struct perf_event *event = info;
2009 struct perf_event_context *ctx = event->ctx;
2010 struct perf_event *leader = event->group_leader;
2011 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2015 * There's a time window between 'ctx->is_active' check
2016 * in perf_event_enable function and this place having:
2018 * - ctx->lock unlocked
2020 * where the task could be killed and 'ctx' deactivated
2021 * by perf_event_exit_task.
2023 if (!ctx->is_active)
2026 raw_spin_lock(&ctx->lock);
2027 update_context_time(ctx);
2029 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2033 * set current task's cgroup time reference point
2035 perf_cgroup_set_timestamp(current, ctx);
2037 __perf_event_mark_enabled(event);
2039 if (!event_filter_match(event)) {
2040 if (is_cgroup_event(event))
2041 perf_cgroup_defer_enabled(event);
2046 * If the event is in a group and isn't the group leader,
2047 * then don't put it on unless the group is on.
2049 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
2052 if (!group_can_go_on(event, cpuctx, 1)) {
2055 if (event == leader)
2056 err = group_sched_in(event, cpuctx, ctx);
2058 err = event_sched_in(event, cpuctx, ctx);
2063 * If this event can't go on and it's part of a
2064 * group, then the whole group has to come off.
2066 if (leader != event) {
2067 group_sched_out(leader, cpuctx, ctx);
2068 perf_cpu_hrtimer_restart(cpuctx);
2070 if (leader->attr.pinned) {
2071 update_group_times(leader);
2072 leader->state = PERF_EVENT_STATE_ERROR;
2077 raw_spin_unlock(&ctx->lock);
2085 * If event->ctx is a cloned context, callers must make sure that
2086 * every task struct that event->ctx->task could possibly point to
2087 * remains valid. This condition is satisfied when called through
2088 * perf_event_for_each_child or perf_event_for_each as described
2089 * for perf_event_disable.
2091 void perf_event_enable(struct perf_event *event)
2093 struct perf_event_context *ctx = event->ctx;
2094 struct task_struct *task = ctx->task;
2098 * Enable the event on the cpu that it's on
2100 cpu_function_call(event->cpu, __perf_event_enable, event);
2104 raw_spin_lock_irq(&ctx->lock);
2105 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2109 * If the event is in error state, clear that first.
2110 * That way, if we see the event in error state below, we
2111 * know that it has gone back into error state, as distinct
2112 * from the task having been scheduled away before the
2113 * cross-call arrived.
2115 if (event->state == PERF_EVENT_STATE_ERROR)
2116 event->state = PERF_EVENT_STATE_OFF;
2119 if (!ctx->is_active) {
2120 __perf_event_mark_enabled(event);
2124 raw_spin_unlock_irq(&ctx->lock);
2126 if (!task_function_call(task, __perf_event_enable, event))
2129 raw_spin_lock_irq(&ctx->lock);
2132 * If the context is active and the event is still off,
2133 * we need to retry the cross-call.
2135 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
2137 * task could have been flipped by a concurrent
2138 * perf_event_context_sched_out()
2145 raw_spin_unlock_irq(&ctx->lock);
2147 EXPORT_SYMBOL_GPL(perf_event_enable);
2149 int perf_event_refresh(struct perf_event *event, int refresh)
2152 * not supported on inherited events
2154 if (event->attr.inherit || !is_sampling_event(event))
2157 atomic_add(refresh, &event->event_limit);
2158 perf_event_enable(event);
2162 EXPORT_SYMBOL_GPL(perf_event_refresh);
2164 static void ctx_sched_out(struct perf_event_context *ctx,
2165 struct perf_cpu_context *cpuctx,
2166 enum event_type_t event_type)
2168 struct perf_event *event;
2169 int is_active = ctx->is_active;
2171 ctx->is_active &= ~event_type;
2172 if (likely(!ctx->nr_events))
2175 update_context_time(ctx);
2176 update_cgrp_time_from_cpuctx(cpuctx);
2177 if (!ctx->nr_active)
2180 perf_pmu_disable(ctx->pmu);
2181 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2182 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2183 group_sched_out(event, cpuctx, ctx);
2186 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2187 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2188 group_sched_out(event, cpuctx, ctx);
2190 perf_pmu_enable(ctx->pmu);
2194 * Test whether two contexts are equivalent, i.e. whether they have both been
2195 * cloned from the same version of the same context.
2197 * Equivalence is measured using a generation number in the context that is
2198 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2199 * and list_del_event().
2201 static int context_equiv(struct perf_event_context *ctx1,
2202 struct perf_event_context *ctx2)
2204 /* Pinning disables the swap optimization */
2205 if (ctx1->pin_count || ctx2->pin_count)
2208 /* If ctx1 is the parent of ctx2 */
2209 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2212 /* If ctx2 is the parent of ctx1 */
2213 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2217 * If ctx1 and ctx2 have the same parent; we flatten the parent
2218 * hierarchy, see perf_event_init_context().
2220 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2221 ctx1->parent_gen == ctx2->parent_gen)
2228 static void __perf_event_sync_stat(struct perf_event *event,
2229 struct perf_event *next_event)
2233 if (!event->attr.inherit_stat)
2237 * Update the event value, we cannot use perf_event_read()
2238 * because we're in the middle of a context switch and have IRQs
2239 * disabled, which upsets smp_call_function_single(), however
2240 * we know the event must be on the current CPU, therefore we
2241 * don't need to use it.
2243 switch (event->state) {
2244 case PERF_EVENT_STATE_ACTIVE:
2245 event->pmu->read(event);
2248 case PERF_EVENT_STATE_INACTIVE:
2249 update_event_times(event);
2257 * In order to keep per-task stats reliable we need to flip the event
2258 * values when we flip the contexts.
2260 value = local64_read(&next_event->count);
2261 value = local64_xchg(&event->count, value);
2262 local64_set(&next_event->count, value);
2264 swap(event->total_time_enabled, next_event->total_time_enabled);
2265 swap(event->total_time_running, next_event->total_time_running);
2268 * Since we swizzled the values, update the user visible data too.
2270 perf_event_update_userpage(event);
2271 perf_event_update_userpage(next_event);
2274 static void perf_event_sync_stat(struct perf_event_context *ctx,
2275 struct perf_event_context *next_ctx)
2277 struct perf_event *event, *next_event;
2282 update_context_time(ctx);
2284 event = list_first_entry(&ctx->event_list,
2285 struct perf_event, event_entry);
2287 next_event = list_first_entry(&next_ctx->event_list,
2288 struct perf_event, event_entry);
2290 while (&event->event_entry != &ctx->event_list &&
2291 &next_event->event_entry != &next_ctx->event_list) {
2293 __perf_event_sync_stat(event, next_event);
2295 event = list_next_entry(event, event_entry);
2296 next_event = list_next_entry(next_event, event_entry);
2300 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2301 struct task_struct *next)
2303 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2304 struct perf_event_context *next_ctx;
2305 struct perf_event_context *parent, *next_parent;
2306 struct perf_cpu_context *cpuctx;
2312 cpuctx = __get_cpu_context(ctx);
2313 if (!cpuctx->task_ctx)
2317 next_ctx = next->perf_event_ctxp[ctxn];
2321 parent = rcu_dereference(ctx->parent_ctx);
2322 next_parent = rcu_dereference(next_ctx->parent_ctx);
2324 /* If neither context have a parent context; they cannot be clones. */
2325 if (!parent || !next_parent)
2328 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2330 * Looks like the two contexts are clones, so we might be
2331 * able to optimize the context switch. We lock both
2332 * contexts and check that they are clones under the
2333 * lock (including re-checking that neither has been
2334 * uncloned in the meantime). It doesn't matter which
2335 * order we take the locks because no other cpu could
2336 * be trying to lock both of these tasks.
2338 raw_spin_lock(&ctx->lock);
2339 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2340 if (context_equiv(ctx, next_ctx)) {
2342 * XXX do we need a memory barrier of sorts
2343 * wrt to rcu_dereference() of perf_event_ctxp
2345 task->perf_event_ctxp[ctxn] = next_ctx;
2346 next->perf_event_ctxp[ctxn] = ctx;
2348 next_ctx->task = task;
2351 perf_event_sync_stat(ctx, next_ctx);
2353 raw_spin_unlock(&next_ctx->lock);
2354 raw_spin_unlock(&ctx->lock);
2360 raw_spin_lock(&ctx->lock);
2361 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2362 cpuctx->task_ctx = NULL;
2363 raw_spin_unlock(&ctx->lock);
2367 #define for_each_task_context_nr(ctxn) \
2368 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2371 * Called from scheduler to remove the events of the current task,
2372 * with interrupts disabled.
2374 * We stop each event and update the event value in event->count.
2376 * This does not protect us against NMI, but disable()
2377 * sets the disabled bit in the control field of event _before_
2378 * accessing the event control register. If a NMI hits, then it will
2379 * not restart the event.
2381 void __perf_event_task_sched_out(struct task_struct *task,
2382 struct task_struct *next)
2386 for_each_task_context_nr(ctxn)
2387 perf_event_context_sched_out(task, ctxn, next);
2390 * if cgroup events exist on this CPU, then we need
2391 * to check if we have to switch out PMU state.
2392 * cgroup event are system-wide mode only
2394 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2395 perf_cgroup_sched_out(task, next);
2398 static void task_ctx_sched_out(struct perf_event_context *ctx)
2400 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2402 if (!cpuctx->task_ctx)
2405 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2408 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2409 cpuctx->task_ctx = NULL;
2413 * Called with IRQs disabled
2415 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2416 enum event_type_t event_type)
2418 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2422 ctx_pinned_sched_in(struct perf_event_context *ctx,
2423 struct perf_cpu_context *cpuctx)
2425 struct perf_event *event;
2427 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2428 if (event->state <= PERF_EVENT_STATE_OFF)
2430 if (!event_filter_match(event))
2433 /* may need to reset tstamp_enabled */
2434 if (is_cgroup_event(event))
2435 perf_cgroup_mark_enabled(event, ctx);
2437 if (group_can_go_on(event, cpuctx, 1))
2438 group_sched_in(event, cpuctx, ctx);
2441 * If this pinned group hasn't been scheduled,
2442 * put it in error state.
2444 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2445 update_group_times(event);
2446 event->state = PERF_EVENT_STATE_ERROR;
2452 ctx_flexible_sched_in(struct perf_event_context *ctx,
2453 struct perf_cpu_context *cpuctx)
2455 struct perf_event *event;
2458 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2459 /* Ignore events in OFF or ERROR state */
2460 if (event->state <= PERF_EVENT_STATE_OFF)
2463 * Listen to the 'cpu' scheduling filter constraint
2466 if (!event_filter_match(event))
2469 /* may need to reset tstamp_enabled */
2470 if (is_cgroup_event(event))
2471 perf_cgroup_mark_enabled(event, ctx);
2473 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2474 if (group_sched_in(event, cpuctx, ctx))
2481 ctx_sched_in(struct perf_event_context *ctx,
2482 struct perf_cpu_context *cpuctx,
2483 enum event_type_t event_type,
2484 struct task_struct *task)
2487 int is_active = ctx->is_active;
2489 ctx->is_active |= event_type;
2490 if (likely(!ctx->nr_events))
2494 ctx->timestamp = now;
2495 perf_cgroup_set_timestamp(task, ctx);
2497 * First go through the list and put on any pinned groups
2498 * in order to give them the best chance of going on.
2500 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2501 ctx_pinned_sched_in(ctx, cpuctx);
2503 /* Then walk through the lower prio flexible groups */
2504 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2505 ctx_flexible_sched_in(ctx, cpuctx);
2508 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2509 enum event_type_t event_type,
2510 struct task_struct *task)
2512 struct perf_event_context *ctx = &cpuctx->ctx;
2514 ctx_sched_in(ctx, cpuctx, event_type, task);
2517 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2518 struct task_struct *task)
2520 struct perf_cpu_context *cpuctx;
2522 cpuctx = __get_cpu_context(ctx);
2523 if (cpuctx->task_ctx == ctx)
2526 perf_ctx_lock(cpuctx, ctx);
2527 perf_pmu_disable(ctx->pmu);
2529 * We want to keep the following priority order:
2530 * cpu pinned (that don't need to move), task pinned,
2531 * cpu flexible, task flexible.
2533 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2536 cpuctx->task_ctx = ctx;
2538 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2540 perf_pmu_enable(ctx->pmu);
2541 perf_ctx_unlock(cpuctx, ctx);
2544 * Since these rotations are per-cpu, we need to ensure the
2545 * cpu-context we got scheduled on is actually rotating.
2547 perf_pmu_rotate_start(ctx->pmu);
2551 * When sampling the branck stack in system-wide, it may be necessary
2552 * to flush the stack on context switch. This happens when the branch
2553 * stack does not tag its entries with the pid of the current task.
2554 * Otherwise it becomes impossible to associate a branch entry with a
2555 * task. This ambiguity is more likely to appear when the branch stack
2556 * supports priv level filtering and the user sets it to monitor only
2557 * at the user level (which could be a useful measurement in system-wide
2558 * mode). In that case, the risk is high of having a branch stack with
2559 * branch from multiple tasks. Flushing may mean dropping the existing
2560 * entries or stashing them somewhere in the PMU specific code layer.
2562 * This function provides the context switch callback to the lower code
2563 * layer. It is invoked ONLY when there is at least one system-wide context
2564 * with at least one active event using taken branch sampling.
2566 static void perf_branch_stack_sched_in(struct task_struct *prev,
2567 struct task_struct *task)
2569 struct perf_cpu_context *cpuctx;
2571 unsigned long flags;
2573 /* no need to flush branch stack if not changing task */
2577 local_irq_save(flags);
2581 list_for_each_entry_rcu(pmu, &pmus, entry) {
2582 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2585 * check if the context has at least one
2586 * event using PERF_SAMPLE_BRANCH_STACK
2588 if (cpuctx->ctx.nr_branch_stack > 0
2589 && pmu->flush_branch_stack) {
2591 pmu = cpuctx->ctx.pmu;
2593 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2595 perf_pmu_disable(pmu);
2597 pmu->flush_branch_stack();
2599 perf_pmu_enable(pmu);
2601 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2607 local_irq_restore(flags);
2611 * Called from scheduler to add the events of the current task
2612 * with interrupts disabled.
2614 * We restore the event value and then enable it.
2616 * This does not protect us against NMI, but enable()
2617 * sets the enabled bit in the control field of event _before_
2618 * accessing the event control register. If a NMI hits, then it will
2619 * keep the event running.
2621 void __perf_event_task_sched_in(struct task_struct *prev,
2622 struct task_struct *task)
2624 struct perf_event_context *ctx;
2627 for_each_task_context_nr(ctxn) {
2628 ctx = task->perf_event_ctxp[ctxn];
2632 perf_event_context_sched_in(ctx, task);
2635 * if cgroup events exist on this CPU, then we need
2636 * to check if we have to switch in PMU state.
2637 * cgroup event are system-wide mode only
2639 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2640 perf_cgroup_sched_in(prev, task);
2642 /* check for system-wide branch_stack events */
2643 if (atomic_read(&__get_cpu_var(perf_branch_stack_events)))
2644 perf_branch_stack_sched_in(prev, task);
2647 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2649 u64 frequency = event->attr.sample_freq;
2650 u64 sec = NSEC_PER_SEC;
2651 u64 divisor, dividend;
2653 int count_fls, nsec_fls, frequency_fls, sec_fls;
2655 count_fls = fls64(count);
2656 nsec_fls = fls64(nsec);
2657 frequency_fls = fls64(frequency);
2661 * We got @count in @nsec, with a target of sample_freq HZ
2662 * the target period becomes:
2665 * period = -------------------
2666 * @nsec * sample_freq
2671 * Reduce accuracy by one bit such that @a and @b converge
2672 * to a similar magnitude.
2674 #define REDUCE_FLS(a, b) \
2676 if (a##_fls > b##_fls) { \
2686 * Reduce accuracy until either term fits in a u64, then proceed with
2687 * the other, so that finally we can do a u64/u64 division.
2689 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2690 REDUCE_FLS(nsec, frequency);
2691 REDUCE_FLS(sec, count);
2694 if (count_fls + sec_fls > 64) {
2695 divisor = nsec * frequency;
2697 while (count_fls + sec_fls > 64) {
2698 REDUCE_FLS(count, sec);
2702 dividend = count * sec;
2704 dividend = count * sec;
2706 while (nsec_fls + frequency_fls > 64) {
2707 REDUCE_FLS(nsec, frequency);
2711 divisor = nsec * frequency;
2717 return div64_u64(dividend, divisor);
2720 static DEFINE_PER_CPU(int, perf_throttled_count);
2721 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2723 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2725 struct hw_perf_event *hwc = &event->hw;
2726 s64 period, sample_period;
2729 period = perf_calculate_period(event, nsec, count);
2731 delta = (s64)(period - hwc->sample_period);
2732 delta = (delta + 7) / 8; /* low pass filter */
2734 sample_period = hwc->sample_period + delta;
2739 hwc->sample_period = sample_period;
2741 if (local64_read(&hwc->period_left) > 8*sample_period) {
2743 event->pmu->stop(event, PERF_EF_UPDATE);
2745 local64_set(&hwc->period_left, 0);
2748 event->pmu->start(event, PERF_EF_RELOAD);
2753 * combine freq adjustment with unthrottling to avoid two passes over the
2754 * events. At the same time, make sure, having freq events does not change
2755 * the rate of unthrottling as that would introduce bias.
2757 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
2760 struct perf_event *event;
2761 struct hw_perf_event *hwc;
2762 u64 now, period = TICK_NSEC;
2766 * only need to iterate over all events iff:
2767 * - context have events in frequency mode (needs freq adjust)
2768 * - there are events to unthrottle on this cpu
2770 if (!(ctx->nr_freq || needs_unthr))
2773 raw_spin_lock(&ctx->lock);
2774 perf_pmu_disable(ctx->pmu);
2776 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
2777 if (event->state != PERF_EVENT_STATE_ACTIVE)
2780 if (!event_filter_match(event))
2783 perf_pmu_disable(event->pmu);
2787 if (hwc->interrupts == MAX_INTERRUPTS) {
2788 hwc->interrupts = 0;
2789 perf_log_throttle(event, 1);
2790 event->pmu->start(event, 0);
2793 if (!event->attr.freq || !event->attr.sample_freq)
2797 * stop the event and update event->count
2799 event->pmu->stop(event, PERF_EF_UPDATE);
2801 now = local64_read(&event->count);
2802 delta = now - hwc->freq_count_stamp;
2803 hwc->freq_count_stamp = now;
2807 * reload only if value has changed
2808 * we have stopped the event so tell that
2809 * to perf_adjust_period() to avoid stopping it
2813 perf_adjust_period(event, period, delta, false);
2815 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
2817 perf_pmu_enable(event->pmu);
2820 perf_pmu_enable(ctx->pmu);
2821 raw_spin_unlock(&ctx->lock);
2825 * Round-robin a context's events:
2827 static void rotate_ctx(struct perf_event_context *ctx)
2830 * Rotate the first entry last of non-pinned groups. Rotation might be
2831 * disabled by the inheritance code.
2833 if (!ctx->rotate_disable)
2834 list_rotate_left(&ctx->flexible_groups);
2838 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
2839 * because they're strictly cpu affine and rotate_start is called with IRQs
2840 * disabled, while rotate_context is called from IRQ context.
2842 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
2844 struct perf_event_context *ctx = NULL;
2845 int rotate = 0, remove = 1;
2847 if (cpuctx->ctx.nr_events) {
2849 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
2853 ctx = cpuctx->task_ctx;
2854 if (ctx && ctx->nr_events) {
2856 if (ctx->nr_events != ctx->nr_active)
2863 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2864 perf_pmu_disable(cpuctx->ctx.pmu);
2866 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2868 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
2870 rotate_ctx(&cpuctx->ctx);
2874 perf_event_sched_in(cpuctx, ctx, current);
2876 perf_pmu_enable(cpuctx->ctx.pmu);
2877 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2880 list_del_init(&cpuctx->rotation_list);
2885 #ifdef CONFIG_NO_HZ_FULL
2886 bool perf_event_can_stop_tick(void)
2888 if (atomic_read(&nr_freq_events) ||
2889 __this_cpu_read(perf_throttled_count))
2896 void perf_event_task_tick(void)
2898 struct list_head *head = &__get_cpu_var(rotation_list);
2899 struct perf_cpu_context *cpuctx, *tmp;
2900 struct perf_event_context *ctx;
2903 WARN_ON(!irqs_disabled());
2905 __this_cpu_inc(perf_throttled_seq);
2906 throttled = __this_cpu_xchg(perf_throttled_count, 0);
2908 list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) {
2910 perf_adjust_freq_unthr_context(ctx, throttled);
2912 ctx = cpuctx->task_ctx;
2914 perf_adjust_freq_unthr_context(ctx, throttled);
2918 static int event_enable_on_exec(struct perf_event *event,
2919 struct perf_event_context *ctx)
2921 if (!event->attr.enable_on_exec)
2924 event->attr.enable_on_exec = 0;
2925 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2928 __perf_event_mark_enabled(event);
2934 * Enable all of a task's events that have been marked enable-on-exec.
2935 * This expects task == current.
2937 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
2939 struct perf_event *event;
2940 unsigned long flags;
2944 local_irq_save(flags);
2945 if (!ctx || !ctx->nr_events)
2949 * We must ctxsw out cgroup events to avoid conflict
2950 * when invoking perf_task_event_sched_in() later on
2951 * in this function. Otherwise we end up trying to
2952 * ctxswin cgroup events which are already scheduled
2955 perf_cgroup_sched_out(current, NULL);
2957 raw_spin_lock(&ctx->lock);
2958 task_ctx_sched_out(ctx);
2960 list_for_each_entry(event, &ctx->event_list, event_entry) {
2961 ret = event_enable_on_exec(event, ctx);
2967 * Unclone this context if we enabled any event.
2972 raw_spin_unlock(&ctx->lock);
2975 * Also calls ctxswin for cgroup events, if any:
2977 perf_event_context_sched_in(ctx, ctx->task);
2979 local_irq_restore(flags);
2983 * Cross CPU call to read the hardware event
2985 static void __perf_event_read(void *info)
2987 struct perf_event *event = info;
2988 struct perf_event_context *ctx = event->ctx;
2989 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2992 * If this is a task context, we need to check whether it is
2993 * the current task context of this cpu. If not it has been
2994 * scheduled out before the smp call arrived. In that case
2995 * event->count would have been updated to a recent sample
2996 * when the event was scheduled out.
2998 if (ctx->task && cpuctx->task_ctx != ctx)
3001 raw_spin_lock(&ctx->lock);
3002 if (ctx->is_active) {
3003 update_context_time(ctx);
3004 update_cgrp_time_from_event(event);
3006 update_event_times(event);
3007 if (event->state == PERF_EVENT_STATE_ACTIVE)
3008 event->pmu->read(event);
3009 raw_spin_unlock(&ctx->lock);
3012 static inline u64 perf_event_count(struct perf_event *event)
3014 return local64_read(&event->count) + atomic64_read(&event->child_count);
3017 static u64 perf_event_read(struct perf_event *event)
3020 * If event is enabled and currently active on a CPU, update the
3021 * value in the event structure:
3023 if (event->state == PERF_EVENT_STATE_ACTIVE) {
3024 smp_call_function_single(event->oncpu,
3025 __perf_event_read, event, 1);
3026 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3027 struct perf_event_context *ctx = event->ctx;
3028 unsigned long flags;
3030 raw_spin_lock_irqsave(&ctx->lock, flags);
3032 * may read while context is not active
3033 * (e.g., thread is blocked), in that case
3034 * we cannot update context time
3036 if (ctx->is_active) {
3037 update_context_time(ctx);
3038 update_cgrp_time_from_event(event);
3040 update_event_times(event);
3041 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3044 return perf_event_count(event);
3048 * Initialize the perf_event context in a task_struct:
3050 static void __perf_event_init_context(struct perf_event_context *ctx)
3052 raw_spin_lock_init(&ctx->lock);
3053 mutex_init(&ctx->mutex);
3054 INIT_LIST_HEAD(&ctx->pinned_groups);
3055 INIT_LIST_HEAD(&ctx->flexible_groups);
3056 INIT_LIST_HEAD(&ctx->event_list);
3057 atomic_set(&ctx->refcount, 1);
3060 static struct perf_event_context *
3061 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3063 struct perf_event_context *ctx;
3065 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3069 __perf_event_init_context(ctx);
3072 get_task_struct(task);
3079 static struct task_struct *
3080 find_lively_task_by_vpid(pid_t vpid)
3082 struct task_struct *task;
3089 task = find_task_by_vpid(vpid);
3091 get_task_struct(task);
3095 return ERR_PTR(-ESRCH);
3097 /* Reuse ptrace permission checks for now. */
3099 if (!ptrace_may_access(task, PTRACE_MODE_READ))
3104 put_task_struct(task);
3105 return ERR_PTR(err);
3110 * Returns a matching context with refcount and pincount.
3112 static struct perf_event_context *
3113 find_get_context(struct pmu *pmu, struct task_struct *task, int cpu)
3115 struct perf_event_context *ctx;
3116 struct perf_cpu_context *cpuctx;
3117 unsigned long flags;
3121 /* Must be root to operate on a CPU event: */
3122 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3123 return ERR_PTR(-EACCES);
3126 * We could be clever and allow to attach a event to an
3127 * offline CPU and activate it when the CPU comes up, but
3130 if (!cpu_online(cpu))
3131 return ERR_PTR(-ENODEV);
3133 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3142 ctxn = pmu->task_ctx_nr;
3147 ctx = perf_lock_task_context(task, ctxn, &flags);
3151 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3153 ctx = alloc_perf_context(pmu, task);
3159 mutex_lock(&task->perf_event_mutex);
3161 * If it has already passed perf_event_exit_task().
3162 * we must see PF_EXITING, it takes this mutex too.
3164 if (task->flags & PF_EXITING)
3166 else if (task->perf_event_ctxp[ctxn])
3171 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3173 mutex_unlock(&task->perf_event_mutex);
3175 if (unlikely(err)) {
3187 return ERR_PTR(err);
3190 static void perf_event_free_filter(struct perf_event *event);
3192 static void free_event_rcu(struct rcu_head *head)
3194 struct perf_event *event;
3196 event = container_of(head, struct perf_event, rcu_head);
3198 put_pid_ns(event->ns);
3199 perf_event_free_filter(event);
3203 static void ring_buffer_put(struct ring_buffer *rb);
3204 static void ring_buffer_detach(struct perf_event *event, struct ring_buffer *rb);
3206 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3211 if (has_branch_stack(event)) {
3212 if (!(event->attach_state & PERF_ATTACH_TASK))
3213 atomic_dec(&per_cpu(perf_branch_stack_events, cpu));
3215 if (is_cgroup_event(event))
3216 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3219 static void unaccount_event(struct perf_event *event)
3224 if (event->attach_state & PERF_ATTACH_TASK)
3225 static_key_slow_dec_deferred(&perf_sched_events);
3226 if (event->attr.mmap || event->attr.mmap_data)
3227 atomic_dec(&nr_mmap_events);
3228 if (event->attr.comm)
3229 atomic_dec(&nr_comm_events);
3230 if (event->attr.task)
3231 atomic_dec(&nr_task_events);
3232 if (event->attr.freq)
3233 atomic_dec(&nr_freq_events);
3234 if (is_cgroup_event(event))
3235 static_key_slow_dec_deferred(&perf_sched_events);
3236 if (has_branch_stack(event))
3237 static_key_slow_dec_deferred(&perf_sched_events);
3239 unaccount_event_cpu(event, event->cpu);
3242 static void __free_event(struct perf_event *event)
3244 if (!event->parent) {
3245 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3246 put_callchain_buffers();
3250 event->destroy(event);
3253 put_ctx(event->ctx);
3255 call_rcu(&event->rcu_head, free_event_rcu);
3257 static void free_event(struct perf_event *event)
3259 irq_work_sync(&event->pending);
3261 unaccount_event(event);
3264 struct ring_buffer *rb;
3267 * Can happen when we close an event with re-directed output.
3269 * Since we have a 0 refcount, perf_mmap_close() will skip
3270 * over us; possibly making our ring_buffer_put() the last.
3272 mutex_lock(&event->mmap_mutex);
3275 rcu_assign_pointer(event->rb, NULL);
3276 ring_buffer_detach(event, rb);
3277 ring_buffer_put(rb); /* could be last */
3279 mutex_unlock(&event->mmap_mutex);
3282 if (is_cgroup_event(event))
3283 perf_detach_cgroup(event);
3286 __free_event(event);
3289 int perf_event_release_kernel(struct perf_event *event)
3291 struct perf_event_context *ctx = event->ctx;
3293 WARN_ON_ONCE(ctx->parent_ctx);
3295 * There are two ways this annotation is useful:
3297 * 1) there is a lock recursion from perf_event_exit_task
3298 * see the comment there.
3300 * 2) there is a lock-inversion with mmap_sem through
3301 * perf_event_read_group(), which takes faults while
3302 * holding ctx->mutex, however this is called after
3303 * the last filedesc died, so there is no possibility
3304 * to trigger the AB-BA case.
3306 mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
3307 perf_remove_from_context(event, true);
3308 mutex_unlock(&ctx->mutex);
3314 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3317 * Called when the last reference to the file is gone.
3319 static void put_event(struct perf_event *event)
3321 struct task_struct *owner;
3323 if (!atomic_long_dec_and_test(&event->refcount))
3327 owner = ACCESS_ONCE(event->owner);
3329 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3330 * !owner it means the list deletion is complete and we can indeed
3331 * free this event, otherwise we need to serialize on
3332 * owner->perf_event_mutex.
3334 smp_read_barrier_depends();
3337 * Since delayed_put_task_struct() also drops the last
3338 * task reference we can safely take a new reference
3339 * while holding the rcu_read_lock().
3341 get_task_struct(owner);
3346 mutex_lock(&owner->perf_event_mutex);
3348 * We have to re-check the event->owner field, if it is cleared
3349 * we raced with perf_event_exit_task(), acquiring the mutex
3350 * ensured they're done, and we can proceed with freeing the
3354 list_del_init(&event->owner_entry);
3355 mutex_unlock(&owner->perf_event_mutex);
3356 put_task_struct(owner);
3359 perf_event_release_kernel(event);
3362 static int perf_release(struct inode *inode, struct file *file)
3364 put_event(file->private_data);
3368 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3370 struct perf_event *child;
3376 mutex_lock(&event->child_mutex);
3377 total += perf_event_read(event);
3378 *enabled += event->total_time_enabled +
3379 atomic64_read(&event->child_total_time_enabled);
3380 *running += event->total_time_running +
3381 atomic64_read(&event->child_total_time_running);
3383 list_for_each_entry(child, &event->child_list, child_list) {
3384 total += perf_event_read(child);
3385 *enabled += child->total_time_enabled;
3386 *running += child->total_time_running;
3388 mutex_unlock(&event->child_mutex);
3392 EXPORT_SYMBOL_GPL(perf_event_read_value);
3394 static int perf_event_read_group(struct perf_event *event,
3395 u64 read_format, char __user *buf)
3397 struct perf_event *leader = event->group_leader, *sub;
3398 int n = 0, size = 0, ret = -EFAULT;
3399 struct perf_event_context *ctx = leader->ctx;
3401 u64 count, enabled, running;
3403 mutex_lock(&ctx->mutex);
3404 count = perf_event_read_value(leader, &enabled, &running);
3406 values[n++] = 1 + leader->nr_siblings;
3407 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3408 values[n++] = enabled;
3409 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3410 values[n++] = running;
3411 values[n++] = count;
3412 if (read_format & PERF_FORMAT_ID)
3413 values[n++] = primary_event_id(leader);
3415 size = n * sizeof(u64);
3417 if (copy_to_user(buf, values, size))
3422 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3425 values[n++] = perf_event_read_value(sub, &enabled, &running);
3426 if (read_format & PERF_FORMAT_ID)
3427 values[n++] = primary_event_id(sub);
3429 size = n * sizeof(u64);
3431 if (copy_to_user(buf + ret, values, size)) {
3439 mutex_unlock(&ctx->mutex);
3444 static int perf_event_read_one(struct perf_event *event,
3445 u64 read_format, char __user *buf)
3447 u64 enabled, running;
3451 values[n++] = perf_event_read_value(event, &enabled, &running);
3452 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3453 values[n++] = enabled;
3454 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3455 values[n++] = running;
3456 if (read_format & PERF_FORMAT_ID)
3457 values[n++] = primary_event_id(event);
3459 if (copy_to_user(buf, values, n * sizeof(u64)))
3462 return n * sizeof(u64);
3466 * Read the performance event - simple non blocking version for now
3469 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
3471 u64 read_format = event->attr.read_format;
3475 * Return end-of-file for a read on a event that is in
3476 * error state (i.e. because it was pinned but it couldn't be
3477 * scheduled on to the CPU at some point).
3479 if (event->state == PERF_EVENT_STATE_ERROR)
3482 if (count < event->read_size)
3485 WARN_ON_ONCE(event->ctx->parent_ctx);
3486 if (read_format & PERF_FORMAT_GROUP)
3487 ret = perf_event_read_group(event, read_format, buf);
3489 ret = perf_event_read_one(event, read_format, buf);
3495 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
3497 struct perf_event *event = file->private_data;
3499 return perf_read_hw(event, buf, count);
3502 static unsigned int perf_poll(struct file *file, poll_table *wait)
3504 struct perf_event *event = file->private_data;
3505 struct ring_buffer *rb;
3506 unsigned int events = POLL_HUP;
3509 * Pin the event->rb by taking event->mmap_mutex; otherwise
3510 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
3512 mutex_lock(&event->mmap_mutex);
3515 events = atomic_xchg(&rb->poll, 0);
3516 mutex_unlock(&event->mmap_mutex);
3518 poll_wait(file, &event->waitq, wait);
3523 static void perf_event_reset(struct perf_event *event)
3525 (void)perf_event_read(event);
3526 local64_set(&event->count, 0);
3527 perf_event_update_userpage(event);
3531 * Holding the top-level event's child_mutex means that any
3532 * descendant process that has inherited this event will block
3533 * in sync_child_event if it goes to exit, thus satisfying the
3534 * task existence requirements of perf_event_enable/disable.
3536 static void perf_event_for_each_child(struct perf_event *event,
3537 void (*func)(struct perf_event *))
3539 struct perf_event *child;
3541 WARN_ON_ONCE(event->ctx->parent_ctx);
3542 mutex_lock(&event->child_mutex);
3544 list_for_each_entry(child, &event->child_list, child_list)
3546 mutex_unlock(&event->child_mutex);
3549 static void perf_event_for_each(struct perf_event *event,
3550 void (*func)(struct perf_event *))
3552 struct perf_event_context *ctx = event->ctx;
3553 struct perf_event *sibling;
3555 WARN_ON_ONCE(ctx->parent_ctx);
3556 mutex_lock(&ctx->mutex);
3557 event = event->group_leader;
3559 perf_event_for_each_child(event, func);
3560 list_for_each_entry(sibling, &event->sibling_list, group_entry)
3561 perf_event_for_each_child(sibling, func);
3562 mutex_unlock(&ctx->mutex);
3565 static int perf_event_period(struct perf_event *event, u64 __user *arg)
3567 struct perf_event_context *ctx = event->ctx;
3568 int ret = 0, active;
3571 if (!is_sampling_event(event))
3574 if (copy_from_user(&value, arg, sizeof(value)))
3580 raw_spin_lock_irq(&ctx->lock);
3581 if (event->attr.freq) {
3582 if (value > sysctl_perf_event_sample_rate) {
3587 event->attr.sample_freq = value;
3589 event->attr.sample_period = value;
3590 event->hw.sample_period = value;
3593 active = (event->state == PERF_EVENT_STATE_ACTIVE);
3595 perf_pmu_disable(ctx->pmu);
3596 event->pmu->stop(event, PERF_EF_UPDATE);
3599 local64_set(&event->hw.period_left, 0);
3602 event->pmu->start(event, PERF_EF_RELOAD);
3603 perf_pmu_enable(ctx->pmu);
3607 raw_spin_unlock_irq(&ctx->lock);
3612 static const struct file_operations perf_fops;
3614 static inline int perf_fget_light(int fd, struct fd *p)
3616 struct fd f = fdget(fd);
3620 if (f.file->f_op != &perf_fops) {
3628 static int perf_event_set_output(struct perf_event *event,
3629 struct perf_event *output_event);
3630 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
3632 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
3634 struct perf_event *event = file->private_data;
3635 void (*func)(struct perf_event *);
3639 case PERF_EVENT_IOC_ENABLE:
3640 func = perf_event_enable;
3642 case PERF_EVENT_IOC_DISABLE:
3643 func = perf_event_disable;
3645 case PERF_EVENT_IOC_RESET:
3646 func = perf_event_reset;
3649 case PERF_EVENT_IOC_REFRESH:
3650 return perf_event_refresh(event, arg);
3652 case PERF_EVENT_IOC_PERIOD:
3653 return perf_event_period(event, (u64 __user *)arg);
3655 case PERF_EVENT_IOC_ID:
3657 u64 id = primary_event_id(event);
3659 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
3664 case PERF_EVENT_IOC_SET_OUTPUT:
3668 struct perf_event *output_event;
3670 ret = perf_fget_light(arg, &output);
3673 output_event = output.file->private_data;
3674 ret = perf_event_set_output(event, output_event);
3677 ret = perf_event_set_output(event, NULL);
3682 case PERF_EVENT_IOC_SET_FILTER:
3683 return perf_event_set_filter(event, (void __user *)arg);
3689 if (flags & PERF_IOC_FLAG_GROUP)
3690 perf_event_for_each(event, func);
3692 perf_event_for_each_child(event, func);
3697 #ifdef CONFIG_COMPAT
3698 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
3701 switch (_IOC_NR(cmd)) {
3702 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
3703 case _IOC_NR(PERF_EVENT_IOC_ID):
3704 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
3705 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
3706 cmd &= ~IOCSIZE_MASK;
3707 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
3711 return perf_ioctl(file, cmd, arg);
3714 # define perf_compat_ioctl NULL
3717 int perf_event_task_enable(void)
3719 struct perf_event *event;
3721 mutex_lock(¤t->perf_event_mutex);
3722 list_for_each_entry(event, ¤t->perf_event_list, owner_entry)
3723 perf_event_for_each_child(event, perf_event_enable);
3724 mutex_unlock(¤t->perf_event_mutex);
3729 int perf_event_task_disable(void)
3731 struct perf_event *event;
3733 mutex_lock(¤t->perf_event_mutex);
3734 list_for_each_entry(event, ¤t->perf_event_list, owner_entry)
3735 perf_event_for_each_child(event, perf_event_disable);
3736 mutex_unlock(¤t->perf_event_mutex);
3741 static int perf_event_index(struct perf_event *event)
3743 if (event->hw.state & PERF_HES_STOPPED)
3746 if (event->state != PERF_EVENT_STATE_ACTIVE)
3749 return event->pmu->event_idx(event);
3752 static void calc_timer_values(struct perf_event *event,
3759 *now = perf_clock();
3760 ctx_time = event->shadow_ctx_time + *now;
3761 *enabled = ctx_time - event->tstamp_enabled;
3762 *running = ctx_time - event->tstamp_running;
3765 static void perf_event_init_userpage(struct perf_event *event)
3767 struct perf_event_mmap_page *userpg;
3768 struct ring_buffer *rb;
3771 rb = rcu_dereference(event->rb);
3775 userpg = rb->user_page;
3777 /* Allow new userspace to detect that bit 0 is deprecated */
3778 userpg->cap_bit0_is_deprecated = 1;
3779 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
3785 void __weak arch_perf_update_userpage(struct perf_event_mmap_page *userpg, u64 now)
3790 * Callers need to ensure there can be no nesting of this function, otherwise
3791 * the seqlock logic goes bad. We can not serialize this because the arch
3792 * code calls this from NMI context.
3794 void perf_event_update_userpage(struct perf_event *event)
3796 struct perf_event_mmap_page *userpg;
3797 struct ring_buffer *rb;
3798 u64 enabled, running, now;
3801 rb = rcu_dereference(event->rb);
3806 * compute total_time_enabled, total_time_running
3807 * based on snapshot values taken when the event
3808 * was last scheduled in.
3810 * we cannot simply called update_context_time()
3811 * because of locking issue as we can be called in
3814 calc_timer_values(event, &now, &enabled, &running);
3816 userpg = rb->user_page;
3818 * Disable preemption so as to not let the corresponding user-space
3819 * spin too long if we get preempted.
3824 userpg->index = perf_event_index(event);
3825 userpg->offset = perf_event_count(event);
3827 userpg->offset -= local64_read(&event->hw.prev_count);
3829 userpg->time_enabled = enabled +
3830 atomic64_read(&event->child_total_time_enabled);
3832 userpg->time_running = running +
3833 atomic64_read(&event->child_total_time_running);
3835 arch_perf_update_userpage(userpg, now);
3844 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
3846 struct perf_event *event = vma->vm_file->private_data;
3847 struct ring_buffer *rb;
3848 int ret = VM_FAULT_SIGBUS;
3850 if (vmf->flags & FAULT_FLAG_MKWRITE) {
3851 if (vmf->pgoff == 0)
3857 rb = rcu_dereference(event->rb);
3861 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
3864 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
3868 get_page(vmf->page);
3869 vmf->page->mapping = vma->vm_file->f_mapping;
3870 vmf->page->index = vmf->pgoff;
3879 static void ring_buffer_attach(struct perf_event *event,
3880 struct ring_buffer *rb)
3882 unsigned long flags;
3884 if (!list_empty(&event->rb_entry))
3887 spin_lock_irqsave(&rb->event_lock, flags);
3888 if (list_empty(&event->rb_entry))
3889 list_add(&event->rb_entry, &rb->event_list);
3890 spin_unlock_irqrestore(&rb->event_lock, flags);
3893 static void ring_buffer_detach(struct perf_event *event, struct ring_buffer *rb)
3895 unsigned long flags;
3897 if (list_empty(&event->rb_entry))
3900 spin_lock_irqsave(&rb->event_lock, flags);
3901 list_del_init(&event->rb_entry);
3902 wake_up_all(&event->waitq);
3903 spin_unlock_irqrestore(&rb->event_lock, flags);
3906 static void ring_buffer_wakeup(struct perf_event *event)
3908 struct ring_buffer *rb;
3911 rb = rcu_dereference(event->rb);
3913 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
3914 wake_up_all(&event->waitq);
3919 static void rb_free_rcu(struct rcu_head *rcu_head)
3921 struct ring_buffer *rb;
3923 rb = container_of(rcu_head, struct ring_buffer, rcu_head);
3927 static struct ring_buffer *ring_buffer_get(struct perf_event *event)
3929 struct ring_buffer *rb;
3932 rb = rcu_dereference(event->rb);
3934 if (!atomic_inc_not_zero(&rb->refcount))
3942 static void ring_buffer_put(struct ring_buffer *rb)
3944 if (!atomic_dec_and_test(&rb->refcount))
3947 WARN_ON_ONCE(!list_empty(&rb->event_list));
3949 call_rcu(&rb->rcu_head, rb_free_rcu);
3952 static void perf_mmap_open(struct vm_area_struct *vma)
3954 struct perf_event *event = vma->vm_file->private_data;
3956 atomic_inc(&event->mmap_count);
3957 atomic_inc(&event->rb->mmap_count);
3961 * A buffer can be mmap()ed multiple times; either directly through the same
3962 * event, or through other events by use of perf_event_set_output().
3964 * In order to undo the VM accounting done by perf_mmap() we need to destroy
3965 * the buffer here, where we still have a VM context. This means we need
3966 * to detach all events redirecting to us.
3968 static void perf_mmap_close(struct vm_area_struct *vma)
3970 struct perf_event *event = vma->vm_file->private_data;
3972 struct ring_buffer *rb = event->rb;
3973 struct user_struct *mmap_user = rb->mmap_user;
3974 int mmap_locked = rb->mmap_locked;
3975 unsigned long size = perf_data_size(rb);
3977 atomic_dec(&rb->mmap_count);
3979 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
3982 /* Detach current event from the buffer. */
3983 rcu_assign_pointer(event->rb, NULL);
3984 ring_buffer_detach(event, rb);
3985 mutex_unlock(&event->mmap_mutex);
3987 /* If there's still other mmap()s of this buffer, we're done. */
3988 if (atomic_read(&rb->mmap_count)) {
3989 ring_buffer_put(rb); /* can't be last */
3994 * No other mmap()s, detach from all other events that might redirect
3995 * into the now unreachable buffer. Somewhat complicated by the
3996 * fact that rb::event_lock otherwise nests inside mmap_mutex.
4000 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4001 if (!atomic_long_inc_not_zero(&event->refcount)) {
4003 * This event is en-route to free_event() which will
4004 * detach it and remove it from the list.
4010 mutex_lock(&event->mmap_mutex);
4012 * Check we didn't race with perf_event_set_output() which can
4013 * swizzle the rb from under us while we were waiting to
4014 * acquire mmap_mutex.
4016 * If we find a different rb; ignore this event, a next
4017 * iteration will no longer find it on the list. We have to
4018 * still restart the iteration to make sure we're not now
4019 * iterating the wrong list.
4021 if (event->rb == rb) {
4022 rcu_assign_pointer(event->rb, NULL);
4023 ring_buffer_detach(event, rb);
4024 ring_buffer_put(rb); /* can't be last, we still have one */
4026 mutex_unlock(&event->mmap_mutex);
4030 * Restart the iteration; either we're on the wrong list or
4031 * destroyed its integrity by doing a deletion.
4038 * It could be there's still a few 0-ref events on the list; they'll
4039 * get cleaned up by free_event() -- they'll also still have their
4040 * ref on the rb and will free it whenever they are done with it.
4042 * Aside from that, this buffer is 'fully' detached and unmapped,
4043 * undo the VM accounting.
4046 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4047 vma->vm_mm->pinned_vm -= mmap_locked;
4048 free_uid(mmap_user);
4050 ring_buffer_put(rb); /* could be last */
4053 static const struct vm_operations_struct perf_mmap_vmops = {
4054 .open = perf_mmap_open,
4055 .close = perf_mmap_close,
4056 .fault = perf_mmap_fault,
4057 .page_mkwrite = perf_mmap_fault,
4060 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
4062 struct perf_event *event = file->private_data;
4063 unsigned long user_locked, user_lock_limit;
4064 struct user_struct *user = current_user();
4065 unsigned long locked, lock_limit;
4066 struct ring_buffer *rb;
4067 unsigned long vma_size;
4068 unsigned long nr_pages;
4069 long user_extra, extra;
4070 int ret = 0, flags = 0;
4073 * Don't allow mmap() of inherited per-task counters. This would
4074 * create a performance issue due to all children writing to the
4077 if (event->cpu == -1 && event->attr.inherit)
4080 if (!(vma->vm_flags & VM_SHARED))
4083 vma_size = vma->vm_end - vma->vm_start;
4084 nr_pages = (vma_size / PAGE_SIZE) - 1;
4087 * If we have rb pages ensure they're a power-of-two number, so we
4088 * can do bitmasks instead of modulo.
4090 if (nr_pages != 0 && !is_power_of_2(nr_pages))
4093 if (vma_size != PAGE_SIZE * (1 + nr_pages))
4096 if (vma->vm_pgoff != 0)
4099 WARN_ON_ONCE(event->ctx->parent_ctx);
4101 mutex_lock(&event->mmap_mutex);
4103 if (event->rb->nr_pages != nr_pages) {
4108 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4110 * Raced against perf_mmap_close() through
4111 * perf_event_set_output(). Try again, hope for better
4114 mutex_unlock(&event->mmap_mutex);
4121 user_extra = nr_pages + 1;
4122 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
4125 * Increase the limit linearly with more CPUs:
4127 user_lock_limit *= num_online_cpus();
4129 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
4132 if (user_locked > user_lock_limit)
4133 extra = user_locked - user_lock_limit;
4135 lock_limit = rlimit(RLIMIT_MEMLOCK);
4136 lock_limit >>= PAGE_SHIFT;
4137 locked = vma->vm_mm->pinned_vm + extra;
4139 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
4140 !capable(CAP_IPC_LOCK)) {
4147 if (vma->vm_flags & VM_WRITE)
4148 flags |= RING_BUFFER_WRITABLE;
4150 rb = rb_alloc(nr_pages,
4151 event->attr.watermark ? event->attr.wakeup_watermark : 0,
4159 atomic_set(&rb->mmap_count, 1);
4160 rb->mmap_locked = extra;
4161 rb->mmap_user = get_current_user();
4163 atomic_long_add(user_extra, &user->locked_vm);
4164 vma->vm_mm->pinned_vm += extra;
4166 ring_buffer_attach(event, rb);
4167 rcu_assign_pointer(event->rb, rb);
4169 perf_event_init_userpage(event);
4170 perf_event_update_userpage(event);
4174 atomic_inc(&event->mmap_count);
4175 mutex_unlock(&event->mmap_mutex);
4178 * Since pinned accounting is per vm we cannot allow fork() to copy our
4181 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
4182 vma->vm_ops = &perf_mmap_vmops;
4187 static int perf_fasync(int fd, struct file *filp, int on)
4189 struct inode *inode = file_inode(filp);
4190 struct perf_event *event = filp->private_data;
4193 mutex_lock(&inode->i_mutex);
4194 retval = fasync_helper(fd, filp, on, &event->fasync);
4195 mutex_unlock(&inode->i_mutex);
4203 static const struct file_operations perf_fops = {
4204 .llseek = no_llseek,
4205 .release = perf_release,
4208 .unlocked_ioctl = perf_ioctl,
4209 .compat_ioctl = perf_compat_ioctl,
4211 .fasync = perf_fasync,
4217 * If there's data, ensure we set the poll() state and publish everything
4218 * to user-space before waking everybody up.
4221 void perf_event_wakeup(struct perf_event *event)
4223 ring_buffer_wakeup(event);
4225 if (event->pending_kill) {
4226 kill_fasync(&event->fasync, SIGIO, event->pending_kill);
4227 event->pending_kill = 0;
4231 static void perf_pending_event(struct irq_work *entry)
4233 struct perf_event *event = container_of(entry,
4234 struct perf_event, pending);
4236 if (event->pending_disable) {
4237 event->pending_disable = 0;
4238 __perf_event_disable(event);
4241 if (event->pending_wakeup) {
4242 event->pending_wakeup = 0;
4243 perf_event_wakeup(event);
4248 * We assume there is only KVM supporting the callbacks.
4249 * Later on, we might change it to a list if there is
4250 * another virtualization implementation supporting the callbacks.
4252 struct perf_guest_info_callbacks *perf_guest_cbs;
4254 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4256 perf_guest_cbs = cbs;
4259 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
4261 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4263 perf_guest_cbs = NULL;
4266 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
4269 perf_output_sample_regs(struct perf_output_handle *handle,
4270 struct pt_regs *regs, u64 mask)
4274 for_each_set_bit(bit, (const unsigned long *) &mask,
4275 sizeof(mask) * BITS_PER_BYTE) {
4278 val = perf_reg_value(regs, bit);
4279 perf_output_put(handle, val);
4283 static void perf_sample_regs_user(struct perf_regs_user *regs_user,
4284 struct pt_regs *regs)
4286 if (!user_mode(regs)) {
4288 regs = task_pt_regs(current);
4294 regs_user->regs = regs;
4295 regs_user->abi = perf_reg_abi(current);
4300 * Get remaining task size from user stack pointer.
4302 * It'd be better to take stack vma map and limit this more
4303 * precisly, but there's no way to get it safely under interrupt,
4304 * so using TASK_SIZE as limit.
4306 static u64 perf_ustack_task_size(struct pt_regs *regs)
4308 unsigned long addr = perf_user_stack_pointer(regs);
4310 if (!addr || addr >= TASK_SIZE)
4313 return TASK_SIZE - addr;
4317 perf_sample_ustack_size(u16 stack_size, u16 header_size,
4318 struct pt_regs *regs)
4322 /* No regs, no stack pointer, no dump. */
4327 * Check if we fit in with the requested stack size into the:
4329 * If we don't, we limit the size to the TASK_SIZE.
4331 * - remaining sample size
4332 * If we don't, we customize the stack size to
4333 * fit in to the remaining sample size.
4336 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
4337 stack_size = min(stack_size, (u16) task_size);
4339 /* Current header size plus static size and dynamic size. */
4340 header_size += 2 * sizeof(u64);
4342 /* Do we fit in with the current stack dump size? */
4343 if ((u16) (header_size + stack_size) < header_size) {
4345 * If we overflow the maximum size for the sample,
4346 * we customize the stack dump size to fit in.
4348 stack_size = USHRT_MAX - header_size - sizeof(u64);
4349 stack_size = round_up(stack_size, sizeof(u64));
4356 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
4357 struct pt_regs *regs)
4359 /* Case of a kernel thread, nothing to dump */
4362 perf_output_put(handle, size);
4371 * - the size requested by user or the best one we can fit
4372 * in to the sample max size
4374 * - user stack dump data
4376 * - the actual dumped size
4380 perf_output_put(handle, dump_size);
4383 sp = perf_user_stack_pointer(regs);
4384 rem = __output_copy_user(handle, (void *) sp, dump_size);
4385 dyn_size = dump_size - rem;
4387 perf_output_skip(handle, rem);
4390 perf_output_put(handle, dyn_size);
4394 static void __perf_event_header__init_id(struct perf_event_header *header,
4395 struct perf_sample_data *data,
4396 struct perf_event *event)
4398 u64 sample_type = event->attr.sample_type;
4400 data->type = sample_type;
4401 header->size += event->id_header_size;
4403 if (sample_type & PERF_SAMPLE_TID) {
4404 /* namespace issues */
4405 data->tid_entry.pid = perf_event_pid(event, current);
4406 data->tid_entry.tid = perf_event_tid(event, current);
4409 if (sample_type & PERF_SAMPLE_TIME)
4410 data->time = perf_clock();
4412 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
4413 data->id = primary_event_id(event);
4415 if (sample_type & PERF_SAMPLE_STREAM_ID)
4416 data->stream_id = event->id;
4418 if (sample_type & PERF_SAMPLE_CPU) {
4419 data->cpu_entry.cpu = raw_smp_processor_id();
4420 data->cpu_entry.reserved = 0;
4424 void perf_event_header__init_id(struct perf_event_header *header,
4425 struct perf_sample_data *data,
4426 struct perf_event *event)
4428 if (event->attr.sample_id_all)
4429 __perf_event_header__init_id(header, data, event);
4432 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
4433 struct perf_sample_data *data)
4435 u64 sample_type = data->type;
4437 if (sample_type & PERF_SAMPLE_TID)
4438 perf_output_put(handle, data->tid_entry);
4440 if (sample_type & PERF_SAMPLE_TIME)
4441 perf_output_put(handle, data->time);
4443 if (sample_type & PERF_SAMPLE_ID)
4444 perf_output_put(handle, data->id);
4446 if (sample_type & PERF_SAMPLE_STREAM_ID)
4447 perf_output_put(handle, data->stream_id);
4449 if (sample_type & PERF_SAMPLE_CPU)
4450 perf_output_put(handle, data->cpu_entry);
4452 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4453 perf_output_put(handle, data->id);
4456 void perf_event__output_id_sample(struct perf_event *event,
4457 struct perf_output_handle *handle,
4458 struct perf_sample_data *sample)
4460 if (event->attr.sample_id_all)
4461 __perf_event__output_id_sample(handle, sample);
4464 static void perf_output_read_one(struct perf_output_handle *handle,
4465 struct perf_event *event,
4466 u64 enabled, u64 running)
4468 u64 read_format = event->attr.read_format;
4472 values[n++] = perf_event_count(event);
4473 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4474 values[n++] = enabled +
4475 atomic64_read(&event->child_total_time_enabled);
4477 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4478 values[n++] = running +
4479 atomic64_read(&event->child_total_time_running);
4481 if (read_format & PERF_FORMAT_ID)
4482 values[n++] = primary_event_id(event);
4484 __output_copy(handle, values, n * sizeof(u64));
4488 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
4490 static void perf_output_read_group(struct perf_output_handle *handle,
4491 struct perf_event *event,
4492 u64 enabled, u64 running)
4494 struct perf_event *leader = event->group_leader, *sub;
4495 u64 read_format = event->attr.read_format;
4499 values[n++] = 1 + leader->nr_siblings;
4501 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4502 values[n++] = enabled;
4504 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4505 values[n++] = running;
4507 if (leader != event)
4508 leader->pmu->read(leader);
4510 values[n++] = perf_event_count(leader);
4511 if (read_format & PERF_FORMAT_ID)
4512 values[n++] = primary_event_id(leader);
4514 __output_copy(handle, values, n * sizeof(u64));
4516 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4519 if ((sub != event) &&
4520 (sub->state == PERF_EVENT_STATE_ACTIVE))
4521 sub->pmu->read(sub);
4523 values[n++] = perf_event_count(sub);
4524 if (read_format & PERF_FORMAT_ID)
4525 values[n++] = primary_event_id(sub);
4527 __output_copy(handle, values, n * sizeof(u64));
4531 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
4532 PERF_FORMAT_TOTAL_TIME_RUNNING)
4534 static void perf_output_read(struct perf_output_handle *handle,
4535 struct perf_event *event)
4537 u64 enabled = 0, running = 0, now;
4538 u64 read_format = event->attr.read_format;
4541 * compute total_time_enabled, total_time_running
4542 * based on snapshot values taken when the event
4543 * was last scheduled in.
4545 * we cannot simply called update_context_time()
4546 * because of locking issue as we are called in
4549 if (read_format & PERF_FORMAT_TOTAL_TIMES)
4550 calc_timer_values(event, &now, &enabled, &running);
4552 if (event->attr.read_format & PERF_FORMAT_GROUP)
4553 perf_output_read_group(handle, event, enabled, running);
4555 perf_output_read_one(handle, event, enabled, running);
4558 void perf_output_sample(struct perf_output_handle *handle,
4559 struct perf_event_header *header,
4560 struct perf_sample_data *data,
4561 struct perf_event *event)
4563 u64 sample_type = data->type;
4565 perf_output_put(handle, *header);
4567 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4568 perf_output_put(handle, data->id);
4570 if (sample_type & PERF_SAMPLE_IP)
4571 perf_output_put(handle, data->ip);
4573 if (sample_type & PERF_SAMPLE_TID)
4574 perf_output_put(handle, data->tid_entry);
4576 if (sample_type & PERF_SAMPLE_TIME)
4577 perf_output_put(handle, data->time);
4579 if (sample_type & PERF_SAMPLE_ADDR)
4580 perf_output_put(handle, data->addr);
4582 if (sample_type & PERF_SAMPLE_ID)
4583 perf_output_put(handle, data->id);
4585 if (sample_type & PERF_SAMPLE_STREAM_ID)
4586 perf_output_put(handle, data->stream_id);
4588 if (sample_type & PERF_SAMPLE_CPU)
4589 perf_output_put(handle, data->cpu_entry);
4591 if (sample_type & PERF_SAMPLE_PERIOD)
4592 perf_output_put(handle, data->period);
4594 if (sample_type & PERF_SAMPLE_READ)
4595 perf_output_read(handle, event);
4597 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4598 if (data->callchain) {
4601 if (data->callchain)
4602 size += data->callchain->nr;
4604 size *= sizeof(u64);
4606 __output_copy(handle, data->callchain, size);
4609 perf_output_put(handle, nr);
4613 if (sample_type & PERF_SAMPLE_RAW) {
4615 perf_output_put(handle, data->raw->size);
4616 __output_copy(handle, data->raw->data,
4623 .size = sizeof(u32),
4626 perf_output_put(handle, raw);
4630 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4631 if (data->br_stack) {
4634 size = data->br_stack->nr
4635 * sizeof(struct perf_branch_entry);
4637 perf_output_put(handle, data->br_stack->nr);
4638 perf_output_copy(handle, data->br_stack->entries, size);
4641 * we always store at least the value of nr
4644 perf_output_put(handle, nr);
4648 if (sample_type & PERF_SAMPLE_REGS_USER) {
4649 u64 abi = data->regs_user.abi;
4652 * If there are no regs to dump, notice it through
4653 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
4655 perf_output_put(handle, abi);
4658 u64 mask = event->attr.sample_regs_user;
4659 perf_output_sample_regs(handle,
4660 data->regs_user.regs,
4665 if (sample_type & PERF_SAMPLE_STACK_USER) {
4666 perf_output_sample_ustack(handle,
4667 data->stack_user_size,
4668 data->regs_user.regs);
4671 if (sample_type & PERF_SAMPLE_WEIGHT)
4672 perf_output_put(handle, data->weight);
4674 if (sample_type & PERF_SAMPLE_DATA_SRC)
4675 perf_output_put(handle, data->data_src.val);
4677 if (sample_type & PERF_SAMPLE_TRANSACTION)
4678 perf_output_put(handle, data->txn);
4680 if (!event->attr.watermark) {
4681 int wakeup_events = event->attr.wakeup_events;
4683 if (wakeup_events) {
4684 struct ring_buffer *rb = handle->rb;
4685 int events = local_inc_return(&rb->events);
4687 if (events >= wakeup_events) {
4688 local_sub(wakeup_events, &rb->events);
4689 local_inc(&rb->wakeup);
4695 void perf_prepare_sample(struct perf_event_header *header,
4696 struct perf_sample_data *data,
4697 struct perf_event *event,
4698 struct pt_regs *regs)
4700 u64 sample_type = event->attr.sample_type;
4702 header->type = PERF_RECORD_SAMPLE;
4703 header->size = sizeof(*header) + event->header_size;
4706 header->misc |= perf_misc_flags(regs);
4708 __perf_event_header__init_id(header, data, event);
4710 if (sample_type & PERF_SAMPLE_IP)
4711 data->ip = perf_instruction_pointer(regs);
4713 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4716 data->callchain = perf_callchain(event, regs);
4718 if (data->callchain)
4719 size += data->callchain->nr;
4721 header->size += size * sizeof(u64);
4724 if (sample_type & PERF_SAMPLE_RAW) {
4725 int size = sizeof(u32);
4728 size += data->raw->size;
4730 size += sizeof(u32);
4732 WARN_ON_ONCE(size & (sizeof(u64)-1));
4733 header->size += size;
4736 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4737 int size = sizeof(u64); /* nr */
4738 if (data->br_stack) {
4739 size += data->br_stack->nr
4740 * sizeof(struct perf_branch_entry);
4742 header->size += size;
4745 if (sample_type & PERF_SAMPLE_REGS_USER) {
4746 /* regs dump ABI info */
4747 int size = sizeof(u64);
4749 perf_sample_regs_user(&data->regs_user, regs);
4751 if (data->regs_user.regs) {
4752 u64 mask = event->attr.sample_regs_user;
4753 size += hweight64(mask) * sizeof(u64);
4756 header->size += size;
4759 if (sample_type & PERF_SAMPLE_STACK_USER) {
4761 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
4762 * processed as the last one or have additional check added
4763 * in case new sample type is added, because we could eat
4764 * up the rest of the sample size.
4766 struct perf_regs_user *uregs = &data->regs_user;
4767 u16 stack_size = event->attr.sample_stack_user;
4768 u16 size = sizeof(u64);
4771 perf_sample_regs_user(uregs, regs);
4773 stack_size = perf_sample_ustack_size(stack_size, header->size,
4777 * If there is something to dump, add space for the dump
4778 * itself and for the field that tells the dynamic size,
4779 * which is how many have been actually dumped.
4782 size += sizeof(u64) + stack_size;
4784 data->stack_user_size = stack_size;
4785 header->size += size;
4789 static void perf_event_output(struct perf_event *event,
4790 struct perf_sample_data *data,
4791 struct pt_regs *regs)
4793 struct perf_output_handle handle;
4794 struct perf_event_header header;
4796 /* protect the callchain buffers */
4799 perf_prepare_sample(&header, data, event, regs);
4801 if (perf_output_begin(&handle, event, header.size))
4804 perf_output_sample(&handle, &header, data, event);
4806 perf_output_end(&handle);
4816 struct perf_read_event {
4817 struct perf_event_header header;
4824 perf_event_read_event(struct perf_event *event,
4825 struct task_struct *task)
4827 struct perf_output_handle handle;
4828 struct perf_sample_data sample;
4829 struct perf_read_event read_event = {
4831 .type = PERF_RECORD_READ,
4833 .size = sizeof(read_event) + event->read_size,
4835 .pid = perf_event_pid(event, task),
4836 .tid = perf_event_tid(event, task),
4840 perf_event_header__init_id(&read_event.header, &sample, event);
4841 ret = perf_output_begin(&handle, event, read_event.header.size);
4845 perf_output_put(&handle, read_event);
4846 perf_output_read(&handle, event);
4847 perf_event__output_id_sample(event, &handle, &sample);
4849 perf_output_end(&handle);
4852 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
4855 perf_event_aux_ctx(struct perf_event_context *ctx,
4856 perf_event_aux_output_cb output,
4859 struct perf_event *event;
4861 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4862 if (event->state < PERF_EVENT_STATE_INACTIVE)
4864 if (!event_filter_match(event))
4866 output(event, data);
4871 perf_event_aux(perf_event_aux_output_cb output, void *data,
4872 struct perf_event_context *task_ctx)
4874 struct perf_cpu_context *cpuctx;
4875 struct perf_event_context *ctx;
4880 list_for_each_entry_rcu(pmu, &pmus, entry) {
4881 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4882 if (cpuctx->unique_pmu != pmu)
4884 perf_event_aux_ctx(&cpuctx->ctx, output, data);
4887 ctxn = pmu->task_ctx_nr;
4890 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4892 perf_event_aux_ctx(ctx, output, data);
4894 put_cpu_ptr(pmu->pmu_cpu_context);
4899 perf_event_aux_ctx(task_ctx, output, data);
4906 * task tracking -- fork/exit
4908 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
4911 struct perf_task_event {
4912 struct task_struct *task;
4913 struct perf_event_context *task_ctx;
4916 struct perf_event_header header;
4926 static int perf_event_task_match(struct perf_event *event)
4928 return event->attr.comm || event->attr.mmap ||
4929 event->attr.mmap2 || event->attr.mmap_data ||
4933 static void perf_event_task_output(struct perf_event *event,
4936 struct perf_task_event *task_event = data;
4937 struct perf_output_handle handle;
4938 struct perf_sample_data sample;
4939 struct task_struct *task = task_event->task;
4940 int ret, size = task_event->event_id.header.size;
4942 if (!perf_event_task_match(event))
4945 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
4947 ret = perf_output_begin(&handle, event,
4948 task_event->event_id.header.size);
4952 task_event->event_id.pid = perf_event_pid(event, task);
4953 task_event->event_id.ppid = perf_event_pid(event, current);
4955 task_event->event_id.tid = perf_event_tid(event, task);
4956 task_event->event_id.ptid = perf_event_tid(event, current);
4958 perf_output_put(&handle, task_event->event_id);
4960 perf_event__output_id_sample(event, &handle, &sample);
4962 perf_output_end(&handle);
4964 task_event->event_id.header.size = size;
4967 static void perf_event_task(struct task_struct *task,
4968 struct perf_event_context *task_ctx,
4971 struct perf_task_event task_event;
4973 if (!atomic_read(&nr_comm_events) &&
4974 !atomic_read(&nr_mmap_events) &&
4975 !atomic_read(&nr_task_events))
4978 task_event = (struct perf_task_event){
4980 .task_ctx = task_ctx,
4983 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
4985 .size = sizeof(task_event.event_id),
4991 .time = perf_clock(),
4995 perf_event_aux(perf_event_task_output,
5000 void perf_event_fork(struct task_struct *task)
5002 perf_event_task(task, NULL, 1);
5009 struct perf_comm_event {
5010 struct task_struct *task;
5015 struct perf_event_header header;
5022 static int perf_event_comm_match(struct perf_event *event)
5024 return event->attr.comm;
5027 static void perf_event_comm_output(struct perf_event *event,
5030 struct perf_comm_event *comm_event = data;
5031 struct perf_output_handle handle;
5032 struct perf_sample_data sample;
5033 int size = comm_event->event_id.header.size;
5036 if (!perf_event_comm_match(event))
5039 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
5040 ret = perf_output_begin(&handle, event,
5041 comm_event->event_id.header.size);
5046 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
5047 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
5049 perf_output_put(&handle, comm_event->event_id);
5050 __output_copy(&handle, comm_event->comm,
5051 comm_event->comm_size);
5053 perf_event__output_id_sample(event, &handle, &sample);
5055 perf_output_end(&handle);
5057 comm_event->event_id.header.size = size;
5060 static void perf_event_comm_event(struct perf_comm_event *comm_event)
5062 char comm[TASK_COMM_LEN];
5065 memset(comm, 0, sizeof(comm));
5066 strlcpy(comm, comm_event->task->comm, sizeof(comm));
5067 size = ALIGN(strlen(comm)+1, sizeof(u64));
5069 comm_event->comm = comm;
5070 comm_event->comm_size = size;
5072 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
5074 perf_event_aux(perf_event_comm_output,
5079 void perf_event_comm(struct task_struct *task)
5081 struct perf_comm_event comm_event;
5082 struct perf_event_context *ctx;
5086 for_each_task_context_nr(ctxn) {
5087 ctx = task->perf_event_ctxp[ctxn];
5091 perf_event_enable_on_exec(ctx);
5095 if (!atomic_read(&nr_comm_events))
5098 comm_event = (struct perf_comm_event){
5104 .type = PERF_RECORD_COMM,
5113 perf_event_comm_event(&comm_event);
5120 struct perf_mmap_event {
5121 struct vm_area_struct *vma;
5123 const char *file_name;
5130 struct perf_event_header header;
5140 static int perf_event_mmap_match(struct perf_event *event,
5143 struct perf_mmap_event *mmap_event = data;
5144 struct vm_area_struct *vma = mmap_event->vma;
5145 int executable = vma->vm_flags & VM_EXEC;
5147 return (!executable && event->attr.mmap_data) ||
5148 (executable && (event->attr.mmap || event->attr.mmap2));
5151 static void perf_event_mmap_output(struct perf_event *event,
5154 struct perf_mmap_event *mmap_event = data;
5155 struct perf_output_handle handle;
5156 struct perf_sample_data sample;
5157 int size = mmap_event->event_id.header.size;
5160 if (!perf_event_mmap_match(event, data))
5163 if (event->attr.mmap2) {
5164 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
5165 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
5166 mmap_event->event_id.header.size += sizeof(mmap_event->min);
5167 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
5168 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
5171 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
5172 ret = perf_output_begin(&handle, event,
5173 mmap_event->event_id.header.size);
5177 mmap_event->event_id.pid = perf_event_pid(event, current);
5178 mmap_event->event_id.tid = perf_event_tid(event, current);
5180 perf_output_put(&handle, mmap_event->event_id);
5182 if (event->attr.mmap2) {
5183 perf_output_put(&handle, mmap_event->maj);
5184 perf_output_put(&handle, mmap_event->min);
5185 perf_output_put(&handle, mmap_event->ino);
5186 perf_output_put(&handle, mmap_event->ino_generation);
5189 __output_copy(&handle, mmap_event->file_name,
5190 mmap_event->file_size);
5192 perf_event__output_id_sample(event, &handle, &sample);
5194 perf_output_end(&handle);
5196 mmap_event->event_id.header.size = size;
5199 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
5201 struct vm_area_struct *vma = mmap_event->vma;
5202 struct file *file = vma->vm_file;
5203 int maj = 0, min = 0;
5204 u64 ino = 0, gen = 0;
5211 struct inode *inode;
5214 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5220 * d_path() works from the end of the rb backwards, so we
5221 * need to add enough zero bytes after the string to handle
5222 * the 64bit alignment we do later.
5224 name = d_path(&file->f_path, buf, PATH_MAX - sizeof(u64));
5229 inode = file_inode(vma->vm_file);
5230 dev = inode->i_sb->s_dev;
5232 gen = inode->i_generation;
5237 name = (char *)arch_vma_name(vma);
5241 if (vma->vm_start <= vma->vm_mm->start_brk &&
5242 vma->vm_end >= vma->vm_mm->brk) {
5246 if (vma->vm_start <= vma->vm_mm->start_stack &&
5247 vma->vm_end >= vma->vm_mm->start_stack) {
5257 strlcpy(tmp, name, sizeof(tmp));
5261 * Since our buffer works in 8 byte units we need to align our string
5262 * size to a multiple of 8. However, we must guarantee the tail end is
5263 * zero'd out to avoid leaking random bits to userspace.
5265 size = strlen(name)+1;
5266 while (!IS_ALIGNED(size, sizeof(u64)))
5267 name[size++] = '\0';
5269 mmap_event->file_name = name;
5270 mmap_event->file_size = size;
5271 mmap_event->maj = maj;
5272 mmap_event->min = min;
5273 mmap_event->ino = ino;
5274 mmap_event->ino_generation = gen;
5276 if (!(vma->vm_flags & VM_EXEC))
5277 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
5279 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
5281 perf_event_aux(perf_event_mmap_output,
5288 void perf_event_mmap(struct vm_area_struct *vma)
5290 struct perf_mmap_event mmap_event;
5292 if (!atomic_read(&nr_mmap_events))
5295 mmap_event = (struct perf_mmap_event){
5301 .type = PERF_RECORD_MMAP,
5302 .misc = PERF_RECORD_MISC_USER,
5307 .start = vma->vm_start,
5308 .len = vma->vm_end - vma->vm_start,
5309 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
5311 /* .maj (attr_mmap2 only) */
5312 /* .min (attr_mmap2 only) */
5313 /* .ino (attr_mmap2 only) */
5314 /* .ino_generation (attr_mmap2 only) */
5317 perf_event_mmap_event(&mmap_event);
5321 * IRQ throttle logging
5324 static void perf_log_throttle(struct perf_event *event, int enable)
5326 struct perf_output_handle handle;
5327 struct perf_sample_data sample;
5331 struct perf_event_header header;
5335 } throttle_event = {
5337 .type = PERF_RECORD_THROTTLE,
5339 .size = sizeof(throttle_event),
5341 .time = perf_clock(),
5342 .id = primary_event_id(event),
5343 .stream_id = event->id,
5347 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
5349 perf_event_header__init_id(&throttle_event.header, &sample, event);
5351 ret = perf_output_begin(&handle, event,
5352 throttle_event.header.size);
5356 perf_output_put(&handle, throttle_event);
5357 perf_event__output_id_sample(event, &handle, &sample);
5358 perf_output_end(&handle);
5362 * Generic event overflow handling, sampling.
5365 static int __perf_event_overflow(struct perf_event *event,
5366 int throttle, struct perf_sample_data *data,
5367 struct pt_regs *regs)
5369 int events = atomic_read(&event->event_limit);
5370 struct hw_perf_event *hwc = &event->hw;
5375 * Non-sampling counters might still use the PMI to fold short
5376 * hardware counters, ignore those.
5378 if (unlikely(!is_sampling_event(event)))
5381 seq = __this_cpu_read(perf_throttled_seq);
5382 if (seq != hwc->interrupts_seq) {
5383 hwc->interrupts_seq = seq;
5384 hwc->interrupts = 1;
5387 if (unlikely(throttle
5388 && hwc->interrupts >= max_samples_per_tick)) {
5389 __this_cpu_inc(perf_throttled_count);
5390 hwc->interrupts = MAX_INTERRUPTS;
5391 perf_log_throttle(event, 0);
5392 tick_nohz_full_kick();
5397 if (event->attr.freq) {
5398 u64 now = perf_clock();
5399 s64 delta = now - hwc->freq_time_stamp;
5401 hwc->freq_time_stamp = now;
5403 if (delta > 0 && delta < 2*TICK_NSEC)
5404 perf_adjust_period(event, delta, hwc->last_period, true);
5408 * XXX event_limit might not quite work as expected on inherited
5412 event->pending_kill = POLL_IN;
5413 if (events && atomic_dec_and_test(&event->event_limit)) {
5415 event->pending_kill = POLL_HUP;
5416 event->pending_disable = 1;
5417 irq_work_queue(&event->pending);
5420 if (event->overflow_handler)
5421 event->overflow_handler(event, data, regs);
5423 perf_event_output(event, data, regs);
5425 if (event->fasync && event->pending_kill) {
5426 event->pending_wakeup = 1;
5427 irq_work_queue(&event->pending);
5433 int perf_event_overflow(struct perf_event *event,
5434 struct perf_sample_data *data,
5435 struct pt_regs *regs)
5437 return __perf_event_overflow(event, 1, data, regs);
5441 * Generic software event infrastructure
5444 struct swevent_htable {
5445 struct swevent_hlist *swevent_hlist;
5446 struct mutex hlist_mutex;
5449 /* Recursion avoidance in each contexts */
5450 int recursion[PERF_NR_CONTEXTS];
5452 /* Keeps track of cpu being initialized/exited */
5456 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
5459 * We directly increment event->count and keep a second value in
5460 * event->hw.period_left to count intervals. This period event
5461 * is kept in the range [-sample_period, 0] so that we can use the
5465 u64 perf_swevent_set_period(struct perf_event *event)
5467 struct hw_perf_event *hwc = &event->hw;
5468 u64 period = hwc->last_period;
5472 hwc->last_period = hwc->sample_period;
5475 old = val = local64_read(&hwc->period_left);
5479 nr = div64_u64(period + val, period);
5480 offset = nr * period;
5482 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
5488 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
5489 struct perf_sample_data *data,
5490 struct pt_regs *regs)
5492 struct hw_perf_event *hwc = &event->hw;
5496 overflow = perf_swevent_set_period(event);
5498 if (hwc->interrupts == MAX_INTERRUPTS)
5501 for (; overflow; overflow--) {
5502 if (__perf_event_overflow(event, throttle,
5505 * We inhibit the overflow from happening when
5506 * hwc->interrupts == MAX_INTERRUPTS.
5514 static void perf_swevent_event(struct perf_event *event, u64 nr,
5515 struct perf_sample_data *data,
5516 struct pt_regs *regs)
5518 struct hw_perf_event *hwc = &event->hw;
5520 local64_add(nr, &event->count);
5525 if (!is_sampling_event(event))
5528 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
5530 return perf_swevent_overflow(event, 1, data, regs);
5532 data->period = event->hw.last_period;
5534 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
5535 return perf_swevent_overflow(event, 1, data, regs);
5537 if (local64_add_negative(nr, &hwc->period_left))
5540 perf_swevent_overflow(event, 0, data, regs);
5543 static int perf_exclude_event(struct perf_event *event,
5544 struct pt_regs *regs)
5546 if (event->hw.state & PERF_HES_STOPPED)
5550 if (event->attr.exclude_user && user_mode(regs))
5553 if (event->attr.exclude_kernel && !user_mode(regs))
5560 static int perf_swevent_match(struct perf_event *event,
5561 enum perf_type_id type,
5563 struct perf_sample_data *data,
5564 struct pt_regs *regs)
5566 if (event->attr.type != type)
5569 if (event->attr.config != event_id)
5572 if (perf_exclude_event(event, regs))
5578 static inline u64 swevent_hash(u64 type, u32 event_id)
5580 u64 val = event_id | (type << 32);
5582 return hash_64(val, SWEVENT_HLIST_BITS);
5585 static inline struct hlist_head *
5586 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
5588 u64 hash = swevent_hash(type, event_id);
5590 return &hlist->heads[hash];
5593 /* For the read side: events when they trigger */
5594 static inline struct hlist_head *
5595 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
5597 struct swevent_hlist *hlist;
5599 hlist = rcu_dereference(swhash->swevent_hlist);
5603 return __find_swevent_head(hlist, type, event_id);
5606 /* For the event head insertion and removal in the hlist */
5607 static inline struct hlist_head *
5608 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
5610 struct swevent_hlist *hlist;
5611 u32 event_id = event->attr.config;
5612 u64 type = event->attr.type;
5615 * Event scheduling is always serialized against hlist allocation
5616 * and release. Which makes the protected version suitable here.
5617 * The context lock guarantees that.
5619 hlist = rcu_dereference_protected(swhash->swevent_hlist,
5620 lockdep_is_held(&event->ctx->lock));
5624 return __find_swevent_head(hlist, type, event_id);
5627 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
5629 struct perf_sample_data *data,
5630 struct pt_regs *regs)
5632 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5633 struct perf_event *event;
5634 struct hlist_head *head;
5637 head = find_swevent_head_rcu(swhash, type, event_id);
5641 hlist_for_each_entry_rcu(event, head, hlist_entry) {
5642 if (perf_swevent_match(event, type, event_id, data, regs))
5643 perf_swevent_event(event, nr, data, regs);
5649 int perf_swevent_get_recursion_context(void)
5651 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5653 return get_recursion_context(swhash->recursion);
5655 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
5657 inline void perf_swevent_put_recursion_context(int rctx)
5659 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5661 put_recursion_context(swhash->recursion, rctx);
5664 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
5666 struct perf_sample_data data;
5669 preempt_disable_notrace();
5670 rctx = perf_swevent_get_recursion_context();
5674 perf_sample_data_init(&data, addr, 0);
5676 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
5678 perf_swevent_put_recursion_context(rctx);
5679 preempt_enable_notrace();
5682 static void perf_swevent_read(struct perf_event *event)
5686 static int perf_swevent_add(struct perf_event *event, int flags)
5688 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5689 struct hw_perf_event *hwc = &event->hw;
5690 struct hlist_head *head;
5692 if (is_sampling_event(event)) {
5693 hwc->last_period = hwc->sample_period;
5694 perf_swevent_set_period(event);
5697 hwc->state = !(flags & PERF_EF_START);
5699 head = find_swevent_head(swhash, event);
5702 * We can race with cpu hotplug code. Do not
5703 * WARN if the cpu just got unplugged.
5705 WARN_ON_ONCE(swhash->online);
5709 hlist_add_head_rcu(&event->hlist_entry, head);
5714 static void perf_swevent_del(struct perf_event *event, int flags)
5716 hlist_del_rcu(&event->hlist_entry);
5719 static void perf_swevent_start(struct perf_event *event, int flags)
5721 event->hw.state = 0;
5724 static void perf_swevent_stop(struct perf_event *event, int flags)
5726 event->hw.state = PERF_HES_STOPPED;
5729 /* Deref the hlist from the update side */
5730 static inline struct swevent_hlist *
5731 swevent_hlist_deref(struct swevent_htable *swhash)
5733 return rcu_dereference_protected(swhash->swevent_hlist,
5734 lockdep_is_held(&swhash->hlist_mutex));
5737 static void swevent_hlist_release(struct swevent_htable *swhash)
5739 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
5744 rcu_assign_pointer(swhash->swevent_hlist, NULL);
5745 kfree_rcu(hlist, rcu_head);
5748 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
5750 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5752 mutex_lock(&swhash->hlist_mutex);
5754 if (!--swhash->hlist_refcount)
5755 swevent_hlist_release(swhash);
5757 mutex_unlock(&swhash->hlist_mutex);
5760 static void swevent_hlist_put(struct perf_event *event)
5764 for_each_possible_cpu(cpu)
5765 swevent_hlist_put_cpu(event, cpu);
5768 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
5770 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5773 mutex_lock(&swhash->hlist_mutex);
5775 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
5776 struct swevent_hlist *hlist;
5778 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
5783 rcu_assign_pointer(swhash->swevent_hlist, hlist);
5785 swhash->hlist_refcount++;
5787 mutex_unlock(&swhash->hlist_mutex);
5792 static int swevent_hlist_get(struct perf_event *event)
5795 int cpu, failed_cpu;
5798 for_each_possible_cpu(cpu) {
5799 err = swevent_hlist_get_cpu(event, cpu);
5809 for_each_possible_cpu(cpu) {
5810 if (cpu == failed_cpu)
5812 swevent_hlist_put_cpu(event, cpu);
5819 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
5821 static void sw_perf_event_destroy(struct perf_event *event)
5823 u64 event_id = event->attr.config;
5825 WARN_ON(event->parent);
5827 static_key_slow_dec(&perf_swevent_enabled[event_id]);
5828 swevent_hlist_put(event);
5831 static int perf_swevent_init(struct perf_event *event)
5833 u64 event_id = event->attr.config;
5835 if (event->attr.type != PERF_TYPE_SOFTWARE)
5839 * no branch sampling for software events
5841 if (has_branch_stack(event))
5845 case PERF_COUNT_SW_CPU_CLOCK:
5846 case PERF_COUNT_SW_TASK_CLOCK:
5853 if (event_id >= PERF_COUNT_SW_MAX)
5856 if (!event->parent) {
5859 err = swevent_hlist_get(event);
5863 static_key_slow_inc(&perf_swevent_enabled[event_id]);
5864 event->destroy = sw_perf_event_destroy;
5870 static int perf_swevent_event_idx(struct perf_event *event)
5875 static struct pmu perf_swevent = {
5876 .task_ctx_nr = perf_sw_context,
5878 .event_init = perf_swevent_init,
5879 .add = perf_swevent_add,
5880 .del = perf_swevent_del,
5881 .start = perf_swevent_start,
5882 .stop = perf_swevent_stop,
5883 .read = perf_swevent_read,
5885 .event_idx = perf_swevent_event_idx,
5888 #ifdef CONFIG_EVENT_TRACING
5890 static int perf_tp_filter_match(struct perf_event *event,
5891 struct perf_sample_data *data)
5893 void *record = data->raw->data;
5895 if (likely(!event->filter) || filter_match_preds(event->filter, record))
5900 static int perf_tp_event_match(struct perf_event *event,
5901 struct perf_sample_data *data,
5902 struct pt_regs *regs)
5904 if (event->hw.state & PERF_HES_STOPPED)
5907 * All tracepoints are from kernel-space.
5909 if (event->attr.exclude_kernel)
5912 if (!perf_tp_filter_match(event, data))
5918 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
5919 struct pt_regs *regs, struct hlist_head *head, int rctx,
5920 struct task_struct *task)
5922 struct perf_sample_data data;
5923 struct perf_event *event;
5925 struct perf_raw_record raw = {
5930 perf_sample_data_init(&data, addr, 0);
5933 hlist_for_each_entry_rcu(event, head, hlist_entry) {
5934 if (perf_tp_event_match(event, &data, regs))
5935 perf_swevent_event(event, count, &data, regs);
5939 * If we got specified a target task, also iterate its context and
5940 * deliver this event there too.
5942 if (task && task != current) {
5943 struct perf_event_context *ctx;
5944 struct trace_entry *entry = record;
5947 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
5951 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5952 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5954 if (event->attr.config != entry->type)
5956 if (perf_tp_event_match(event, &data, regs))
5957 perf_swevent_event(event, count, &data, regs);
5963 perf_swevent_put_recursion_context(rctx);
5965 EXPORT_SYMBOL_GPL(perf_tp_event);
5967 static void tp_perf_event_destroy(struct perf_event *event)
5969 perf_trace_destroy(event);
5972 static int perf_tp_event_init(struct perf_event *event)
5976 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5980 * no branch sampling for tracepoint events
5982 if (has_branch_stack(event))
5985 err = perf_trace_init(event);
5989 event->destroy = tp_perf_event_destroy;
5994 static struct pmu perf_tracepoint = {
5995 .task_ctx_nr = perf_sw_context,
5997 .event_init = perf_tp_event_init,
5998 .add = perf_trace_add,
5999 .del = perf_trace_del,
6000 .start = perf_swevent_start,
6001 .stop = perf_swevent_stop,
6002 .read = perf_swevent_read,
6004 .event_idx = perf_swevent_event_idx,
6007 static inline void perf_tp_register(void)
6009 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
6012 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
6017 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6020 filter_str = strndup_user(arg, PAGE_SIZE);
6021 if (IS_ERR(filter_str))
6022 return PTR_ERR(filter_str);
6024 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
6030 static void perf_event_free_filter(struct perf_event *event)
6032 ftrace_profile_free_filter(event);
6037 static inline void perf_tp_register(void)
6041 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
6046 static void perf_event_free_filter(struct perf_event *event)
6050 #endif /* CONFIG_EVENT_TRACING */
6052 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6053 void perf_bp_event(struct perf_event *bp, void *data)
6055 struct perf_sample_data sample;
6056 struct pt_regs *regs = data;
6058 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
6060 if (!bp->hw.state && !perf_exclude_event(bp, regs))
6061 perf_swevent_event(bp, 1, &sample, regs);
6066 * hrtimer based swevent callback
6069 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
6071 enum hrtimer_restart ret = HRTIMER_RESTART;
6072 struct perf_sample_data data;
6073 struct pt_regs *regs;
6074 struct perf_event *event;
6077 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
6079 if (event->state != PERF_EVENT_STATE_ACTIVE)
6080 return HRTIMER_NORESTART;
6082 event->pmu->read(event);
6084 perf_sample_data_init(&data, 0, event->hw.last_period);
6085 regs = get_irq_regs();
6087 if (regs && !perf_exclude_event(event, regs)) {
6088 if (!(event->attr.exclude_idle && is_idle_task(current)))
6089 if (__perf_event_overflow(event, 1, &data, regs))
6090 ret = HRTIMER_NORESTART;
6093 period = max_t(u64, 10000, event->hw.sample_period);
6094 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
6099 static void perf_swevent_start_hrtimer(struct perf_event *event)
6101 struct hw_perf_event *hwc = &event->hw;
6104 if (!is_sampling_event(event))
6107 period = local64_read(&hwc->period_left);
6112 local64_set(&hwc->period_left, 0);
6114 period = max_t(u64, 10000, hwc->sample_period);
6116 __hrtimer_start_range_ns(&hwc->hrtimer,
6117 ns_to_ktime(period), 0,
6118 HRTIMER_MODE_REL_PINNED, 0);
6121 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
6123 struct hw_perf_event *hwc = &event->hw;
6125 if (is_sampling_event(event)) {
6126 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
6127 local64_set(&hwc->period_left, ktime_to_ns(remaining));
6129 hrtimer_cancel(&hwc->hrtimer);
6133 static void perf_swevent_init_hrtimer(struct perf_event *event)
6135 struct hw_perf_event *hwc = &event->hw;
6137 if (!is_sampling_event(event))
6140 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6141 hwc->hrtimer.function = perf_swevent_hrtimer;
6144 * Since hrtimers have a fixed rate, we can do a static freq->period
6145 * mapping and avoid the whole period adjust feedback stuff.
6147 if (event->attr.freq) {
6148 long freq = event->attr.sample_freq;
6150 event->attr.sample_period = NSEC_PER_SEC / freq;
6151 hwc->sample_period = event->attr.sample_period;
6152 local64_set(&hwc->period_left, hwc->sample_period);
6153 hwc->last_period = hwc->sample_period;
6154 event->attr.freq = 0;
6159 * Software event: cpu wall time clock
6162 static void cpu_clock_event_update(struct perf_event *event)
6167 now = local_clock();
6168 prev = local64_xchg(&event->hw.prev_count, now);
6169 local64_add(now - prev, &event->count);
6172 static void cpu_clock_event_start(struct perf_event *event, int flags)
6174 local64_set(&event->hw.prev_count, local_clock());
6175 perf_swevent_start_hrtimer(event);
6178 static void cpu_clock_event_stop(struct perf_event *event, int flags)
6180 perf_swevent_cancel_hrtimer(event);
6181 cpu_clock_event_update(event);
6184 static int cpu_clock_event_add(struct perf_event *event, int flags)
6186 if (flags & PERF_EF_START)
6187 cpu_clock_event_start(event, flags);
6192 static void cpu_clock_event_del(struct perf_event *event, int flags)
6194 cpu_clock_event_stop(event, flags);
6197 static void cpu_clock_event_read(struct perf_event *event)
6199 cpu_clock_event_update(event);
6202 static int cpu_clock_event_init(struct perf_event *event)
6204 if (event->attr.type != PERF_TYPE_SOFTWARE)
6207 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
6211 * no branch sampling for software events
6213 if (has_branch_stack(event))
6216 perf_swevent_init_hrtimer(event);
6221 static struct pmu perf_cpu_clock = {
6222 .task_ctx_nr = perf_sw_context,
6224 .event_init = cpu_clock_event_init,
6225 .add = cpu_clock_event_add,
6226 .del = cpu_clock_event_del,
6227 .start = cpu_clock_event_start,
6228 .stop = cpu_clock_event_stop,
6229 .read = cpu_clock_event_read,
6231 .event_idx = perf_swevent_event_idx,
6235 * Software event: task time clock
6238 static void task_clock_event_update(struct perf_event *event, u64 now)
6243 prev = local64_xchg(&event->hw.prev_count, now);
6245 local64_add(delta, &event->count);
6248 static void task_clock_event_start(struct perf_event *event, int flags)
6250 local64_set(&event->hw.prev_count, event->ctx->time);
6251 perf_swevent_start_hrtimer(event);
6254 static void task_clock_event_stop(struct perf_event *event, int flags)
6256 perf_swevent_cancel_hrtimer(event);
6257 task_clock_event_update(event, event->ctx->time);
6260 static int task_clock_event_add(struct perf_event *event, int flags)
6262 if (flags & PERF_EF_START)
6263 task_clock_event_start(event, flags);
6268 static void task_clock_event_del(struct perf_event *event, int flags)
6270 task_clock_event_stop(event, PERF_EF_UPDATE);
6273 static void task_clock_event_read(struct perf_event *event)
6275 u64 now = perf_clock();
6276 u64 delta = now - event->ctx->timestamp;
6277 u64 time = event->ctx->time + delta;
6279 task_clock_event_update(event, time);
6282 static int task_clock_event_init(struct perf_event *event)
6284 if (event->attr.type != PERF_TYPE_SOFTWARE)
6287 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
6291 * no branch sampling for software events
6293 if (has_branch_stack(event))
6296 perf_swevent_init_hrtimer(event);
6301 static struct pmu perf_task_clock = {
6302 .task_ctx_nr = perf_sw_context,
6304 .event_init = task_clock_event_init,
6305 .add = task_clock_event_add,
6306 .del = task_clock_event_del,
6307 .start = task_clock_event_start,
6308 .stop = task_clock_event_stop,
6309 .read = task_clock_event_read,
6311 .event_idx = perf_swevent_event_idx,
6314 static void perf_pmu_nop_void(struct pmu *pmu)
6318 static int perf_pmu_nop_int(struct pmu *pmu)
6323 static void perf_pmu_start_txn(struct pmu *pmu)
6325 perf_pmu_disable(pmu);
6328 static int perf_pmu_commit_txn(struct pmu *pmu)
6330 perf_pmu_enable(pmu);
6334 static void perf_pmu_cancel_txn(struct pmu *pmu)
6336 perf_pmu_enable(pmu);
6339 static int perf_event_idx_default(struct perf_event *event)
6341 return event->hw.idx + 1;
6345 * Ensures all contexts with the same task_ctx_nr have the same
6346 * pmu_cpu_context too.
6348 static void *find_pmu_context(int ctxn)
6355 list_for_each_entry(pmu, &pmus, entry) {
6356 if (pmu->task_ctx_nr == ctxn)
6357 return pmu->pmu_cpu_context;
6363 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
6367 for_each_possible_cpu(cpu) {
6368 struct perf_cpu_context *cpuctx;
6370 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6372 if (cpuctx->unique_pmu == old_pmu)
6373 cpuctx->unique_pmu = pmu;
6377 static void free_pmu_context(struct pmu *pmu)
6381 mutex_lock(&pmus_lock);
6383 * Like a real lame refcount.
6385 list_for_each_entry(i, &pmus, entry) {
6386 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
6387 update_pmu_context(i, pmu);
6392 free_percpu(pmu->pmu_cpu_context);
6394 mutex_unlock(&pmus_lock);
6396 static struct idr pmu_idr;
6399 type_show(struct device *dev, struct device_attribute *attr, char *page)
6401 struct pmu *pmu = dev_get_drvdata(dev);
6403 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
6405 static DEVICE_ATTR_RO(type);
6408 perf_event_mux_interval_ms_show(struct device *dev,
6409 struct device_attribute *attr,
6412 struct pmu *pmu = dev_get_drvdata(dev);
6414 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
6418 perf_event_mux_interval_ms_store(struct device *dev,
6419 struct device_attribute *attr,
6420 const char *buf, size_t count)
6422 struct pmu *pmu = dev_get_drvdata(dev);
6423 int timer, cpu, ret;
6425 ret = kstrtoint(buf, 0, &timer);
6432 /* same value, noting to do */
6433 if (timer == pmu->hrtimer_interval_ms)
6436 pmu->hrtimer_interval_ms = timer;
6438 /* update all cpuctx for this PMU */
6439 for_each_possible_cpu(cpu) {
6440 struct perf_cpu_context *cpuctx;
6441 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6442 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
6444 if (hrtimer_active(&cpuctx->hrtimer))
6445 hrtimer_forward_now(&cpuctx->hrtimer, cpuctx->hrtimer_interval);
6450 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
6452 static struct attribute *pmu_dev_attrs[] = {
6453 &dev_attr_type.attr,
6454 &dev_attr_perf_event_mux_interval_ms.attr,
6457 ATTRIBUTE_GROUPS(pmu_dev);
6459 static int pmu_bus_running;
6460 static struct bus_type pmu_bus = {
6461 .name = "event_source",
6462 .dev_groups = pmu_dev_groups,
6465 static void pmu_dev_release(struct device *dev)
6470 static int pmu_dev_alloc(struct pmu *pmu)
6474 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
6478 pmu->dev->groups = pmu->attr_groups;
6479 device_initialize(pmu->dev);
6480 ret = dev_set_name(pmu->dev, "%s", pmu->name);
6484 dev_set_drvdata(pmu->dev, pmu);
6485 pmu->dev->bus = &pmu_bus;
6486 pmu->dev->release = pmu_dev_release;
6487 ret = device_add(pmu->dev);
6495 put_device(pmu->dev);
6499 static struct lock_class_key cpuctx_mutex;
6500 static struct lock_class_key cpuctx_lock;
6502 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
6506 mutex_lock(&pmus_lock);
6508 pmu->pmu_disable_count = alloc_percpu(int);
6509 if (!pmu->pmu_disable_count)
6518 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
6526 if (pmu_bus_running) {
6527 ret = pmu_dev_alloc(pmu);
6533 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
6534 if (pmu->pmu_cpu_context)
6535 goto got_cpu_context;
6538 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
6539 if (!pmu->pmu_cpu_context)
6542 for_each_possible_cpu(cpu) {
6543 struct perf_cpu_context *cpuctx;
6545 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6546 __perf_event_init_context(&cpuctx->ctx);
6547 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
6548 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
6549 cpuctx->ctx.type = cpu_context;
6550 cpuctx->ctx.pmu = pmu;
6552 __perf_cpu_hrtimer_init(cpuctx, cpu);
6554 INIT_LIST_HEAD(&cpuctx->rotation_list);
6555 cpuctx->unique_pmu = pmu;
6559 if (!pmu->start_txn) {
6560 if (pmu->pmu_enable) {
6562 * If we have pmu_enable/pmu_disable calls, install
6563 * transaction stubs that use that to try and batch
6564 * hardware accesses.
6566 pmu->start_txn = perf_pmu_start_txn;
6567 pmu->commit_txn = perf_pmu_commit_txn;
6568 pmu->cancel_txn = perf_pmu_cancel_txn;
6570 pmu->start_txn = perf_pmu_nop_void;
6571 pmu->commit_txn = perf_pmu_nop_int;
6572 pmu->cancel_txn = perf_pmu_nop_void;
6576 if (!pmu->pmu_enable) {
6577 pmu->pmu_enable = perf_pmu_nop_void;
6578 pmu->pmu_disable = perf_pmu_nop_void;
6581 if (!pmu->event_idx)
6582 pmu->event_idx = perf_event_idx_default;
6584 list_add_rcu(&pmu->entry, &pmus);
6587 mutex_unlock(&pmus_lock);
6592 device_del(pmu->dev);
6593 put_device(pmu->dev);
6596 if (pmu->type >= PERF_TYPE_MAX)
6597 idr_remove(&pmu_idr, pmu->type);
6600 free_percpu(pmu->pmu_disable_count);
6604 void perf_pmu_unregister(struct pmu *pmu)
6606 mutex_lock(&pmus_lock);
6607 list_del_rcu(&pmu->entry);
6608 mutex_unlock(&pmus_lock);
6611 * We dereference the pmu list under both SRCU and regular RCU, so
6612 * synchronize against both of those.
6614 synchronize_srcu(&pmus_srcu);
6617 free_percpu(pmu->pmu_disable_count);
6618 if (pmu->type >= PERF_TYPE_MAX)
6619 idr_remove(&pmu_idr, pmu->type);
6620 device_del(pmu->dev);
6621 put_device(pmu->dev);
6622 free_pmu_context(pmu);
6625 struct pmu *perf_init_event(struct perf_event *event)
6627 struct pmu *pmu = NULL;
6631 idx = srcu_read_lock(&pmus_srcu);
6634 pmu = idr_find(&pmu_idr, event->attr.type);
6638 ret = pmu->event_init(event);
6644 list_for_each_entry_rcu(pmu, &pmus, entry) {
6646 ret = pmu->event_init(event);
6650 if (ret != -ENOENT) {
6655 pmu = ERR_PTR(-ENOENT);
6657 srcu_read_unlock(&pmus_srcu, idx);
6662 static void account_event_cpu(struct perf_event *event, int cpu)
6667 if (has_branch_stack(event)) {
6668 if (!(event->attach_state & PERF_ATTACH_TASK))
6669 atomic_inc(&per_cpu(perf_branch_stack_events, cpu));
6671 if (is_cgroup_event(event))
6672 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
6675 static void account_event(struct perf_event *event)
6680 if (event->attach_state & PERF_ATTACH_TASK)
6681 static_key_slow_inc(&perf_sched_events.key);
6682 if (event->attr.mmap || event->attr.mmap_data)
6683 atomic_inc(&nr_mmap_events);
6684 if (event->attr.comm)
6685 atomic_inc(&nr_comm_events);
6686 if (event->attr.task)
6687 atomic_inc(&nr_task_events);
6688 if (event->attr.freq) {
6689 if (atomic_inc_return(&nr_freq_events) == 1)
6690 tick_nohz_full_kick_all();
6692 if (has_branch_stack(event))
6693 static_key_slow_inc(&perf_sched_events.key);
6694 if (is_cgroup_event(event))
6695 static_key_slow_inc(&perf_sched_events.key);
6697 account_event_cpu(event, event->cpu);
6701 * Allocate and initialize a event structure
6703 static struct perf_event *
6704 perf_event_alloc(struct perf_event_attr *attr, int cpu,
6705 struct task_struct *task,
6706 struct perf_event *group_leader,
6707 struct perf_event *parent_event,
6708 perf_overflow_handler_t overflow_handler,
6712 struct perf_event *event;
6713 struct hw_perf_event *hwc;
6716 if ((unsigned)cpu >= nr_cpu_ids) {
6717 if (!task || cpu != -1)
6718 return ERR_PTR(-EINVAL);
6721 event = kzalloc(sizeof(*event), GFP_KERNEL);
6723 return ERR_PTR(-ENOMEM);
6726 * Single events are their own group leaders, with an
6727 * empty sibling list:
6730 group_leader = event;
6732 mutex_init(&event->child_mutex);
6733 INIT_LIST_HEAD(&event->child_list);
6735 INIT_LIST_HEAD(&event->group_entry);
6736 INIT_LIST_HEAD(&event->event_entry);
6737 INIT_LIST_HEAD(&event->sibling_list);
6738 INIT_LIST_HEAD(&event->rb_entry);
6739 INIT_LIST_HEAD(&event->active_entry);
6740 INIT_HLIST_NODE(&event->hlist_entry);
6743 init_waitqueue_head(&event->waitq);
6744 init_irq_work(&event->pending, perf_pending_event);
6746 mutex_init(&event->mmap_mutex);
6748 atomic_long_set(&event->refcount, 1);
6750 event->attr = *attr;
6751 event->group_leader = group_leader;
6755 event->parent = parent_event;
6757 event->ns = get_pid_ns(task_active_pid_ns(current));
6758 event->id = atomic64_inc_return(&perf_event_id);
6760 event->state = PERF_EVENT_STATE_INACTIVE;
6763 event->attach_state = PERF_ATTACH_TASK;
6765 if (attr->type == PERF_TYPE_TRACEPOINT)
6766 event->hw.tp_target = task;
6767 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6769 * hw_breakpoint is a bit difficult here..
6771 else if (attr->type == PERF_TYPE_BREAKPOINT)
6772 event->hw.bp_target = task;
6776 if (!overflow_handler && parent_event) {
6777 overflow_handler = parent_event->overflow_handler;
6778 context = parent_event->overflow_handler_context;
6781 event->overflow_handler = overflow_handler;
6782 event->overflow_handler_context = context;
6784 perf_event__state_init(event);
6789 hwc->sample_period = attr->sample_period;
6790 if (attr->freq && attr->sample_freq)
6791 hwc->sample_period = 1;
6792 hwc->last_period = hwc->sample_period;
6794 local64_set(&hwc->period_left, hwc->sample_period);
6797 * we currently do not support PERF_FORMAT_GROUP on inherited events
6799 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
6802 pmu = perf_init_event(event);
6805 else if (IS_ERR(pmu)) {
6810 if (!event->parent) {
6811 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
6812 err = get_callchain_buffers();
6822 event->destroy(event);
6825 put_pid_ns(event->ns);
6828 return ERR_PTR(err);
6831 static int perf_copy_attr(struct perf_event_attr __user *uattr,
6832 struct perf_event_attr *attr)
6837 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
6841 * zero the full structure, so that a short copy will be nice.
6843 memset(attr, 0, sizeof(*attr));
6845 ret = get_user(size, &uattr->size);
6849 if (size > PAGE_SIZE) /* silly large */
6852 if (!size) /* abi compat */
6853 size = PERF_ATTR_SIZE_VER0;
6855 if (size < PERF_ATTR_SIZE_VER0)
6859 * If we're handed a bigger struct than we know of,
6860 * ensure all the unknown bits are 0 - i.e. new
6861 * user-space does not rely on any kernel feature
6862 * extensions we dont know about yet.
6864 if (size > sizeof(*attr)) {
6865 unsigned char __user *addr;
6866 unsigned char __user *end;
6869 addr = (void __user *)uattr + sizeof(*attr);
6870 end = (void __user *)uattr + size;
6872 for (; addr < end; addr++) {
6873 ret = get_user(val, addr);
6879 size = sizeof(*attr);
6882 ret = copy_from_user(attr, uattr, size);
6886 /* disabled for now */
6890 if (attr->__reserved_1)
6893 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
6896 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
6899 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
6900 u64 mask = attr->branch_sample_type;
6902 /* only using defined bits */
6903 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
6906 /* at least one branch bit must be set */
6907 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
6910 /* propagate priv level, when not set for branch */
6911 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
6913 /* exclude_kernel checked on syscall entry */
6914 if (!attr->exclude_kernel)
6915 mask |= PERF_SAMPLE_BRANCH_KERNEL;
6917 if (!attr->exclude_user)
6918 mask |= PERF_SAMPLE_BRANCH_USER;
6920 if (!attr->exclude_hv)
6921 mask |= PERF_SAMPLE_BRANCH_HV;
6923 * adjust user setting (for HW filter setup)
6925 attr->branch_sample_type = mask;
6927 /* privileged levels capture (kernel, hv): check permissions */
6928 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
6929 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
6933 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
6934 ret = perf_reg_validate(attr->sample_regs_user);
6939 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
6940 if (!arch_perf_have_user_stack_dump())
6944 * We have __u32 type for the size, but so far
6945 * we can only use __u16 as maximum due to the
6946 * __u16 sample size limit.
6948 if (attr->sample_stack_user >= USHRT_MAX)
6950 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
6958 put_user(sizeof(*attr), &uattr->size);
6964 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
6966 struct ring_buffer *rb = NULL, *old_rb = NULL;
6972 /* don't allow circular references */
6973 if (event == output_event)
6977 * Don't allow cross-cpu buffers
6979 if (output_event->cpu != event->cpu)
6983 * If its not a per-cpu rb, it must be the same task.
6985 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
6989 mutex_lock(&event->mmap_mutex);
6990 /* Can't redirect output if we've got an active mmap() */
6991 if (atomic_read(&event->mmap_count))
6997 /* get the rb we want to redirect to */
6998 rb = ring_buffer_get(output_event);
7004 ring_buffer_detach(event, old_rb);
7007 ring_buffer_attach(event, rb);
7009 rcu_assign_pointer(event->rb, rb);
7012 ring_buffer_put(old_rb);
7014 * Since we detached before setting the new rb, so that we
7015 * could attach the new rb, we could have missed a wakeup.
7018 wake_up_all(&event->waitq);
7023 mutex_unlock(&event->mmap_mutex);
7030 * sys_perf_event_open - open a performance event, associate it to a task/cpu
7032 * @attr_uptr: event_id type attributes for monitoring/sampling
7035 * @group_fd: group leader event fd
7037 SYSCALL_DEFINE5(perf_event_open,
7038 struct perf_event_attr __user *, attr_uptr,
7039 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
7041 struct perf_event *group_leader = NULL, *output_event = NULL;
7042 struct perf_event *event, *sibling;
7043 struct perf_event_attr attr;
7044 struct perf_event_context *ctx;
7045 struct file *event_file = NULL;
7046 struct fd group = {NULL, 0};
7047 struct task_struct *task = NULL;
7052 int f_flags = O_RDWR;
7054 /* for future expandability... */
7055 if (flags & ~PERF_FLAG_ALL)
7058 err = perf_copy_attr(attr_uptr, &attr);
7062 if (!attr.exclude_kernel) {
7063 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
7068 if (attr.sample_freq > sysctl_perf_event_sample_rate)
7071 if (attr.sample_period & (1ULL << 63))
7076 * In cgroup mode, the pid argument is used to pass the fd
7077 * opened to the cgroup directory in cgroupfs. The cpu argument
7078 * designates the cpu on which to monitor threads from that
7081 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
7084 if (flags & PERF_FLAG_FD_CLOEXEC)
7085 f_flags |= O_CLOEXEC;
7087 event_fd = get_unused_fd_flags(f_flags);
7091 if (group_fd != -1) {
7092 err = perf_fget_light(group_fd, &group);
7095 group_leader = group.file->private_data;
7096 if (flags & PERF_FLAG_FD_OUTPUT)
7097 output_event = group_leader;
7098 if (flags & PERF_FLAG_FD_NO_GROUP)
7099 group_leader = NULL;
7102 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
7103 task = find_lively_task_by_vpid(pid);
7105 err = PTR_ERR(task);
7112 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
7114 if (IS_ERR(event)) {
7115 err = PTR_ERR(event);
7119 if (flags & PERF_FLAG_PID_CGROUP) {
7120 err = perf_cgroup_connect(pid, event, &attr, group_leader);
7122 __free_event(event);
7127 account_event(event);
7130 * Special case software events and allow them to be part of
7131 * any hardware group.
7136 (is_software_event(event) != is_software_event(group_leader))) {
7137 if (is_software_event(event)) {
7139 * If event and group_leader are not both a software
7140 * event, and event is, then group leader is not.
7142 * Allow the addition of software events to !software
7143 * groups, this is safe because software events never
7146 pmu = group_leader->pmu;
7147 } else if (is_software_event(group_leader) &&
7148 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
7150 * In case the group is a pure software group, and we
7151 * try to add a hardware event, move the whole group to
7152 * the hardware context.
7159 * Get the target context (task or percpu):
7161 ctx = find_get_context(pmu, task, event->cpu);
7168 put_task_struct(task);
7173 * Look up the group leader (we will attach this event to it):
7179 * Do not allow a recursive hierarchy (this new sibling
7180 * becoming part of another group-sibling):
7182 if (group_leader->group_leader != group_leader)
7185 * Do not allow to attach to a group in a different
7186 * task or CPU context:
7189 if (group_leader->ctx->type != ctx->type)
7192 if (group_leader->ctx != ctx)
7197 * Only a group leader can be exclusive or pinned
7199 if (attr.exclusive || attr.pinned)
7204 err = perf_event_set_output(event, output_event);
7209 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
7211 if (IS_ERR(event_file)) {
7212 err = PTR_ERR(event_file);
7217 struct perf_event_context *gctx = group_leader->ctx;
7219 mutex_lock(&gctx->mutex);
7220 perf_remove_from_context(group_leader, false);
7223 * Removing from the context ends up with disabled
7224 * event. What we want here is event in the initial
7225 * startup state, ready to be add into new context.
7227 perf_event__state_init(group_leader);
7228 list_for_each_entry(sibling, &group_leader->sibling_list,
7230 perf_remove_from_context(sibling, false);
7231 perf_event__state_init(sibling);
7234 mutex_unlock(&gctx->mutex);
7238 WARN_ON_ONCE(ctx->parent_ctx);
7239 mutex_lock(&ctx->mutex);
7243 perf_install_in_context(ctx, group_leader, event->cpu);
7245 list_for_each_entry(sibling, &group_leader->sibling_list,
7247 perf_install_in_context(ctx, sibling, event->cpu);
7252 perf_install_in_context(ctx, event, event->cpu);
7253 perf_unpin_context(ctx);
7254 mutex_unlock(&ctx->mutex);
7258 event->owner = current;
7260 mutex_lock(¤t->perf_event_mutex);
7261 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
7262 mutex_unlock(¤t->perf_event_mutex);
7265 * Precalculate sample_data sizes
7267 perf_event__header_size(event);
7268 perf_event__id_header_size(event);
7271 * Drop the reference on the group_event after placing the
7272 * new event on the sibling_list. This ensures destruction
7273 * of the group leader will find the pointer to itself in
7274 * perf_group_detach().
7277 fd_install(event_fd, event_file);
7281 perf_unpin_context(ctx);
7288 put_task_struct(task);
7292 put_unused_fd(event_fd);
7297 * perf_event_create_kernel_counter
7299 * @attr: attributes of the counter to create
7300 * @cpu: cpu in which the counter is bound
7301 * @task: task to profile (NULL for percpu)
7304 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
7305 struct task_struct *task,
7306 perf_overflow_handler_t overflow_handler,
7309 struct perf_event_context *ctx;
7310 struct perf_event *event;
7314 * Get the target context (task or percpu):
7317 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
7318 overflow_handler, context);
7319 if (IS_ERR(event)) {
7320 err = PTR_ERR(event);
7324 account_event(event);
7326 ctx = find_get_context(event->pmu, task, cpu);
7332 WARN_ON_ONCE(ctx->parent_ctx);
7333 mutex_lock(&ctx->mutex);
7334 perf_install_in_context(ctx, event, cpu);
7335 perf_unpin_context(ctx);
7336 mutex_unlock(&ctx->mutex);
7343 return ERR_PTR(err);
7345 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
7347 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
7349 struct perf_event_context *src_ctx;
7350 struct perf_event_context *dst_ctx;
7351 struct perf_event *event, *tmp;
7354 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
7355 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
7357 mutex_lock(&src_ctx->mutex);
7358 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
7360 perf_remove_from_context(event, false);
7361 unaccount_event_cpu(event, src_cpu);
7363 list_add(&event->migrate_entry, &events);
7365 mutex_unlock(&src_ctx->mutex);
7369 mutex_lock(&dst_ctx->mutex);
7370 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
7371 list_del(&event->migrate_entry);
7372 if (event->state >= PERF_EVENT_STATE_OFF)
7373 event->state = PERF_EVENT_STATE_INACTIVE;
7374 account_event_cpu(event, dst_cpu);
7375 perf_install_in_context(dst_ctx, event, dst_cpu);
7378 mutex_unlock(&dst_ctx->mutex);
7380 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
7382 static void sync_child_event(struct perf_event *child_event,
7383 struct task_struct *child)
7385 struct perf_event *parent_event = child_event->parent;
7388 if (child_event->attr.inherit_stat)
7389 perf_event_read_event(child_event, child);
7391 child_val = perf_event_count(child_event);
7394 * Add back the child's count to the parent's count:
7396 atomic64_add(child_val, &parent_event->child_count);
7397 atomic64_add(child_event->total_time_enabled,
7398 &parent_event->child_total_time_enabled);
7399 atomic64_add(child_event->total_time_running,
7400 &parent_event->child_total_time_running);
7403 * Remove this event from the parent's list
7405 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7406 mutex_lock(&parent_event->child_mutex);
7407 list_del_init(&child_event->child_list);
7408 mutex_unlock(&parent_event->child_mutex);
7411 * Release the parent event, if this was the last
7414 put_event(parent_event);
7418 __perf_event_exit_task(struct perf_event *child_event,
7419 struct perf_event_context *child_ctx,
7420 struct task_struct *child)
7422 perf_remove_from_context(child_event, !!child_event->parent);
7425 * It can happen that the parent exits first, and has events
7426 * that are still around due to the child reference. These
7427 * events need to be zapped.
7429 if (child_event->parent) {
7430 sync_child_event(child_event, child);
7431 free_event(child_event);
7435 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
7437 struct perf_event *child_event, *tmp;
7438 struct perf_event_context *child_ctx;
7439 unsigned long flags;
7441 if (likely(!child->perf_event_ctxp[ctxn])) {
7442 perf_event_task(child, NULL, 0);
7446 local_irq_save(flags);
7448 * We can't reschedule here because interrupts are disabled,
7449 * and either child is current or it is a task that can't be
7450 * scheduled, so we are now safe from rescheduling changing
7453 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
7456 * Take the context lock here so that if find_get_context is
7457 * reading child->perf_event_ctxp, we wait until it has
7458 * incremented the context's refcount before we do put_ctx below.
7460 raw_spin_lock(&child_ctx->lock);
7461 task_ctx_sched_out(child_ctx);
7462 child->perf_event_ctxp[ctxn] = NULL;
7464 * If this context is a clone; unclone it so it can't get
7465 * swapped to another process while we're removing all
7466 * the events from it.
7468 unclone_ctx(child_ctx);
7469 update_context_time(child_ctx);
7470 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7473 * Report the task dead after unscheduling the events so that we
7474 * won't get any samples after PERF_RECORD_EXIT. We can however still
7475 * get a few PERF_RECORD_READ events.
7477 perf_event_task(child, child_ctx, 0);
7480 * We can recurse on the same lock type through:
7482 * __perf_event_exit_task()
7483 * sync_child_event()
7485 * mutex_lock(&ctx->mutex)
7487 * But since its the parent context it won't be the same instance.
7489 mutex_lock(&child_ctx->mutex);
7492 list_for_each_entry_safe(child_event, tmp, &child_ctx->pinned_groups,
7494 __perf_event_exit_task(child_event, child_ctx, child);
7496 list_for_each_entry_safe(child_event, tmp, &child_ctx->flexible_groups,
7498 __perf_event_exit_task(child_event, child_ctx, child);
7501 * If the last event was a group event, it will have appended all
7502 * its siblings to the list, but we obtained 'tmp' before that which
7503 * will still point to the list head terminating the iteration.
7505 if (!list_empty(&child_ctx->pinned_groups) ||
7506 !list_empty(&child_ctx->flexible_groups))
7509 mutex_unlock(&child_ctx->mutex);
7515 * When a child task exits, feed back event values to parent events.
7517 void perf_event_exit_task(struct task_struct *child)
7519 struct perf_event *event, *tmp;
7522 mutex_lock(&child->perf_event_mutex);
7523 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
7525 list_del_init(&event->owner_entry);
7528 * Ensure the list deletion is visible before we clear
7529 * the owner, closes a race against perf_release() where
7530 * we need to serialize on the owner->perf_event_mutex.
7533 event->owner = NULL;
7535 mutex_unlock(&child->perf_event_mutex);
7537 for_each_task_context_nr(ctxn)
7538 perf_event_exit_task_context(child, ctxn);
7541 static void perf_free_event(struct perf_event *event,
7542 struct perf_event_context *ctx)
7544 struct perf_event *parent = event->parent;
7546 if (WARN_ON_ONCE(!parent))
7549 mutex_lock(&parent->child_mutex);
7550 list_del_init(&event->child_list);
7551 mutex_unlock(&parent->child_mutex);
7555 perf_group_detach(event);
7556 list_del_event(event, ctx);
7561 * free an unexposed, unused context as created by inheritance by
7562 * perf_event_init_task below, used by fork() in case of fail.
7564 void perf_event_free_task(struct task_struct *task)
7566 struct perf_event_context *ctx;
7567 struct perf_event *event, *tmp;
7570 for_each_task_context_nr(ctxn) {
7571 ctx = task->perf_event_ctxp[ctxn];
7575 mutex_lock(&ctx->mutex);
7577 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
7579 perf_free_event(event, ctx);
7581 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
7583 perf_free_event(event, ctx);
7585 if (!list_empty(&ctx->pinned_groups) ||
7586 !list_empty(&ctx->flexible_groups))
7589 mutex_unlock(&ctx->mutex);
7595 void perf_event_delayed_put(struct task_struct *task)
7599 for_each_task_context_nr(ctxn)
7600 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
7604 * inherit a event from parent task to child task:
7606 static struct perf_event *
7607 inherit_event(struct perf_event *parent_event,
7608 struct task_struct *parent,
7609 struct perf_event_context *parent_ctx,
7610 struct task_struct *child,
7611 struct perf_event *group_leader,
7612 struct perf_event_context *child_ctx)
7614 struct perf_event *child_event;
7615 unsigned long flags;
7618 * Instead of creating recursive hierarchies of events,
7619 * we link inherited events back to the original parent,
7620 * which has a filp for sure, which we use as the reference
7623 if (parent_event->parent)
7624 parent_event = parent_event->parent;
7626 child_event = perf_event_alloc(&parent_event->attr,
7629 group_leader, parent_event,
7631 if (IS_ERR(child_event))
7634 if (!atomic_long_inc_not_zero(&parent_event->refcount)) {
7635 free_event(child_event);
7642 * Make the child state follow the state of the parent event,
7643 * not its attr.disabled bit. We hold the parent's mutex,
7644 * so we won't race with perf_event_{en, dis}able_family.
7646 if (parent_event->state >= PERF_EVENT_STATE_INACTIVE)
7647 child_event->state = PERF_EVENT_STATE_INACTIVE;
7649 child_event->state = PERF_EVENT_STATE_OFF;
7651 if (parent_event->attr.freq) {
7652 u64 sample_period = parent_event->hw.sample_period;
7653 struct hw_perf_event *hwc = &child_event->hw;
7655 hwc->sample_period = sample_period;
7656 hwc->last_period = sample_period;
7658 local64_set(&hwc->period_left, sample_period);
7661 child_event->ctx = child_ctx;
7662 child_event->overflow_handler = parent_event->overflow_handler;
7663 child_event->overflow_handler_context
7664 = parent_event->overflow_handler_context;
7667 * Precalculate sample_data sizes
7669 perf_event__header_size(child_event);
7670 perf_event__id_header_size(child_event);
7673 * Link it up in the child's context:
7675 raw_spin_lock_irqsave(&child_ctx->lock, flags);
7676 add_event_to_ctx(child_event, child_ctx);
7677 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7680 * Link this into the parent event's child list
7682 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7683 mutex_lock(&parent_event->child_mutex);
7684 list_add_tail(&child_event->child_list, &parent_event->child_list);
7685 mutex_unlock(&parent_event->child_mutex);
7690 static int inherit_group(struct perf_event *parent_event,
7691 struct task_struct *parent,
7692 struct perf_event_context *parent_ctx,
7693 struct task_struct *child,
7694 struct perf_event_context *child_ctx)
7696 struct perf_event *leader;
7697 struct perf_event *sub;
7698 struct perf_event *child_ctr;
7700 leader = inherit_event(parent_event, parent, parent_ctx,
7701 child, NULL, child_ctx);
7703 return PTR_ERR(leader);
7704 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
7705 child_ctr = inherit_event(sub, parent, parent_ctx,
7706 child, leader, child_ctx);
7707 if (IS_ERR(child_ctr))
7708 return PTR_ERR(child_ctr);
7714 inherit_task_group(struct perf_event *event, struct task_struct *parent,
7715 struct perf_event_context *parent_ctx,
7716 struct task_struct *child, int ctxn,
7720 struct perf_event_context *child_ctx;
7722 if (!event->attr.inherit) {
7727 child_ctx = child->perf_event_ctxp[ctxn];
7730 * This is executed from the parent task context, so
7731 * inherit events that have been marked for cloning.
7732 * First allocate and initialize a context for the
7736 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
7740 child->perf_event_ctxp[ctxn] = child_ctx;
7743 ret = inherit_group(event, parent, parent_ctx,
7753 * Initialize the perf_event context in task_struct
7755 int perf_event_init_context(struct task_struct *child, int ctxn)
7757 struct perf_event_context *child_ctx, *parent_ctx;
7758 struct perf_event_context *cloned_ctx;
7759 struct perf_event *event;
7760 struct task_struct *parent = current;
7761 int inherited_all = 1;
7762 unsigned long flags;
7765 if (likely(!parent->perf_event_ctxp[ctxn]))
7769 * If the parent's context is a clone, pin it so it won't get
7772 parent_ctx = perf_pin_task_context(parent, ctxn);
7775 * No need to check if parent_ctx != NULL here; since we saw
7776 * it non-NULL earlier, the only reason for it to become NULL
7777 * is if we exit, and since we're currently in the middle of
7778 * a fork we can't be exiting at the same time.
7782 * Lock the parent list. No need to lock the child - not PID
7783 * hashed yet and not running, so nobody can access it.
7785 mutex_lock(&parent_ctx->mutex);
7788 * We dont have to disable NMIs - we are only looking at
7789 * the list, not manipulating it:
7791 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
7792 ret = inherit_task_group(event, parent, parent_ctx,
7793 child, ctxn, &inherited_all);
7799 * We can't hold ctx->lock when iterating the ->flexible_group list due
7800 * to allocations, but we need to prevent rotation because
7801 * rotate_ctx() will change the list from interrupt context.
7803 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7804 parent_ctx->rotate_disable = 1;
7805 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7807 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
7808 ret = inherit_task_group(event, parent, parent_ctx,
7809 child, ctxn, &inherited_all);
7814 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7815 parent_ctx->rotate_disable = 0;
7817 child_ctx = child->perf_event_ctxp[ctxn];
7819 if (child_ctx && inherited_all) {
7821 * Mark the child context as a clone of the parent
7822 * context, or of whatever the parent is a clone of.
7824 * Note that if the parent is a clone, the holding of
7825 * parent_ctx->lock avoids it from being uncloned.
7827 cloned_ctx = parent_ctx->parent_ctx;
7829 child_ctx->parent_ctx = cloned_ctx;
7830 child_ctx->parent_gen = parent_ctx->parent_gen;
7832 child_ctx->parent_ctx = parent_ctx;
7833 child_ctx->parent_gen = parent_ctx->generation;
7835 get_ctx(child_ctx->parent_ctx);
7838 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7839 mutex_unlock(&parent_ctx->mutex);
7841 perf_unpin_context(parent_ctx);
7842 put_ctx(parent_ctx);
7848 * Initialize the perf_event context in task_struct
7850 int perf_event_init_task(struct task_struct *child)
7854 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
7855 mutex_init(&child->perf_event_mutex);
7856 INIT_LIST_HEAD(&child->perf_event_list);
7858 for_each_task_context_nr(ctxn) {
7859 ret = perf_event_init_context(child, ctxn);
7861 perf_event_free_task(child);
7869 static void __init perf_event_init_all_cpus(void)
7871 struct swevent_htable *swhash;
7874 for_each_possible_cpu(cpu) {
7875 swhash = &per_cpu(swevent_htable, cpu);
7876 mutex_init(&swhash->hlist_mutex);
7877 INIT_LIST_HEAD(&per_cpu(rotation_list, cpu));
7881 static void perf_event_init_cpu(int cpu)
7883 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7885 mutex_lock(&swhash->hlist_mutex);
7886 swhash->online = true;
7887 if (swhash->hlist_refcount > 0) {
7888 struct swevent_hlist *hlist;
7890 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
7892 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7894 mutex_unlock(&swhash->hlist_mutex);
7897 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC
7898 static void perf_pmu_rotate_stop(struct pmu *pmu)
7900 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7902 WARN_ON(!irqs_disabled());
7904 list_del_init(&cpuctx->rotation_list);
7907 static void __perf_event_exit_context(void *__info)
7909 struct remove_event re = { .detach_group = false };
7910 struct perf_event_context *ctx = __info;
7912 perf_pmu_rotate_stop(ctx->pmu);
7915 list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
7916 __perf_remove_from_context(&re);
7920 static void perf_event_exit_cpu_context(int cpu)
7922 struct perf_event_context *ctx;
7926 idx = srcu_read_lock(&pmus_srcu);
7927 list_for_each_entry_rcu(pmu, &pmus, entry) {
7928 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
7930 mutex_lock(&ctx->mutex);
7931 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
7932 mutex_unlock(&ctx->mutex);
7934 srcu_read_unlock(&pmus_srcu, idx);
7937 static void perf_event_exit_cpu(int cpu)
7939 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7941 perf_event_exit_cpu_context(cpu);
7943 mutex_lock(&swhash->hlist_mutex);
7944 swhash->online = false;
7945 swevent_hlist_release(swhash);
7946 mutex_unlock(&swhash->hlist_mutex);
7949 static inline void perf_event_exit_cpu(int cpu) { }
7953 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
7957 for_each_online_cpu(cpu)
7958 perf_event_exit_cpu(cpu);
7964 * Run the perf reboot notifier at the very last possible moment so that
7965 * the generic watchdog code runs as long as possible.
7967 static struct notifier_block perf_reboot_notifier = {
7968 .notifier_call = perf_reboot,
7969 .priority = INT_MIN,
7973 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
7975 unsigned int cpu = (long)hcpu;
7977 switch (action & ~CPU_TASKS_FROZEN) {
7979 case CPU_UP_PREPARE:
7980 case CPU_DOWN_FAILED:
7981 perf_event_init_cpu(cpu);
7984 case CPU_UP_CANCELED:
7985 case CPU_DOWN_PREPARE:
7986 perf_event_exit_cpu(cpu);
7995 void __init perf_event_init(void)
8001 perf_event_init_all_cpus();
8002 init_srcu_struct(&pmus_srcu);
8003 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
8004 perf_pmu_register(&perf_cpu_clock, NULL, -1);
8005 perf_pmu_register(&perf_task_clock, NULL, -1);
8007 perf_cpu_notifier(perf_cpu_notify);
8008 register_reboot_notifier(&perf_reboot_notifier);
8010 ret = init_hw_breakpoint();
8011 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
8013 /* do not patch jump label more than once per second */
8014 jump_label_rate_limit(&perf_sched_events, HZ);
8017 * Build time assertion that we keep the data_head at the intended
8018 * location. IOW, validation we got the __reserved[] size right.
8020 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
8024 static int __init perf_event_sysfs_init(void)
8029 mutex_lock(&pmus_lock);
8031 ret = bus_register(&pmu_bus);
8035 list_for_each_entry(pmu, &pmus, entry) {
8036 if (!pmu->name || pmu->type < 0)
8039 ret = pmu_dev_alloc(pmu);
8040 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
8042 pmu_bus_running = 1;
8046 mutex_unlock(&pmus_lock);
8050 device_initcall(perf_event_sysfs_init);
8052 #ifdef CONFIG_CGROUP_PERF
8053 static struct cgroup_subsys_state *
8054 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
8056 struct perf_cgroup *jc;
8058 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
8060 return ERR_PTR(-ENOMEM);
8062 jc->info = alloc_percpu(struct perf_cgroup_info);
8065 return ERR_PTR(-ENOMEM);
8071 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
8073 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
8075 free_percpu(jc->info);
8079 static int __perf_cgroup_move(void *info)
8081 struct task_struct *task = info;
8082 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
8086 static void perf_cgroup_attach(struct cgroup_subsys_state *css,
8087 struct cgroup_taskset *tset)
8089 struct task_struct *task;
8091 cgroup_taskset_for_each(task, css, tset)
8092 task_function_call(task, __perf_cgroup_move, task);
8095 static void perf_cgroup_exit(struct cgroup_subsys_state *css,
8096 struct cgroup_subsys_state *old_css,
8097 struct task_struct *task)
8100 * cgroup_exit() is called in the copy_process() failure path.
8101 * Ignore this case since the task hasn't ran yet, this avoids
8102 * trying to poke a half freed task state from generic code.
8104 if (!(task->flags & PF_EXITING))
8107 task_function_call(task, __perf_cgroup_move, task);
8110 struct cgroup_subsys perf_subsys = {
8111 .name = "perf_event",
8112 .subsys_id = perf_subsys_id,
8113 .css_alloc = perf_cgroup_css_alloc,
8114 .css_free = perf_cgroup_css_free,
8115 .exit = perf_cgroup_exit,
8116 .attach = perf_cgroup_attach,
8118 #endif /* CONFIG_CGROUP_PERF */