2 * Performance events core code:
4 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
5 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
6 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
7 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
9 * For licensing details see kernel-base/COPYING
14 #include <linux/cpu.h>
15 #include <linux/smp.h>
16 #include <linux/idr.h>
17 #include <linux/file.h>
18 #include <linux/poll.h>
19 #include <linux/slab.h>
20 #include <linux/hash.h>
21 #include <linux/tick.h>
22 #include <linux/sysfs.h>
23 #include <linux/dcache.h>
24 #include <linux/percpu.h>
25 #include <linux/ptrace.h>
26 #include <linux/reboot.h>
27 #include <linux/vmstat.h>
28 #include <linux/device.h>
29 #include <linux/export.h>
30 #include <linux/vmalloc.h>
31 #include <linux/hardirq.h>
32 #include <linux/rculist.h>
33 #include <linux/uaccess.h>
34 #include <linux/syscalls.h>
35 #include <linux/anon_inodes.h>
36 #include <linux/kernel_stat.h>
37 #include <linux/perf_event.h>
38 #include <linux/ftrace_event.h>
39 #include <linux/hw_breakpoint.h>
40 #include <linux/mm_types.h>
41 #include <linux/cgroup.h>
42 #include <linux/module.h>
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 static void perf_duration_warn(struct irq_work *w)
237 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
238 u64 avg_local_sample_len;
239 u64 local_samples_len;
241 local_samples_len = __get_cpu_var(running_sample_length);
242 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
244 printk_ratelimited(KERN_WARNING
245 "perf interrupt took too long (%lld > %lld), lowering "
246 "kernel.perf_event_max_sample_rate to %d\n",
247 avg_local_sample_len, allowed_ns >> 1,
248 sysctl_perf_event_sample_rate);
251 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
253 void perf_sample_event_took(u64 sample_len_ns)
255 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
256 u64 avg_local_sample_len;
257 u64 local_samples_len;
262 /* decay the counter by 1 average sample */
263 local_samples_len = __get_cpu_var(running_sample_length);
264 local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES;
265 local_samples_len += sample_len_ns;
266 __get_cpu_var(running_sample_length) = local_samples_len;
269 * note: this will be biased artifically low until we have
270 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
271 * from having to maintain a count.
273 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
275 if (avg_local_sample_len <= allowed_ns)
278 if (max_samples_per_tick <= 1)
281 max_samples_per_tick = DIV_ROUND_UP(max_samples_per_tick, 2);
282 sysctl_perf_event_sample_rate = max_samples_per_tick * HZ;
283 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
285 update_perf_cpu_limits();
287 if (!irq_work_queue(&perf_duration_work)) {
288 early_printk("perf interrupt took too long (%lld > %lld), lowering "
289 "kernel.perf_event_max_sample_rate to %d\n",
290 avg_local_sample_len, allowed_ns >> 1,
291 sysctl_perf_event_sample_rate);
295 static atomic64_t perf_event_id;
297 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
298 enum event_type_t event_type);
300 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
301 enum event_type_t event_type,
302 struct task_struct *task);
304 static void update_context_time(struct perf_event_context *ctx);
305 static u64 perf_event_time(struct perf_event *event);
307 void __weak perf_event_print_debug(void) { }
309 extern __weak const char *perf_pmu_name(void)
314 static inline u64 perf_clock(void)
316 return local_clock();
319 static inline struct perf_cpu_context *
320 __get_cpu_context(struct perf_event_context *ctx)
322 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
325 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
326 struct perf_event_context *ctx)
328 raw_spin_lock(&cpuctx->ctx.lock);
330 raw_spin_lock(&ctx->lock);
333 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
334 struct perf_event_context *ctx)
337 raw_spin_unlock(&ctx->lock);
338 raw_spin_unlock(&cpuctx->ctx.lock);
341 #ifdef CONFIG_CGROUP_PERF
344 * perf_cgroup_info keeps track of time_enabled for a cgroup.
345 * This is a per-cpu dynamically allocated data structure.
347 struct perf_cgroup_info {
353 struct cgroup_subsys_state css;
354 struct perf_cgroup_info __percpu *info;
358 * Must ensure cgroup is pinned (css_get) before calling
359 * this function. In other words, we cannot call this function
360 * if there is no cgroup event for the current CPU context.
362 static inline struct perf_cgroup *
363 perf_cgroup_from_task(struct task_struct *task)
365 return container_of(task_css(task, perf_event_cgrp_id),
366 struct perf_cgroup, css);
370 perf_cgroup_match(struct perf_event *event)
372 struct perf_event_context *ctx = event->ctx;
373 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
375 /* @event doesn't care about cgroup */
379 /* wants specific cgroup scope but @cpuctx isn't associated with any */
384 * Cgroup scoping is recursive. An event enabled for a cgroup is
385 * also enabled for all its descendant cgroups. If @cpuctx's
386 * cgroup is a descendant of @event's (the test covers identity
387 * case), it's a match.
389 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
390 event->cgrp->css.cgroup);
393 static inline void perf_put_cgroup(struct perf_event *event)
395 css_put(&event->cgrp->css);
398 static inline void perf_detach_cgroup(struct perf_event *event)
400 perf_put_cgroup(event);
404 static inline int is_cgroup_event(struct perf_event *event)
406 return event->cgrp != NULL;
409 static inline u64 perf_cgroup_event_time(struct perf_event *event)
411 struct perf_cgroup_info *t;
413 t = per_cpu_ptr(event->cgrp->info, event->cpu);
417 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
419 struct perf_cgroup_info *info;
424 info = this_cpu_ptr(cgrp->info);
426 info->time += now - info->timestamp;
427 info->timestamp = now;
430 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
432 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
434 __update_cgrp_time(cgrp_out);
437 static inline void update_cgrp_time_from_event(struct perf_event *event)
439 struct perf_cgroup *cgrp;
442 * ensure we access cgroup data only when needed and
443 * when we know the cgroup is pinned (css_get)
445 if (!is_cgroup_event(event))
448 cgrp = perf_cgroup_from_task(current);
450 * Do not update time when cgroup is not active
452 if (cgrp == event->cgrp)
453 __update_cgrp_time(event->cgrp);
457 perf_cgroup_set_timestamp(struct task_struct *task,
458 struct perf_event_context *ctx)
460 struct perf_cgroup *cgrp;
461 struct perf_cgroup_info *info;
464 * ctx->lock held by caller
465 * ensure we do not access cgroup data
466 * unless we have the cgroup pinned (css_get)
468 if (!task || !ctx->nr_cgroups)
471 cgrp = perf_cgroup_from_task(task);
472 info = this_cpu_ptr(cgrp->info);
473 info->timestamp = ctx->timestamp;
476 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
477 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
480 * reschedule events based on the cgroup constraint of task.
482 * mode SWOUT : schedule out everything
483 * mode SWIN : schedule in based on cgroup for next
485 void perf_cgroup_switch(struct task_struct *task, int mode)
487 struct perf_cpu_context *cpuctx;
492 * disable interrupts to avoid geting nr_cgroup
493 * changes via __perf_event_disable(). Also
496 local_irq_save(flags);
499 * we reschedule only in the presence of cgroup
500 * constrained events.
504 list_for_each_entry_rcu(pmu, &pmus, entry) {
505 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
506 if (cpuctx->unique_pmu != pmu)
507 continue; /* ensure we process each cpuctx once */
510 * perf_cgroup_events says at least one
511 * context on this CPU has cgroup events.
513 * ctx->nr_cgroups reports the number of cgroup
514 * events for a context.
516 if (cpuctx->ctx.nr_cgroups > 0) {
517 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
518 perf_pmu_disable(cpuctx->ctx.pmu);
520 if (mode & PERF_CGROUP_SWOUT) {
521 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
523 * must not be done before ctxswout due
524 * to event_filter_match() in event_sched_out()
529 if (mode & PERF_CGROUP_SWIN) {
530 WARN_ON_ONCE(cpuctx->cgrp);
532 * set cgrp before ctxsw in to allow
533 * event_filter_match() to not have to pass
536 cpuctx->cgrp = perf_cgroup_from_task(task);
537 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
539 perf_pmu_enable(cpuctx->ctx.pmu);
540 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
546 local_irq_restore(flags);
549 static inline void perf_cgroup_sched_out(struct task_struct *task,
550 struct task_struct *next)
552 struct perf_cgroup *cgrp1;
553 struct perf_cgroup *cgrp2 = NULL;
556 * we come here when we know perf_cgroup_events > 0
558 cgrp1 = perf_cgroup_from_task(task);
561 * next is NULL when called from perf_event_enable_on_exec()
562 * that will systematically cause a cgroup_switch()
565 cgrp2 = perf_cgroup_from_task(next);
568 * only schedule out current cgroup events if we know
569 * that we are switching to a different cgroup. Otherwise,
570 * do no touch the cgroup events.
573 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
576 static inline void perf_cgroup_sched_in(struct task_struct *prev,
577 struct task_struct *task)
579 struct perf_cgroup *cgrp1;
580 struct perf_cgroup *cgrp2 = NULL;
583 * we come here when we know perf_cgroup_events > 0
585 cgrp1 = perf_cgroup_from_task(task);
587 /* prev can never be NULL */
588 cgrp2 = perf_cgroup_from_task(prev);
591 * only need to schedule in cgroup events if we are changing
592 * cgroup during ctxsw. Cgroup events were not scheduled
593 * out of ctxsw out if that was not the case.
596 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
599 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
600 struct perf_event_attr *attr,
601 struct perf_event *group_leader)
603 struct perf_cgroup *cgrp;
604 struct cgroup_subsys_state *css;
605 struct fd f = fdget(fd);
611 css = css_tryget_online_from_dir(f.file->f_dentry,
612 &perf_event_cgrp_subsys);
618 cgrp = container_of(css, struct perf_cgroup, css);
622 * all events in a group must monitor
623 * the same cgroup because a task belongs
624 * to only one perf cgroup at a time
626 if (group_leader && group_leader->cgrp != cgrp) {
627 perf_detach_cgroup(event);
636 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
638 struct perf_cgroup_info *t;
639 t = per_cpu_ptr(event->cgrp->info, event->cpu);
640 event->shadow_ctx_time = now - t->timestamp;
644 perf_cgroup_defer_enabled(struct perf_event *event)
647 * when the current task's perf cgroup does not match
648 * the event's, we need to remember to call the
649 * perf_mark_enable() function the first time a task with
650 * a matching perf cgroup is scheduled in.
652 if (is_cgroup_event(event) && !perf_cgroup_match(event))
653 event->cgrp_defer_enabled = 1;
657 perf_cgroup_mark_enabled(struct perf_event *event,
658 struct perf_event_context *ctx)
660 struct perf_event *sub;
661 u64 tstamp = perf_event_time(event);
663 if (!event->cgrp_defer_enabled)
666 event->cgrp_defer_enabled = 0;
668 event->tstamp_enabled = tstamp - event->total_time_enabled;
669 list_for_each_entry(sub, &event->sibling_list, group_entry) {
670 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
671 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
672 sub->cgrp_defer_enabled = 0;
676 #else /* !CONFIG_CGROUP_PERF */
679 perf_cgroup_match(struct perf_event *event)
684 static inline void perf_detach_cgroup(struct perf_event *event)
687 static inline int is_cgroup_event(struct perf_event *event)
692 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
697 static inline void update_cgrp_time_from_event(struct perf_event *event)
701 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
705 static inline void perf_cgroup_sched_out(struct task_struct *task,
706 struct task_struct *next)
710 static inline void perf_cgroup_sched_in(struct task_struct *prev,
711 struct task_struct *task)
715 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
716 struct perf_event_attr *attr,
717 struct perf_event *group_leader)
723 perf_cgroup_set_timestamp(struct task_struct *task,
724 struct perf_event_context *ctx)
729 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
734 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
738 static inline u64 perf_cgroup_event_time(struct perf_event *event)
744 perf_cgroup_defer_enabled(struct perf_event *event)
749 perf_cgroup_mark_enabled(struct perf_event *event,
750 struct perf_event_context *ctx)
756 * set default to be dependent on timer tick just
759 #define PERF_CPU_HRTIMER (1000 / HZ)
761 * function must be called with interrupts disbled
763 static enum hrtimer_restart perf_cpu_hrtimer_handler(struct hrtimer *hr)
765 struct perf_cpu_context *cpuctx;
766 enum hrtimer_restart ret = HRTIMER_NORESTART;
769 WARN_ON(!irqs_disabled());
771 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
773 rotations = perf_rotate_context(cpuctx);
776 * arm timer if needed
779 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
780 ret = HRTIMER_RESTART;
786 /* CPU is going down */
787 void perf_cpu_hrtimer_cancel(int cpu)
789 struct perf_cpu_context *cpuctx;
793 if (WARN_ON(cpu != smp_processor_id()))
796 local_irq_save(flags);
800 list_for_each_entry_rcu(pmu, &pmus, entry) {
801 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
803 if (pmu->task_ctx_nr == perf_sw_context)
806 hrtimer_cancel(&cpuctx->hrtimer);
811 local_irq_restore(flags);
814 static void __perf_cpu_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
816 struct hrtimer *hr = &cpuctx->hrtimer;
817 struct pmu *pmu = cpuctx->ctx.pmu;
820 /* no multiplexing needed for SW PMU */
821 if (pmu->task_ctx_nr == perf_sw_context)
825 * check default is sane, if not set then force to
826 * default interval (1/tick)
828 timer = pmu->hrtimer_interval_ms;
830 timer = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
832 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
834 hrtimer_init(hr, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
835 hr->function = perf_cpu_hrtimer_handler;
838 static void perf_cpu_hrtimer_restart(struct perf_cpu_context *cpuctx)
840 struct hrtimer *hr = &cpuctx->hrtimer;
841 struct pmu *pmu = cpuctx->ctx.pmu;
844 if (pmu->task_ctx_nr == perf_sw_context)
847 if (hrtimer_active(hr))
850 if (!hrtimer_callback_running(hr))
851 __hrtimer_start_range_ns(hr, cpuctx->hrtimer_interval,
852 0, HRTIMER_MODE_REL_PINNED, 0);
855 void perf_pmu_disable(struct pmu *pmu)
857 int *count = this_cpu_ptr(pmu->pmu_disable_count);
859 pmu->pmu_disable(pmu);
862 void perf_pmu_enable(struct pmu *pmu)
864 int *count = this_cpu_ptr(pmu->pmu_disable_count);
866 pmu->pmu_enable(pmu);
869 static DEFINE_PER_CPU(struct list_head, rotation_list);
872 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
873 * because they're strictly cpu affine and rotate_start is called with IRQs
874 * disabled, while rotate_context is called from IRQ context.
876 static void perf_pmu_rotate_start(struct pmu *pmu)
878 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
879 struct list_head *head = &__get_cpu_var(rotation_list);
881 WARN_ON(!irqs_disabled());
883 if (list_empty(&cpuctx->rotation_list))
884 list_add(&cpuctx->rotation_list, head);
887 static void get_ctx(struct perf_event_context *ctx)
889 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
892 static void put_ctx(struct perf_event_context *ctx)
894 if (atomic_dec_and_test(&ctx->refcount)) {
896 put_ctx(ctx->parent_ctx);
898 put_task_struct(ctx->task);
899 kfree_rcu(ctx, rcu_head);
903 static void unclone_ctx(struct perf_event_context *ctx)
905 if (ctx->parent_ctx) {
906 put_ctx(ctx->parent_ctx);
907 ctx->parent_ctx = NULL;
912 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
915 * only top level events have the pid namespace they were created in
918 event = event->parent;
920 return task_tgid_nr_ns(p, event->ns);
923 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
926 * only top level events have the pid namespace they were created in
929 event = event->parent;
931 return task_pid_nr_ns(p, event->ns);
935 * If we inherit events we want to return the parent event id
938 static u64 primary_event_id(struct perf_event *event)
943 id = event->parent->id;
949 * Get the perf_event_context for a task and lock it.
950 * This has to cope with with the fact that until it is locked,
951 * the context could get moved to another task.
953 static struct perf_event_context *
954 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
956 struct perf_event_context *ctx;
960 * One of the few rules of preemptible RCU is that one cannot do
961 * rcu_read_unlock() while holding a scheduler (or nested) lock when
962 * part of the read side critical section was preemptible -- see
963 * rcu_read_unlock_special().
965 * Since ctx->lock nests under rq->lock we must ensure the entire read
966 * side critical section is non-preemptible.
970 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
973 * If this context is a clone of another, it might
974 * get swapped for another underneath us by
975 * perf_event_task_sched_out, though the
976 * rcu_read_lock() protects us from any context
977 * getting freed. Lock the context and check if it
978 * got swapped before we could get the lock, and retry
979 * if so. If we locked the right context, then it
980 * can't get swapped on us any more.
982 raw_spin_lock_irqsave(&ctx->lock, *flags);
983 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
984 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
990 if (!atomic_inc_not_zero(&ctx->refcount)) {
991 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
1001 * Get the context for a task and increment its pin_count so it
1002 * can't get swapped to another task. This also increments its
1003 * reference count so that the context can't get freed.
1005 static struct perf_event_context *
1006 perf_pin_task_context(struct task_struct *task, int ctxn)
1008 struct perf_event_context *ctx;
1009 unsigned long flags;
1011 ctx = perf_lock_task_context(task, ctxn, &flags);
1014 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1019 static void perf_unpin_context(struct perf_event_context *ctx)
1021 unsigned long flags;
1023 raw_spin_lock_irqsave(&ctx->lock, flags);
1025 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1029 * Update the record of the current time in a context.
1031 static void update_context_time(struct perf_event_context *ctx)
1033 u64 now = perf_clock();
1035 ctx->time += now - ctx->timestamp;
1036 ctx->timestamp = now;
1039 static u64 perf_event_time(struct perf_event *event)
1041 struct perf_event_context *ctx = event->ctx;
1043 if (is_cgroup_event(event))
1044 return perf_cgroup_event_time(event);
1046 return ctx ? ctx->time : 0;
1050 * Update the total_time_enabled and total_time_running fields for a event.
1051 * The caller of this function needs to hold the ctx->lock.
1053 static void update_event_times(struct perf_event *event)
1055 struct perf_event_context *ctx = event->ctx;
1058 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1059 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1062 * in cgroup mode, time_enabled represents
1063 * the time the event was enabled AND active
1064 * tasks were in the monitored cgroup. This is
1065 * independent of the activity of the context as
1066 * there may be a mix of cgroup and non-cgroup events.
1068 * That is why we treat cgroup events differently
1071 if (is_cgroup_event(event))
1072 run_end = perf_cgroup_event_time(event);
1073 else if (ctx->is_active)
1074 run_end = ctx->time;
1076 run_end = event->tstamp_stopped;
1078 event->total_time_enabled = run_end - event->tstamp_enabled;
1080 if (event->state == PERF_EVENT_STATE_INACTIVE)
1081 run_end = event->tstamp_stopped;
1083 run_end = perf_event_time(event);
1085 event->total_time_running = run_end - event->tstamp_running;
1090 * Update total_time_enabled and total_time_running for all events in a group.
1092 static void update_group_times(struct perf_event *leader)
1094 struct perf_event *event;
1096 update_event_times(leader);
1097 list_for_each_entry(event, &leader->sibling_list, group_entry)
1098 update_event_times(event);
1101 static struct list_head *
1102 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1104 if (event->attr.pinned)
1105 return &ctx->pinned_groups;
1107 return &ctx->flexible_groups;
1111 * Add a event from the lists for its context.
1112 * Must be called with ctx->mutex and ctx->lock held.
1115 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1117 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1118 event->attach_state |= PERF_ATTACH_CONTEXT;
1121 * If we're a stand alone event or group leader, we go to the context
1122 * list, group events are kept attached to the group so that
1123 * perf_group_detach can, at all times, locate all siblings.
1125 if (event->group_leader == event) {
1126 struct list_head *list;
1128 if (is_software_event(event))
1129 event->group_flags |= PERF_GROUP_SOFTWARE;
1131 list = ctx_group_list(event, ctx);
1132 list_add_tail(&event->group_entry, list);
1135 if (is_cgroup_event(event))
1138 if (has_branch_stack(event))
1139 ctx->nr_branch_stack++;
1141 list_add_rcu(&event->event_entry, &ctx->event_list);
1142 if (!ctx->nr_events)
1143 perf_pmu_rotate_start(ctx->pmu);
1145 if (event->attr.inherit_stat)
1152 * Initialize event state based on the perf_event_attr::disabled.
1154 static inline void perf_event__state_init(struct perf_event *event)
1156 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1157 PERF_EVENT_STATE_INACTIVE;
1161 * Called at perf_event creation and when events are attached/detached from a
1164 static void perf_event__read_size(struct perf_event *event)
1166 int entry = sizeof(u64); /* value */
1170 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1171 size += sizeof(u64);
1173 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1174 size += sizeof(u64);
1176 if (event->attr.read_format & PERF_FORMAT_ID)
1177 entry += sizeof(u64);
1179 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1180 nr += event->group_leader->nr_siblings;
1181 size += sizeof(u64);
1185 event->read_size = size;
1188 static void perf_event__header_size(struct perf_event *event)
1190 struct perf_sample_data *data;
1191 u64 sample_type = event->attr.sample_type;
1194 perf_event__read_size(event);
1196 if (sample_type & PERF_SAMPLE_IP)
1197 size += sizeof(data->ip);
1199 if (sample_type & PERF_SAMPLE_ADDR)
1200 size += sizeof(data->addr);
1202 if (sample_type & PERF_SAMPLE_PERIOD)
1203 size += sizeof(data->period);
1205 if (sample_type & PERF_SAMPLE_WEIGHT)
1206 size += sizeof(data->weight);
1208 if (sample_type & PERF_SAMPLE_READ)
1209 size += event->read_size;
1211 if (sample_type & PERF_SAMPLE_DATA_SRC)
1212 size += sizeof(data->data_src.val);
1214 if (sample_type & PERF_SAMPLE_TRANSACTION)
1215 size += sizeof(data->txn);
1217 event->header_size = size;
1220 static void perf_event__id_header_size(struct perf_event *event)
1222 struct perf_sample_data *data;
1223 u64 sample_type = event->attr.sample_type;
1226 if (sample_type & PERF_SAMPLE_TID)
1227 size += sizeof(data->tid_entry);
1229 if (sample_type & PERF_SAMPLE_TIME)
1230 size += sizeof(data->time);
1232 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1233 size += sizeof(data->id);
1235 if (sample_type & PERF_SAMPLE_ID)
1236 size += sizeof(data->id);
1238 if (sample_type & PERF_SAMPLE_STREAM_ID)
1239 size += sizeof(data->stream_id);
1241 if (sample_type & PERF_SAMPLE_CPU)
1242 size += sizeof(data->cpu_entry);
1244 event->id_header_size = size;
1247 static void perf_group_attach(struct perf_event *event)
1249 struct perf_event *group_leader = event->group_leader, *pos;
1252 * We can have double attach due to group movement in perf_event_open.
1254 if (event->attach_state & PERF_ATTACH_GROUP)
1257 event->attach_state |= PERF_ATTACH_GROUP;
1259 if (group_leader == event)
1262 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1263 !is_software_event(event))
1264 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1266 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1267 group_leader->nr_siblings++;
1269 perf_event__header_size(group_leader);
1271 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1272 perf_event__header_size(pos);
1276 * Remove a event from the lists for its context.
1277 * Must be called with ctx->mutex and ctx->lock held.
1280 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1282 struct perf_cpu_context *cpuctx;
1284 * We can have double detach due to exit/hot-unplug + close.
1286 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1289 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1291 if (is_cgroup_event(event)) {
1293 cpuctx = __get_cpu_context(ctx);
1295 * if there are no more cgroup events
1296 * then cler cgrp to avoid stale pointer
1297 * in update_cgrp_time_from_cpuctx()
1299 if (!ctx->nr_cgroups)
1300 cpuctx->cgrp = NULL;
1303 if (has_branch_stack(event))
1304 ctx->nr_branch_stack--;
1307 if (event->attr.inherit_stat)
1310 list_del_rcu(&event->event_entry);
1312 if (event->group_leader == event)
1313 list_del_init(&event->group_entry);
1315 update_group_times(event);
1318 * If event was in error state, then keep it
1319 * that way, otherwise bogus counts will be
1320 * returned on read(). The only way to get out
1321 * of error state is by explicit re-enabling
1324 if (event->state > PERF_EVENT_STATE_OFF)
1325 event->state = PERF_EVENT_STATE_OFF;
1330 static void perf_group_detach(struct perf_event *event)
1332 struct perf_event *sibling, *tmp;
1333 struct list_head *list = NULL;
1336 * We can have double detach due to exit/hot-unplug + close.
1338 if (!(event->attach_state & PERF_ATTACH_GROUP))
1341 event->attach_state &= ~PERF_ATTACH_GROUP;
1344 * If this is a sibling, remove it from its group.
1346 if (event->group_leader != event) {
1347 list_del_init(&event->group_entry);
1348 event->group_leader->nr_siblings--;
1352 if (!list_empty(&event->group_entry))
1353 list = &event->group_entry;
1356 * If this was a group event with sibling events then
1357 * upgrade the siblings to singleton events by adding them
1358 * to whatever list we are on.
1360 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1362 list_move_tail(&sibling->group_entry, list);
1363 sibling->group_leader = sibling;
1365 /* Inherit group flags from the previous leader */
1366 sibling->group_flags = event->group_flags;
1370 perf_event__header_size(event->group_leader);
1372 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1373 perf_event__header_size(tmp);
1377 event_filter_match(struct perf_event *event)
1379 return (event->cpu == -1 || event->cpu == smp_processor_id())
1380 && perf_cgroup_match(event);
1384 event_sched_out(struct perf_event *event,
1385 struct perf_cpu_context *cpuctx,
1386 struct perf_event_context *ctx)
1388 u64 tstamp = perf_event_time(event);
1391 * An event which could not be activated because of
1392 * filter mismatch still needs to have its timings
1393 * maintained, otherwise bogus information is return
1394 * via read() for time_enabled, time_running:
1396 if (event->state == PERF_EVENT_STATE_INACTIVE
1397 && !event_filter_match(event)) {
1398 delta = tstamp - event->tstamp_stopped;
1399 event->tstamp_running += delta;
1400 event->tstamp_stopped = tstamp;
1403 if (event->state != PERF_EVENT_STATE_ACTIVE)
1406 perf_pmu_disable(event->pmu);
1408 event->state = PERF_EVENT_STATE_INACTIVE;
1409 if (event->pending_disable) {
1410 event->pending_disable = 0;
1411 event->state = PERF_EVENT_STATE_OFF;
1413 event->tstamp_stopped = tstamp;
1414 event->pmu->del(event, 0);
1417 if (!is_software_event(event))
1418 cpuctx->active_oncpu--;
1420 if (event->attr.freq && event->attr.sample_freq)
1422 if (event->attr.exclusive || !cpuctx->active_oncpu)
1423 cpuctx->exclusive = 0;
1425 perf_pmu_enable(event->pmu);
1429 group_sched_out(struct perf_event *group_event,
1430 struct perf_cpu_context *cpuctx,
1431 struct perf_event_context *ctx)
1433 struct perf_event *event;
1434 int state = group_event->state;
1436 event_sched_out(group_event, cpuctx, ctx);
1439 * Schedule out siblings (if any):
1441 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1442 event_sched_out(event, cpuctx, ctx);
1444 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1445 cpuctx->exclusive = 0;
1448 struct remove_event {
1449 struct perf_event *event;
1454 * Cross CPU call to remove a performance event
1456 * We disable the event on the hardware level first. After that we
1457 * remove it from the context list.
1459 static int __perf_remove_from_context(void *info)
1461 struct remove_event *re = info;
1462 struct perf_event *event = re->event;
1463 struct perf_event_context *ctx = event->ctx;
1464 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1466 raw_spin_lock(&ctx->lock);
1467 event_sched_out(event, cpuctx, ctx);
1468 if (re->detach_group)
1469 perf_group_detach(event);
1470 list_del_event(event, ctx);
1471 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1473 cpuctx->task_ctx = NULL;
1475 raw_spin_unlock(&ctx->lock);
1482 * Remove the event from a task's (or a CPU's) list of events.
1484 * CPU events are removed with a smp call. For task events we only
1485 * call when the task is on a CPU.
1487 * If event->ctx is a cloned context, callers must make sure that
1488 * every task struct that event->ctx->task could possibly point to
1489 * remains valid. This is OK when called from perf_release since
1490 * that only calls us on the top-level context, which can't be a clone.
1491 * When called from perf_event_exit_task, it's OK because the
1492 * context has been detached from its task.
1494 static void perf_remove_from_context(struct perf_event *event, bool detach_group)
1496 struct perf_event_context *ctx = event->ctx;
1497 struct task_struct *task = ctx->task;
1498 struct remove_event re = {
1500 .detach_group = detach_group,
1503 lockdep_assert_held(&ctx->mutex);
1507 * Per cpu events are removed via an smp call and
1508 * the removal is always successful.
1510 cpu_function_call(event->cpu, __perf_remove_from_context, &re);
1515 if (!task_function_call(task, __perf_remove_from_context, &re))
1518 raw_spin_lock_irq(&ctx->lock);
1520 * If we failed to find a running task, but find the context active now
1521 * that we've acquired the ctx->lock, retry.
1523 if (ctx->is_active) {
1524 raw_spin_unlock_irq(&ctx->lock);
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 lockdep_assert_held(&ctx->lock);
1684 if (event->state <= PERF_EVENT_STATE_OFF)
1687 event->state = PERF_EVENT_STATE_ACTIVE;
1688 event->oncpu = smp_processor_id();
1691 * Unthrottle events, since we scheduled we might have missed several
1692 * ticks already, also for a heavily scheduling task there is little
1693 * guarantee it'll get a tick in a timely manner.
1695 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1696 perf_log_throttle(event, 1);
1697 event->hw.interrupts = 0;
1701 * The new state must be visible before we turn it on in the hardware:
1705 perf_pmu_disable(event->pmu);
1707 if (event->pmu->add(event, PERF_EF_START)) {
1708 event->state = PERF_EVENT_STATE_INACTIVE;
1714 event->tstamp_running += tstamp - event->tstamp_stopped;
1716 perf_set_shadow_time(event, ctx, tstamp);
1718 if (!is_software_event(event))
1719 cpuctx->active_oncpu++;
1721 if (event->attr.freq && event->attr.sample_freq)
1724 if (event->attr.exclusive)
1725 cpuctx->exclusive = 1;
1728 perf_pmu_enable(event->pmu);
1734 group_sched_in(struct perf_event *group_event,
1735 struct perf_cpu_context *cpuctx,
1736 struct perf_event_context *ctx)
1738 struct perf_event *event, *partial_group = NULL;
1739 struct pmu *pmu = ctx->pmu;
1740 u64 now = ctx->time;
1741 bool simulate = false;
1743 if (group_event->state == PERF_EVENT_STATE_OFF)
1746 pmu->start_txn(pmu);
1748 if (event_sched_in(group_event, cpuctx, ctx)) {
1749 pmu->cancel_txn(pmu);
1750 perf_cpu_hrtimer_restart(cpuctx);
1755 * Schedule in siblings as one group (if any):
1757 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1758 if (event_sched_in(event, cpuctx, ctx)) {
1759 partial_group = event;
1764 if (!pmu->commit_txn(pmu))
1769 * Groups can be scheduled in as one unit only, so undo any
1770 * partial group before returning:
1771 * The events up to the failed event are scheduled out normally,
1772 * tstamp_stopped will be updated.
1774 * The failed events and the remaining siblings need to have
1775 * their timings updated as if they had gone thru event_sched_in()
1776 * and event_sched_out(). This is required to get consistent timings
1777 * across the group. This also takes care of the case where the group
1778 * could never be scheduled by ensuring tstamp_stopped is set to mark
1779 * the time the event was actually stopped, such that time delta
1780 * calculation in update_event_times() is correct.
1782 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1783 if (event == partial_group)
1787 event->tstamp_running += now - event->tstamp_stopped;
1788 event->tstamp_stopped = now;
1790 event_sched_out(event, cpuctx, ctx);
1793 event_sched_out(group_event, cpuctx, ctx);
1795 pmu->cancel_txn(pmu);
1797 perf_cpu_hrtimer_restart(cpuctx);
1803 * Work out whether we can put this event group on the CPU now.
1805 static int group_can_go_on(struct perf_event *event,
1806 struct perf_cpu_context *cpuctx,
1810 * Groups consisting entirely of software events can always go on.
1812 if (event->group_flags & PERF_GROUP_SOFTWARE)
1815 * If an exclusive group is already on, no other hardware
1818 if (cpuctx->exclusive)
1821 * If this group is exclusive and there are already
1822 * events on the CPU, it can't go on.
1824 if (event->attr.exclusive && cpuctx->active_oncpu)
1827 * Otherwise, try to add it if all previous groups were able
1833 static void add_event_to_ctx(struct perf_event *event,
1834 struct perf_event_context *ctx)
1836 u64 tstamp = perf_event_time(event);
1838 list_add_event(event, ctx);
1839 perf_group_attach(event);
1840 event->tstamp_enabled = tstamp;
1841 event->tstamp_running = tstamp;
1842 event->tstamp_stopped = tstamp;
1845 static void task_ctx_sched_out(struct perf_event_context *ctx);
1847 ctx_sched_in(struct perf_event_context *ctx,
1848 struct perf_cpu_context *cpuctx,
1849 enum event_type_t event_type,
1850 struct task_struct *task);
1852 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
1853 struct perf_event_context *ctx,
1854 struct task_struct *task)
1856 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
1858 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
1859 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
1861 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
1865 * Cross CPU call to install and enable a performance event
1867 * Must be called with ctx->mutex held
1869 static int __perf_install_in_context(void *info)
1871 struct perf_event *event = info;
1872 struct perf_event_context *ctx = event->ctx;
1873 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1874 struct perf_event_context *task_ctx = cpuctx->task_ctx;
1875 struct task_struct *task = current;
1877 perf_ctx_lock(cpuctx, task_ctx);
1878 perf_pmu_disable(cpuctx->ctx.pmu);
1881 * If there was an active task_ctx schedule it out.
1884 task_ctx_sched_out(task_ctx);
1887 * If the context we're installing events in is not the
1888 * active task_ctx, flip them.
1890 if (ctx->task && task_ctx != ctx) {
1892 raw_spin_unlock(&task_ctx->lock);
1893 raw_spin_lock(&ctx->lock);
1898 cpuctx->task_ctx = task_ctx;
1899 task = task_ctx->task;
1902 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
1904 update_context_time(ctx);
1906 * update cgrp time only if current cgrp
1907 * matches event->cgrp. Must be done before
1908 * calling add_event_to_ctx()
1910 update_cgrp_time_from_event(event);
1912 add_event_to_ctx(event, ctx);
1915 * Schedule everything back in
1917 perf_event_sched_in(cpuctx, task_ctx, task);
1919 perf_pmu_enable(cpuctx->ctx.pmu);
1920 perf_ctx_unlock(cpuctx, task_ctx);
1926 * Attach a performance event to a context
1928 * First we add the event to the list with the hardware enable bit
1929 * in event->hw_config cleared.
1931 * If the event is attached to a task which is on a CPU we use a smp
1932 * call to enable it in the task context. The task might have been
1933 * scheduled away, but we check this in the smp call again.
1936 perf_install_in_context(struct perf_event_context *ctx,
1937 struct perf_event *event,
1940 struct task_struct *task = ctx->task;
1942 lockdep_assert_held(&ctx->mutex);
1945 if (event->cpu != -1)
1950 * Per cpu events are installed via an smp call and
1951 * the install is always successful.
1953 cpu_function_call(cpu, __perf_install_in_context, event);
1958 if (!task_function_call(task, __perf_install_in_context, event))
1961 raw_spin_lock_irq(&ctx->lock);
1963 * If we failed to find a running task, but find the context active now
1964 * that we've acquired the ctx->lock, retry.
1966 if (ctx->is_active) {
1967 raw_spin_unlock_irq(&ctx->lock);
1972 * Since the task isn't running, its safe to add the event, us holding
1973 * the ctx->lock ensures the task won't get scheduled in.
1975 add_event_to_ctx(event, ctx);
1976 raw_spin_unlock_irq(&ctx->lock);
1980 * Put a event into inactive state and update time fields.
1981 * Enabling the leader of a group effectively enables all
1982 * the group members that aren't explicitly disabled, so we
1983 * have to update their ->tstamp_enabled also.
1984 * Note: this works for group members as well as group leaders
1985 * since the non-leader members' sibling_lists will be empty.
1987 static void __perf_event_mark_enabled(struct perf_event *event)
1989 struct perf_event *sub;
1990 u64 tstamp = perf_event_time(event);
1992 event->state = PERF_EVENT_STATE_INACTIVE;
1993 event->tstamp_enabled = tstamp - event->total_time_enabled;
1994 list_for_each_entry(sub, &event->sibling_list, group_entry) {
1995 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
1996 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2001 * Cross CPU call to enable a performance event
2003 static int __perf_event_enable(void *info)
2005 struct perf_event *event = info;
2006 struct perf_event_context *ctx = event->ctx;
2007 struct perf_event *leader = event->group_leader;
2008 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2012 * There's a time window between 'ctx->is_active' check
2013 * in perf_event_enable function and this place having:
2015 * - ctx->lock unlocked
2017 * where the task could be killed and 'ctx' deactivated
2018 * by perf_event_exit_task.
2020 if (!ctx->is_active)
2023 raw_spin_lock(&ctx->lock);
2024 update_context_time(ctx);
2026 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2030 * set current task's cgroup time reference point
2032 perf_cgroup_set_timestamp(current, ctx);
2034 __perf_event_mark_enabled(event);
2036 if (!event_filter_match(event)) {
2037 if (is_cgroup_event(event))
2038 perf_cgroup_defer_enabled(event);
2043 * If the event is in a group and isn't the group leader,
2044 * then don't put it on unless the group is on.
2046 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
2049 if (!group_can_go_on(event, cpuctx, 1)) {
2052 if (event == leader)
2053 err = group_sched_in(event, cpuctx, ctx);
2055 err = event_sched_in(event, cpuctx, ctx);
2060 * If this event can't go on and it's part of a
2061 * group, then the whole group has to come off.
2063 if (leader != event) {
2064 group_sched_out(leader, cpuctx, ctx);
2065 perf_cpu_hrtimer_restart(cpuctx);
2067 if (leader->attr.pinned) {
2068 update_group_times(leader);
2069 leader->state = PERF_EVENT_STATE_ERROR;
2074 raw_spin_unlock(&ctx->lock);
2082 * If event->ctx is a cloned context, callers must make sure that
2083 * every task struct that event->ctx->task could possibly point to
2084 * remains valid. This condition is satisfied when called through
2085 * perf_event_for_each_child or perf_event_for_each as described
2086 * for perf_event_disable.
2088 void perf_event_enable(struct perf_event *event)
2090 struct perf_event_context *ctx = event->ctx;
2091 struct task_struct *task = ctx->task;
2095 * Enable the event on the cpu that it's on
2097 cpu_function_call(event->cpu, __perf_event_enable, event);
2101 raw_spin_lock_irq(&ctx->lock);
2102 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2106 * If the event is in error state, clear that first.
2107 * That way, if we see the event in error state below, we
2108 * know that it has gone back into error state, as distinct
2109 * from the task having been scheduled away before the
2110 * cross-call arrived.
2112 if (event->state == PERF_EVENT_STATE_ERROR)
2113 event->state = PERF_EVENT_STATE_OFF;
2116 if (!ctx->is_active) {
2117 __perf_event_mark_enabled(event);
2121 raw_spin_unlock_irq(&ctx->lock);
2123 if (!task_function_call(task, __perf_event_enable, event))
2126 raw_spin_lock_irq(&ctx->lock);
2129 * If the context is active and the event is still off,
2130 * we need to retry the cross-call.
2132 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
2134 * task could have been flipped by a concurrent
2135 * perf_event_context_sched_out()
2142 raw_spin_unlock_irq(&ctx->lock);
2144 EXPORT_SYMBOL_GPL(perf_event_enable);
2146 int perf_event_refresh(struct perf_event *event, int refresh)
2149 * not supported on inherited events
2151 if (event->attr.inherit || !is_sampling_event(event))
2154 atomic_add(refresh, &event->event_limit);
2155 perf_event_enable(event);
2159 EXPORT_SYMBOL_GPL(perf_event_refresh);
2161 static void ctx_sched_out(struct perf_event_context *ctx,
2162 struct perf_cpu_context *cpuctx,
2163 enum event_type_t event_type)
2165 struct perf_event *event;
2166 int is_active = ctx->is_active;
2168 ctx->is_active &= ~event_type;
2169 if (likely(!ctx->nr_events))
2172 update_context_time(ctx);
2173 update_cgrp_time_from_cpuctx(cpuctx);
2174 if (!ctx->nr_active)
2177 perf_pmu_disable(ctx->pmu);
2178 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2179 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2180 group_sched_out(event, cpuctx, ctx);
2183 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2184 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2185 group_sched_out(event, cpuctx, ctx);
2187 perf_pmu_enable(ctx->pmu);
2191 * Test whether two contexts are equivalent, i.e. whether they have both been
2192 * cloned from the same version of the same context.
2194 * Equivalence is measured using a generation number in the context that is
2195 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2196 * and list_del_event().
2198 static int context_equiv(struct perf_event_context *ctx1,
2199 struct perf_event_context *ctx2)
2201 /* Pinning disables the swap optimization */
2202 if (ctx1->pin_count || ctx2->pin_count)
2205 /* If ctx1 is the parent of ctx2 */
2206 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2209 /* If ctx2 is the parent of ctx1 */
2210 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2214 * If ctx1 and ctx2 have the same parent; we flatten the parent
2215 * hierarchy, see perf_event_init_context().
2217 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2218 ctx1->parent_gen == ctx2->parent_gen)
2225 static void __perf_event_sync_stat(struct perf_event *event,
2226 struct perf_event *next_event)
2230 if (!event->attr.inherit_stat)
2234 * Update the event value, we cannot use perf_event_read()
2235 * because we're in the middle of a context switch and have IRQs
2236 * disabled, which upsets smp_call_function_single(), however
2237 * we know the event must be on the current CPU, therefore we
2238 * don't need to use it.
2240 switch (event->state) {
2241 case PERF_EVENT_STATE_ACTIVE:
2242 event->pmu->read(event);
2245 case PERF_EVENT_STATE_INACTIVE:
2246 update_event_times(event);
2254 * In order to keep per-task stats reliable we need to flip the event
2255 * values when we flip the contexts.
2257 value = local64_read(&next_event->count);
2258 value = local64_xchg(&event->count, value);
2259 local64_set(&next_event->count, value);
2261 swap(event->total_time_enabled, next_event->total_time_enabled);
2262 swap(event->total_time_running, next_event->total_time_running);
2265 * Since we swizzled the values, update the user visible data too.
2267 perf_event_update_userpage(event);
2268 perf_event_update_userpage(next_event);
2271 static void perf_event_sync_stat(struct perf_event_context *ctx,
2272 struct perf_event_context *next_ctx)
2274 struct perf_event *event, *next_event;
2279 update_context_time(ctx);
2281 event = list_first_entry(&ctx->event_list,
2282 struct perf_event, event_entry);
2284 next_event = list_first_entry(&next_ctx->event_list,
2285 struct perf_event, event_entry);
2287 while (&event->event_entry != &ctx->event_list &&
2288 &next_event->event_entry != &next_ctx->event_list) {
2290 __perf_event_sync_stat(event, next_event);
2292 event = list_next_entry(event, event_entry);
2293 next_event = list_next_entry(next_event, event_entry);
2297 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2298 struct task_struct *next)
2300 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2301 struct perf_event_context *next_ctx;
2302 struct perf_event_context *parent, *next_parent;
2303 struct perf_cpu_context *cpuctx;
2309 cpuctx = __get_cpu_context(ctx);
2310 if (!cpuctx->task_ctx)
2314 next_ctx = next->perf_event_ctxp[ctxn];
2318 parent = rcu_dereference(ctx->parent_ctx);
2319 next_parent = rcu_dereference(next_ctx->parent_ctx);
2321 /* If neither context have a parent context; they cannot be clones. */
2322 if (!parent && !next_parent)
2325 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2327 * Looks like the two contexts are clones, so we might be
2328 * able to optimize the context switch. We lock both
2329 * contexts and check that they are clones under the
2330 * lock (including re-checking that neither has been
2331 * uncloned in the meantime). It doesn't matter which
2332 * order we take the locks because no other cpu could
2333 * be trying to lock both of these tasks.
2335 raw_spin_lock(&ctx->lock);
2336 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2337 if (context_equiv(ctx, next_ctx)) {
2339 * XXX do we need a memory barrier of sorts
2340 * wrt to rcu_dereference() of perf_event_ctxp
2342 task->perf_event_ctxp[ctxn] = next_ctx;
2343 next->perf_event_ctxp[ctxn] = ctx;
2345 next_ctx->task = task;
2348 perf_event_sync_stat(ctx, next_ctx);
2350 raw_spin_unlock(&next_ctx->lock);
2351 raw_spin_unlock(&ctx->lock);
2357 raw_spin_lock(&ctx->lock);
2358 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2359 cpuctx->task_ctx = NULL;
2360 raw_spin_unlock(&ctx->lock);
2364 #define for_each_task_context_nr(ctxn) \
2365 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2368 * Called from scheduler to remove the events of the current task,
2369 * with interrupts disabled.
2371 * We stop each event and update the event value in event->count.
2373 * This does not protect us against NMI, but disable()
2374 * sets the disabled bit in the control field of event _before_
2375 * accessing the event control register. If a NMI hits, then it will
2376 * not restart the event.
2378 void __perf_event_task_sched_out(struct task_struct *task,
2379 struct task_struct *next)
2383 for_each_task_context_nr(ctxn)
2384 perf_event_context_sched_out(task, ctxn, next);
2387 * if cgroup events exist on this CPU, then we need
2388 * to check if we have to switch out PMU state.
2389 * cgroup event are system-wide mode only
2391 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2392 perf_cgroup_sched_out(task, next);
2395 static void task_ctx_sched_out(struct perf_event_context *ctx)
2397 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2399 if (!cpuctx->task_ctx)
2402 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2405 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2406 cpuctx->task_ctx = NULL;
2410 * Called with IRQs disabled
2412 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2413 enum event_type_t event_type)
2415 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2419 ctx_pinned_sched_in(struct perf_event_context *ctx,
2420 struct perf_cpu_context *cpuctx)
2422 struct perf_event *event;
2424 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2425 if (event->state <= PERF_EVENT_STATE_OFF)
2427 if (!event_filter_match(event))
2430 /* may need to reset tstamp_enabled */
2431 if (is_cgroup_event(event))
2432 perf_cgroup_mark_enabled(event, ctx);
2434 if (group_can_go_on(event, cpuctx, 1))
2435 group_sched_in(event, cpuctx, ctx);
2438 * If this pinned group hasn't been scheduled,
2439 * put it in error state.
2441 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2442 update_group_times(event);
2443 event->state = PERF_EVENT_STATE_ERROR;
2449 ctx_flexible_sched_in(struct perf_event_context *ctx,
2450 struct perf_cpu_context *cpuctx)
2452 struct perf_event *event;
2455 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2456 /* Ignore events in OFF or ERROR state */
2457 if (event->state <= PERF_EVENT_STATE_OFF)
2460 * Listen to the 'cpu' scheduling filter constraint
2463 if (!event_filter_match(event))
2466 /* may need to reset tstamp_enabled */
2467 if (is_cgroup_event(event))
2468 perf_cgroup_mark_enabled(event, ctx);
2470 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2471 if (group_sched_in(event, cpuctx, ctx))
2478 ctx_sched_in(struct perf_event_context *ctx,
2479 struct perf_cpu_context *cpuctx,
2480 enum event_type_t event_type,
2481 struct task_struct *task)
2484 int is_active = ctx->is_active;
2486 ctx->is_active |= event_type;
2487 if (likely(!ctx->nr_events))
2491 ctx->timestamp = now;
2492 perf_cgroup_set_timestamp(task, ctx);
2494 * First go through the list and put on any pinned groups
2495 * in order to give them the best chance of going on.
2497 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2498 ctx_pinned_sched_in(ctx, cpuctx);
2500 /* Then walk through the lower prio flexible groups */
2501 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2502 ctx_flexible_sched_in(ctx, cpuctx);
2505 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2506 enum event_type_t event_type,
2507 struct task_struct *task)
2509 struct perf_event_context *ctx = &cpuctx->ctx;
2511 ctx_sched_in(ctx, cpuctx, event_type, task);
2514 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2515 struct task_struct *task)
2517 struct perf_cpu_context *cpuctx;
2519 cpuctx = __get_cpu_context(ctx);
2520 if (cpuctx->task_ctx == ctx)
2523 perf_ctx_lock(cpuctx, ctx);
2524 perf_pmu_disable(ctx->pmu);
2526 * We want to keep the following priority order:
2527 * cpu pinned (that don't need to move), task pinned,
2528 * cpu flexible, task flexible.
2530 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2533 cpuctx->task_ctx = ctx;
2535 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2537 perf_pmu_enable(ctx->pmu);
2538 perf_ctx_unlock(cpuctx, ctx);
2541 * Since these rotations are per-cpu, we need to ensure the
2542 * cpu-context we got scheduled on is actually rotating.
2544 perf_pmu_rotate_start(ctx->pmu);
2548 * When sampling the branck stack in system-wide, it may be necessary
2549 * to flush the stack on context switch. This happens when the branch
2550 * stack does not tag its entries with the pid of the current task.
2551 * Otherwise it becomes impossible to associate a branch entry with a
2552 * task. This ambiguity is more likely to appear when the branch stack
2553 * supports priv level filtering and the user sets it to monitor only
2554 * at the user level (which could be a useful measurement in system-wide
2555 * mode). In that case, the risk is high of having a branch stack with
2556 * branch from multiple tasks. Flushing may mean dropping the existing
2557 * entries or stashing them somewhere in the PMU specific code layer.
2559 * This function provides the context switch callback to the lower code
2560 * layer. It is invoked ONLY when there is at least one system-wide context
2561 * with at least one active event using taken branch sampling.
2563 static void perf_branch_stack_sched_in(struct task_struct *prev,
2564 struct task_struct *task)
2566 struct perf_cpu_context *cpuctx;
2568 unsigned long flags;
2570 /* no need to flush branch stack if not changing task */
2574 local_irq_save(flags);
2578 list_for_each_entry_rcu(pmu, &pmus, entry) {
2579 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2582 * check if the context has at least one
2583 * event using PERF_SAMPLE_BRANCH_STACK
2585 if (cpuctx->ctx.nr_branch_stack > 0
2586 && pmu->flush_branch_stack) {
2588 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2590 perf_pmu_disable(pmu);
2592 pmu->flush_branch_stack();
2594 perf_pmu_enable(pmu);
2596 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2602 local_irq_restore(flags);
2606 * Called from scheduler to add the events of the current task
2607 * with interrupts disabled.
2609 * We restore the event value and then enable it.
2611 * This does not protect us against NMI, but enable()
2612 * sets the enabled bit in the control field of event _before_
2613 * accessing the event control register. If a NMI hits, then it will
2614 * keep the event running.
2616 void __perf_event_task_sched_in(struct task_struct *prev,
2617 struct task_struct *task)
2619 struct perf_event_context *ctx;
2622 for_each_task_context_nr(ctxn) {
2623 ctx = task->perf_event_ctxp[ctxn];
2627 perf_event_context_sched_in(ctx, task);
2630 * if cgroup events exist on this CPU, then we need
2631 * to check if we have to switch in PMU state.
2632 * cgroup event are system-wide mode only
2634 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2635 perf_cgroup_sched_in(prev, task);
2637 /* check for system-wide branch_stack events */
2638 if (atomic_read(&__get_cpu_var(perf_branch_stack_events)))
2639 perf_branch_stack_sched_in(prev, task);
2642 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2644 u64 frequency = event->attr.sample_freq;
2645 u64 sec = NSEC_PER_SEC;
2646 u64 divisor, dividend;
2648 int count_fls, nsec_fls, frequency_fls, sec_fls;
2650 count_fls = fls64(count);
2651 nsec_fls = fls64(nsec);
2652 frequency_fls = fls64(frequency);
2656 * We got @count in @nsec, with a target of sample_freq HZ
2657 * the target period becomes:
2660 * period = -------------------
2661 * @nsec * sample_freq
2666 * Reduce accuracy by one bit such that @a and @b converge
2667 * to a similar magnitude.
2669 #define REDUCE_FLS(a, b) \
2671 if (a##_fls > b##_fls) { \
2681 * Reduce accuracy until either term fits in a u64, then proceed with
2682 * the other, so that finally we can do a u64/u64 division.
2684 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2685 REDUCE_FLS(nsec, frequency);
2686 REDUCE_FLS(sec, count);
2689 if (count_fls + sec_fls > 64) {
2690 divisor = nsec * frequency;
2692 while (count_fls + sec_fls > 64) {
2693 REDUCE_FLS(count, sec);
2697 dividend = count * sec;
2699 dividend = count * sec;
2701 while (nsec_fls + frequency_fls > 64) {
2702 REDUCE_FLS(nsec, frequency);
2706 divisor = nsec * frequency;
2712 return div64_u64(dividend, divisor);
2715 static DEFINE_PER_CPU(int, perf_throttled_count);
2716 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2718 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2720 struct hw_perf_event *hwc = &event->hw;
2721 s64 period, sample_period;
2724 period = perf_calculate_period(event, nsec, count);
2726 delta = (s64)(period - hwc->sample_period);
2727 delta = (delta + 7) / 8; /* low pass filter */
2729 sample_period = hwc->sample_period + delta;
2734 hwc->sample_period = sample_period;
2736 if (local64_read(&hwc->period_left) > 8*sample_period) {
2738 event->pmu->stop(event, PERF_EF_UPDATE);
2740 local64_set(&hwc->period_left, 0);
2743 event->pmu->start(event, PERF_EF_RELOAD);
2748 * combine freq adjustment with unthrottling to avoid two passes over the
2749 * events. At the same time, make sure, having freq events does not change
2750 * the rate of unthrottling as that would introduce bias.
2752 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
2755 struct perf_event *event;
2756 struct hw_perf_event *hwc;
2757 u64 now, period = TICK_NSEC;
2761 * only need to iterate over all events iff:
2762 * - context have events in frequency mode (needs freq adjust)
2763 * - there are events to unthrottle on this cpu
2765 if (!(ctx->nr_freq || needs_unthr))
2768 raw_spin_lock(&ctx->lock);
2769 perf_pmu_disable(ctx->pmu);
2771 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
2772 if (event->state != PERF_EVENT_STATE_ACTIVE)
2775 if (!event_filter_match(event))
2778 perf_pmu_disable(event->pmu);
2782 if (hwc->interrupts == MAX_INTERRUPTS) {
2783 hwc->interrupts = 0;
2784 perf_log_throttle(event, 1);
2785 event->pmu->start(event, 0);
2788 if (!event->attr.freq || !event->attr.sample_freq)
2792 * stop the event and update event->count
2794 event->pmu->stop(event, PERF_EF_UPDATE);
2796 now = local64_read(&event->count);
2797 delta = now - hwc->freq_count_stamp;
2798 hwc->freq_count_stamp = now;
2802 * reload only if value has changed
2803 * we have stopped the event so tell that
2804 * to perf_adjust_period() to avoid stopping it
2808 perf_adjust_period(event, period, delta, false);
2810 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
2812 perf_pmu_enable(event->pmu);
2815 perf_pmu_enable(ctx->pmu);
2816 raw_spin_unlock(&ctx->lock);
2820 * Round-robin a context's events:
2822 static void rotate_ctx(struct perf_event_context *ctx)
2825 * Rotate the first entry last of non-pinned groups. Rotation might be
2826 * disabled by the inheritance code.
2828 if (!ctx->rotate_disable)
2829 list_rotate_left(&ctx->flexible_groups);
2833 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
2834 * because they're strictly cpu affine and rotate_start is called with IRQs
2835 * disabled, while rotate_context is called from IRQ context.
2837 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
2839 struct perf_event_context *ctx = NULL;
2840 int rotate = 0, remove = 1;
2842 if (cpuctx->ctx.nr_events) {
2844 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
2848 ctx = cpuctx->task_ctx;
2849 if (ctx && ctx->nr_events) {
2851 if (ctx->nr_events != ctx->nr_active)
2858 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2859 perf_pmu_disable(cpuctx->ctx.pmu);
2861 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2863 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
2865 rotate_ctx(&cpuctx->ctx);
2869 perf_event_sched_in(cpuctx, ctx, current);
2871 perf_pmu_enable(cpuctx->ctx.pmu);
2872 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2875 list_del_init(&cpuctx->rotation_list);
2880 #ifdef CONFIG_NO_HZ_FULL
2881 bool perf_event_can_stop_tick(void)
2883 if (atomic_read(&nr_freq_events) ||
2884 __this_cpu_read(perf_throttled_count))
2891 void perf_event_task_tick(void)
2893 struct list_head *head = &__get_cpu_var(rotation_list);
2894 struct perf_cpu_context *cpuctx, *tmp;
2895 struct perf_event_context *ctx;
2898 WARN_ON(!irqs_disabled());
2900 __this_cpu_inc(perf_throttled_seq);
2901 throttled = __this_cpu_xchg(perf_throttled_count, 0);
2903 list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) {
2905 perf_adjust_freq_unthr_context(ctx, throttled);
2907 ctx = cpuctx->task_ctx;
2909 perf_adjust_freq_unthr_context(ctx, throttled);
2913 static int event_enable_on_exec(struct perf_event *event,
2914 struct perf_event_context *ctx)
2916 if (!event->attr.enable_on_exec)
2919 event->attr.enable_on_exec = 0;
2920 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2923 __perf_event_mark_enabled(event);
2929 * Enable all of a task's events that have been marked enable-on-exec.
2930 * This expects task == current.
2932 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
2934 struct perf_event *event;
2935 unsigned long flags;
2939 local_irq_save(flags);
2940 if (!ctx || !ctx->nr_events)
2944 * We must ctxsw out cgroup events to avoid conflict
2945 * when invoking perf_task_event_sched_in() later on
2946 * in this function. Otherwise we end up trying to
2947 * ctxswin cgroup events which are already scheduled
2950 perf_cgroup_sched_out(current, NULL);
2952 raw_spin_lock(&ctx->lock);
2953 task_ctx_sched_out(ctx);
2955 list_for_each_entry(event, &ctx->event_list, event_entry) {
2956 ret = event_enable_on_exec(event, ctx);
2962 * Unclone this context if we enabled any event.
2967 raw_spin_unlock(&ctx->lock);
2970 * Also calls ctxswin for cgroup events, if any:
2972 perf_event_context_sched_in(ctx, ctx->task);
2974 local_irq_restore(flags);
2978 * Cross CPU call to read the hardware event
2980 static void __perf_event_read(void *info)
2982 struct perf_event *event = info;
2983 struct perf_event_context *ctx = event->ctx;
2984 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2987 * If this is a task context, we need to check whether it is
2988 * the current task context of this cpu. If not it has been
2989 * scheduled out before the smp call arrived. In that case
2990 * event->count would have been updated to a recent sample
2991 * when the event was scheduled out.
2993 if (ctx->task && cpuctx->task_ctx != ctx)
2996 raw_spin_lock(&ctx->lock);
2997 if (ctx->is_active) {
2998 update_context_time(ctx);
2999 update_cgrp_time_from_event(event);
3001 update_event_times(event);
3002 if (event->state == PERF_EVENT_STATE_ACTIVE)
3003 event->pmu->read(event);
3004 raw_spin_unlock(&ctx->lock);
3007 static inline u64 perf_event_count(struct perf_event *event)
3009 return local64_read(&event->count) + atomic64_read(&event->child_count);
3012 static u64 perf_event_read(struct perf_event *event)
3015 * If event is enabled and currently active on a CPU, update the
3016 * value in the event structure:
3018 if (event->state == PERF_EVENT_STATE_ACTIVE) {
3019 smp_call_function_single(event->oncpu,
3020 __perf_event_read, event, 1);
3021 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3022 struct perf_event_context *ctx = event->ctx;
3023 unsigned long flags;
3025 raw_spin_lock_irqsave(&ctx->lock, flags);
3027 * may read while context is not active
3028 * (e.g., thread is blocked), in that case
3029 * we cannot update context time
3031 if (ctx->is_active) {
3032 update_context_time(ctx);
3033 update_cgrp_time_from_event(event);
3035 update_event_times(event);
3036 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3039 return perf_event_count(event);
3043 * Initialize the perf_event context in a task_struct:
3045 static void __perf_event_init_context(struct perf_event_context *ctx)
3047 raw_spin_lock_init(&ctx->lock);
3048 mutex_init(&ctx->mutex);
3049 INIT_LIST_HEAD(&ctx->pinned_groups);
3050 INIT_LIST_HEAD(&ctx->flexible_groups);
3051 INIT_LIST_HEAD(&ctx->event_list);
3052 atomic_set(&ctx->refcount, 1);
3055 static struct perf_event_context *
3056 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3058 struct perf_event_context *ctx;
3060 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3064 __perf_event_init_context(ctx);
3067 get_task_struct(task);
3074 static struct task_struct *
3075 find_lively_task_by_vpid(pid_t vpid)
3077 struct task_struct *task;
3084 task = find_task_by_vpid(vpid);
3086 get_task_struct(task);
3090 return ERR_PTR(-ESRCH);
3092 /* Reuse ptrace permission checks for now. */
3094 if (!ptrace_may_access(task, PTRACE_MODE_READ))
3099 put_task_struct(task);
3100 return ERR_PTR(err);
3105 * Returns a matching context with refcount and pincount.
3107 static struct perf_event_context *
3108 find_get_context(struct pmu *pmu, struct task_struct *task, int cpu)
3110 struct perf_event_context *ctx;
3111 struct perf_cpu_context *cpuctx;
3112 unsigned long flags;
3116 /* Must be root to operate on a CPU event: */
3117 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3118 return ERR_PTR(-EACCES);
3121 * We could be clever and allow to attach a event to an
3122 * offline CPU and activate it when the CPU comes up, but
3125 if (!cpu_online(cpu))
3126 return ERR_PTR(-ENODEV);
3128 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3137 ctxn = pmu->task_ctx_nr;
3142 ctx = perf_lock_task_context(task, ctxn, &flags);
3146 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3148 ctx = alloc_perf_context(pmu, task);
3154 mutex_lock(&task->perf_event_mutex);
3156 * If it has already passed perf_event_exit_task().
3157 * we must see PF_EXITING, it takes this mutex too.
3159 if (task->flags & PF_EXITING)
3161 else if (task->perf_event_ctxp[ctxn])
3166 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3168 mutex_unlock(&task->perf_event_mutex);
3170 if (unlikely(err)) {
3182 return ERR_PTR(err);
3185 static void perf_event_free_filter(struct perf_event *event);
3187 static void free_event_rcu(struct rcu_head *head)
3189 struct perf_event *event;
3191 event = container_of(head, struct perf_event, rcu_head);
3193 put_pid_ns(event->ns);
3194 perf_event_free_filter(event);
3198 static void ring_buffer_put(struct ring_buffer *rb);
3199 static void ring_buffer_attach(struct perf_event *event,
3200 struct ring_buffer *rb);
3202 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3207 if (has_branch_stack(event)) {
3208 if (!(event->attach_state & PERF_ATTACH_TASK))
3209 atomic_dec(&per_cpu(perf_branch_stack_events, cpu));
3211 if (is_cgroup_event(event))
3212 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3215 static void unaccount_event(struct perf_event *event)
3220 if (event->attach_state & PERF_ATTACH_TASK)
3221 static_key_slow_dec_deferred(&perf_sched_events);
3222 if (event->attr.mmap || event->attr.mmap_data)
3223 atomic_dec(&nr_mmap_events);
3224 if (event->attr.comm)
3225 atomic_dec(&nr_comm_events);
3226 if (event->attr.task)
3227 atomic_dec(&nr_task_events);
3228 if (event->attr.freq)
3229 atomic_dec(&nr_freq_events);
3230 if (is_cgroup_event(event))
3231 static_key_slow_dec_deferred(&perf_sched_events);
3232 if (has_branch_stack(event))
3233 static_key_slow_dec_deferred(&perf_sched_events);
3235 unaccount_event_cpu(event, event->cpu);
3238 static void __free_event(struct perf_event *event)
3240 if (!event->parent) {
3241 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3242 put_callchain_buffers();
3246 event->destroy(event);
3249 put_ctx(event->ctx);
3252 module_put(event->pmu->module);
3254 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);
3265 * Can happen when we close an event with re-directed output.
3267 * Since we have a 0 refcount, perf_mmap_close() will skip
3268 * over us; possibly making our ring_buffer_put() the last.
3270 mutex_lock(&event->mmap_mutex);
3271 ring_buffer_attach(event, NULL);
3272 mutex_unlock(&event->mmap_mutex);
3275 if (is_cgroup_event(event))
3276 perf_detach_cgroup(event);
3278 __free_event(event);
3282 * Used to free events which have a known refcount of 1, such as in error paths
3283 * where the event isn't exposed yet and inherited events.
3285 static void free_event(struct perf_event *event)
3287 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3288 "unexpected event refcount: %ld; ptr=%p\n",
3289 atomic_long_read(&event->refcount), event)) {
3290 /* leak to avoid use-after-free */
3298 * Called when the last reference to the file is gone.
3300 static void put_event(struct perf_event *event)
3302 struct perf_event_context *ctx = event->ctx;
3303 struct task_struct *owner;
3305 if (!atomic_long_dec_and_test(&event->refcount))
3309 owner = ACCESS_ONCE(event->owner);
3311 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3312 * !owner it means the list deletion is complete and we can indeed
3313 * free this event, otherwise we need to serialize on
3314 * owner->perf_event_mutex.
3316 smp_read_barrier_depends();
3319 * Since delayed_put_task_struct() also drops the last
3320 * task reference we can safely take a new reference
3321 * while holding the rcu_read_lock().
3323 get_task_struct(owner);
3328 mutex_lock(&owner->perf_event_mutex);
3330 * We have to re-check the event->owner field, if it is cleared
3331 * we raced with perf_event_exit_task(), acquiring the mutex
3332 * ensured they're done, and we can proceed with freeing the
3336 list_del_init(&event->owner_entry);
3337 mutex_unlock(&owner->perf_event_mutex);
3338 put_task_struct(owner);
3341 WARN_ON_ONCE(ctx->parent_ctx);
3343 * There are two ways this annotation is useful:
3345 * 1) there is a lock recursion from perf_event_exit_task
3346 * see the comment there.
3348 * 2) there is a lock-inversion with mmap_sem through
3349 * perf_event_read_group(), which takes faults while
3350 * holding ctx->mutex, however this is called after
3351 * the last filedesc died, so there is no possibility
3352 * to trigger the AB-BA case.
3354 mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
3355 perf_remove_from_context(event, true);
3356 mutex_unlock(&ctx->mutex);
3361 int perf_event_release_kernel(struct perf_event *event)
3366 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3368 static int perf_release(struct inode *inode, struct file *file)
3370 put_event(file->private_data);
3374 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3376 struct perf_event *child;
3382 mutex_lock(&event->child_mutex);
3383 total += perf_event_read(event);
3384 *enabled += event->total_time_enabled +
3385 atomic64_read(&event->child_total_time_enabled);
3386 *running += event->total_time_running +
3387 atomic64_read(&event->child_total_time_running);
3389 list_for_each_entry(child, &event->child_list, child_list) {
3390 total += perf_event_read(child);
3391 *enabled += child->total_time_enabled;
3392 *running += child->total_time_running;
3394 mutex_unlock(&event->child_mutex);
3398 EXPORT_SYMBOL_GPL(perf_event_read_value);
3400 static int perf_event_read_group(struct perf_event *event,
3401 u64 read_format, char __user *buf)
3403 struct perf_event *leader = event->group_leader, *sub;
3404 int n = 0, size = 0, ret = -EFAULT;
3405 struct perf_event_context *ctx = leader->ctx;
3407 u64 count, enabled, running;
3409 mutex_lock(&ctx->mutex);
3410 count = perf_event_read_value(leader, &enabled, &running);
3412 values[n++] = 1 + leader->nr_siblings;
3413 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3414 values[n++] = enabled;
3415 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3416 values[n++] = running;
3417 values[n++] = count;
3418 if (read_format & PERF_FORMAT_ID)
3419 values[n++] = primary_event_id(leader);
3421 size = n * sizeof(u64);
3423 if (copy_to_user(buf, values, size))
3428 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3431 values[n++] = perf_event_read_value(sub, &enabled, &running);
3432 if (read_format & PERF_FORMAT_ID)
3433 values[n++] = primary_event_id(sub);
3435 size = n * sizeof(u64);
3437 if (copy_to_user(buf + ret, values, size)) {
3445 mutex_unlock(&ctx->mutex);
3450 static int perf_event_read_one(struct perf_event *event,
3451 u64 read_format, char __user *buf)
3453 u64 enabled, running;
3457 values[n++] = perf_event_read_value(event, &enabled, &running);
3458 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3459 values[n++] = enabled;
3460 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3461 values[n++] = running;
3462 if (read_format & PERF_FORMAT_ID)
3463 values[n++] = primary_event_id(event);
3465 if (copy_to_user(buf, values, n * sizeof(u64)))
3468 return n * sizeof(u64);
3472 * Read the performance event - simple non blocking version for now
3475 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
3477 u64 read_format = event->attr.read_format;
3481 * Return end-of-file for a read on a event that is in
3482 * error state (i.e. because it was pinned but it couldn't be
3483 * scheduled on to the CPU at some point).
3485 if (event->state == PERF_EVENT_STATE_ERROR)
3488 if (count < event->read_size)
3491 WARN_ON_ONCE(event->ctx->parent_ctx);
3492 if (read_format & PERF_FORMAT_GROUP)
3493 ret = perf_event_read_group(event, read_format, buf);
3495 ret = perf_event_read_one(event, read_format, buf);
3501 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
3503 struct perf_event *event = file->private_data;
3505 return perf_read_hw(event, buf, count);
3508 static unsigned int perf_poll(struct file *file, poll_table *wait)
3510 struct perf_event *event = file->private_data;
3511 struct ring_buffer *rb;
3512 unsigned int events = POLL_HUP;
3515 * Pin the event->rb by taking event->mmap_mutex; otherwise
3516 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
3518 mutex_lock(&event->mmap_mutex);
3521 events = atomic_xchg(&rb->poll, 0);
3522 mutex_unlock(&event->mmap_mutex);
3524 poll_wait(file, &event->waitq, wait);
3529 static void perf_event_reset(struct perf_event *event)
3531 (void)perf_event_read(event);
3532 local64_set(&event->count, 0);
3533 perf_event_update_userpage(event);
3537 * Holding the top-level event's child_mutex means that any
3538 * descendant process that has inherited this event will block
3539 * in sync_child_event if it goes to exit, thus satisfying the
3540 * task existence requirements of perf_event_enable/disable.
3542 static void perf_event_for_each_child(struct perf_event *event,
3543 void (*func)(struct perf_event *))
3545 struct perf_event *child;
3547 WARN_ON_ONCE(event->ctx->parent_ctx);
3548 mutex_lock(&event->child_mutex);
3550 list_for_each_entry(child, &event->child_list, child_list)
3552 mutex_unlock(&event->child_mutex);
3555 static void perf_event_for_each(struct perf_event *event,
3556 void (*func)(struct perf_event *))
3558 struct perf_event_context *ctx = event->ctx;
3559 struct perf_event *sibling;
3561 WARN_ON_ONCE(ctx->parent_ctx);
3562 mutex_lock(&ctx->mutex);
3563 event = event->group_leader;
3565 perf_event_for_each_child(event, func);
3566 list_for_each_entry(sibling, &event->sibling_list, group_entry)
3567 perf_event_for_each_child(sibling, func);
3568 mutex_unlock(&ctx->mutex);
3571 static int perf_event_period(struct perf_event *event, u64 __user *arg)
3573 struct perf_event_context *ctx = event->ctx;
3574 int ret = 0, active;
3577 if (!is_sampling_event(event))
3580 if (copy_from_user(&value, arg, sizeof(value)))
3586 raw_spin_lock_irq(&ctx->lock);
3587 if (event->attr.freq) {
3588 if (value > sysctl_perf_event_sample_rate) {
3593 event->attr.sample_freq = value;
3595 event->attr.sample_period = value;
3596 event->hw.sample_period = value;
3599 active = (event->state == PERF_EVENT_STATE_ACTIVE);
3601 perf_pmu_disable(ctx->pmu);
3602 event->pmu->stop(event, PERF_EF_UPDATE);
3605 local64_set(&event->hw.period_left, 0);
3608 event->pmu->start(event, PERF_EF_RELOAD);
3609 perf_pmu_enable(ctx->pmu);
3613 raw_spin_unlock_irq(&ctx->lock);
3618 static const struct file_operations perf_fops;
3620 static inline int perf_fget_light(int fd, struct fd *p)
3622 struct fd f = fdget(fd);
3626 if (f.file->f_op != &perf_fops) {
3634 static int perf_event_set_output(struct perf_event *event,
3635 struct perf_event *output_event);
3636 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
3638 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
3640 struct perf_event *event = file->private_data;
3641 void (*func)(struct perf_event *);
3645 case PERF_EVENT_IOC_ENABLE:
3646 func = perf_event_enable;
3648 case PERF_EVENT_IOC_DISABLE:
3649 func = perf_event_disable;
3651 case PERF_EVENT_IOC_RESET:
3652 func = perf_event_reset;
3655 case PERF_EVENT_IOC_REFRESH:
3656 return perf_event_refresh(event, arg);
3658 case PERF_EVENT_IOC_PERIOD:
3659 return perf_event_period(event, (u64 __user *)arg);
3661 case PERF_EVENT_IOC_ID:
3663 u64 id = primary_event_id(event);
3665 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
3670 case PERF_EVENT_IOC_SET_OUTPUT:
3674 struct perf_event *output_event;
3676 ret = perf_fget_light(arg, &output);
3679 output_event = output.file->private_data;
3680 ret = perf_event_set_output(event, output_event);
3683 ret = perf_event_set_output(event, NULL);
3688 case PERF_EVENT_IOC_SET_FILTER:
3689 return perf_event_set_filter(event, (void __user *)arg);
3695 if (flags & PERF_IOC_FLAG_GROUP)
3696 perf_event_for_each(event, func);
3698 perf_event_for_each_child(event, func);
3703 int perf_event_task_enable(void)
3705 struct perf_event *event;
3707 mutex_lock(¤t->perf_event_mutex);
3708 list_for_each_entry(event, ¤t->perf_event_list, owner_entry)
3709 perf_event_for_each_child(event, perf_event_enable);
3710 mutex_unlock(¤t->perf_event_mutex);
3715 int perf_event_task_disable(void)
3717 struct perf_event *event;
3719 mutex_lock(¤t->perf_event_mutex);
3720 list_for_each_entry(event, ¤t->perf_event_list, owner_entry)
3721 perf_event_for_each_child(event, perf_event_disable);
3722 mutex_unlock(¤t->perf_event_mutex);
3727 static int perf_event_index(struct perf_event *event)
3729 if (event->hw.state & PERF_HES_STOPPED)
3732 if (event->state != PERF_EVENT_STATE_ACTIVE)
3735 return event->pmu->event_idx(event);
3738 static void calc_timer_values(struct perf_event *event,
3745 *now = perf_clock();
3746 ctx_time = event->shadow_ctx_time + *now;
3747 *enabled = ctx_time - event->tstamp_enabled;
3748 *running = ctx_time - event->tstamp_running;
3751 static void perf_event_init_userpage(struct perf_event *event)
3753 struct perf_event_mmap_page *userpg;
3754 struct ring_buffer *rb;
3757 rb = rcu_dereference(event->rb);
3761 userpg = rb->user_page;
3763 /* Allow new userspace to detect that bit 0 is deprecated */
3764 userpg->cap_bit0_is_deprecated = 1;
3765 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
3771 void __weak arch_perf_update_userpage(struct perf_event_mmap_page *userpg, u64 now)
3776 * Callers need to ensure there can be no nesting of this function, otherwise
3777 * the seqlock logic goes bad. We can not serialize this because the arch
3778 * code calls this from NMI context.
3780 void perf_event_update_userpage(struct perf_event *event)
3782 struct perf_event_mmap_page *userpg;
3783 struct ring_buffer *rb;
3784 u64 enabled, running, now;
3787 rb = rcu_dereference(event->rb);
3792 * compute total_time_enabled, total_time_running
3793 * based on snapshot values taken when the event
3794 * was last scheduled in.
3796 * we cannot simply called update_context_time()
3797 * because of locking issue as we can be called in
3800 calc_timer_values(event, &now, &enabled, &running);
3802 userpg = rb->user_page;
3804 * Disable preemption so as to not let the corresponding user-space
3805 * spin too long if we get preempted.
3810 userpg->index = perf_event_index(event);
3811 userpg->offset = perf_event_count(event);
3813 userpg->offset -= local64_read(&event->hw.prev_count);
3815 userpg->time_enabled = enabled +
3816 atomic64_read(&event->child_total_time_enabled);
3818 userpg->time_running = running +
3819 atomic64_read(&event->child_total_time_running);
3821 arch_perf_update_userpage(userpg, now);
3830 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
3832 struct perf_event *event = vma->vm_file->private_data;
3833 struct ring_buffer *rb;
3834 int ret = VM_FAULT_SIGBUS;
3836 if (vmf->flags & FAULT_FLAG_MKWRITE) {
3837 if (vmf->pgoff == 0)
3843 rb = rcu_dereference(event->rb);
3847 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
3850 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
3854 get_page(vmf->page);
3855 vmf->page->mapping = vma->vm_file->f_mapping;
3856 vmf->page->index = vmf->pgoff;
3865 static void ring_buffer_attach(struct perf_event *event,
3866 struct ring_buffer *rb)
3868 struct ring_buffer *old_rb = NULL;
3869 unsigned long flags;
3873 * Should be impossible, we set this when removing
3874 * event->rb_entry and wait/clear when adding event->rb_entry.
3876 WARN_ON_ONCE(event->rcu_pending);
3879 event->rcu_batches = get_state_synchronize_rcu();
3880 event->rcu_pending = 1;
3882 spin_lock_irqsave(&old_rb->event_lock, flags);
3883 list_del_rcu(&event->rb_entry);
3884 spin_unlock_irqrestore(&old_rb->event_lock, flags);
3887 if (event->rcu_pending && rb) {
3888 cond_synchronize_rcu(event->rcu_batches);
3889 event->rcu_pending = 0;
3893 spin_lock_irqsave(&rb->event_lock, flags);
3894 list_add_rcu(&event->rb_entry, &rb->event_list);
3895 spin_unlock_irqrestore(&rb->event_lock, flags);
3898 rcu_assign_pointer(event->rb, rb);
3901 ring_buffer_put(old_rb);
3903 * Since we detached before setting the new rb, so that we
3904 * could attach the new rb, we could have missed a wakeup.
3907 wake_up_all(&event->waitq);
3911 static void ring_buffer_wakeup(struct perf_event *event)
3913 struct ring_buffer *rb;
3916 rb = rcu_dereference(event->rb);
3918 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
3919 wake_up_all(&event->waitq);
3924 static void rb_free_rcu(struct rcu_head *rcu_head)
3926 struct ring_buffer *rb;
3928 rb = container_of(rcu_head, struct ring_buffer, rcu_head);
3932 static struct ring_buffer *ring_buffer_get(struct perf_event *event)
3934 struct ring_buffer *rb;
3937 rb = rcu_dereference(event->rb);
3939 if (!atomic_inc_not_zero(&rb->refcount))
3947 static void ring_buffer_put(struct ring_buffer *rb)
3949 if (!atomic_dec_and_test(&rb->refcount))
3952 WARN_ON_ONCE(!list_empty(&rb->event_list));
3954 call_rcu(&rb->rcu_head, rb_free_rcu);
3957 static void perf_mmap_open(struct vm_area_struct *vma)
3959 struct perf_event *event = vma->vm_file->private_data;
3961 atomic_inc(&event->mmap_count);
3962 atomic_inc(&event->rb->mmap_count);
3966 * A buffer can be mmap()ed multiple times; either directly through the same
3967 * event, or through other events by use of perf_event_set_output().
3969 * In order to undo the VM accounting done by perf_mmap() we need to destroy
3970 * the buffer here, where we still have a VM context. This means we need
3971 * to detach all events redirecting to us.
3973 static void perf_mmap_close(struct vm_area_struct *vma)
3975 struct perf_event *event = vma->vm_file->private_data;
3977 struct ring_buffer *rb = ring_buffer_get(event);
3978 struct user_struct *mmap_user = rb->mmap_user;
3979 int mmap_locked = rb->mmap_locked;
3980 unsigned long size = perf_data_size(rb);
3982 atomic_dec(&rb->mmap_count);
3984 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
3987 ring_buffer_attach(event, NULL);
3988 mutex_unlock(&event->mmap_mutex);
3990 /* If there's still other mmap()s of this buffer, we're done. */
3991 if (atomic_read(&rb->mmap_count))
3995 * No other mmap()s, detach from all other events that might redirect
3996 * into the now unreachable buffer. Somewhat complicated by the
3997 * fact that rb::event_lock otherwise nests inside mmap_mutex.
4001 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4002 if (!atomic_long_inc_not_zero(&event->refcount)) {
4004 * This event is en-route to free_event() which will
4005 * detach it and remove it from the list.
4011 mutex_lock(&event->mmap_mutex);
4013 * Check we didn't race with perf_event_set_output() which can
4014 * swizzle the rb from under us while we were waiting to
4015 * acquire mmap_mutex.
4017 * If we find a different rb; ignore this event, a next
4018 * iteration will no longer find it on the list. We have to
4019 * still restart the iteration to make sure we're not now
4020 * iterating the wrong list.
4022 if (event->rb == rb)
4023 ring_buffer_attach(event, NULL);
4025 mutex_unlock(&event->mmap_mutex);
4029 * Restart the iteration; either we're on the wrong list or
4030 * destroyed its integrity by doing a deletion.
4037 * It could be there's still a few 0-ref events on the list; they'll
4038 * get cleaned up by free_event() -- they'll also still have their
4039 * ref on the rb and will free it whenever they are done with it.
4041 * Aside from that, this buffer is 'fully' detached and unmapped,
4042 * undo the VM accounting.
4045 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4046 vma->vm_mm->pinned_vm -= mmap_locked;
4047 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);
4168 perf_event_init_userpage(event);
4169 perf_event_update_userpage(event);
4173 atomic_inc(&event->mmap_count);
4174 mutex_unlock(&event->mmap_mutex);
4177 * Since pinned accounting is per vm we cannot allow fork() to copy our
4180 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
4181 vma->vm_ops = &perf_mmap_vmops;
4186 static int perf_fasync(int fd, struct file *filp, int on)
4188 struct inode *inode = file_inode(filp);
4189 struct perf_event *event = filp->private_data;
4192 mutex_lock(&inode->i_mutex);
4193 retval = fasync_helper(fd, filp, on, &event->fasync);
4194 mutex_unlock(&inode->i_mutex);
4202 static const struct file_operations perf_fops = {
4203 .llseek = no_llseek,
4204 .release = perf_release,
4207 .unlocked_ioctl = perf_ioctl,
4208 .compat_ioctl = perf_ioctl,
4210 .fasync = perf_fasync,
4216 * If there's data, ensure we set the poll() state and publish everything
4217 * to user-space before waking everybody up.
4220 void perf_event_wakeup(struct perf_event *event)
4222 ring_buffer_wakeup(event);
4224 if (event->pending_kill) {
4225 kill_fasync(&event->fasync, SIGIO, event->pending_kill);
4226 event->pending_kill = 0;
4230 static void perf_pending_event(struct irq_work *entry)
4232 struct perf_event *event = container_of(entry,
4233 struct perf_event, pending);
4235 if (event->pending_disable) {
4236 event->pending_disable = 0;
4237 __perf_event_disable(event);
4240 if (event->pending_wakeup) {
4241 event->pending_wakeup = 0;
4242 perf_event_wakeup(event);
4247 * We assume there is only KVM supporting the callbacks.
4248 * Later on, we might change it to a list if there is
4249 * another virtualization implementation supporting the callbacks.
4251 struct perf_guest_info_callbacks *perf_guest_cbs;
4253 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4255 perf_guest_cbs = cbs;
4258 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
4260 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4262 perf_guest_cbs = NULL;
4265 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
4268 perf_output_sample_regs(struct perf_output_handle *handle,
4269 struct pt_regs *regs, u64 mask)
4273 for_each_set_bit(bit, (const unsigned long *) &mask,
4274 sizeof(mask) * BITS_PER_BYTE) {
4277 val = perf_reg_value(regs, bit);
4278 perf_output_put(handle, val);
4282 static void perf_sample_regs_user(struct perf_regs_user *regs_user,
4283 struct pt_regs *regs)
4285 if (!user_mode(regs)) {
4287 regs = task_pt_regs(current);
4293 regs_user->regs = regs;
4294 regs_user->abi = perf_reg_abi(current);
4299 * Get remaining task size from user stack pointer.
4301 * It'd be better to take stack vma map and limit this more
4302 * precisly, but there's no way to get it safely under interrupt,
4303 * so using TASK_SIZE as limit.
4305 static u64 perf_ustack_task_size(struct pt_regs *regs)
4307 unsigned long addr = perf_user_stack_pointer(regs);
4309 if (!addr || addr >= TASK_SIZE)
4312 return TASK_SIZE - addr;
4316 perf_sample_ustack_size(u16 stack_size, u16 header_size,
4317 struct pt_regs *regs)
4321 /* No regs, no stack pointer, no dump. */
4326 * Check if we fit in with the requested stack size into the:
4328 * If we don't, we limit the size to the TASK_SIZE.
4330 * - remaining sample size
4331 * If we don't, we customize the stack size to
4332 * fit in to the remaining sample size.
4335 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
4336 stack_size = min(stack_size, (u16) task_size);
4338 /* Current header size plus static size and dynamic size. */
4339 header_size += 2 * sizeof(u64);
4341 /* Do we fit in with the current stack dump size? */
4342 if ((u16) (header_size + stack_size) < header_size) {
4344 * If we overflow the maximum size for the sample,
4345 * we customize the stack dump size to fit in.
4347 stack_size = USHRT_MAX - header_size - sizeof(u64);
4348 stack_size = round_up(stack_size, sizeof(u64));
4355 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
4356 struct pt_regs *regs)
4358 /* Case of a kernel thread, nothing to dump */
4361 perf_output_put(handle, size);
4370 * - the size requested by user or the best one we can fit
4371 * in to the sample max size
4373 * - user stack dump data
4375 * - the actual dumped size
4379 perf_output_put(handle, dump_size);
4382 sp = perf_user_stack_pointer(regs);
4383 rem = __output_copy_user(handle, (void *) sp, dump_size);
4384 dyn_size = dump_size - rem;
4386 perf_output_skip(handle, rem);
4389 perf_output_put(handle, dyn_size);
4393 static void __perf_event_header__init_id(struct perf_event_header *header,
4394 struct perf_sample_data *data,
4395 struct perf_event *event)
4397 u64 sample_type = event->attr.sample_type;
4399 data->type = sample_type;
4400 header->size += event->id_header_size;
4402 if (sample_type & PERF_SAMPLE_TID) {
4403 /* namespace issues */
4404 data->tid_entry.pid = perf_event_pid(event, current);
4405 data->tid_entry.tid = perf_event_tid(event, current);
4408 if (sample_type & PERF_SAMPLE_TIME)
4409 data->time = perf_clock();
4411 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
4412 data->id = primary_event_id(event);
4414 if (sample_type & PERF_SAMPLE_STREAM_ID)
4415 data->stream_id = event->id;
4417 if (sample_type & PERF_SAMPLE_CPU) {
4418 data->cpu_entry.cpu = raw_smp_processor_id();
4419 data->cpu_entry.reserved = 0;
4423 void perf_event_header__init_id(struct perf_event_header *header,
4424 struct perf_sample_data *data,
4425 struct perf_event *event)
4427 if (event->attr.sample_id_all)
4428 __perf_event_header__init_id(header, data, event);
4431 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
4432 struct perf_sample_data *data)
4434 u64 sample_type = data->type;
4436 if (sample_type & PERF_SAMPLE_TID)
4437 perf_output_put(handle, data->tid_entry);
4439 if (sample_type & PERF_SAMPLE_TIME)
4440 perf_output_put(handle, data->time);
4442 if (sample_type & PERF_SAMPLE_ID)
4443 perf_output_put(handle, data->id);
4445 if (sample_type & PERF_SAMPLE_STREAM_ID)
4446 perf_output_put(handle, data->stream_id);
4448 if (sample_type & PERF_SAMPLE_CPU)
4449 perf_output_put(handle, data->cpu_entry);
4451 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4452 perf_output_put(handle, data->id);
4455 void perf_event__output_id_sample(struct perf_event *event,
4456 struct perf_output_handle *handle,
4457 struct perf_sample_data *sample)
4459 if (event->attr.sample_id_all)
4460 __perf_event__output_id_sample(handle, sample);
4463 static void perf_output_read_one(struct perf_output_handle *handle,
4464 struct perf_event *event,
4465 u64 enabled, u64 running)
4467 u64 read_format = event->attr.read_format;
4471 values[n++] = perf_event_count(event);
4472 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4473 values[n++] = enabled +
4474 atomic64_read(&event->child_total_time_enabled);
4476 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4477 values[n++] = running +
4478 atomic64_read(&event->child_total_time_running);
4480 if (read_format & PERF_FORMAT_ID)
4481 values[n++] = primary_event_id(event);
4483 __output_copy(handle, values, n * sizeof(u64));
4487 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
4489 static void perf_output_read_group(struct perf_output_handle *handle,
4490 struct perf_event *event,
4491 u64 enabled, u64 running)
4493 struct perf_event *leader = event->group_leader, *sub;
4494 u64 read_format = event->attr.read_format;
4498 values[n++] = 1 + leader->nr_siblings;
4500 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4501 values[n++] = enabled;
4503 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4504 values[n++] = running;
4506 if (leader != event)
4507 leader->pmu->read(leader);
4509 values[n++] = perf_event_count(leader);
4510 if (read_format & PERF_FORMAT_ID)
4511 values[n++] = primary_event_id(leader);
4513 __output_copy(handle, values, n * sizeof(u64));
4515 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4518 if ((sub != event) &&
4519 (sub->state == PERF_EVENT_STATE_ACTIVE))
4520 sub->pmu->read(sub);
4522 values[n++] = perf_event_count(sub);
4523 if (read_format & PERF_FORMAT_ID)
4524 values[n++] = primary_event_id(sub);
4526 __output_copy(handle, values, n * sizeof(u64));
4530 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
4531 PERF_FORMAT_TOTAL_TIME_RUNNING)
4533 static void perf_output_read(struct perf_output_handle *handle,
4534 struct perf_event *event)
4536 u64 enabled = 0, running = 0, now;
4537 u64 read_format = event->attr.read_format;
4540 * compute total_time_enabled, total_time_running
4541 * based on snapshot values taken when the event
4542 * was last scheduled in.
4544 * we cannot simply called update_context_time()
4545 * because of locking issue as we are called in
4548 if (read_format & PERF_FORMAT_TOTAL_TIMES)
4549 calc_timer_values(event, &now, &enabled, &running);
4551 if (event->attr.read_format & PERF_FORMAT_GROUP)
4552 perf_output_read_group(handle, event, enabled, running);
4554 perf_output_read_one(handle, event, enabled, running);
4557 void perf_output_sample(struct perf_output_handle *handle,
4558 struct perf_event_header *header,
4559 struct perf_sample_data *data,
4560 struct perf_event *event)
4562 u64 sample_type = data->type;
4564 perf_output_put(handle, *header);
4566 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4567 perf_output_put(handle, data->id);
4569 if (sample_type & PERF_SAMPLE_IP)
4570 perf_output_put(handle, data->ip);
4572 if (sample_type & PERF_SAMPLE_TID)
4573 perf_output_put(handle, data->tid_entry);
4575 if (sample_type & PERF_SAMPLE_TIME)
4576 perf_output_put(handle, data->time);
4578 if (sample_type & PERF_SAMPLE_ADDR)
4579 perf_output_put(handle, data->addr);
4581 if (sample_type & PERF_SAMPLE_ID)
4582 perf_output_put(handle, data->id);
4584 if (sample_type & PERF_SAMPLE_STREAM_ID)
4585 perf_output_put(handle, data->stream_id);
4587 if (sample_type & PERF_SAMPLE_CPU)
4588 perf_output_put(handle, data->cpu_entry);
4590 if (sample_type & PERF_SAMPLE_PERIOD)
4591 perf_output_put(handle, data->period);
4593 if (sample_type & PERF_SAMPLE_READ)
4594 perf_output_read(handle, event);
4596 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4597 if (data->callchain) {
4600 if (data->callchain)
4601 size += data->callchain->nr;
4603 size *= sizeof(u64);
4605 __output_copy(handle, data->callchain, size);
4608 perf_output_put(handle, nr);
4612 if (sample_type & PERF_SAMPLE_RAW) {
4614 perf_output_put(handle, data->raw->size);
4615 __output_copy(handle, data->raw->data,
4622 .size = sizeof(u32),
4625 perf_output_put(handle, raw);
4629 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4630 if (data->br_stack) {
4633 size = data->br_stack->nr
4634 * sizeof(struct perf_branch_entry);
4636 perf_output_put(handle, data->br_stack->nr);
4637 perf_output_copy(handle, data->br_stack->entries, size);
4640 * we always store at least the value of nr
4643 perf_output_put(handle, nr);
4647 if (sample_type & PERF_SAMPLE_REGS_USER) {
4648 u64 abi = data->regs_user.abi;
4651 * If there are no regs to dump, notice it through
4652 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
4654 perf_output_put(handle, abi);
4657 u64 mask = event->attr.sample_regs_user;
4658 perf_output_sample_regs(handle,
4659 data->regs_user.regs,
4664 if (sample_type & PERF_SAMPLE_STACK_USER) {
4665 perf_output_sample_ustack(handle,
4666 data->stack_user_size,
4667 data->regs_user.regs);
4670 if (sample_type & PERF_SAMPLE_WEIGHT)
4671 perf_output_put(handle, data->weight);
4673 if (sample_type & PERF_SAMPLE_DATA_SRC)
4674 perf_output_put(handle, data->data_src.val);
4676 if (sample_type & PERF_SAMPLE_TRANSACTION)
4677 perf_output_put(handle, data->txn);
4679 if (!event->attr.watermark) {
4680 int wakeup_events = event->attr.wakeup_events;
4682 if (wakeup_events) {
4683 struct ring_buffer *rb = handle->rb;
4684 int events = local_inc_return(&rb->events);
4686 if (events >= wakeup_events) {
4687 local_sub(wakeup_events, &rb->events);
4688 local_inc(&rb->wakeup);
4694 void perf_prepare_sample(struct perf_event_header *header,
4695 struct perf_sample_data *data,
4696 struct perf_event *event,
4697 struct pt_regs *regs)
4699 u64 sample_type = event->attr.sample_type;
4701 header->type = PERF_RECORD_SAMPLE;
4702 header->size = sizeof(*header) + event->header_size;
4705 header->misc |= perf_misc_flags(regs);
4707 __perf_event_header__init_id(header, data, event);
4709 if (sample_type & PERF_SAMPLE_IP)
4710 data->ip = perf_instruction_pointer(regs);
4712 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4715 data->callchain = perf_callchain(event, regs);
4717 if (data->callchain)
4718 size += data->callchain->nr;
4720 header->size += size * sizeof(u64);
4723 if (sample_type & PERF_SAMPLE_RAW) {
4724 int size = sizeof(u32);
4727 size += data->raw->size;
4729 size += sizeof(u32);
4731 WARN_ON_ONCE(size & (sizeof(u64)-1));
4732 header->size += size;
4735 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4736 int size = sizeof(u64); /* nr */
4737 if (data->br_stack) {
4738 size += data->br_stack->nr
4739 * sizeof(struct perf_branch_entry);
4741 header->size += size;
4744 if (sample_type & PERF_SAMPLE_REGS_USER) {
4745 /* regs dump ABI info */
4746 int size = sizeof(u64);
4748 perf_sample_regs_user(&data->regs_user, regs);
4750 if (data->regs_user.regs) {
4751 u64 mask = event->attr.sample_regs_user;
4752 size += hweight64(mask) * sizeof(u64);
4755 header->size += size;
4758 if (sample_type & PERF_SAMPLE_STACK_USER) {
4760 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
4761 * processed as the last one or have additional check added
4762 * in case new sample type is added, because we could eat
4763 * up the rest of the sample size.
4765 struct perf_regs_user *uregs = &data->regs_user;
4766 u16 stack_size = event->attr.sample_stack_user;
4767 u16 size = sizeof(u64);
4770 perf_sample_regs_user(uregs, regs);
4772 stack_size = perf_sample_ustack_size(stack_size, header->size,
4776 * If there is something to dump, add space for the dump
4777 * itself and for the field that tells the dynamic size,
4778 * which is how many have been actually dumped.
4781 size += sizeof(u64) + stack_size;
4783 data->stack_user_size = stack_size;
4784 header->size += size;
4788 static void perf_event_output(struct perf_event *event,
4789 struct perf_sample_data *data,
4790 struct pt_regs *regs)
4792 struct perf_output_handle handle;
4793 struct perf_event_header header;
4795 /* protect the callchain buffers */
4798 perf_prepare_sample(&header, data, event, regs);
4800 if (perf_output_begin(&handle, event, header.size))
4803 perf_output_sample(&handle, &header, data, event);
4805 perf_output_end(&handle);
4815 struct perf_read_event {
4816 struct perf_event_header header;
4823 perf_event_read_event(struct perf_event *event,
4824 struct task_struct *task)
4826 struct perf_output_handle handle;
4827 struct perf_sample_data sample;
4828 struct perf_read_event read_event = {
4830 .type = PERF_RECORD_READ,
4832 .size = sizeof(read_event) + event->read_size,
4834 .pid = perf_event_pid(event, task),
4835 .tid = perf_event_tid(event, task),
4839 perf_event_header__init_id(&read_event.header, &sample, event);
4840 ret = perf_output_begin(&handle, event, read_event.header.size);
4844 perf_output_put(&handle, read_event);
4845 perf_output_read(&handle, event);
4846 perf_event__output_id_sample(event, &handle, &sample);
4848 perf_output_end(&handle);
4851 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
4854 perf_event_aux_ctx(struct perf_event_context *ctx,
4855 perf_event_aux_output_cb output,
4858 struct perf_event *event;
4860 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4861 if (event->state < PERF_EVENT_STATE_INACTIVE)
4863 if (!event_filter_match(event))
4865 output(event, data);
4870 perf_event_aux(perf_event_aux_output_cb output, void *data,
4871 struct perf_event_context *task_ctx)
4873 struct perf_cpu_context *cpuctx;
4874 struct perf_event_context *ctx;
4879 list_for_each_entry_rcu(pmu, &pmus, entry) {
4880 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4881 if (cpuctx->unique_pmu != pmu)
4883 perf_event_aux_ctx(&cpuctx->ctx, output, data);
4886 ctxn = pmu->task_ctx_nr;
4889 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4891 perf_event_aux_ctx(ctx, output, data);
4893 put_cpu_ptr(pmu->pmu_cpu_context);
4898 perf_event_aux_ctx(task_ctx, output, data);
4905 * task tracking -- fork/exit
4907 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
4910 struct perf_task_event {
4911 struct task_struct *task;
4912 struct perf_event_context *task_ctx;
4915 struct perf_event_header header;
4925 static int perf_event_task_match(struct perf_event *event)
4927 return event->attr.comm || event->attr.mmap ||
4928 event->attr.mmap2 || event->attr.mmap_data ||
4932 static void perf_event_task_output(struct perf_event *event,
4935 struct perf_task_event *task_event = data;
4936 struct perf_output_handle handle;
4937 struct perf_sample_data sample;
4938 struct task_struct *task = task_event->task;
4939 int ret, size = task_event->event_id.header.size;
4941 if (!perf_event_task_match(event))
4944 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
4946 ret = perf_output_begin(&handle, event,
4947 task_event->event_id.header.size);
4951 task_event->event_id.pid = perf_event_pid(event, task);
4952 task_event->event_id.ppid = perf_event_pid(event, current);
4954 task_event->event_id.tid = perf_event_tid(event, task);
4955 task_event->event_id.ptid = perf_event_tid(event, current);
4957 perf_output_put(&handle, task_event->event_id);
4959 perf_event__output_id_sample(event, &handle, &sample);
4961 perf_output_end(&handle);
4963 task_event->event_id.header.size = size;
4966 static void perf_event_task(struct task_struct *task,
4967 struct perf_event_context *task_ctx,
4970 struct perf_task_event task_event;
4972 if (!atomic_read(&nr_comm_events) &&
4973 !atomic_read(&nr_mmap_events) &&
4974 !atomic_read(&nr_task_events))
4977 task_event = (struct perf_task_event){
4979 .task_ctx = task_ctx,
4982 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
4984 .size = sizeof(task_event.event_id),
4990 .time = perf_clock(),
4994 perf_event_aux(perf_event_task_output,
4999 void perf_event_fork(struct task_struct *task)
5001 perf_event_task(task, NULL, 1);
5008 struct perf_comm_event {
5009 struct task_struct *task;
5014 struct perf_event_header header;
5021 static int perf_event_comm_match(struct perf_event *event)
5023 return event->attr.comm;
5026 static void perf_event_comm_output(struct perf_event *event,
5029 struct perf_comm_event *comm_event = data;
5030 struct perf_output_handle handle;
5031 struct perf_sample_data sample;
5032 int size = comm_event->event_id.header.size;
5035 if (!perf_event_comm_match(event))
5038 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
5039 ret = perf_output_begin(&handle, event,
5040 comm_event->event_id.header.size);
5045 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
5046 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
5048 perf_output_put(&handle, comm_event->event_id);
5049 __output_copy(&handle, comm_event->comm,
5050 comm_event->comm_size);
5052 perf_event__output_id_sample(event, &handle, &sample);
5054 perf_output_end(&handle);
5056 comm_event->event_id.header.size = size;
5059 static void perf_event_comm_event(struct perf_comm_event *comm_event)
5061 char comm[TASK_COMM_LEN];
5064 memset(comm, 0, sizeof(comm));
5065 strlcpy(comm, comm_event->task->comm, sizeof(comm));
5066 size = ALIGN(strlen(comm)+1, sizeof(u64));
5068 comm_event->comm = comm;
5069 comm_event->comm_size = size;
5071 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
5073 perf_event_aux(perf_event_comm_output,
5078 void perf_event_comm(struct task_struct *task)
5080 struct perf_comm_event comm_event;
5081 struct perf_event_context *ctx;
5085 for_each_task_context_nr(ctxn) {
5086 ctx = task->perf_event_ctxp[ctxn];
5090 perf_event_enable_on_exec(ctx);
5094 if (!atomic_read(&nr_comm_events))
5097 comm_event = (struct perf_comm_event){
5103 .type = PERF_RECORD_COMM,
5112 perf_event_comm_event(&comm_event);
5119 struct perf_mmap_event {
5120 struct vm_area_struct *vma;
5122 const char *file_name;
5129 struct perf_event_header header;
5139 static int perf_event_mmap_match(struct perf_event *event,
5142 struct perf_mmap_event *mmap_event = data;
5143 struct vm_area_struct *vma = mmap_event->vma;
5144 int executable = vma->vm_flags & VM_EXEC;
5146 return (!executable && event->attr.mmap_data) ||
5147 (executable && (event->attr.mmap || event->attr.mmap2));
5150 static void perf_event_mmap_output(struct perf_event *event,
5153 struct perf_mmap_event *mmap_event = data;
5154 struct perf_output_handle handle;
5155 struct perf_sample_data sample;
5156 int size = mmap_event->event_id.header.size;
5159 if (!perf_event_mmap_match(event, data))
5162 if (event->attr.mmap2) {
5163 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
5164 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
5165 mmap_event->event_id.header.size += sizeof(mmap_event->min);
5166 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
5167 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
5170 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
5171 ret = perf_output_begin(&handle, event,
5172 mmap_event->event_id.header.size);
5176 mmap_event->event_id.pid = perf_event_pid(event, current);
5177 mmap_event->event_id.tid = perf_event_tid(event, current);
5179 perf_output_put(&handle, mmap_event->event_id);
5181 if (event->attr.mmap2) {
5182 perf_output_put(&handle, mmap_event->maj);
5183 perf_output_put(&handle, mmap_event->min);
5184 perf_output_put(&handle, mmap_event->ino);
5185 perf_output_put(&handle, mmap_event->ino_generation);
5188 __output_copy(&handle, mmap_event->file_name,
5189 mmap_event->file_size);
5191 perf_event__output_id_sample(event, &handle, &sample);
5193 perf_output_end(&handle);
5195 mmap_event->event_id.header.size = size;
5198 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
5200 struct vm_area_struct *vma = mmap_event->vma;
5201 struct file *file = vma->vm_file;
5202 int maj = 0, min = 0;
5203 u64 ino = 0, gen = 0;
5210 struct inode *inode;
5213 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5219 * d_path() works from the end of the rb backwards, so we
5220 * need to add enough zero bytes after the string to handle
5221 * the 64bit alignment we do later.
5223 name = d_path(&file->f_path, buf, PATH_MAX - sizeof(u64));
5228 inode = file_inode(vma->vm_file);
5229 dev = inode->i_sb->s_dev;
5231 gen = inode->i_generation;
5236 name = (char *)arch_vma_name(vma);
5240 if (vma->vm_start <= vma->vm_mm->start_brk &&
5241 vma->vm_end >= vma->vm_mm->brk) {
5245 if (vma->vm_start <= vma->vm_mm->start_stack &&
5246 vma->vm_end >= vma->vm_mm->start_stack) {
5256 strlcpy(tmp, name, sizeof(tmp));
5260 * Since our buffer works in 8 byte units we need to align our string
5261 * size to a multiple of 8. However, we must guarantee the tail end is
5262 * zero'd out to avoid leaking random bits to userspace.
5264 size = strlen(name)+1;
5265 while (!IS_ALIGNED(size, sizeof(u64)))
5266 name[size++] = '\0';
5268 mmap_event->file_name = name;
5269 mmap_event->file_size = size;
5270 mmap_event->maj = maj;
5271 mmap_event->min = min;
5272 mmap_event->ino = ino;
5273 mmap_event->ino_generation = gen;
5275 if (!(vma->vm_flags & VM_EXEC))
5276 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
5278 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
5280 perf_event_aux(perf_event_mmap_output,
5287 void perf_event_mmap(struct vm_area_struct *vma)
5289 struct perf_mmap_event mmap_event;
5291 if (!atomic_read(&nr_mmap_events))
5294 mmap_event = (struct perf_mmap_event){
5300 .type = PERF_RECORD_MMAP,
5301 .misc = PERF_RECORD_MISC_USER,
5306 .start = vma->vm_start,
5307 .len = vma->vm_end - vma->vm_start,
5308 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
5310 /* .maj (attr_mmap2 only) */
5311 /* .min (attr_mmap2 only) */
5312 /* .ino (attr_mmap2 only) */
5313 /* .ino_generation (attr_mmap2 only) */
5316 perf_event_mmap_event(&mmap_event);
5320 * IRQ throttle logging
5323 static void perf_log_throttle(struct perf_event *event, int enable)
5325 struct perf_output_handle handle;
5326 struct perf_sample_data sample;
5330 struct perf_event_header header;
5334 } throttle_event = {
5336 .type = PERF_RECORD_THROTTLE,
5338 .size = sizeof(throttle_event),
5340 .time = perf_clock(),
5341 .id = primary_event_id(event),
5342 .stream_id = event->id,
5346 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
5348 perf_event_header__init_id(&throttle_event.header, &sample, event);
5350 ret = perf_output_begin(&handle, event,
5351 throttle_event.header.size);
5355 perf_output_put(&handle, throttle_event);
5356 perf_event__output_id_sample(event, &handle, &sample);
5357 perf_output_end(&handle);
5361 * Generic event overflow handling, sampling.
5364 static int __perf_event_overflow(struct perf_event *event,
5365 int throttle, struct perf_sample_data *data,
5366 struct pt_regs *regs)
5368 int events = atomic_read(&event->event_limit);
5369 struct hw_perf_event *hwc = &event->hw;
5374 * Non-sampling counters might still use the PMI to fold short
5375 * hardware counters, ignore those.
5377 if (unlikely(!is_sampling_event(event)))
5380 seq = __this_cpu_read(perf_throttled_seq);
5381 if (seq != hwc->interrupts_seq) {
5382 hwc->interrupts_seq = seq;
5383 hwc->interrupts = 1;
5386 if (unlikely(throttle
5387 && hwc->interrupts >= max_samples_per_tick)) {
5388 __this_cpu_inc(perf_throttled_count);
5389 hwc->interrupts = MAX_INTERRUPTS;
5390 perf_log_throttle(event, 0);
5391 tick_nohz_full_kick();
5396 if (event->attr.freq) {
5397 u64 now = perf_clock();
5398 s64 delta = now - hwc->freq_time_stamp;
5400 hwc->freq_time_stamp = now;
5402 if (delta > 0 && delta < 2*TICK_NSEC)
5403 perf_adjust_period(event, delta, hwc->last_period, true);
5407 * XXX event_limit might not quite work as expected on inherited
5411 event->pending_kill = POLL_IN;
5412 if (events && atomic_dec_and_test(&event->event_limit)) {
5414 event->pending_kill = POLL_HUP;
5415 event->pending_disable = 1;
5416 irq_work_queue(&event->pending);
5419 if (event->overflow_handler)
5420 event->overflow_handler(event, data, regs);
5422 perf_event_output(event, data, regs);
5424 if (event->fasync && event->pending_kill) {
5425 event->pending_wakeup = 1;
5426 irq_work_queue(&event->pending);
5432 int perf_event_overflow(struct perf_event *event,
5433 struct perf_sample_data *data,
5434 struct pt_regs *regs)
5436 return __perf_event_overflow(event, 1, data, regs);
5440 * Generic software event infrastructure
5443 struct swevent_htable {
5444 struct swevent_hlist *swevent_hlist;
5445 struct mutex hlist_mutex;
5448 /* Recursion avoidance in each contexts */
5449 int recursion[PERF_NR_CONTEXTS];
5451 /* Keeps track of cpu being initialized/exited */
5455 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
5458 * We directly increment event->count and keep a second value in
5459 * event->hw.period_left to count intervals. This period event
5460 * is kept in the range [-sample_period, 0] so that we can use the
5464 u64 perf_swevent_set_period(struct perf_event *event)
5466 struct hw_perf_event *hwc = &event->hw;
5467 u64 period = hwc->last_period;
5471 hwc->last_period = hwc->sample_period;
5474 old = val = local64_read(&hwc->period_left);
5478 nr = div64_u64(period + val, period);
5479 offset = nr * period;
5481 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
5487 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
5488 struct perf_sample_data *data,
5489 struct pt_regs *regs)
5491 struct hw_perf_event *hwc = &event->hw;
5495 overflow = perf_swevent_set_period(event);
5497 if (hwc->interrupts == MAX_INTERRUPTS)
5500 for (; overflow; overflow--) {
5501 if (__perf_event_overflow(event, throttle,
5504 * We inhibit the overflow from happening when
5505 * hwc->interrupts == MAX_INTERRUPTS.
5513 static void perf_swevent_event(struct perf_event *event, u64 nr,
5514 struct perf_sample_data *data,
5515 struct pt_regs *regs)
5517 struct hw_perf_event *hwc = &event->hw;
5519 local64_add(nr, &event->count);
5524 if (!is_sampling_event(event))
5527 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
5529 return perf_swevent_overflow(event, 1, data, regs);
5531 data->period = event->hw.last_period;
5533 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
5534 return perf_swevent_overflow(event, 1, data, regs);
5536 if (local64_add_negative(nr, &hwc->period_left))
5539 perf_swevent_overflow(event, 0, data, regs);
5542 static int perf_exclude_event(struct perf_event *event,
5543 struct pt_regs *regs)
5545 if (event->hw.state & PERF_HES_STOPPED)
5549 if (event->attr.exclude_user && user_mode(regs))
5552 if (event->attr.exclude_kernel && !user_mode(regs))
5559 static int perf_swevent_match(struct perf_event *event,
5560 enum perf_type_id type,
5562 struct perf_sample_data *data,
5563 struct pt_regs *regs)
5565 if (event->attr.type != type)
5568 if (event->attr.config != event_id)
5571 if (perf_exclude_event(event, regs))
5577 static inline u64 swevent_hash(u64 type, u32 event_id)
5579 u64 val = event_id | (type << 32);
5581 return hash_64(val, SWEVENT_HLIST_BITS);
5584 static inline struct hlist_head *
5585 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
5587 u64 hash = swevent_hash(type, event_id);
5589 return &hlist->heads[hash];
5592 /* For the read side: events when they trigger */
5593 static inline struct hlist_head *
5594 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
5596 struct swevent_hlist *hlist;
5598 hlist = rcu_dereference(swhash->swevent_hlist);
5602 return __find_swevent_head(hlist, type, event_id);
5605 /* For the event head insertion and removal in the hlist */
5606 static inline struct hlist_head *
5607 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
5609 struct swevent_hlist *hlist;
5610 u32 event_id = event->attr.config;
5611 u64 type = event->attr.type;
5614 * Event scheduling is always serialized against hlist allocation
5615 * and release. Which makes the protected version suitable here.
5616 * The context lock guarantees that.
5618 hlist = rcu_dereference_protected(swhash->swevent_hlist,
5619 lockdep_is_held(&event->ctx->lock));
5623 return __find_swevent_head(hlist, type, event_id);
5626 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
5628 struct perf_sample_data *data,
5629 struct pt_regs *regs)
5631 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5632 struct perf_event *event;
5633 struct hlist_head *head;
5636 head = find_swevent_head_rcu(swhash, type, event_id);
5640 hlist_for_each_entry_rcu(event, head, hlist_entry) {
5641 if (perf_swevent_match(event, type, event_id, data, regs))
5642 perf_swevent_event(event, nr, data, regs);
5648 int perf_swevent_get_recursion_context(void)
5650 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5652 return get_recursion_context(swhash->recursion);
5654 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
5656 inline void perf_swevent_put_recursion_context(int rctx)
5658 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5660 put_recursion_context(swhash->recursion, rctx);
5663 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
5665 struct perf_sample_data data;
5668 preempt_disable_notrace();
5669 rctx = perf_swevent_get_recursion_context();
5673 perf_sample_data_init(&data, addr, 0);
5675 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
5677 perf_swevent_put_recursion_context(rctx);
5678 preempt_enable_notrace();
5681 static void perf_swevent_read(struct perf_event *event)
5685 static int perf_swevent_add(struct perf_event *event, int flags)
5687 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5688 struct hw_perf_event *hwc = &event->hw;
5689 struct hlist_head *head;
5691 if (is_sampling_event(event)) {
5692 hwc->last_period = hwc->sample_period;
5693 perf_swevent_set_period(event);
5696 hwc->state = !(flags & PERF_EF_START);
5698 head = find_swevent_head(swhash, event);
5701 * We can race with cpu hotplug code. Do not
5702 * WARN if the cpu just got unplugged.
5704 WARN_ON_ONCE(swhash->online);
5708 hlist_add_head_rcu(&event->hlist_entry, head);
5713 static void perf_swevent_del(struct perf_event *event, int flags)
5715 hlist_del_rcu(&event->hlist_entry);
5718 static void perf_swevent_start(struct perf_event *event, int flags)
5720 event->hw.state = 0;
5723 static void perf_swevent_stop(struct perf_event *event, int flags)
5725 event->hw.state = PERF_HES_STOPPED;
5728 /* Deref the hlist from the update side */
5729 static inline struct swevent_hlist *
5730 swevent_hlist_deref(struct swevent_htable *swhash)
5732 return rcu_dereference_protected(swhash->swevent_hlist,
5733 lockdep_is_held(&swhash->hlist_mutex));
5736 static void swevent_hlist_release(struct swevent_htable *swhash)
5738 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
5743 rcu_assign_pointer(swhash->swevent_hlist, NULL);
5744 kfree_rcu(hlist, rcu_head);
5747 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
5749 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5751 mutex_lock(&swhash->hlist_mutex);
5753 if (!--swhash->hlist_refcount)
5754 swevent_hlist_release(swhash);
5756 mutex_unlock(&swhash->hlist_mutex);
5759 static void swevent_hlist_put(struct perf_event *event)
5763 for_each_possible_cpu(cpu)
5764 swevent_hlist_put_cpu(event, cpu);
5767 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
5769 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5772 mutex_lock(&swhash->hlist_mutex);
5774 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
5775 struct swevent_hlist *hlist;
5777 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
5782 rcu_assign_pointer(swhash->swevent_hlist, hlist);
5784 swhash->hlist_refcount++;
5786 mutex_unlock(&swhash->hlist_mutex);
5791 static int swevent_hlist_get(struct perf_event *event)
5794 int cpu, failed_cpu;
5797 for_each_possible_cpu(cpu) {
5798 err = swevent_hlist_get_cpu(event, cpu);
5808 for_each_possible_cpu(cpu) {
5809 if (cpu == failed_cpu)
5811 swevent_hlist_put_cpu(event, cpu);
5818 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
5820 static void sw_perf_event_destroy(struct perf_event *event)
5822 u64 event_id = event->attr.config;
5824 WARN_ON(event->parent);
5826 static_key_slow_dec(&perf_swevent_enabled[event_id]);
5827 swevent_hlist_put(event);
5830 static int perf_swevent_init(struct perf_event *event)
5832 u64 event_id = event->attr.config;
5834 if (event->attr.type != PERF_TYPE_SOFTWARE)
5838 * no branch sampling for software events
5840 if (has_branch_stack(event))
5844 case PERF_COUNT_SW_CPU_CLOCK:
5845 case PERF_COUNT_SW_TASK_CLOCK:
5852 if (event_id >= PERF_COUNT_SW_MAX)
5855 if (!event->parent) {
5858 err = swevent_hlist_get(event);
5862 static_key_slow_inc(&perf_swevent_enabled[event_id]);
5863 event->destroy = sw_perf_event_destroy;
5869 static int perf_swevent_event_idx(struct perf_event *event)
5874 static struct pmu perf_swevent = {
5875 .task_ctx_nr = perf_sw_context,
5877 .event_init = perf_swevent_init,
5878 .add = perf_swevent_add,
5879 .del = perf_swevent_del,
5880 .start = perf_swevent_start,
5881 .stop = perf_swevent_stop,
5882 .read = perf_swevent_read,
5884 .event_idx = perf_swevent_event_idx,
5887 #ifdef CONFIG_EVENT_TRACING
5889 static int perf_tp_filter_match(struct perf_event *event,
5890 struct perf_sample_data *data)
5892 void *record = data->raw->data;
5894 if (likely(!event->filter) || filter_match_preds(event->filter, record))
5899 static int perf_tp_event_match(struct perf_event *event,
5900 struct perf_sample_data *data,
5901 struct pt_regs *regs)
5903 if (event->hw.state & PERF_HES_STOPPED)
5906 * All tracepoints are from kernel-space.
5908 if (event->attr.exclude_kernel)
5911 if (!perf_tp_filter_match(event, data))
5917 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
5918 struct pt_regs *regs, struct hlist_head *head, int rctx,
5919 struct task_struct *task)
5921 struct perf_sample_data data;
5922 struct perf_event *event;
5924 struct perf_raw_record raw = {
5929 perf_sample_data_init(&data, addr, 0);
5932 hlist_for_each_entry_rcu(event, head, hlist_entry) {
5933 if (perf_tp_event_match(event, &data, regs))
5934 perf_swevent_event(event, count, &data, regs);
5938 * If we got specified a target task, also iterate its context and
5939 * deliver this event there too.
5941 if (task && task != current) {
5942 struct perf_event_context *ctx;
5943 struct trace_entry *entry = record;
5946 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
5950 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5951 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5953 if (event->attr.config != entry->type)
5955 if (perf_tp_event_match(event, &data, regs))
5956 perf_swevent_event(event, count, &data, regs);
5962 perf_swevent_put_recursion_context(rctx);
5964 EXPORT_SYMBOL_GPL(perf_tp_event);
5966 static void tp_perf_event_destroy(struct perf_event *event)
5968 perf_trace_destroy(event);
5971 static int perf_tp_event_init(struct perf_event *event)
5975 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5979 * no branch sampling for tracepoint events
5981 if (has_branch_stack(event))
5984 err = perf_trace_init(event);
5988 event->destroy = tp_perf_event_destroy;
5993 static struct pmu perf_tracepoint = {
5994 .task_ctx_nr = perf_sw_context,
5996 .event_init = perf_tp_event_init,
5997 .add = perf_trace_add,
5998 .del = perf_trace_del,
5999 .start = perf_swevent_start,
6000 .stop = perf_swevent_stop,
6001 .read = perf_swevent_read,
6003 .event_idx = perf_swevent_event_idx,
6006 static inline void perf_tp_register(void)
6008 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
6011 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
6016 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6019 filter_str = strndup_user(arg, PAGE_SIZE);
6020 if (IS_ERR(filter_str))
6021 return PTR_ERR(filter_str);
6023 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
6029 static void perf_event_free_filter(struct perf_event *event)
6031 ftrace_profile_free_filter(event);
6036 static inline void perf_tp_register(void)
6040 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
6045 static void perf_event_free_filter(struct perf_event *event)
6049 #endif /* CONFIG_EVENT_TRACING */
6051 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6052 void perf_bp_event(struct perf_event *bp, void *data)
6054 struct perf_sample_data sample;
6055 struct pt_regs *regs = data;
6057 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
6059 if (!bp->hw.state && !perf_exclude_event(bp, regs))
6060 perf_swevent_event(bp, 1, &sample, regs);
6065 * hrtimer based swevent callback
6068 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
6070 enum hrtimer_restart ret = HRTIMER_RESTART;
6071 struct perf_sample_data data;
6072 struct pt_regs *regs;
6073 struct perf_event *event;
6076 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
6078 if (event->state != PERF_EVENT_STATE_ACTIVE)
6079 return HRTIMER_NORESTART;
6081 event->pmu->read(event);
6083 perf_sample_data_init(&data, 0, event->hw.last_period);
6084 regs = get_irq_regs();
6086 if (regs && !perf_exclude_event(event, regs)) {
6087 if (!(event->attr.exclude_idle && is_idle_task(current)))
6088 if (__perf_event_overflow(event, 1, &data, regs))
6089 ret = HRTIMER_NORESTART;
6092 period = max_t(u64, 10000, event->hw.sample_period);
6093 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
6098 static void perf_swevent_start_hrtimer(struct perf_event *event)
6100 struct hw_perf_event *hwc = &event->hw;
6103 if (!is_sampling_event(event))
6106 period = local64_read(&hwc->period_left);
6111 local64_set(&hwc->period_left, 0);
6113 period = max_t(u64, 10000, hwc->sample_period);
6115 __hrtimer_start_range_ns(&hwc->hrtimer,
6116 ns_to_ktime(period), 0,
6117 HRTIMER_MODE_REL_PINNED, 0);
6120 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
6122 struct hw_perf_event *hwc = &event->hw;
6124 if (is_sampling_event(event)) {
6125 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
6126 local64_set(&hwc->period_left, ktime_to_ns(remaining));
6128 hrtimer_cancel(&hwc->hrtimer);
6132 static void perf_swevent_init_hrtimer(struct perf_event *event)
6134 struct hw_perf_event *hwc = &event->hw;
6136 if (!is_sampling_event(event))
6139 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6140 hwc->hrtimer.function = perf_swevent_hrtimer;
6143 * Since hrtimers have a fixed rate, we can do a static freq->period
6144 * mapping and avoid the whole period adjust feedback stuff.
6146 if (event->attr.freq) {
6147 long freq = event->attr.sample_freq;
6149 event->attr.sample_period = NSEC_PER_SEC / freq;
6150 hwc->sample_period = event->attr.sample_period;
6151 local64_set(&hwc->period_left, hwc->sample_period);
6152 hwc->last_period = hwc->sample_period;
6153 event->attr.freq = 0;
6158 * Software event: cpu wall time clock
6161 static void cpu_clock_event_update(struct perf_event *event)
6166 now = local_clock();
6167 prev = local64_xchg(&event->hw.prev_count, now);
6168 local64_add(now - prev, &event->count);
6171 static void cpu_clock_event_start(struct perf_event *event, int flags)
6173 local64_set(&event->hw.prev_count, local_clock());
6174 perf_swevent_start_hrtimer(event);
6177 static void cpu_clock_event_stop(struct perf_event *event, int flags)
6179 perf_swevent_cancel_hrtimer(event);
6180 cpu_clock_event_update(event);
6183 static int cpu_clock_event_add(struct perf_event *event, int flags)
6185 if (flags & PERF_EF_START)
6186 cpu_clock_event_start(event, flags);
6191 static void cpu_clock_event_del(struct perf_event *event, int flags)
6193 cpu_clock_event_stop(event, flags);
6196 static void cpu_clock_event_read(struct perf_event *event)
6198 cpu_clock_event_update(event);
6201 static int cpu_clock_event_init(struct perf_event *event)
6203 if (event->attr.type != PERF_TYPE_SOFTWARE)
6206 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
6210 * no branch sampling for software events
6212 if (has_branch_stack(event))
6215 perf_swevent_init_hrtimer(event);
6220 static struct pmu perf_cpu_clock = {
6221 .task_ctx_nr = perf_sw_context,
6223 .event_init = cpu_clock_event_init,
6224 .add = cpu_clock_event_add,
6225 .del = cpu_clock_event_del,
6226 .start = cpu_clock_event_start,
6227 .stop = cpu_clock_event_stop,
6228 .read = cpu_clock_event_read,
6230 .event_idx = perf_swevent_event_idx,
6234 * Software event: task time clock
6237 static void task_clock_event_update(struct perf_event *event, u64 now)
6242 prev = local64_xchg(&event->hw.prev_count, now);
6244 local64_add(delta, &event->count);
6247 static void task_clock_event_start(struct perf_event *event, int flags)
6249 local64_set(&event->hw.prev_count, event->ctx->time);
6250 perf_swevent_start_hrtimer(event);
6253 static void task_clock_event_stop(struct perf_event *event, int flags)
6255 perf_swevent_cancel_hrtimer(event);
6256 task_clock_event_update(event, event->ctx->time);
6259 static int task_clock_event_add(struct perf_event *event, int flags)
6261 if (flags & PERF_EF_START)
6262 task_clock_event_start(event, flags);
6267 static void task_clock_event_del(struct perf_event *event, int flags)
6269 task_clock_event_stop(event, PERF_EF_UPDATE);
6272 static void task_clock_event_read(struct perf_event *event)
6274 u64 now = perf_clock();
6275 u64 delta = now - event->ctx->timestamp;
6276 u64 time = event->ctx->time + delta;
6278 task_clock_event_update(event, time);
6281 static int task_clock_event_init(struct perf_event *event)
6283 if (event->attr.type != PERF_TYPE_SOFTWARE)
6286 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
6290 * no branch sampling for software events
6292 if (has_branch_stack(event))
6295 perf_swevent_init_hrtimer(event);
6300 static struct pmu perf_task_clock = {
6301 .task_ctx_nr = perf_sw_context,
6303 .event_init = task_clock_event_init,
6304 .add = task_clock_event_add,
6305 .del = task_clock_event_del,
6306 .start = task_clock_event_start,
6307 .stop = task_clock_event_stop,
6308 .read = task_clock_event_read,
6310 .event_idx = perf_swevent_event_idx,
6313 static void perf_pmu_nop_void(struct pmu *pmu)
6317 static int perf_pmu_nop_int(struct pmu *pmu)
6322 static void perf_pmu_start_txn(struct pmu *pmu)
6324 perf_pmu_disable(pmu);
6327 static int perf_pmu_commit_txn(struct pmu *pmu)
6329 perf_pmu_enable(pmu);
6333 static void perf_pmu_cancel_txn(struct pmu *pmu)
6335 perf_pmu_enable(pmu);
6338 static int perf_event_idx_default(struct perf_event *event)
6340 return event->hw.idx + 1;
6344 * Ensures all contexts with the same task_ctx_nr have the same
6345 * pmu_cpu_context too.
6347 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
6354 list_for_each_entry(pmu, &pmus, entry) {
6355 if (pmu->task_ctx_nr == ctxn)
6356 return pmu->pmu_cpu_context;
6362 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
6366 for_each_possible_cpu(cpu) {
6367 struct perf_cpu_context *cpuctx;
6369 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6371 if (cpuctx->unique_pmu == old_pmu)
6372 cpuctx->unique_pmu = pmu;
6376 static void free_pmu_context(struct pmu *pmu)
6380 mutex_lock(&pmus_lock);
6382 * Like a real lame refcount.
6384 list_for_each_entry(i, &pmus, entry) {
6385 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
6386 update_pmu_context(i, pmu);
6391 free_percpu(pmu->pmu_cpu_context);
6393 mutex_unlock(&pmus_lock);
6395 static struct idr pmu_idr;
6398 type_show(struct device *dev, struct device_attribute *attr, char *page)
6400 struct pmu *pmu = dev_get_drvdata(dev);
6402 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
6404 static DEVICE_ATTR_RO(type);
6407 perf_event_mux_interval_ms_show(struct device *dev,
6408 struct device_attribute *attr,
6411 struct pmu *pmu = dev_get_drvdata(dev);
6413 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
6417 perf_event_mux_interval_ms_store(struct device *dev,
6418 struct device_attribute *attr,
6419 const char *buf, size_t count)
6421 struct pmu *pmu = dev_get_drvdata(dev);
6422 int timer, cpu, ret;
6424 ret = kstrtoint(buf, 0, &timer);
6431 /* same value, noting to do */
6432 if (timer == pmu->hrtimer_interval_ms)
6435 pmu->hrtimer_interval_ms = timer;
6437 /* update all cpuctx for this PMU */
6438 for_each_possible_cpu(cpu) {
6439 struct perf_cpu_context *cpuctx;
6440 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6441 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
6443 if (hrtimer_active(&cpuctx->hrtimer))
6444 hrtimer_forward_now(&cpuctx->hrtimer, cpuctx->hrtimer_interval);
6449 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
6451 static struct attribute *pmu_dev_attrs[] = {
6452 &dev_attr_type.attr,
6453 &dev_attr_perf_event_mux_interval_ms.attr,
6456 ATTRIBUTE_GROUPS(pmu_dev);
6458 static int pmu_bus_running;
6459 static struct bus_type pmu_bus = {
6460 .name = "event_source",
6461 .dev_groups = pmu_dev_groups,
6464 static void pmu_dev_release(struct device *dev)
6469 static int pmu_dev_alloc(struct pmu *pmu)
6473 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
6477 pmu->dev->groups = pmu->attr_groups;
6478 device_initialize(pmu->dev);
6479 ret = dev_set_name(pmu->dev, "%s", pmu->name);
6483 dev_set_drvdata(pmu->dev, pmu);
6484 pmu->dev->bus = &pmu_bus;
6485 pmu->dev->release = pmu_dev_release;
6486 ret = device_add(pmu->dev);
6494 put_device(pmu->dev);
6498 static struct lock_class_key cpuctx_mutex;
6499 static struct lock_class_key cpuctx_lock;
6501 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
6505 mutex_lock(&pmus_lock);
6507 pmu->pmu_disable_count = alloc_percpu(int);
6508 if (!pmu->pmu_disable_count)
6517 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
6525 if (pmu_bus_running) {
6526 ret = pmu_dev_alloc(pmu);
6532 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
6533 if (pmu->pmu_cpu_context)
6534 goto got_cpu_context;
6537 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
6538 if (!pmu->pmu_cpu_context)
6541 for_each_possible_cpu(cpu) {
6542 struct perf_cpu_context *cpuctx;
6544 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6545 __perf_event_init_context(&cpuctx->ctx);
6546 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
6547 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
6548 cpuctx->ctx.type = cpu_context;
6549 cpuctx->ctx.pmu = pmu;
6551 __perf_cpu_hrtimer_init(cpuctx, cpu);
6553 INIT_LIST_HEAD(&cpuctx->rotation_list);
6554 cpuctx->unique_pmu = pmu;
6558 if (!pmu->start_txn) {
6559 if (pmu->pmu_enable) {
6561 * If we have pmu_enable/pmu_disable calls, install
6562 * transaction stubs that use that to try and batch
6563 * hardware accesses.
6565 pmu->start_txn = perf_pmu_start_txn;
6566 pmu->commit_txn = perf_pmu_commit_txn;
6567 pmu->cancel_txn = perf_pmu_cancel_txn;
6569 pmu->start_txn = perf_pmu_nop_void;
6570 pmu->commit_txn = perf_pmu_nop_int;
6571 pmu->cancel_txn = perf_pmu_nop_void;
6575 if (!pmu->pmu_enable) {
6576 pmu->pmu_enable = perf_pmu_nop_void;
6577 pmu->pmu_disable = perf_pmu_nop_void;
6580 if (!pmu->event_idx)
6581 pmu->event_idx = perf_event_idx_default;
6583 list_add_rcu(&pmu->entry, &pmus);
6586 mutex_unlock(&pmus_lock);
6591 device_del(pmu->dev);
6592 put_device(pmu->dev);
6595 if (pmu->type >= PERF_TYPE_MAX)
6596 idr_remove(&pmu_idr, pmu->type);
6599 free_percpu(pmu->pmu_disable_count);
6602 EXPORT_SYMBOL_GPL(perf_pmu_register);
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);
6624 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
6626 struct pmu *perf_init_event(struct perf_event *event)
6628 struct pmu *pmu = NULL;
6632 idx = srcu_read_lock(&pmus_srcu);
6635 pmu = idr_find(&pmu_idr, event->attr.type);
6638 if (!try_module_get(pmu->module)) {
6639 pmu = ERR_PTR(-ENODEV);
6643 ret = pmu->event_init(event);
6649 list_for_each_entry_rcu(pmu, &pmus, entry) {
6650 if (!try_module_get(pmu->module)) {
6651 pmu = ERR_PTR(-ENODEV);
6655 ret = pmu->event_init(event);
6659 if (ret != -ENOENT) {
6664 pmu = ERR_PTR(-ENOENT);
6666 srcu_read_unlock(&pmus_srcu, idx);
6671 static void account_event_cpu(struct perf_event *event, int cpu)
6676 if (has_branch_stack(event)) {
6677 if (!(event->attach_state & PERF_ATTACH_TASK))
6678 atomic_inc(&per_cpu(perf_branch_stack_events, cpu));
6680 if (is_cgroup_event(event))
6681 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
6684 static void account_event(struct perf_event *event)
6689 if (event->attach_state & PERF_ATTACH_TASK)
6690 static_key_slow_inc(&perf_sched_events.key);
6691 if (event->attr.mmap || event->attr.mmap_data)
6692 atomic_inc(&nr_mmap_events);
6693 if (event->attr.comm)
6694 atomic_inc(&nr_comm_events);
6695 if (event->attr.task)
6696 atomic_inc(&nr_task_events);
6697 if (event->attr.freq) {
6698 if (atomic_inc_return(&nr_freq_events) == 1)
6699 tick_nohz_full_kick_all();
6701 if (has_branch_stack(event))
6702 static_key_slow_inc(&perf_sched_events.key);
6703 if (is_cgroup_event(event))
6704 static_key_slow_inc(&perf_sched_events.key);
6706 account_event_cpu(event, event->cpu);
6710 * Allocate and initialize a event structure
6712 static struct perf_event *
6713 perf_event_alloc(struct perf_event_attr *attr, int cpu,
6714 struct task_struct *task,
6715 struct perf_event *group_leader,
6716 struct perf_event *parent_event,
6717 perf_overflow_handler_t overflow_handler,
6721 struct perf_event *event;
6722 struct hw_perf_event *hwc;
6725 if ((unsigned)cpu >= nr_cpu_ids) {
6726 if (!task || cpu != -1)
6727 return ERR_PTR(-EINVAL);
6730 event = kzalloc(sizeof(*event), GFP_KERNEL);
6732 return ERR_PTR(-ENOMEM);
6735 * Single events are their own group leaders, with an
6736 * empty sibling list:
6739 group_leader = event;
6741 mutex_init(&event->child_mutex);
6742 INIT_LIST_HEAD(&event->child_list);
6744 INIT_LIST_HEAD(&event->group_entry);
6745 INIT_LIST_HEAD(&event->event_entry);
6746 INIT_LIST_HEAD(&event->sibling_list);
6747 INIT_LIST_HEAD(&event->rb_entry);
6748 INIT_LIST_HEAD(&event->active_entry);
6749 INIT_HLIST_NODE(&event->hlist_entry);
6752 init_waitqueue_head(&event->waitq);
6753 init_irq_work(&event->pending, perf_pending_event);
6755 mutex_init(&event->mmap_mutex);
6757 atomic_long_set(&event->refcount, 1);
6759 event->attr = *attr;
6760 event->group_leader = group_leader;
6764 event->parent = parent_event;
6766 event->ns = get_pid_ns(task_active_pid_ns(current));
6767 event->id = atomic64_inc_return(&perf_event_id);
6769 event->state = PERF_EVENT_STATE_INACTIVE;
6772 event->attach_state = PERF_ATTACH_TASK;
6774 if (attr->type == PERF_TYPE_TRACEPOINT)
6775 event->hw.tp_target = task;
6776 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6778 * hw_breakpoint is a bit difficult here..
6780 else if (attr->type == PERF_TYPE_BREAKPOINT)
6781 event->hw.bp_target = task;
6785 if (!overflow_handler && parent_event) {
6786 overflow_handler = parent_event->overflow_handler;
6787 context = parent_event->overflow_handler_context;
6790 event->overflow_handler = overflow_handler;
6791 event->overflow_handler_context = context;
6793 perf_event__state_init(event);
6798 hwc->sample_period = attr->sample_period;
6799 if (attr->freq && attr->sample_freq)
6800 hwc->sample_period = 1;
6801 hwc->last_period = hwc->sample_period;
6803 local64_set(&hwc->period_left, hwc->sample_period);
6806 * we currently do not support PERF_FORMAT_GROUP on inherited events
6808 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
6811 pmu = perf_init_event(event);
6814 else if (IS_ERR(pmu)) {
6819 if (!event->parent) {
6820 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
6821 err = get_callchain_buffers();
6831 event->destroy(event);
6832 module_put(pmu->module);
6835 put_pid_ns(event->ns);
6838 return ERR_PTR(err);
6841 static int perf_copy_attr(struct perf_event_attr __user *uattr,
6842 struct perf_event_attr *attr)
6847 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
6851 * zero the full structure, so that a short copy will be nice.
6853 memset(attr, 0, sizeof(*attr));
6855 ret = get_user(size, &uattr->size);
6859 if (size > PAGE_SIZE) /* silly large */
6862 if (!size) /* abi compat */
6863 size = PERF_ATTR_SIZE_VER0;
6865 if (size < PERF_ATTR_SIZE_VER0)
6869 * If we're handed a bigger struct than we know of,
6870 * ensure all the unknown bits are 0 - i.e. new
6871 * user-space does not rely on any kernel feature
6872 * extensions we dont know about yet.
6874 if (size > sizeof(*attr)) {
6875 unsigned char __user *addr;
6876 unsigned char __user *end;
6879 addr = (void __user *)uattr + sizeof(*attr);
6880 end = (void __user *)uattr + size;
6882 for (; addr < end; addr++) {
6883 ret = get_user(val, addr);
6889 size = sizeof(*attr);
6892 ret = copy_from_user(attr, uattr, size);
6896 /* disabled for now */
6900 if (attr->__reserved_1)
6903 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
6906 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
6909 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
6910 u64 mask = attr->branch_sample_type;
6912 /* only using defined bits */
6913 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
6916 /* at least one branch bit must be set */
6917 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
6920 /* propagate priv level, when not set for branch */
6921 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
6923 /* exclude_kernel checked on syscall entry */
6924 if (!attr->exclude_kernel)
6925 mask |= PERF_SAMPLE_BRANCH_KERNEL;
6927 if (!attr->exclude_user)
6928 mask |= PERF_SAMPLE_BRANCH_USER;
6930 if (!attr->exclude_hv)
6931 mask |= PERF_SAMPLE_BRANCH_HV;
6933 * adjust user setting (for HW filter setup)
6935 attr->branch_sample_type = mask;
6937 /* privileged levels capture (kernel, hv): check permissions */
6938 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
6939 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
6943 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
6944 ret = perf_reg_validate(attr->sample_regs_user);
6949 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
6950 if (!arch_perf_have_user_stack_dump())
6954 * We have __u32 type for the size, but so far
6955 * we can only use __u16 as maximum due to the
6956 * __u16 sample size limit.
6958 if (attr->sample_stack_user >= USHRT_MAX)
6960 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
6968 put_user(sizeof(*attr), &uattr->size);
6974 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
6976 struct ring_buffer *rb = NULL;
6982 /* don't allow circular references */
6983 if (event == output_event)
6987 * Don't allow cross-cpu buffers
6989 if (output_event->cpu != event->cpu)
6993 * If its not a per-cpu rb, it must be the same task.
6995 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
6999 mutex_lock(&event->mmap_mutex);
7000 /* Can't redirect output if we've got an active mmap() */
7001 if (atomic_read(&event->mmap_count))
7005 /* get the rb we want to redirect to */
7006 rb = ring_buffer_get(output_event);
7011 ring_buffer_attach(event, rb);
7015 mutex_unlock(&event->mmap_mutex);
7022 * sys_perf_event_open - open a performance event, associate it to a task/cpu
7024 * @attr_uptr: event_id type attributes for monitoring/sampling
7027 * @group_fd: group leader event fd
7029 SYSCALL_DEFINE5(perf_event_open,
7030 struct perf_event_attr __user *, attr_uptr,
7031 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
7033 struct perf_event *group_leader = NULL, *output_event = NULL;
7034 struct perf_event *event, *sibling;
7035 struct perf_event_attr attr;
7036 struct perf_event_context *ctx;
7037 struct file *event_file = NULL;
7038 struct fd group = {NULL, 0};
7039 struct task_struct *task = NULL;
7044 int f_flags = O_RDWR;
7046 /* for future expandability... */
7047 if (flags & ~PERF_FLAG_ALL)
7050 err = perf_copy_attr(attr_uptr, &attr);
7054 if (!attr.exclude_kernel) {
7055 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
7060 if (attr.sample_freq > sysctl_perf_event_sample_rate)
7063 if (attr.sample_period & (1ULL << 63))
7068 * In cgroup mode, the pid argument is used to pass the fd
7069 * opened to the cgroup directory in cgroupfs. The cpu argument
7070 * designates the cpu on which to monitor threads from that
7073 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
7076 if (flags & PERF_FLAG_FD_CLOEXEC)
7077 f_flags |= O_CLOEXEC;
7079 event_fd = get_unused_fd_flags(f_flags);
7083 if (group_fd != -1) {
7084 err = perf_fget_light(group_fd, &group);
7087 group_leader = group.file->private_data;
7088 if (flags & PERF_FLAG_FD_OUTPUT)
7089 output_event = group_leader;
7090 if (flags & PERF_FLAG_FD_NO_GROUP)
7091 group_leader = NULL;
7094 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
7095 task = find_lively_task_by_vpid(pid);
7097 err = PTR_ERR(task);
7102 if (task && group_leader &&
7103 group_leader->attr.inherit != attr.inherit) {
7110 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
7112 if (IS_ERR(event)) {
7113 err = PTR_ERR(event);
7117 if (flags & PERF_FLAG_PID_CGROUP) {
7118 err = perf_cgroup_connect(pid, event, &attr, group_leader);
7120 __free_event(event);
7125 account_event(event);
7128 * Special case software events and allow them to be part of
7129 * any hardware group.
7134 (is_software_event(event) != is_software_event(group_leader))) {
7135 if (is_software_event(event)) {
7137 * If event and group_leader are not both a software
7138 * event, and event is, then group leader is not.
7140 * Allow the addition of software events to !software
7141 * groups, this is safe because software events never
7144 pmu = group_leader->pmu;
7145 } else if (is_software_event(group_leader) &&
7146 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
7148 * In case the group is a pure software group, and we
7149 * try to add a hardware event, move the whole group to
7150 * the hardware context.
7157 * Get the target context (task or percpu):
7159 ctx = find_get_context(pmu, task, event->cpu);
7166 put_task_struct(task);
7171 * Look up the group leader (we will attach this event to it):
7177 * Do not allow a recursive hierarchy (this new sibling
7178 * becoming part of another group-sibling):
7180 if (group_leader->group_leader != group_leader)
7183 * Do not allow to attach to a group in a different
7184 * task or CPU context:
7187 if (group_leader->ctx->type != ctx->type)
7190 if (group_leader->ctx != ctx)
7195 * Only a group leader can be exclusive or pinned
7197 if (attr.exclusive || attr.pinned)
7202 err = perf_event_set_output(event, output_event);
7207 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
7209 if (IS_ERR(event_file)) {
7210 err = PTR_ERR(event_file);
7215 struct perf_event_context *gctx = group_leader->ctx;
7217 mutex_lock(&gctx->mutex);
7218 perf_remove_from_context(group_leader, false);
7221 * Removing from the context ends up with disabled
7222 * event. What we want here is event in the initial
7223 * startup state, ready to be add into new context.
7225 perf_event__state_init(group_leader);
7226 list_for_each_entry(sibling, &group_leader->sibling_list,
7228 perf_remove_from_context(sibling, false);
7229 perf_event__state_init(sibling);
7232 mutex_unlock(&gctx->mutex);
7236 WARN_ON_ONCE(ctx->parent_ctx);
7237 mutex_lock(&ctx->mutex);
7241 perf_install_in_context(ctx, group_leader, event->cpu);
7243 list_for_each_entry(sibling, &group_leader->sibling_list,
7245 perf_install_in_context(ctx, sibling, event->cpu);
7250 perf_install_in_context(ctx, event, event->cpu);
7251 perf_unpin_context(ctx);
7252 mutex_unlock(&ctx->mutex);
7256 event->owner = current;
7258 mutex_lock(¤t->perf_event_mutex);
7259 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
7260 mutex_unlock(¤t->perf_event_mutex);
7263 * Precalculate sample_data sizes
7265 perf_event__header_size(event);
7266 perf_event__id_header_size(event);
7269 * Drop the reference on the group_event after placing the
7270 * new event on the sibling_list. This ensures destruction
7271 * of the group leader will find the pointer to itself in
7272 * perf_group_detach().
7275 fd_install(event_fd, event_file);
7279 perf_unpin_context(ctx);
7287 put_task_struct(task);
7291 put_unused_fd(event_fd);
7296 * perf_event_create_kernel_counter
7298 * @attr: attributes of the counter to create
7299 * @cpu: cpu in which the counter is bound
7300 * @task: task to profile (NULL for percpu)
7303 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
7304 struct task_struct *task,
7305 perf_overflow_handler_t overflow_handler,
7308 struct perf_event_context *ctx;
7309 struct perf_event *event;
7313 * Get the target context (task or percpu):
7316 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
7317 overflow_handler, context);
7318 if (IS_ERR(event)) {
7319 err = PTR_ERR(event);
7323 account_event(event);
7325 ctx = find_get_context(event->pmu, task, cpu);
7331 WARN_ON_ONCE(ctx->parent_ctx);
7332 mutex_lock(&ctx->mutex);
7333 perf_install_in_context(ctx, event, cpu);
7334 perf_unpin_context(ctx);
7335 mutex_unlock(&ctx->mutex);
7342 return ERR_PTR(err);
7344 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
7346 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
7348 struct perf_event_context *src_ctx;
7349 struct perf_event_context *dst_ctx;
7350 struct perf_event *event, *tmp;
7353 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
7354 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
7356 mutex_lock(&src_ctx->mutex);
7357 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
7359 perf_remove_from_context(event, false);
7360 unaccount_event_cpu(event, src_cpu);
7362 list_add(&event->migrate_entry, &events);
7364 mutex_unlock(&src_ctx->mutex);
7368 mutex_lock(&dst_ctx->mutex);
7369 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
7370 list_del(&event->migrate_entry);
7371 if (event->state >= PERF_EVENT_STATE_OFF)
7372 event->state = PERF_EVENT_STATE_INACTIVE;
7373 account_event_cpu(event, dst_cpu);
7374 perf_install_in_context(dst_ctx, event, dst_cpu);
7377 mutex_unlock(&dst_ctx->mutex);
7379 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
7381 static void sync_child_event(struct perf_event *child_event,
7382 struct task_struct *child)
7384 struct perf_event *parent_event = child_event->parent;
7387 if (child_event->attr.inherit_stat)
7388 perf_event_read_event(child_event, child);
7390 child_val = perf_event_count(child_event);
7393 * Add back the child's count to the parent's count:
7395 atomic64_add(child_val, &parent_event->child_count);
7396 atomic64_add(child_event->total_time_enabled,
7397 &parent_event->child_total_time_enabled);
7398 atomic64_add(child_event->total_time_running,
7399 &parent_event->child_total_time_running);
7402 * Remove this event from the parent's list
7404 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7405 mutex_lock(&parent_event->child_mutex);
7406 list_del_init(&child_event->child_list);
7407 mutex_unlock(&parent_event->child_mutex);
7410 * Release the parent event, if this was the last
7413 put_event(parent_event);
7417 __perf_event_exit_task(struct perf_event *child_event,
7418 struct perf_event_context *child_ctx,
7419 struct task_struct *child)
7421 perf_remove_from_context(child_event, true);
7424 * It can happen that the parent exits first, and has events
7425 * that are still around due to the child reference. These
7426 * events need to be zapped.
7428 if (child_event->parent) {
7429 sync_child_event(child_event, child);
7430 free_event(child_event);
7434 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
7436 struct perf_event *child_event;
7437 struct perf_event_context *child_ctx;
7438 unsigned long flags;
7440 if (likely(!child->perf_event_ctxp[ctxn])) {
7441 perf_event_task(child, NULL, 0);
7445 local_irq_save(flags);
7447 * We can't reschedule here because interrupts are disabled,
7448 * and either child is current or it is a task that can't be
7449 * scheduled, so we are now safe from rescheduling changing
7452 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
7455 * Take the context lock here so that if find_get_context is
7456 * reading child->perf_event_ctxp, we wait until it has
7457 * incremented the context's refcount before we do put_ctx below.
7459 raw_spin_lock(&child_ctx->lock);
7460 task_ctx_sched_out(child_ctx);
7461 child->perf_event_ctxp[ctxn] = NULL;
7463 * If this context is a clone; unclone it so it can't get
7464 * swapped to another process while we're removing all
7465 * the events from it.
7467 unclone_ctx(child_ctx);
7468 update_context_time(child_ctx);
7469 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7472 * Report the task dead after unscheduling the events so that we
7473 * won't get any samples after PERF_RECORD_EXIT. We can however still
7474 * get a few PERF_RECORD_READ events.
7476 perf_event_task(child, child_ctx, 0);
7479 * We can recurse on the same lock type through:
7481 * __perf_event_exit_task()
7482 * sync_child_event()
7484 * mutex_lock(&ctx->mutex)
7486 * But since its the parent context it won't be the same instance.
7488 mutex_lock(&child_ctx->mutex);
7490 list_for_each_entry_rcu(child_event, &child_ctx->event_list, event_entry)
7491 __perf_event_exit_task(child_event, child_ctx, child);
7493 mutex_unlock(&child_ctx->mutex);
7499 * When a child task exits, feed back event values to parent events.
7501 void perf_event_exit_task(struct task_struct *child)
7503 struct perf_event *event, *tmp;
7506 mutex_lock(&child->perf_event_mutex);
7507 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
7509 list_del_init(&event->owner_entry);
7512 * Ensure the list deletion is visible before we clear
7513 * the owner, closes a race against perf_release() where
7514 * we need to serialize on the owner->perf_event_mutex.
7517 event->owner = NULL;
7519 mutex_unlock(&child->perf_event_mutex);
7521 for_each_task_context_nr(ctxn)
7522 perf_event_exit_task_context(child, ctxn);
7525 static void perf_free_event(struct perf_event *event,
7526 struct perf_event_context *ctx)
7528 struct perf_event *parent = event->parent;
7530 if (WARN_ON_ONCE(!parent))
7533 mutex_lock(&parent->child_mutex);
7534 list_del_init(&event->child_list);
7535 mutex_unlock(&parent->child_mutex);
7539 perf_group_detach(event);
7540 list_del_event(event, ctx);
7545 * free an unexposed, unused context as created by inheritance by
7546 * perf_event_init_task below, used by fork() in case of fail.
7548 void perf_event_free_task(struct task_struct *task)
7550 struct perf_event_context *ctx;
7551 struct perf_event *event, *tmp;
7554 for_each_task_context_nr(ctxn) {
7555 ctx = task->perf_event_ctxp[ctxn];
7559 mutex_lock(&ctx->mutex);
7561 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
7563 perf_free_event(event, ctx);
7565 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
7567 perf_free_event(event, ctx);
7569 if (!list_empty(&ctx->pinned_groups) ||
7570 !list_empty(&ctx->flexible_groups))
7573 mutex_unlock(&ctx->mutex);
7579 void perf_event_delayed_put(struct task_struct *task)
7583 for_each_task_context_nr(ctxn)
7584 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
7588 * inherit a event from parent task to child task:
7590 static struct perf_event *
7591 inherit_event(struct perf_event *parent_event,
7592 struct task_struct *parent,
7593 struct perf_event_context *parent_ctx,
7594 struct task_struct *child,
7595 struct perf_event *group_leader,
7596 struct perf_event_context *child_ctx)
7598 struct perf_event *child_event;
7599 unsigned long flags;
7602 * Instead of creating recursive hierarchies of events,
7603 * we link inherited events back to the original parent,
7604 * which has a filp for sure, which we use as the reference
7607 if (parent_event->parent)
7608 parent_event = parent_event->parent;
7610 child_event = perf_event_alloc(&parent_event->attr,
7613 group_leader, parent_event,
7615 if (IS_ERR(child_event))
7618 if (!atomic_long_inc_not_zero(&parent_event->refcount)) {
7619 free_event(child_event);
7626 * Make the child state follow the state of the parent event,
7627 * not its attr.disabled bit. We hold the parent's mutex,
7628 * so we won't race with perf_event_{en, dis}able_family.
7630 if (parent_event->state >= PERF_EVENT_STATE_INACTIVE)
7631 child_event->state = PERF_EVENT_STATE_INACTIVE;
7633 child_event->state = PERF_EVENT_STATE_OFF;
7635 if (parent_event->attr.freq) {
7636 u64 sample_period = parent_event->hw.sample_period;
7637 struct hw_perf_event *hwc = &child_event->hw;
7639 hwc->sample_period = sample_period;
7640 hwc->last_period = sample_period;
7642 local64_set(&hwc->period_left, sample_period);
7645 child_event->ctx = child_ctx;
7646 child_event->overflow_handler = parent_event->overflow_handler;
7647 child_event->overflow_handler_context
7648 = parent_event->overflow_handler_context;
7651 * Precalculate sample_data sizes
7653 perf_event__header_size(child_event);
7654 perf_event__id_header_size(child_event);
7657 * Link it up in the child's context:
7659 raw_spin_lock_irqsave(&child_ctx->lock, flags);
7660 add_event_to_ctx(child_event, child_ctx);
7661 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7664 * Link this into the parent event's child list
7666 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7667 mutex_lock(&parent_event->child_mutex);
7668 list_add_tail(&child_event->child_list, &parent_event->child_list);
7669 mutex_unlock(&parent_event->child_mutex);
7674 static int inherit_group(struct perf_event *parent_event,
7675 struct task_struct *parent,
7676 struct perf_event_context *parent_ctx,
7677 struct task_struct *child,
7678 struct perf_event_context *child_ctx)
7680 struct perf_event *leader;
7681 struct perf_event *sub;
7682 struct perf_event *child_ctr;
7684 leader = inherit_event(parent_event, parent, parent_ctx,
7685 child, NULL, child_ctx);
7687 return PTR_ERR(leader);
7688 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
7689 child_ctr = inherit_event(sub, parent, parent_ctx,
7690 child, leader, child_ctx);
7691 if (IS_ERR(child_ctr))
7692 return PTR_ERR(child_ctr);
7698 inherit_task_group(struct perf_event *event, struct task_struct *parent,
7699 struct perf_event_context *parent_ctx,
7700 struct task_struct *child, int ctxn,
7704 struct perf_event_context *child_ctx;
7706 if (!event->attr.inherit) {
7711 child_ctx = child->perf_event_ctxp[ctxn];
7714 * This is executed from the parent task context, so
7715 * inherit events that have been marked for cloning.
7716 * First allocate and initialize a context for the
7720 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
7724 child->perf_event_ctxp[ctxn] = child_ctx;
7727 ret = inherit_group(event, parent, parent_ctx,
7737 * Initialize the perf_event context in task_struct
7739 int perf_event_init_context(struct task_struct *child, int ctxn)
7741 struct perf_event_context *child_ctx, *parent_ctx;
7742 struct perf_event_context *cloned_ctx;
7743 struct perf_event *event;
7744 struct task_struct *parent = current;
7745 int inherited_all = 1;
7746 unsigned long flags;
7749 if (likely(!parent->perf_event_ctxp[ctxn]))
7753 * If the parent's context is a clone, pin it so it won't get
7756 parent_ctx = perf_pin_task_context(parent, ctxn);
7761 * No need to check if parent_ctx != NULL here; since we saw
7762 * it non-NULL earlier, the only reason for it to become NULL
7763 * is if we exit, and since we're currently in the middle of
7764 * a fork we can't be exiting at the same time.
7768 * Lock the parent list. No need to lock the child - not PID
7769 * hashed yet and not running, so nobody can access it.
7771 mutex_lock(&parent_ctx->mutex);
7774 * We dont have to disable NMIs - we are only looking at
7775 * the list, not manipulating it:
7777 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
7778 ret = inherit_task_group(event, parent, parent_ctx,
7779 child, ctxn, &inherited_all);
7785 * We can't hold ctx->lock when iterating the ->flexible_group list due
7786 * to allocations, but we need to prevent rotation because
7787 * rotate_ctx() will change the list from interrupt context.
7789 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7790 parent_ctx->rotate_disable = 1;
7791 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7793 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
7794 ret = inherit_task_group(event, parent, parent_ctx,
7795 child, ctxn, &inherited_all);
7800 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7801 parent_ctx->rotate_disable = 0;
7803 child_ctx = child->perf_event_ctxp[ctxn];
7805 if (child_ctx && inherited_all) {
7807 * Mark the child context as a clone of the parent
7808 * context, or of whatever the parent is a clone of.
7810 * Note that if the parent is a clone, the holding of
7811 * parent_ctx->lock avoids it from being uncloned.
7813 cloned_ctx = parent_ctx->parent_ctx;
7815 child_ctx->parent_ctx = cloned_ctx;
7816 child_ctx->parent_gen = parent_ctx->parent_gen;
7818 child_ctx->parent_ctx = parent_ctx;
7819 child_ctx->parent_gen = parent_ctx->generation;
7821 get_ctx(child_ctx->parent_ctx);
7824 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7825 mutex_unlock(&parent_ctx->mutex);
7827 perf_unpin_context(parent_ctx);
7828 put_ctx(parent_ctx);
7834 * Initialize the perf_event context in task_struct
7836 int perf_event_init_task(struct task_struct *child)
7840 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
7841 mutex_init(&child->perf_event_mutex);
7842 INIT_LIST_HEAD(&child->perf_event_list);
7844 for_each_task_context_nr(ctxn) {
7845 ret = perf_event_init_context(child, ctxn);
7853 static void __init perf_event_init_all_cpus(void)
7855 struct swevent_htable *swhash;
7858 for_each_possible_cpu(cpu) {
7859 swhash = &per_cpu(swevent_htable, cpu);
7860 mutex_init(&swhash->hlist_mutex);
7861 INIT_LIST_HEAD(&per_cpu(rotation_list, cpu));
7865 static void perf_event_init_cpu(int cpu)
7867 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7869 mutex_lock(&swhash->hlist_mutex);
7870 swhash->online = true;
7871 if (swhash->hlist_refcount > 0) {
7872 struct swevent_hlist *hlist;
7874 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
7876 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7878 mutex_unlock(&swhash->hlist_mutex);
7881 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC
7882 static void perf_pmu_rotate_stop(struct pmu *pmu)
7884 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7886 WARN_ON(!irqs_disabled());
7888 list_del_init(&cpuctx->rotation_list);
7891 static void __perf_event_exit_context(void *__info)
7893 struct remove_event re = { .detach_group = false };
7894 struct perf_event_context *ctx = __info;
7896 perf_pmu_rotate_stop(ctx->pmu);
7899 list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
7900 __perf_remove_from_context(&re);
7904 static void perf_event_exit_cpu_context(int cpu)
7906 struct perf_event_context *ctx;
7910 idx = srcu_read_lock(&pmus_srcu);
7911 list_for_each_entry_rcu(pmu, &pmus, entry) {
7912 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
7914 mutex_lock(&ctx->mutex);
7915 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
7916 mutex_unlock(&ctx->mutex);
7918 srcu_read_unlock(&pmus_srcu, idx);
7921 static void perf_event_exit_cpu(int cpu)
7923 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7925 perf_event_exit_cpu_context(cpu);
7927 mutex_lock(&swhash->hlist_mutex);
7928 swhash->online = false;
7929 swevent_hlist_release(swhash);
7930 mutex_unlock(&swhash->hlist_mutex);
7933 static inline void perf_event_exit_cpu(int cpu) { }
7937 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
7941 for_each_online_cpu(cpu)
7942 perf_event_exit_cpu(cpu);
7948 * Run the perf reboot notifier at the very last possible moment so that
7949 * the generic watchdog code runs as long as possible.
7951 static struct notifier_block perf_reboot_notifier = {
7952 .notifier_call = perf_reboot,
7953 .priority = INT_MIN,
7957 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
7959 unsigned int cpu = (long)hcpu;
7961 switch (action & ~CPU_TASKS_FROZEN) {
7963 case CPU_UP_PREPARE:
7964 case CPU_DOWN_FAILED:
7965 perf_event_init_cpu(cpu);
7968 case CPU_UP_CANCELED:
7969 case CPU_DOWN_PREPARE:
7970 perf_event_exit_cpu(cpu);
7979 void __init perf_event_init(void)
7985 perf_event_init_all_cpus();
7986 init_srcu_struct(&pmus_srcu);
7987 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
7988 perf_pmu_register(&perf_cpu_clock, NULL, -1);
7989 perf_pmu_register(&perf_task_clock, NULL, -1);
7991 perf_cpu_notifier(perf_cpu_notify);
7992 register_reboot_notifier(&perf_reboot_notifier);
7994 ret = init_hw_breakpoint();
7995 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
7997 /* do not patch jump label more than once per second */
7998 jump_label_rate_limit(&perf_sched_events, HZ);
8001 * Build time assertion that we keep the data_head at the intended
8002 * location. IOW, validation we got the __reserved[] size right.
8004 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
8008 static int __init perf_event_sysfs_init(void)
8013 mutex_lock(&pmus_lock);
8015 ret = bus_register(&pmu_bus);
8019 list_for_each_entry(pmu, &pmus, entry) {
8020 if (!pmu->name || pmu->type < 0)
8023 ret = pmu_dev_alloc(pmu);
8024 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
8026 pmu_bus_running = 1;
8030 mutex_unlock(&pmus_lock);
8034 device_initcall(perf_event_sysfs_init);
8036 #ifdef CONFIG_CGROUP_PERF
8037 static struct cgroup_subsys_state *
8038 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
8040 struct perf_cgroup *jc;
8042 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
8044 return ERR_PTR(-ENOMEM);
8046 jc->info = alloc_percpu(struct perf_cgroup_info);
8049 return ERR_PTR(-ENOMEM);
8055 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
8057 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
8059 free_percpu(jc->info);
8063 static int __perf_cgroup_move(void *info)
8065 struct task_struct *task = info;
8066 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
8070 static void perf_cgroup_attach(struct cgroup_subsys_state *css,
8071 struct cgroup_taskset *tset)
8073 struct task_struct *task;
8075 cgroup_taskset_for_each(task, tset)
8076 task_function_call(task, __perf_cgroup_move, task);
8079 static void perf_cgroup_exit(struct cgroup_subsys_state *css,
8080 struct cgroup_subsys_state *old_css,
8081 struct task_struct *task)
8084 * cgroup_exit() is called in the copy_process() failure path.
8085 * Ignore this case since the task hasn't ran yet, this avoids
8086 * trying to poke a half freed task state from generic code.
8088 if (!(task->flags & PF_EXITING))
8091 task_function_call(task, __perf_cgroup_move, task);
8094 struct cgroup_subsys perf_event_cgrp_subsys = {
8095 .css_alloc = perf_cgroup_css_alloc,
8096 .css_free = perf_cgroup_css_free,
8097 .exit = perf_cgroup_exit,
8098 .attach = perf_cgroup_attach,
8100 #endif /* CONFIG_CGROUP_PERF */