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
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/cgroup.h>
38 #include <linux/perf_event.h>
39 #include <linux/trace_events.h>
40 #include <linux/hw_breakpoint.h>
41 #include <linux/mm_types.h>
42 #include <linux/module.h>
43 #include <linux/mman.h>
44 #include <linux/compat.h>
45 #include <linux/bpf.h>
46 #include <linux/filter.h>
50 #include <asm/irq_regs.h>
52 static struct workqueue_struct *perf_wq;
54 typedef int (*remote_function_f)(void *);
56 struct remote_function_call {
57 struct task_struct *p;
58 remote_function_f func;
63 static void remote_function(void *data)
65 struct remote_function_call *tfc = data;
66 struct task_struct *p = tfc->p;
70 if (task_cpu(p) != smp_processor_id() || !task_curr(p))
74 tfc->ret = tfc->func(tfc->info);
78 * task_function_call - call a function on the cpu on which a task runs
79 * @p: the task to evaluate
80 * @func: the function to be called
81 * @info: the function call argument
83 * Calls the function @func when the task is currently running. This might
84 * be on the current CPU, which just calls the function directly
86 * returns: @func return value, or
87 * -ESRCH - when the process isn't running
88 * -EAGAIN - when the process moved away
91 task_function_call(struct task_struct *p, remote_function_f func, void *info)
93 struct remote_function_call data = {
97 .ret = -ESRCH, /* No such (running) process */
101 smp_call_function_single(task_cpu(p), remote_function, &data, 1);
107 * cpu_function_call - call a function on the cpu
108 * @func: the function to be called
109 * @info: the function call argument
111 * Calls the function @func on the remote cpu.
113 * returns: @func return value or -ENXIO when the cpu is offline
115 static int cpu_function_call(int cpu, remote_function_f func, void *info)
117 struct remote_function_call data = {
121 .ret = -ENXIO, /* No such CPU */
124 smp_call_function_single(cpu, remote_function, &data, 1);
129 #define EVENT_OWNER_KERNEL ((void *) -1)
131 static bool is_kernel_event(struct perf_event *event)
133 return event->owner == EVENT_OWNER_KERNEL;
136 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
137 PERF_FLAG_FD_OUTPUT |\
138 PERF_FLAG_PID_CGROUP |\
139 PERF_FLAG_FD_CLOEXEC)
142 * branch priv levels that need permission checks
144 #define PERF_SAMPLE_BRANCH_PERM_PLM \
145 (PERF_SAMPLE_BRANCH_KERNEL |\
146 PERF_SAMPLE_BRANCH_HV)
149 EVENT_FLEXIBLE = 0x1,
151 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
155 * perf_sched_events : >0 events exist
156 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
158 struct static_key_deferred perf_sched_events __read_mostly;
159 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
160 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
161 static DEFINE_PER_CPU(bool, is_idle);
163 static atomic_t nr_mmap_events __read_mostly;
164 static atomic_t nr_comm_events __read_mostly;
165 static atomic_t nr_task_events __read_mostly;
166 static atomic_t nr_freq_events __read_mostly;
167 static atomic_t nr_switch_events __read_mostly;
169 static LIST_HEAD(pmus);
170 static DEFINE_MUTEX(pmus_lock);
171 static struct srcu_struct pmus_srcu;
174 * perf event paranoia level:
175 * -1 - not paranoid at all
176 * 0 - disallow raw tracepoint access for unpriv
177 * 1 - disallow cpu events for unpriv
178 * 2 - disallow kernel profiling for unpriv
179 * 3 - disallow all unpriv perf event use
181 #ifdef CONFIG_PERF_EVENTS_USERMODE
182 int sysctl_perf_event_paranoid __read_mostly = -1;
183 #elif defined CONFIG_SECURITY_PERF_EVENTS_RESTRICT
184 int sysctl_perf_event_paranoid __read_mostly = 3;
186 int sysctl_perf_event_paranoid __read_mostly = 1;
189 /* Minimum for 512 kiB + 1 user control page */
190 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
193 * max perf event sample rate
195 #define DEFAULT_MAX_SAMPLE_RATE 100000
196 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
197 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
199 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
201 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
202 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
204 static int perf_sample_allowed_ns __read_mostly =
205 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
207 static void update_perf_cpu_limits(void)
209 u64 tmp = perf_sample_period_ns;
211 tmp *= sysctl_perf_cpu_time_max_percent;
213 ACCESS_ONCE(perf_sample_allowed_ns) = tmp;
216 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
218 int perf_proc_update_handler(struct ctl_table *table, int write,
219 void __user *buffer, size_t *lenp,
222 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
227 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
228 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
229 update_perf_cpu_limits();
234 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
236 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
237 void __user *buffer, size_t *lenp,
240 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
245 update_perf_cpu_limits();
251 * perf samples are done in some very critical code paths (NMIs).
252 * If they take too much CPU time, the system can lock up and not
253 * get any real work done. This will drop the sample rate when
254 * we detect that events are taking too long.
256 #define NR_ACCUMULATED_SAMPLES 128
257 static DEFINE_PER_CPU(u64, running_sample_length);
259 static void perf_duration_warn(struct irq_work *w)
261 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
262 u64 avg_local_sample_len;
263 u64 local_samples_len;
265 local_samples_len = __this_cpu_read(running_sample_length);
266 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
268 printk_ratelimited(KERN_WARNING
269 "perf interrupt took too long (%lld > %lld), lowering "
270 "kernel.perf_event_max_sample_rate to %d\n",
271 avg_local_sample_len, allowed_ns >> 1,
272 sysctl_perf_event_sample_rate);
275 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
277 void perf_sample_event_took(u64 sample_len_ns)
279 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
280 u64 avg_local_sample_len;
281 u64 local_samples_len;
286 /* decay the counter by 1 average sample */
287 local_samples_len = __this_cpu_read(running_sample_length);
288 local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES;
289 local_samples_len += sample_len_ns;
290 __this_cpu_write(running_sample_length, local_samples_len);
293 * note: this will be biased artifically low until we have
294 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
295 * from having to maintain a count.
297 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
299 if (avg_local_sample_len <= allowed_ns)
302 if (max_samples_per_tick <= 1)
305 max_samples_per_tick = DIV_ROUND_UP(max_samples_per_tick, 2);
306 sysctl_perf_event_sample_rate = max_samples_per_tick * HZ;
307 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
309 update_perf_cpu_limits();
311 if (!irq_work_queue(&perf_duration_work)) {
312 early_printk("perf interrupt took too long (%lld > %lld), lowering "
313 "kernel.perf_event_max_sample_rate to %d\n",
314 avg_local_sample_len, allowed_ns >> 1,
315 sysctl_perf_event_sample_rate);
319 static atomic64_t perf_event_id;
321 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
322 enum event_type_t event_type);
324 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
325 enum event_type_t event_type,
326 struct task_struct *task);
328 static void update_context_time(struct perf_event_context *ctx);
329 static u64 perf_event_time(struct perf_event *event);
331 void __weak perf_event_print_debug(void) { }
333 extern __weak const char *perf_pmu_name(void)
338 static inline u64 perf_clock(void)
340 return local_clock();
343 static inline u64 perf_event_clock(struct perf_event *event)
345 return event->clock();
348 static inline struct perf_cpu_context *
349 __get_cpu_context(struct perf_event_context *ctx)
351 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
354 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
355 struct perf_event_context *ctx)
357 raw_spin_lock(&cpuctx->ctx.lock);
359 raw_spin_lock(&ctx->lock);
362 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
363 struct perf_event_context *ctx)
366 raw_spin_unlock(&ctx->lock);
367 raw_spin_unlock(&cpuctx->ctx.lock);
370 #ifdef CONFIG_CGROUP_PERF
373 perf_cgroup_match(struct perf_event *event)
375 struct perf_event_context *ctx = event->ctx;
376 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
378 /* @event doesn't care about cgroup */
382 /* wants specific cgroup scope but @cpuctx isn't associated with any */
387 * Cgroup scoping is recursive. An event enabled for a cgroup is
388 * also enabled for all its descendant cgroups. If @cpuctx's
389 * cgroup is a descendant of @event's (the test covers identity
390 * case), it's a match.
392 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
393 event->cgrp->css.cgroup);
396 static inline void perf_detach_cgroup(struct perf_event *event)
398 css_put(&event->cgrp->css);
402 static inline int is_cgroup_event(struct perf_event *event)
404 return event->cgrp != NULL;
407 static inline u64 perf_cgroup_event_time(struct perf_event *event)
409 struct perf_cgroup_info *t;
411 t = per_cpu_ptr(event->cgrp->info, event->cpu);
415 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
417 struct perf_cgroup_info *info;
422 info = this_cpu_ptr(cgrp->info);
424 info->time += now - info->timestamp;
425 info->timestamp = now;
428 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
430 struct perf_cgroup *cgrp = cpuctx->cgrp;
431 struct cgroup_subsys_state *css;
434 for (css = &cgrp->css; css; css = css->parent) {
435 cgrp = container_of(css, struct perf_cgroup, css);
436 __update_cgrp_time(cgrp);
441 static inline void update_cgrp_time_from_event(struct perf_event *event)
443 struct perf_cgroup *cgrp;
446 * ensure we access cgroup data only when needed and
447 * when we know the cgroup is pinned (css_get)
449 if (!is_cgroup_event(event))
452 cgrp = perf_cgroup_from_task(current, event->ctx);
454 * Do not update time when cgroup is not active
456 if (cgrp == event->cgrp)
457 __update_cgrp_time(event->cgrp);
461 perf_cgroup_set_timestamp(struct task_struct *task,
462 struct perf_event_context *ctx)
464 struct perf_cgroup *cgrp;
465 struct perf_cgroup_info *info;
466 struct cgroup_subsys_state *css;
469 * ctx->lock held by caller
470 * ensure we do not access cgroup data
471 * unless we have the cgroup pinned (css_get)
473 if (!task || !ctx->nr_cgroups)
476 cgrp = perf_cgroup_from_task(task, ctx);
478 for (css = &cgrp->css; css; css = css->parent) {
479 cgrp = container_of(css, struct perf_cgroup, css);
480 info = this_cpu_ptr(cgrp->info);
481 info->timestamp = ctx->timestamp;
485 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
486 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
489 * reschedule events based on the cgroup constraint of task.
491 * mode SWOUT : schedule out everything
492 * mode SWIN : schedule in based on cgroup for next
494 static void perf_cgroup_switch(struct task_struct *task, int mode)
496 struct perf_cpu_context *cpuctx;
501 * disable interrupts to avoid geting nr_cgroup
502 * changes via __perf_event_disable(). Also
505 local_irq_save(flags);
508 * we reschedule only in the presence of cgroup
509 * constrained events.
512 list_for_each_entry_rcu(pmu, &pmus, entry) {
513 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
514 if (cpuctx->unique_pmu != pmu)
515 continue; /* ensure we process each cpuctx once */
518 * perf_cgroup_events says at least one
519 * context on this CPU has cgroup events.
521 * ctx->nr_cgroups reports the number of cgroup
522 * events for a context.
524 if (cpuctx->ctx.nr_cgroups > 0) {
525 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
526 perf_pmu_disable(cpuctx->ctx.pmu);
528 if (mode & PERF_CGROUP_SWOUT) {
529 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
531 * must not be done before ctxswout due
532 * to event_filter_match() in event_sched_out()
537 if (mode & PERF_CGROUP_SWIN) {
538 WARN_ON_ONCE(cpuctx->cgrp);
540 * set cgrp before ctxsw in to allow
541 * event_filter_match() to not have to pass
543 * we pass the cpuctx->ctx to perf_cgroup_from_task()
544 * because cgorup events are only per-cpu
546 cpuctx->cgrp = perf_cgroup_from_task(task, &cpuctx->ctx);
547 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
549 perf_pmu_enable(cpuctx->ctx.pmu);
550 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
554 local_irq_restore(flags);
557 static inline void perf_cgroup_sched_out(struct task_struct *task,
558 struct task_struct *next)
560 struct perf_cgroup *cgrp1;
561 struct perf_cgroup *cgrp2 = NULL;
565 * we come here when we know perf_cgroup_events > 0
566 * we do not need to pass the ctx here because we know
567 * we are holding the rcu lock
569 cgrp1 = perf_cgroup_from_task(task, NULL);
572 * next is NULL when called from perf_event_enable_on_exec()
573 * that will systematically cause a cgroup_switch()
576 cgrp2 = perf_cgroup_from_task(next, NULL);
579 * only schedule out current cgroup events if we know
580 * that we are switching to a different cgroup. Otherwise,
581 * do no touch the cgroup events.
584 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
589 static inline void perf_cgroup_sched_in(struct task_struct *prev,
590 struct task_struct *task)
592 struct perf_cgroup *cgrp1;
593 struct perf_cgroup *cgrp2 = NULL;
597 * we come here when we know perf_cgroup_events > 0
598 * we do not need to pass the ctx here because we know
599 * we are holding the rcu lock
601 cgrp1 = perf_cgroup_from_task(task, NULL);
603 /* prev can never be NULL */
604 cgrp2 = perf_cgroup_from_task(prev, NULL);
607 * only need to schedule in cgroup events if we are changing
608 * cgroup during ctxsw. Cgroup events were not scheduled
609 * out of ctxsw out if that was not the case.
612 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
617 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
618 struct perf_event_attr *attr,
619 struct perf_event *group_leader)
621 struct perf_cgroup *cgrp;
622 struct cgroup_subsys_state *css;
623 struct fd f = fdget(fd);
629 css = css_tryget_online_from_dir(f.file->f_path.dentry,
630 &perf_event_cgrp_subsys);
636 cgrp = container_of(css, struct perf_cgroup, css);
640 * all events in a group must monitor
641 * the same cgroup because a task belongs
642 * to only one perf cgroup at a time
644 if (group_leader && group_leader->cgrp != cgrp) {
645 perf_detach_cgroup(event);
654 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
656 struct perf_cgroup_info *t;
657 t = per_cpu_ptr(event->cgrp->info, event->cpu);
658 event->shadow_ctx_time = now - t->timestamp;
662 perf_cgroup_defer_enabled(struct perf_event *event)
665 * when the current task's perf cgroup does not match
666 * the event's, we need to remember to call the
667 * perf_mark_enable() function the first time a task with
668 * a matching perf cgroup is scheduled in.
670 if (is_cgroup_event(event) && !perf_cgroup_match(event))
671 event->cgrp_defer_enabled = 1;
675 perf_cgroup_mark_enabled(struct perf_event *event,
676 struct perf_event_context *ctx)
678 struct perf_event *sub;
679 u64 tstamp = perf_event_time(event);
681 if (!event->cgrp_defer_enabled)
684 event->cgrp_defer_enabled = 0;
686 event->tstamp_enabled = tstamp - event->total_time_enabled;
687 list_for_each_entry(sub, &event->sibling_list, group_entry) {
688 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
689 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
690 sub->cgrp_defer_enabled = 0;
694 #else /* !CONFIG_CGROUP_PERF */
697 perf_cgroup_match(struct perf_event *event)
702 static inline void perf_detach_cgroup(struct perf_event *event)
705 static inline int is_cgroup_event(struct perf_event *event)
710 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
715 static inline void update_cgrp_time_from_event(struct perf_event *event)
719 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
723 static inline void perf_cgroup_sched_out(struct task_struct *task,
724 struct task_struct *next)
728 static inline void perf_cgroup_sched_in(struct task_struct *prev,
729 struct task_struct *task)
733 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
734 struct perf_event_attr *attr,
735 struct perf_event *group_leader)
741 perf_cgroup_set_timestamp(struct task_struct *task,
742 struct perf_event_context *ctx)
747 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
752 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
756 static inline u64 perf_cgroup_event_time(struct perf_event *event)
762 perf_cgroup_defer_enabled(struct perf_event *event)
767 perf_cgroup_mark_enabled(struct perf_event *event,
768 struct perf_event_context *ctx)
774 * set default to be dependent on timer tick just
777 #define PERF_CPU_HRTIMER (1000 / HZ)
779 * function must be called with interrupts disbled
781 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
783 struct perf_cpu_context *cpuctx;
786 WARN_ON(!irqs_disabled());
788 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
789 rotations = perf_rotate_context(cpuctx);
791 raw_spin_lock(&cpuctx->hrtimer_lock);
793 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
795 cpuctx->hrtimer_active = 0;
796 raw_spin_unlock(&cpuctx->hrtimer_lock);
798 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
801 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
803 struct hrtimer *timer = &cpuctx->hrtimer;
804 struct pmu *pmu = cpuctx->ctx.pmu;
807 /* no multiplexing needed for SW PMU */
808 if (pmu->task_ctx_nr == perf_sw_context)
812 * check default is sane, if not set then force to
813 * default interval (1/tick)
815 interval = pmu->hrtimer_interval_ms;
817 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
819 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
821 raw_spin_lock_init(&cpuctx->hrtimer_lock);
822 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
823 timer->function = perf_mux_hrtimer_handler;
826 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
828 struct hrtimer *timer = &cpuctx->hrtimer;
829 struct pmu *pmu = cpuctx->ctx.pmu;
833 if (pmu->task_ctx_nr == perf_sw_context)
836 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
837 if (!cpuctx->hrtimer_active) {
838 cpuctx->hrtimer_active = 1;
839 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
840 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
842 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
847 void perf_pmu_disable(struct pmu *pmu)
849 int *count = this_cpu_ptr(pmu->pmu_disable_count);
851 pmu->pmu_disable(pmu);
854 void perf_pmu_enable(struct pmu *pmu)
856 int *count = this_cpu_ptr(pmu->pmu_disable_count);
858 pmu->pmu_enable(pmu);
861 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
864 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
865 * perf_event_task_tick() are fully serialized because they're strictly cpu
866 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
867 * disabled, while perf_event_task_tick is called from IRQ context.
869 static void perf_event_ctx_activate(struct perf_event_context *ctx)
871 struct list_head *head = this_cpu_ptr(&active_ctx_list);
873 WARN_ON(!irqs_disabled());
875 WARN_ON(!list_empty(&ctx->active_ctx_list));
877 list_add(&ctx->active_ctx_list, head);
880 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
882 WARN_ON(!irqs_disabled());
884 WARN_ON(list_empty(&ctx->active_ctx_list));
886 list_del_init(&ctx->active_ctx_list);
889 static void get_ctx(struct perf_event_context *ctx)
891 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
894 static void free_ctx(struct rcu_head *head)
896 struct perf_event_context *ctx;
898 ctx = container_of(head, struct perf_event_context, rcu_head);
899 kfree(ctx->task_ctx_data);
903 static void put_ctx(struct perf_event_context *ctx)
905 if (atomic_dec_and_test(&ctx->refcount)) {
907 put_ctx(ctx->parent_ctx);
909 put_task_struct(ctx->task);
910 call_rcu(&ctx->rcu_head, free_ctx);
915 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
916 * perf_pmu_migrate_context() we need some magic.
918 * Those places that change perf_event::ctx will hold both
919 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
921 * Lock ordering is by mutex address. There are two other sites where
922 * perf_event_context::mutex nests and those are:
924 * - perf_event_exit_task_context() [ child , 0 ]
925 * __perf_event_exit_task()
927 * put_event() [ parent, 1 ]
929 * - perf_event_init_context() [ parent, 0 ]
930 * inherit_task_group()
935 * perf_try_init_event() [ child , 1 ]
937 * While it appears there is an obvious deadlock here -- the parent and child
938 * nesting levels are inverted between the two. This is in fact safe because
939 * life-time rules separate them. That is an exiting task cannot fork, and a
940 * spawning task cannot (yet) exit.
942 * But remember that that these are parent<->child context relations, and
943 * migration does not affect children, therefore these two orderings should not
946 * The change in perf_event::ctx does not affect children (as claimed above)
947 * because the sys_perf_event_open() case will install a new event and break
948 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
949 * concerned with cpuctx and that doesn't have children.
951 * The places that change perf_event::ctx will issue:
953 * perf_remove_from_context();
955 * perf_install_in_context();
957 * to affect the change. The remove_from_context() + synchronize_rcu() should
958 * quiesce the event, after which we can install it in the new location. This
959 * means that only external vectors (perf_fops, prctl) can perturb the event
960 * while in transit. Therefore all such accessors should also acquire
961 * perf_event_context::mutex to serialize against this.
963 * However; because event->ctx can change while we're waiting to acquire
964 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
969 * task_struct::perf_event_mutex
970 * perf_event_context::mutex
971 * perf_event_context::lock
972 * perf_event::child_mutex;
973 * perf_event::mmap_mutex
976 static struct perf_event_context *
977 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
979 struct perf_event_context *ctx;
983 ctx = ACCESS_ONCE(event->ctx);
984 if (!atomic_inc_not_zero(&ctx->refcount)) {
990 mutex_lock_nested(&ctx->mutex, nesting);
991 if (event->ctx != ctx) {
992 mutex_unlock(&ctx->mutex);
1000 static inline struct perf_event_context *
1001 perf_event_ctx_lock(struct perf_event *event)
1003 return perf_event_ctx_lock_nested(event, 0);
1006 static void perf_event_ctx_unlock(struct perf_event *event,
1007 struct perf_event_context *ctx)
1009 mutex_unlock(&ctx->mutex);
1014 * This must be done under the ctx->lock, such as to serialize against
1015 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1016 * calling scheduler related locks and ctx->lock nests inside those.
1018 static __must_check struct perf_event_context *
1019 unclone_ctx(struct perf_event_context *ctx)
1021 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1023 lockdep_assert_held(&ctx->lock);
1026 ctx->parent_ctx = NULL;
1032 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1035 * only top level events have the pid namespace they were created in
1038 event = event->parent;
1040 return task_tgid_nr_ns(p, event->ns);
1043 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1046 * only top level events have the pid namespace they were created in
1049 event = event->parent;
1051 return task_pid_nr_ns(p, event->ns);
1055 * If we inherit events we want to return the parent event id
1058 static u64 primary_event_id(struct perf_event *event)
1063 id = event->parent->id;
1069 * Get the perf_event_context for a task and lock it.
1070 * This has to cope with with the fact that until it is locked,
1071 * the context could get moved to another task.
1073 static struct perf_event_context *
1074 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1076 struct perf_event_context *ctx;
1080 * One of the few rules of preemptible RCU is that one cannot do
1081 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1082 * part of the read side critical section was irqs-enabled -- see
1083 * rcu_read_unlock_special().
1085 * Since ctx->lock nests under rq->lock we must ensure the entire read
1086 * side critical section has interrupts disabled.
1088 local_irq_save(*flags);
1090 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1093 * If this context is a clone of another, it might
1094 * get swapped for another underneath us by
1095 * perf_event_task_sched_out, though the
1096 * rcu_read_lock() protects us from any context
1097 * getting freed. Lock the context and check if it
1098 * got swapped before we could get the lock, and retry
1099 * if so. If we locked the right context, then it
1100 * can't get swapped on us any more.
1102 raw_spin_lock(&ctx->lock);
1103 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1104 raw_spin_unlock(&ctx->lock);
1106 local_irq_restore(*flags);
1110 if (!atomic_inc_not_zero(&ctx->refcount)) {
1111 raw_spin_unlock(&ctx->lock);
1117 local_irq_restore(*flags);
1122 * Get the context for a task and increment its pin_count so it
1123 * can't get swapped to another task. This also increments its
1124 * reference count so that the context can't get freed.
1126 static struct perf_event_context *
1127 perf_pin_task_context(struct task_struct *task, int ctxn)
1129 struct perf_event_context *ctx;
1130 unsigned long flags;
1132 ctx = perf_lock_task_context(task, ctxn, &flags);
1135 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1140 static void perf_unpin_context(struct perf_event_context *ctx)
1142 unsigned long flags;
1144 raw_spin_lock_irqsave(&ctx->lock, flags);
1146 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1150 * Update the record of the current time in a context.
1152 static void update_context_time(struct perf_event_context *ctx)
1154 u64 now = perf_clock();
1156 ctx->time += now - ctx->timestamp;
1157 ctx->timestamp = now;
1160 static u64 perf_event_time(struct perf_event *event)
1162 struct perf_event_context *ctx = event->ctx;
1164 if (is_cgroup_event(event))
1165 return perf_cgroup_event_time(event);
1167 return ctx ? ctx->time : 0;
1171 * Update the total_time_enabled and total_time_running fields for a event.
1172 * The caller of this function needs to hold the ctx->lock.
1174 static void update_event_times(struct perf_event *event)
1176 struct perf_event_context *ctx = event->ctx;
1179 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1180 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1183 * in cgroup mode, time_enabled represents
1184 * the time the event was enabled AND active
1185 * tasks were in the monitored cgroup. This is
1186 * independent of the activity of the context as
1187 * there may be a mix of cgroup and non-cgroup events.
1189 * That is why we treat cgroup events differently
1192 if (is_cgroup_event(event))
1193 run_end = perf_cgroup_event_time(event);
1194 else if (ctx->is_active)
1195 run_end = ctx->time;
1197 run_end = event->tstamp_stopped;
1199 event->total_time_enabled = run_end - event->tstamp_enabled;
1201 if (event->state == PERF_EVENT_STATE_INACTIVE)
1202 run_end = event->tstamp_stopped;
1204 run_end = perf_event_time(event);
1206 event->total_time_running = run_end - event->tstamp_running;
1211 * Update total_time_enabled and total_time_running for all events in a group.
1213 static void update_group_times(struct perf_event *leader)
1215 struct perf_event *event;
1217 update_event_times(leader);
1218 list_for_each_entry(event, &leader->sibling_list, group_entry)
1219 update_event_times(event);
1222 static struct list_head *
1223 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1225 if (event->attr.pinned)
1226 return &ctx->pinned_groups;
1228 return &ctx->flexible_groups;
1232 * Add a event from the lists for its context.
1233 * Must be called with ctx->mutex and ctx->lock held.
1236 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1238 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1239 event->attach_state |= PERF_ATTACH_CONTEXT;
1242 * If we're a stand alone event or group leader, we go to the context
1243 * list, group events are kept attached to the group so that
1244 * perf_group_detach can, at all times, locate all siblings.
1246 if (event->group_leader == event) {
1247 struct list_head *list;
1249 if (is_software_event(event))
1250 event->group_flags |= PERF_GROUP_SOFTWARE;
1252 list = ctx_group_list(event, ctx);
1253 list_add_tail(&event->group_entry, list);
1256 if (is_cgroup_event(event))
1259 list_add_rcu(&event->event_entry, &ctx->event_list);
1261 if (event->attr.inherit_stat)
1268 * Initialize event state based on the perf_event_attr::disabled.
1270 static inline void perf_event__state_init(struct perf_event *event)
1272 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1273 PERF_EVENT_STATE_INACTIVE;
1276 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1278 int entry = sizeof(u64); /* value */
1282 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1283 size += sizeof(u64);
1285 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1286 size += sizeof(u64);
1288 if (event->attr.read_format & PERF_FORMAT_ID)
1289 entry += sizeof(u64);
1291 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1293 size += sizeof(u64);
1297 event->read_size = size;
1300 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1302 struct perf_sample_data *data;
1305 if (sample_type & PERF_SAMPLE_IP)
1306 size += sizeof(data->ip);
1308 if (sample_type & PERF_SAMPLE_ADDR)
1309 size += sizeof(data->addr);
1311 if (sample_type & PERF_SAMPLE_PERIOD)
1312 size += sizeof(data->period);
1314 if (sample_type & PERF_SAMPLE_WEIGHT)
1315 size += sizeof(data->weight);
1317 if (sample_type & PERF_SAMPLE_READ)
1318 size += event->read_size;
1320 if (sample_type & PERF_SAMPLE_DATA_SRC)
1321 size += sizeof(data->data_src.val);
1323 if (sample_type & PERF_SAMPLE_TRANSACTION)
1324 size += sizeof(data->txn);
1326 event->header_size = size;
1330 * Called at perf_event creation and when events are attached/detached from a
1333 static void perf_event__header_size(struct perf_event *event)
1335 __perf_event_read_size(event,
1336 event->group_leader->nr_siblings);
1337 __perf_event_header_size(event, event->attr.sample_type);
1340 static void perf_event__id_header_size(struct perf_event *event)
1342 struct perf_sample_data *data;
1343 u64 sample_type = event->attr.sample_type;
1346 if (sample_type & PERF_SAMPLE_TID)
1347 size += sizeof(data->tid_entry);
1349 if (sample_type & PERF_SAMPLE_TIME)
1350 size += sizeof(data->time);
1352 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1353 size += sizeof(data->id);
1355 if (sample_type & PERF_SAMPLE_ID)
1356 size += sizeof(data->id);
1358 if (sample_type & PERF_SAMPLE_STREAM_ID)
1359 size += sizeof(data->stream_id);
1361 if (sample_type & PERF_SAMPLE_CPU)
1362 size += sizeof(data->cpu_entry);
1364 event->id_header_size = size;
1367 static bool perf_event_validate_size(struct perf_event *event)
1370 * The values computed here will be over-written when we actually
1373 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1374 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1375 perf_event__id_header_size(event);
1378 * Sum the lot; should not exceed the 64k limit we have on records.
1379 * Conservative limit to allow for callchains and other variable fields.
1381 if (event->read_size + event->header_size +
1382 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1388 static void perf_group_attach(struct perf_event *event)
1390 struct perf_event *group_leader = event->group_leader, *pos;
1393 * We can have double attach due to group movement in perf_event_open.
1395 if (event->attach_state & PERF_ATTACH_GROUP)
1398 event->attach_state |= PERF_ATTACH_GROUP;
1400 if (group_leader == event)
1403 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1405 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1406 !is_software_event(event))
1407 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1409 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1410 group_leader->nr_siblings++;
1412 perf_event__header_size(group_leader);
1414 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1415 perf_event__header_size(pos);
1419 * Remove a event from the lists for its context.
1420 * Must be called with ctx->mutex and ctx->lock held.
1423 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1425 struct perf_cpu_context *cpuctx;
1427 WARN_ON_ONCE(event->ctx != ctx);
1428 lockdep_assert_held(&ctx->lock);
1431 * We can have double detach due to exit/hot-unplug + close.
1433 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1436 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1438 if (is_cgroup_event(event)) {
1440 cpuctx = __get_cpu_context(ctx);
1442 * if there are no more cgroup events
1443 * then cler cgrp to avoid stale pointer
1444 * in update_cgrp_time_from_cpuctx()
1446 if (!ctx->nr_cgroups)
1447 cpuctx->cgrp = NULL;
1451 if (event->attr.inherit_stat)
1454 list_del_rcu(&event->event_entry);
1456 if (event->group_leader == event)
1457 list_del_init(&event->group_entry);
1459 update_group_times(event);
1462 * If event was in error state, then keep it
1463 * that way, otherwise bogus counts will be
1464 * returned on read(). The only way to get out
1465 * of error state is by explicit re-enabling
1468 if (event->state > PERF_EVENT_STATE_OFF)
1469 event->state = PERF_EVENT_STATE_OFF;
1474 static void perf_group_detach(struct perf_event *event)
1476 struct perf_event *sibling, *tmp;
1477 struct list_head *list = NULL;
1480 * We can have double detach due to exit/hot-unplug + close.
1482 if (!(event->attach_state & PERF_ATTACH_GROUP))
1485 event->attach_state &= ~PERF_ATTACH_GROUP;
1488 * If this is a sibling, remove it from its group.
1490 if (event->group_leader != event) {
1491 list_del_init(&event->group_entry);
1492 event->group_leader->nr_siblings--;
1496 if (!list_empty(&event->group_entry))
1497 list = &event->group_entry;
1500 * If this was a group event with sibling events then
1501 * upgrade the siblings to singleton events by adding them
1502 * to whatever list we are on.
1503 * If this isn't on a list, make sure we still remove the sibling's
1504 * group_entry from this sibling_list; otherwise, when that sibling
1505 * is later deallocated, it will try to remove itself from this
1506 * sibling_list, which may well have been deallocated already,
1507 * resulting in a use-after-free.
1509 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1511 list_move_tail(&sibling->group_entry, list);
1513 list_del_init(&sibling->group_entry);
1514 sibling->group_leader = sibling;
1516 /* Inherit group flags from the previous leader */
1517 sibling->group_flags = event->group_flags;
1519 WARN_ON_ONCE(sibling->ctx != event->ctx);
1523 perf_event__header_size(event->group_leader);
1525 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1526 perf_event__header_size(tmp);
1530 * User event without the task.
1532 static bool is_orphaned_event(struct perf_event *event)
1534 return event && !is_kernel_event(event) && !event->owner;
1538 * Event has a parent but parent's task finished and it's
1539 * alive only because of children holding refference.
1541 static bool is_orphaned_child(struct perf_event *event)
1543 return is_orphaned_event(event->parent);
1546 static void orphans_remove_work(struct work_struct *work);
1548 static void schedule_orphans_remove(struct perf_event_context *ctx)
1550 if (!ctx->task || ctx->orphans_remove_sched || !perf_wq)
1553 if (queue_delayed_work(perf_wq, &ctx->orphans_remove, 1)) {
1555 ctx->orphans_remove_sched = true;
1559 static int __init perf_workqueue_init(void)
1561 perf_wq = create_singlethread_workqueue("perf");
1562 WARN(!perf_wq, "failed to create perf workqueue\n");
1563 return perf_wq ? 0 : -1;
1566 core_initcall(perf_workqueue_init);
1568 static inline int __pmu_filter_match(struct perf_event *event)
1570 struct pmu *pmu = event->pmu;
1571 return pmu->filter_match ? pmu->filter_match(event) : 1;
1575 * Check whether we should attempt to schedule an event group based on
1576 * PMU-specific filtering. An event group can consist of HW and SW events,
1577 * potentially with a SW leader, so we must check all the filters, to
1578 * determine whether a group is schedulable:
1580 static inline int pmu_filter_match(struct perf_event *event)
1582 struct perf_event *child;
1584 if (!__pmu_filter_match(event))
1587 list_for_each_entry(child, &event->sibling_list, group_entry) {
1588 if (!__pmu_filter_match(child))
1596 event_filter_match(struct perf_event *event)
1598 return (event->cpu == -1 || event->cpu == smp_processor_id())
1599 && perf_cgroup_match(event) && pmu_filter_match(event);
1603 event_sched_out(struct perf_event *event,
1604 struct perf_cpu_context *cpuctx,
1605 struct perf_event_context *ctx)
1607 u64 tstamp = perf_event_time(event);
1610 WARN_ON_ONCE(event->ctx != ctx);
1611 lockdep_assert_held(&ctx->lock);
1614 * An event which could not be activated because of
1615 * filter mismatch still needs to have its timings
1616 * maintained, otherwise bogus information is return
1617 * via read() for time_enabled, time_running:
1619 if (event->state == PERF_EVENT_STATE_INACTIVE
1620 && !event_filter_match(event)) {
1621 delta = tstamp - event->tstamp_stopped;
1622 event->tstamp_running += delta;
1623 event->tstamp_stopped = tstamp;
1626 if (event->state != PERF_EVENT_STATE_ACTIVE)
1629 perf_pmu_disable(event->pmu);
1631 event->tstamp_stopped = tstamp;
1632 event->pmu->del(event, 0);
1634 event->state = PERF_EVENT_STATE_INACTIVE;
1635 if (event->pending_disable) {
1636 event->pending_disable = 0;
1637 event->state = PERF_EVENT_STATE_OFF;
1640 if (!is_software_event(event))
1641 cpuctx->active_oncpu--;
1642 if (!--ctx->nr_active)
1643 perf_event_ctx_deactivate(ctx);
1644 if (event->attr.freq && event->attr.sample_freq)
1646 if (event->attr.exclusive || !cpuctx->active_oncpu)
1647 cpuctx->exclusive = 0;
1649 if (is_orphaned_child(event))
1650 schedule_orphans_remove(ctx);
1652 perf_pmu_enable(event->pmu);
1656 group_sched_out(struct perf_event *group_event,
1657 struct perf_cpu_context *cpuctx,
1658 struct perf_event_context *ctx)
1660 struct perf_event *event;
1661 int state = group_event->state;
1663 event_sched_out(group_event, cpuctx, ctx);
1666 * Schedule out siblings (if any):
1668 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1669 event_sched_out(event, cpuctx, ctx);
1671 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1672 cpuctx->exclusive = 0;
1675 struct remove_event {
1676 struct perf_event *event;
1681 * Cross CPU call to remove a performance event
1683 * We disable the event on the hardware level first. After that we
1684 * remove it from the context list.
1686 static int __perf_remove_from_context(void *info)
1688 struct remove_event *re = info;
1689 struct perf_event *event = re->event;
1690 struct perf_event_context *ctx = event->ctx;
1691 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1693 raw_spin_lock(&ctx->lock);
1694 event_sched_out(event, cpuctx, ctx);
1695 if (re->detach_group)
1696 perf_group_detach(event);
1697 list_del_event(event, ctx);
1698 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1700 cpuctx->task_ctx = NULL;
1702 raw_spin_unlock(&ctx->lock);
1709 static void perf_retry_remove(struct perf_event *event,
1710 struct remove_event *rep)
1714 * CPU was offline. Bring it online so we can
1715 * gracefully exit a perf context.
1717 up_ret = cpu_up(event->cpu);
1719 /* Try the remove call once again. */
1720 cpu_function_call(event->cpu, __perf_remove_from_context,
1723 pr_err("Failed to bring up CPU: %d, ret: %d\n",
1724 event->cpu, up_ret);
1727 static void perf_retry_remove(struct perf_event *event,
1728 struct remove_event *rep)
1734 * Remove the event from a task's (or a CPU's) list of events.
1736 * CPU events are removed with a smp call. For task events we only
1737 * call when the task is on a CPU.
1739 * If event->ctx is a cloned context, callers must make sure that
1740 * every task struct that event->ctx->task could possibly point to
1741 * remains valid. This is OK when called from perf_release since
1742 * that only calls us on the top-level context, which can't be a clone.
1743 * When called from perf_event_exit_task, it's OK because the
1744 * context has been detached from its task.
1746 static void __ref perf_remove_from_context(struct perf_event *event,
1749 struct perf_event_context *ctx = event->ctx;
1750 struct task_struct *task = ctx->task;
1751 struct remove_event re = {
1753 .detach_group = detach_group,
1757 lockdep_assert_held(&ctx->mutex);
1761 * Per cpu events are removed via an smp call. The removal can
1762 * fail if the CPU is currently offline, but in that case we
1763 * already called __perf_remove_from_context from
1764 * perf_event_exit_cpu.
1766 ret = cpu_function_call(event->cpu, __perf_remove_from_context,
1769 perf_retry_remove(event, &re);
1775 if (!task_function_call(task, __perf_remove_from_context, &re))
1778 raw_spin_lock_irq(&ctx->lock);
1780 * If we failed to find a running task, but find the context active now
1781 * that we've acquired the ctx->lock, retry.
1783 if (ctx->is_active) {
1784 raw_spin_unlock_irq(&ctx->lock);
1786 * Reload the task pointer, it might have been changed by
1787 * a concurrent perf_event_context_sched_out().
1794 * Since the task isn't running, its safe to remove the event, us
1795 * holding the ctx->lock ensures the task won't get scheduled in.
1798 perf_group_detach(event);
1799 list_del_event(event, ctx);
1800 raw_spin_unlock_irq(&ctx->lock);
1804 * Cross CPU call to disable a performance event
1806 int __perf_event_disable(void *info)
1808 struct perf_event *event = info;
1809 struct perf_event_context *ctx = event->ctx;
1810 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1813 * If this is a per-task event, need to check whether this
1814 * event's task is the current task on this cpu.
1816 * Can trigger due to concurrent perf_event_context_sched_out()
1817 * flipping contexts around.
1819 if (ctx->task && cpuctx->task_ctx != ctx)
1822 raw_spin_lock(&ctx->lock);
1825 * If the event is on, turn it off.
1826 * If it is in error state, leave it in error state.
1828 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1829 update_context_time(ctx);
1830 update_cgrp_time_from_event(event);
1831 update_group_times(event);
1832 if (event == event->group_leader)
1833 group_sched_out(event, cpuctx, ctx);
1835 event_sched_out(event, cpuctx, ctx);
1836 event->state = PERF_EVENT_STATE_OFF;
1839 raw_spin_unlock(&ctx->lock);
1847 * If event->ctx is a cloned context, callers must make sure that
1848 * every task struct that event->ctx->task could possibly point to
1849 * remains valid. This condition is satisifed when called through
1850 * perf_event_for_each_child or perf_event_for_each because they
1851 * hold the top-level event's child_mutex, so any descendant that
1852 * goes to exit will block in sync_child_event.
1853 * When called from perf_pending_event it's OK because event->ctx
1854 * is the current context on this CPU and preemption is disabled,
1855 * hence we can't get into perf_event_task_sched_out for this context.
1857 static void _perf_event_disable(struct perf_event *event)
1859 struct perf_event_context *ctx = event->ctx;
1860 struct task_struct *task = ctx->task;
1864 * Disable the event on the cpu that it's on
1866 cpu_function_call(event->cpu, __perf_event_disable, event);
1871 if (!task_function_call(task, __perf_event_disable, event))
1874 raw_spin_lock_irq(&ctx->lock);
1876 * If the event is still active, we need to retry the cross-call.
1878 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1879 raw_spin_unlock_irq(&ctx->lock);
1881 * Reload the task pointer, it might have been changed by
1882 * a concurrent perf_event_context_sched_out().
1889 * Since we have the lock this context can't be scheduled
1890 * in, so we can change the state safely.
1892 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1893 update_group_times(event);
1894 event->state = PERF_EVENT_STATE_OFF;
1896 raw_spin_unlock_irq(&ctx->lock);
1900 * Strictly speaking kernel users cannot create groups and therefore this
1901 * interface does not need the perf_event_ctx_lock() magic.
1903 void perf_event_disable(struct perf_event *event)
1905 struct perf_event_context *ctx;
1907 ctx = perf_event_ctx_lock(event);
1908 _perf_event_disable(event);
1909 perf_event_ctx_unlock(event, ctx);
1911 EXPORT_SYMBOL_GPL(perf_event_disable);
1913 static void perf_set_shadow_time(struct perf_event *event,
1914 struct perf_event_context *ctx,
1918 * use the correct time source for the time snapshot
1920 * We could get by without this by leveraging the
1921 * fact that to get to this function, the caller
1922 * has most likely already called update_context_time()
1923 * and update_cgrp_time_xx() and thus both timestamp
1924 * are identical (or very close). Given that tstamp is,
1925 * already adjusted for cgroup, we could say that:
1926 * tstamp - ctx->timestamp
1928 * tstamp - cgrp->timestamp.
1930 * Then, in perf_output_read(), the calculation would
1931 * work with no changes because:
1932 * - event is guaranteed scheduled in
1933 * - no scheduled out in between
1934 * - thus the timestamp would be the same
1936 * But this is a bit hairy.
1938 * So instead, we have an explicit cgroup call to remain
1939 * within the time time source all along. We believe it
1940 * is cleaner and simpler to understand.
1942 if (is_cgroup_event(event))
1943 perf_cgroup_set_shadow_time(event, tstamp);
1945 event->shadow_ctx_time = tstamp - ctx->timestamp;
1948 #define MAX_INTERRUPTS (~0ULL)
1950 static void perf_log_throttle(struct perf_event *event, int enable);
1951 static void perf_log_itrace_start(struct perf_event *event);
1954 event_sched_in(struct perf_event *event,
1955 struct perf_cpu_context *cpuctx,
1956 struct perf_event_context *ctx)
1958 u64 tstamp = perf_event_time(event);
1961 lockdep_assert_held(&ctx->lock);
1963 if (event->state <= PERF_EVENT_STATE_OFF)
1966 WRITE_ONCE(event->oncpu, smp_processor_id());
1968 * Order event::oncpu write to happen before the ACTIVE state
1972 WRITE_ONCE(event->state, PERF_EVENT_STATE_ACTIVE);
1975 * Unthrottle events, since we scheduled we might have missed several
1976 * ticks already, also for a heavily scheduling task there is little
1977 * guarantee it'll get a tick in a timely manner.
1979 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1980 perf_log_throttle(event, 1);
1981 event->hw.interrupts = 0;
1985 * The new state must be visible before we turn it on in the hardware:
1989 perf_pmu_disable(event->pmu);
1991 perf_set_shadow_time(event, ctx, tstamp);
1993 perf_log_itrace_start(event);
1995 if (event->pmu->add(event, PERF_EF_START)) {
1996 event->state = PERF_EVENT_STATE_INACTIVE;
2002 event->tstamp_running += tstamp - event->tstamp_stopped;
2004 if (!is_software_event(event))
2005 cpuctx->active_oncpu++;
2006 if (!ctx->nr_active++)
2007 perf_event_ctx_activate(ctx);
2008 if (event->attr.freq && event->attr.sample_freq)
2011 if (event->attr.exclusive)
2012 cpuctx->exclusive = 1;
2014 if (is_orphaned_child(event))
2015 schedule_orphans_remove(ctx);
2018 perf_pmu_enable(event->pmu);
2024 group_sched_in(struct perf_event *group_event,
2025 struct perf_cpu_context *cpuctx,
2026 struct perf_event_context *ctx)
2028 struct perf_event *event, *partial_group = NULL;
2029 struct pmu *pmu = ctx->pmu;
2030 u64 now = ctx->time;
2031 bool simulate = false;
2033 if (group_event->state == PERF_EVENT_STATE_OFF)
2036 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2038 if (event_sched_in(group_event, cpuctx, ctx)) {
2039 pmu->cancel_txn(pmu);
2040 perf_mux_hrtimer_restart(cpuctx);
2045 * Schedule in siblings as one group (if any):
2047 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2048 if (event_sched_in(event, cpuctx, ctx)) {
2049 partial_group = event;
2054 if (!pmu->commit_txn(pmu))
2059 * Groups can be scheduled in as one unit only, so undo any
2060 * partial group before returning:
2061 * The events up to the failed event are scheduled out normally,
2062 * tstamp_stopped will be updated.
2064 * The failed events and the remaining siblings need to have
2065 * their timings updated as if they had gone thru event_sched_in()
2066 * and event_sched_out(). This is required to get consistent timings
2067 * across the group. This also takes care of the case where the group
2068 * could never be scheduled by ensuring tstamp_stopped is set to mark
2069 * the time the event was actually stopped, such that time delta
2070 * calculation in update_event_times() is correct.
2072 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2073 if (event == partial_group)
2077 event->tstamp_running += now - event->tstamp_stopped;
2078 event->tstamp_stopped = now;
2080 event_sched_out(event, cpuctx, ctx);
2083 event_sched_out(group_event, cpuctx, ctx);
2085 pmu->cancel_txn(pmu);
2087 perf_mux_hrtimer_restart(cpuctx);
2093 * Work out whether we can put this event group on the CPU now.
2095 static int group_can_go_on(struct perf_event *event,
2096 struct perf_cpu_context *cpuctx,
2100 * Groups consisting entirely of software events can always go on.
2102 if (event->group_flags & PERF_GROUP_SOFTWARE)
2105 * If an exclusive group is already on, no other hardware
2108 if (cpuctx->exclusive)
2111 * If this group is exclusive and there are already
2112 * events on the CPU, it can't go on.
2114 if (event->attr.exclusive && cpuctx->active_oncpu)
2117 * Otherwise, try to add it if all previous groups were able
2123 static void add_event_to_ctx(struct perf_event *event,
2124 struct perf_event_context *ctx)
2126 u64 tstamp = perf_event_time(event);
2128 list_add_event(event, ctx);
2129 perf_group_attach(event);
2130 event->tstamp_enabled = tstamp;
2131 event->tstamp_running = tstamp;
2132 event->tstamp_stopped = tstamp;
2135 static void task_ctx_sched_out(struct perf_event_context *ctx);
2137 ctx_sched_in(struct perf_event_context *ctx,
2138 struct perf_cpu_context *cpuctx,
2139 enum event_type_t event_type,
2140 struct task_struct *task);
2142 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2143 struct perf_event_context *ctx,
2144 struct task_struct *task)
2146 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2148 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2149 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2151 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2155 * Cross CPU call to install and enable a performance event
2157 * Must be called with ctx->mutex held
2159 static int __perf_install_in_context(void *info)
2161 struct perf_event *event = info;
2162 struct perf_event_context *ctx = event->ctx;
2163 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2164 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2165 struct task_struct *task = current;
2167 perf_ctx_lock(cpuctx, task_ctx);
2168 perf_pmu_disable(cpuctx->ctx.pmu);
2171 * If there was an active task_ctx schedule it out.
2174 task_ctx_sched_out(task_ctx);
2177 * If the context we're installing events in is not the
2178 * active task_ctx, flip them.
2180 if (ctx->task && task_ctx != ctx) {
2182 raw_spin_unlock(&task_ctx->lock);
2183 raw_spin_lock(&ctx->lock);
2188 cpuctx->task_ctx = task_ctx;
2189 task = task_ctx->task;
2192 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
2194 update_context_time(ctx);
2196 * update cgrp time only if current cgrp
2197 * matches event->cgrp. Must be done before
2198 * calling add_event_to_ctx()
2200 update_cgrp_time_from_event(event);
2202 add_event_to_ctx(event, ctx);
2205 * Schedule everything back in
2207 perf_event_sched_in(cpuctx, task_ctx, task);
2209 perf_pmu_enable(cpuctx->ctx.pmu);
2210 perf_ctx_unlock(cpuctx, task_ctx);
2216 * Attach a performance event to a context
2218 * First we add the event to the list with the hardware enable bit
2219 * in event->hw_config cleared.
2221 * If the event is attached to a task which is on a CPU we use a smp
2222 * call to enable it in the task context. The task might have been
2223 * scheduled away, but we check this in the smp call again.
2226 perf_install_in_context(struct perf_event_context *ctx,
2227 struct perf_event *event,
2230 struct task_struct *task = ctx->task;
2232 lockdep_assert_held(&ctx->mutex);
2235 if (event->cpu != -1)
2240 * Per cpu events are installed via an smp call and
2241 * the install is always successful.
2243 cpu_function_call(cpu, __perf_install_in_context, event);
2248 if (!task_function_call(task, __perf_install_in_context, event))
2251 raw_spin_lock_irq(&ctx->lock);
2253 * If we failed to find a running task, but find the context active now
2254 * that we've acquired the ctx->lock, retry.
2256 if (ctx->is_active) {
2257 raw_spin_unlock_irq(&ctx->lock);
2259 * Reload the task pointer, it might have been changed by
2260 * a concurrent perf_event_context_sched_out().
2267 * Since the task isn't running, its safe to add the event, us holding
2268 * the ctx->lock ensures the task won't get scheduled in.
2270 add_event_to_ctx(event, ctx);
2271 raw_spin_unlock_irq(&ctx->lock);
2275 * Put a event into inactive state and update time fields.
2276 * Enabling the leader of a group effectively enables all
2277 * the group members that aren't explicitly disabled, so we
2278 * have to update their ->tstamp_enabled also.
2279 * Note: this works for group members as well as group leaders
2280 * since the non-leader members' sibling_lists will be empty.
2282 static void __perf_event_mark_enabled(struct perf_event *event)
2284 struct perf_event *sub;
2285 u64 tstamp = perf_event_time(event);
2287 event->state = PERF_EVENT_STATE_INACTIVE;
2288 event->tstamp_enabled = tstamp - event->total_time_enabled;
2289 list_for_each_entry(sub, &event->sibling_list, group_entry) {
2290 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2291 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2296 * Cross CPU call to enable a performance event
2298 static int __perf_event_enable(void *info)
2300 struct perf_event *event = info;
2301 struct perf_event_context *ctx = event->ctx;
2302 struct perf_event *leader = event->group_leader;
2303 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2307 * There's a time window between 'ctx->is_active' check
2308 * in perf_event_enable function and this place having:
2310 * - ctx->lock unlocked
2312 * where the task could be killed and 'ctx' deactivated
2313 * by perf_event_exit_task.
2315 if (!ctx->is_active)
2318 raw_spin_lock(&ctx->lock);
2319 update_context_time(ctx);
2321 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2325 * set current task's cgroup time reference point
2327 perf_cgroup_set_timestamp(current, ctx);
2329 __perf_event_mark_enabled(event);
2331 if (!event_filter_match(event)) {
2332 if (is_cgroup_event(event))
2333 perf_cgroup_defer_enabled(event);
2338 * If the event is in a group and isn't the group leader,
2339 * then don't put it on unless the group is on.
2341 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
2344 if (!group_can_go_on(event, cpuctx, 1)) {
2347 if (event == leader)
2348 err = group_sched_in(event, cpuctx, ctx);
2350 err = event_sched_in(event, cpuctx, ctx);
2355 * If this event can't go on and it's part of a
2356 * group, then the whole group has to come off.
2358 if (leader != event) {
2359 group_sched_out(leader, cpuctx, ctx);
2360 perf_mux_hrtimer_restart(cpuctx);
2362 if (leader->attr.pinned) {
2363 update_group_times(leader);
2364 leader->state = PERF_EVENT_STATE_ERROR;
2369 raw_spin_unlock(&ctx->lock);
2377 * If event->ctx is a cloned context, callers must make sure that
2378 * every task struct that event->ctx->task could possibly point to
2379 * remains valid. This condition is satisfied when called through
2380 * perf_event_for_each_child or perf_event_for_each as described
2381 * for perf_event_disable.
2383 static void _perf_event_enable(struct perf_event *event)
2385 struct perf_event_context *ctx = event->ctx;
2386 struct task_struct *task = ctx->task;
2390 * Enable the event on the cpu that it's on
2392 cpu_function_call(event->cpu, __perf_event_enable, event);
2396 raw_spin_lock_irq(&ctx->lock);
2397 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2401 * If the event is in error state, clear that first.
2402 * That way, if we see the event in error state below, we
2403 * know that it has gone back into error state, as distinct
2404 * from the task having been scheduled away before the
2405 * cross-call arrived.
2407 if (event->state == PERF_EVENT_STATE_ERROR)
2408 event->state = PERF_EVENT_STATE_OFF;
2411 if (!ctx->is_active) {
2412 __perf_event_mark_enabled(event);
2416 raw_spin_unlock_irq(&ctx->lock);
2418 if (!task_function_call(task, __perf_event_enable, event))
2421 raw_spin_lock_irq(&ctx->lock);
2424 * If the context is active and the event is still off,
2425 * we need to retry the cross-call.
2427 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
2429 * task could have been flipped by a concurrent
2430 * perf_event_context_sched_out()
2437 raw_spin_unlock_irq(&ctx->lock);
2441 * See perf_event_disable();
2443 void perf_event_enable(struct perf_event *event)
2445 struct perf_event_context *ctx;
2447 ctx = perf_event_ctx_lock(event);
2448 _perf_event_enable(event);
2449 perf_event_ctx_unlock(event, ctx);
2451 EXPORT_SYMBOL_GPL(perf_event_enable);
2453 static int __perf_event_stop(void *info)
2455 struct perf_event *event = info;
2457 /* for AUX events, our job is done if the event is already inactive */
2458 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2461 /* matches smp_wmb() in event_sched_in() */
2465 * There is a window with interrupts enabled before we get here,
2466 * so we need to check again lest we try to stop another CPU's event.
2468 if (READ_ONCE(event->oncpu) != smp_processor_id())
2471 event->pmu->stop(event, PERF_EF_UPDATE);
2476 static int _perf_event_refresh(struct perf_event *event, int refresh)
2479 * not supported on inherited events
2481 if (event->attr.inherit || !is_sampling_event(event))
2484 atomic_add(refresh, &event->event_limit);
2485 _perf_event_enable(event);
2491 * See perf_event_disable()
2493 int perf_event_refresh(struct perf_event *event, int refresh)
2495 struct perf_event_context *ctx;
2498 ctx = perf_event_ctx_lock(event);
2499 ret = _perf_event_refresh(event, refresh);
2500 perf_event_ctx_unlock(event, ctx);
2504 EXPORT_SYMBOL_GPL(perf_event_refresh);
2506 static void ctx_sched_out(struct perf_event_context *ctx,
2507 struct perf_cpu_context *cpuctx,
2508 enum event_type_t event_type)
2510 struct perf_event *event;
2511 int is_active = ctx->is_active;
2513 ctx->is_active &= ~event_type;
2514 if (likely(!ctx->nr_events))
2517 update_context_time(ctx);
2518 update_cgrp_time_from_cpuctx(cpuctx);
2519 if (!ctx->nr_active)
2522 perf_pmu_disable(ctx->pmu);
2523 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2524 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2525 group_sched_out(event, cpuctx, ctx);
2528 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2529 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2530 group_sched_out(event, cpuctx, ctx);
2532 perf_pmu_enable(ctx->pmu);
2536 * Test whether two contexts are equivalent, i.e. whether they have both been
2537 * cloned from the same version of the same context.
2539 * Equivalence is measured using a generation number in the context that is
2540 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2541 * and list_del_event().
2543 static int context_equiv(struct perf_event_context *ctx1,
2544 struct perf_event_context *ctx2)
2546 lockdep_assert_held(&ctx1->lock);
2547 lockdep_assert_held(&ctx2->lock);
2549 /* Pinning disables the swap optimization */
2550 if (ctx1->pin_count || ctx2->pin_count)
2553 /* If ctx1 is the parent of ctx2 */
2554 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2557 /* If ctx2 is the parent of ctx1 */
2558 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2562 * If ctx1 and ctx2 have the same parent; we flatten the parent
2563 * hierarchy, see perf_event_init_context().
2565 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2566 ctx1->parent_gen == ctx2->parent_gen)
2573 static void __perf_event_sync_stat(struct perf_event *event,
2574 struct perf_event *next_event)
2578 if (!event->attr.inherit_stat)
2582 * Update the event value, we cannot use perf_event_read()
2583 * because we're in the middle of a context switch and have IRQs
2584 * disabled, which upsets smp_call_function_single(), however
2585 * we know the event must be on the current CPU, therefore we
2586 * don't need to use it.
2588 switch (event->state) {
2589 case PERF_EVENT_STATE_ACTIVE:
2590 event->pmu->read(event);
2593 case PERF_EVENT_STATE_INACTIVE:
2594 update_event_times(event);
2602 * In order to keep per-task stats reliable we need to flip the event
2603 * values when we flip the contexts.
2605 value = local64_read(&next_event->count);
2606 value = local64_xchg(&event->count, value);
2607 local64_set(&next_event->count, value);
2609 swap(event->total_time_enabled, next_event->total_time_enabled);
2610 swap(event->total_time_running, next_event->total_time_running);
2613 * Since we swizzled the values, update the user visible data too.
2615 perf_event_update_userpage(event);
2616 perf_event_update_userpage(next_event);
2619 static void perf_event_sync_stat(struct perf_event_context *ctx,
2620 struct perf_event_context *next_ctx)
2622 struct perf_event *event, *next_event;
2627 update_context_time(ctx);
2629 event = list_first_entry(&ctx->event_list,
2630 struct perf_event, event_entry);
2632 next_event = list_first_entry(&next_ctx->event_list,
2633 struct perf_event, event_entry);
2635 while (&event->event_entry != &ctx->event_list &&
2636 &next_event->event_entry != &next_ctx->event_list) {
2638 __perf_event_sync_stat(event, next_event);
2640 event = list_next_entry(event, event_entry);
2641 next_event = list_next_entry(next_event, event_entry);
2645 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2646 struct task_struct *next)
2648 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2649 struct perf_event_context *next_ctx;
2650 struct perf_event_context *parent, *next_parent;
2651 struct perf_cpu_context *cpuctx;
2657 cpuctx = __get_cpu_context(ctx);
2658 if (!cpuctx->task_ctx)
2662 next_ctx = next->perf_event_ctxp[ctxn];
2666 parent = rcu_dereference(ctx->parent_ctx);
2667 next_parent = rcu_dereference(next_ctx->parent_ctx);
2669 /* If neither context have a parent context; they cannot be clones. */
2670 if (!parent && !next_parent)
2673 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2675 * Looks like the two contexts are clones, so we might be
2676 * able to optimize the context switch. We lock both
2677 * contexts and check that they are clones under the
2678 * lock (including re-checking that neither has been
2679 * uncloned in the meantime). It doesn't matter which
2680 * order we take the locks because no other cpu could
2681 * be trying to lock both of these tasks.
2683 raw_spin_lock(&ctx->lock);
2684 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2685 if (context_equiv(ctx, next_ctx)) {
2687 * XXX do we need a memory barrier of sorts
2688 * wrt to rcu_dereference() of perf_event_ctxp
2690 task->perf_event_ctxp[ctxn] = next_ctx;
2691 next->perf_event_ctxp[ctxn] = ctx;
2693 next_ctx->task = task;
2695 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
2699 perf_event_sync_stat(ctx, next_ctx);
2701 raw_spin_unlock(&next_ctx->lock);
2702 raw_spin_unlock(&ctx->lock);
2708 raw_spin_lock(&ctx->lock);
2709 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2710 cpuctx->task_ctx = NULL;
2711 raw_spin_unlock(&ctx->lock);
2715 void perf_sched_cb_dec(struct pmu *pmu)
2717 this_cpu_dec(perf_sched_cb_usages);
2720 void perf_sched_cb_inc(struct pmu *pmu)
2722 this_cpu_inc(perf_sched_cb_usages);
2726 * This function provides the context switch callback to the lower code
2727 * layer. It is invoked ONLY when the context switch callback is enabled.
2729 static void perf_pmu_sched_task(struct task_struct *prev,
2730 struct task_struct *next,
2733 struct perf_cpu_context *cpuctx;
2735 unsigned long flags;
2740 local_irq_save(flags);
2744 list_for_each_entry_rcu(pmu, &pmus, entry) {
2745 if (pmu->sched_task) {
2746 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2748 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2750 perf_pmu_disable(pmu);
2752 pmu->sched_task(cpuctx->task_ctx, sched_in);
2754 perf_pmu_enable(pmu);
2756 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2762 local_irq_restore(flags);
2765 static void perf_event_switch(struct task_struct *task,
2766 struct task_struct *next_prev, bool sched_in);
2768 #define for_each_task_context_nr(ctxn) \
2769 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2772 * Called from scheduler to remove the events of the current task,
2773 * with interrupts disabled.
2775 * We stop each event and update the event value in event->count.
2777 * This does not protect us against NMI, but disable()
2778 * sets the disabled bit in the control field of event _before_
2779 * accessing the event control register. If a NMI hits, then it will
2780 * not restart the event.
2782 void __perf_event_task_sched_out(struct task_struct *task,
2783 struct task_struct *next)
2787 if (__this_cpu_read(perf_sched_cb_usages))
2788 perf_pmu_sched_task(task, next, false);
2790 if (atomic_read(&nr_switch_events))
2791 perf_event_switch(task, next, false);
2793 for_each_task_context_nr(ctxn)
2794 perf_event_context_sched_out(task, ctxn, next);
2797 * if cgroup events exist on this CPU, then we need
2798 * to check if we have to switch out PMU state.
2799 * cgroup event are system-wide mode only
2801 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2802 perf_cgroup_sched_out(task, next);
2805 static void task_ctx_sched_out(struct perf_event_context *ctx)
2807 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2809 if (!cpuctx->task_ctx)
2812 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2815 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2816 cpuctx->task_ctx = NULL;
2820 * Called with IRQs disabled
2822 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2823 enum event_type_t event_type)
2825 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2829 ctx_pinned_sched_in(struct perf_event_context *ctx,
2830 struct perf_cpu_context *cpuctx)
2832 struct perf_event *event;
2834 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2835 if (event->state <= PERF_EVENT_STATE_OFF)
2837 if (!event_filter_match(event))
2840 /* may need to reset tstamp_enabled */
2841 if (is_cgroup_event(event))
2842 perf_cgroup_mark_enabled(event, ctx);
2844 if (group_can_go_on(event, cpuctx, 1))
2845 group_sched_in(event, cpuctx, ctx);
2848 * If this pinned group hasn't been scheduled,
2849 * put it in error state.
2851 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2852 update_group_times(event);
2853 event->state = PERF_EVENT_STATE_ERROR;
2859 ctx_flexible_sched_in(struct perf_event_context *ctx,
2860 struct perf_cpu_context *cpuctx)
2862 struct perf_event *event;
2865 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2866 /* Ignore events in OFF or ERROR state */
2867 if (event->state <= PERF_EVENT_STATE_OFF)
2870 * Listen to the 'cpu' scheduling filter constraint
2873 if (!event_filter_match(event))
2876 /* may need to reset tstamp_enabled */
2877 if (is_cgroup_event(event))
2878 perf_cgroup_mark_enabled(event, ctx);
2880 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2881 if (group_sched_in(event, cpuctx, ctx))
2888 ctx_sched_in(struct perf_event_context *ctx,
2889 struct perf_cpu_context *cpuctx,
2890 enum event_type_t event_type,
2891 struct task_struct *task)
2894 int is_active = ctx->is_active;
2896 ctx->is_active |= event_type;
2897 if (likely(!ctx->nr_events))
2901 ctx->timestamp = now;
2902 perf_cgroup_set_timestamp(task, ctx);
2904 * First go through the list and put on any pinned groups
2905 * in order to give them the best chance of going on.
2907 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2908 ctx_pinned_sched_in(ctx, cpuctx);
2910 /* Then walk through the lower prio flexible groups */
2911 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2912 ctx_flexible_sched_in(ctx, cpuctx);
2915 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2916 enum event_type_t event_type,
2917 struct task_struct *task)
2919 struct perf_event_context *ctx = &cpuctx->ctx;
2921 ctx_sched_in(ctx, cpuctx, event_type, task);
2924 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2925 struct task_struct *task)
2927 struct perf_cpu_context *cpuctx;
2929 cpuctx = __get_cpu_context(ctx);
2930 if (cpuctx->task_ctx == ctx)
2933 perf_ctx_lock(cpuctx, ctx);
2934 perf_pmu_disable(ctx->pmu);
2936 * We want to keep the following priority order:
2937 * cpu pinned (that don't need to move), task pinned,
2938 * cpu flexible, task flexible.
2940 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2943 cpuctx->task_ctx = ctx;
2945 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2947 perf_pmu_enable(ctx->pmu);
2948 perf_ctx_unlock(cpuctx, ctx);
2952 * Called from scheduler to add the events of the current task
2953 * with interrupts disabled.
2955 * We restore the event value and then enable it.
2957 * This does not protect us against NMI, but enable()
2958 * sets the enabled bit in the control field of event _before_
2959 * accessing the event control register. If a NMI hits, then it will
2960 * keep the event running.
2962 void __perf_event_task_sched_in(struct task_struct *prev,
2963 struct task_struct *task)
2965 struct perf_event_context *ctx;
2968 for_each_task_context_nr(ctxn) {
2969 ctx = task->perf_event_ctxp[ctxn];
2973 perf_event_context_sched_in(ctx, task);
2976 * if cgroup events exist on this CPU, then we need
2977 * to check if we have to switch in PMU state.
2978 * cgroup event are system-wide mode only
2980 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2981 perf_cgroup_sched_in(prev, task);
2983 if (atomic_read(&nr_switch_events))
2984 perf_event_switch(task, prev, true);
2986 if (__this_cpu_read(perf_sched_cb_usages))
2987 perf_pmu_sched_task(prev, task, true);
2990 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2992 u64 frequency = event->attr.sample_freq;
2993 u64 sec = NSEC_PER_SEC;
2994 u64 divisor, dividend;
2996 int count_fls, nsec_fls, frequency_fls, sec_fls;
2998 count_fls = fls64(count);
2999 nsec_fls = fls64(nsec);
3000 frequency_fls = fls64(frequency);
3004 * We got @count in @nsec, with a target of sample_freq HZ
3005 * the target period becomes:
3008 * period = -------------------
3009 * @nsec * sample_freq
3014 * Reduce accuracy by one bit such that @a and @b converge
3015 * to a similar magnitude.
3017 #define REDUCE_FLS(a, b) \
3019 if (a##_fls > b##_fls) { \
3029 * Reduce accuracy until either term fits in a u64, then proceed with
3030 * the other, so that finally we can do a u64/u64 division.
3032 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3033 REDUCE_FLS(nsec, frequency);
3034 REDUCE_FLS(sec, count);
3037 if (count_fls + sec_fls > 64) {
3038 divisor = nsec * frequency;
3040 while (count_fls + sec_fls > 64) {
3041 REDUCE_FLS(count, sec);
3045 dividend = count * sec;
3047 dividend = count * sec;
3049 while (nsec_fls + frequency_fls > 64) {
3050 REDUCE_FLS(nsec, frequency);
3054 divisor = nsec * frequency;
3060 return div64_u64(dividend, divisor);
3063 static DEFINE_PER_CPU(int, perf_throttled_count);
3064 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3066 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3068 struct hw_perf_event *hwc = &event->hw;
3069 s64 period, sample_period;
3072 period = perf_calculate_period(event, nsec, count);
3074 delta = (s64)(period - hwc->sample_period);
3075 delta = (delta + 7) / 8; /* low pass filter */
3077 sample_period = hwc->sample_period + delta;
3082 hwc->sample_period = sample_period;
3084 if (local64_read(&hwc->period_left) > 8*sample_period) {
3086 event->pmu->stop(event, PERF_EF_UPDATE);
3088 local64_set(&hwc->period_left, 0);
3091 event->pmu->start(event, PERF_EF_RELOAD);
3096 * combine freq adjustment with unthrottling to avoid two passes over the
3097 * events. At the same time, make sure, having freq events does not change
3098 * the rate of unthrottling as that would introduce bias.
3100 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3103 struct perf_event *event;
3104 struct hw_perf_event *hwc;
3105 u64 now, period = TICK_NSEC;
3109 * only need to iterate over all events iff:
3110 * - context have events in frequency mode (needs freq adjust)
3111 * - there are events to unthrottle on this cpu
3113 if (!(ctx->nr_freq || needs_unthr))
3116 raw_spin_lock(&ctx->lock);
3117 perf_pmu_disable(ctx->pmu);
3119 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3120 if (event->state != PERF_EVENT_STATE_ACTIVE)
3123 if (!event_filter_match(event))
3126 perf_pmu_disable(event->pmu);
3130 if (hwc->interrupts == MAX_INTERRUPTS) {
3131 hwc->interrupts = 0;
3132 perf_log_throttle(event, 1);
3133 event->pmu->start(event, 0);
3136 if (!event->attr.freq || !event->attr.sample_freq)
3140 * stop the event and update event->count
3142 event->pmu->stop(event, PERF_EF_UPDATE);
3144 now = local64_read(&event->count);
3145 delta = now - hwc->freq_count_stamp;
3146 hwc->freq_count_stamp = now;
3150 * reload only if value has changed
3151 * we have stopped the event so tell that
3152 * to perf_adjust_period() to avoid stopping it
3156 perf_adjust_period(event, period, delta, false);
3158 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3160 perf_pmu_enable(event->pmu);
3163 perf_pmu_enable(ctx->pmu);
3164 raw_spin_unlock(&ctx->lock);
3168 * Round-robin a context's events:
3170 static void rotate_ctx(struct perf_event_context *ctx)
3173 * Rotate the first entry last of non-pinned groups. Rotation might be
3174 * disabled by the inheritance code.
3176 if (!ctx->rotate_disable)
3177 list_rotate_left(&ctx->flexible_groups);
3180 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
3182 struct perf_event_context *ctx = NULL;
3185 if (cpuctx->ctx.nr_events) {
3186 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
3190 ctx = cpuctx->task_ctx;
3191 if (ctx && ctx->nr_events) {
3192 if (ctx->nr_events != ctx->nr_active)
3199 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3200 perf_pmu_disable(cpuctx->ctx.pmu);
3202 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3204 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
3206 rotate_ctx(&cpuctx->ctx);
3210 perf_event_sched_in(cpuctx, ctx, current);
3212 perf_pmu_enable(cpuctx->ctx.pmu);
3213 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3219 #ifdef CONFIG_NO_HZ_FULL
3220 bool perf_event_can_stop_tick(void)
3222 if (atomic_read(&nr_freq_events) ||
3223 __this_cpu_read(perf_throttled_count))
3230 void perf_event_task_tick(void)
3232 struct list_head *head = this_cpu_ptr(&active_ctx_list);
3233 struct perf_event_context *ctx, *tmp;
3236 WARN_ON(!irqs_disabled());
3238 __this_cpu_inc(perf_throttled_seq);
3239 throttled = __this_cpu_xchg(perf_throttled_count, 0);
3241 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
3242 perf_adjust_freq_unthr_context(ctx, throttled);
3245 static int event_enable_on_exec(struct perf_event *event,
3246 struct perf_event_context *ctx)
3248 if (!event->attr.enable_on_exec)
3251 event->attr.enable_on_exec = 0;
3252 if (event->state >= PERF_EVENT_STATE_INACTIVE)
3255 __perf_event_mark_enabled(event);
3261 * Enable all of a task's events that have been marked enable-on-exec.
3262 * This expects task == current.
3264 static void perf_event_enable_on_exec(int ctxn)
3266 struct perf_event_context *ctx, *clone_ctx = NULL;
3267 struct perf_event *event;
3268 unsigned long flags;
3272 local_irq_save(flags);
3273 ctx = current->perf_event_ctxp[ctxn];
3274 if (!ctx || !ctx->nr_events)
3278 * We must ctxsw out cgroup events to avoid conflict
3279 * when invoking perf_task_event_sched_in() later on
3280 * in this function. Otherwise we end up trying to
3281 * ctxswin cgroup events which are already scheduled
3284 perf_cgroup_sched_out(current, NULL);
3286 raw_spin_lock(&ctx->lock);
3287 task_ctx_sched_out(ctx);
3289 list_for_each_entry(event, &ctx->event_list, event_entry) {
3290 ret = event_enable_on_exec(event, ctx);
3296 * Unclone this context if we enabled any event.
3299 clone_ctx = unclone_ctx(ctx);
3301 raw_spin_unlock(&ctx->lock);
3304 * Also calls ctxswin for cgroup events, if any:
3306 perf_event_context_sched_in(ctx, ctx->task);
3308 local_irq_restore(flags);
3314 void perf_event_exec(void)
3319 for_each_task_context_nr(ctxn)
3320 perf_event_enable_on_exec(ctxn);
3324 struct perf_read_data {
3325 struct perf_event *event;
3331 * Cross CPU call to read the hardware event
3333 static void __perf_event_read(void *info)
3335 struct perf_read_data *data = info;
3336 struct perf_event *sub, *event = data->event;
3337 struct perf_event_context *ctx = event->ctx;
3338 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3339 struct pmu *pmu = event->pmu;
3342 * If this is a task context, we need to check whether it is
3343 * the current task context of this cpu. If not it has been
3344 * scheduled out before the smp call arrived. In that case
3345 * event->count would have been updated to a recent sample
3346 * when the event was scheduled out.
3348 if (ctx->task && cpuctx->task_ctx != ctx)
3351 raw_spin_lock(&ctx->lock);
3352 if (ctx->is_active) {
3353 update_context_time(ctx);
3354 update_cgrp_time_from_event(event);
3357 update_event_times(event);
3358 if (event->state != PERF_EVENT_STATE_ACTIVE)
3367 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
3371 list_for_each_entry(sub, &event->sibling_list, group_entry) {
3372 update_event_times(sub);
3373 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
3375 * Use sibling's PMU rather than @event's since
3376 * sibling could be on different (eg: software) PMU.
3378 sub->pmu->read(sub);
3382 data->ret = pmu->commit_txn(pmu);
3385 raw_spin_unlock(&ctx->lock);
3388 static inline u64 perf_event_count(struct perf_event *event)
3390 if (event->pmu->count)
3391 return event->pmu->count(event);
3393 return __perf_event_count(event);
3397 * NMI-safe method to read a local event, that is an event that
3399 * - either for the current task, or for this CPU
3400 * - does not have inherit set, for inherited task events
3401 * will not be local and we cannot read them atomically
3402 * - must not have a pmu::count method
3404 u64 perf_event_read_local(struct perf_event *event)
3406 unsigned long flags;
3410 * Disabling interrupts avoids all counter scheduling (context
3411 * switches, timer based rotation and IPIs).
3413 local_irq_save(flags);
3415 /* If this is a per-task event, it must be for current */
3416 WARN_ON_ONCE((event->attach_state & PERF_ATTACH_TASK) &&
3417 event->hw.target != current);
3419 /* If this is a per-CPU event, it must be for this CPU */
3420 WARN_ON_ONCE(!(event->attach_state & PERF_ATTACH_TASK) &&
3421 event->cpu != smp_processor_id());
3424 * It must not be an event with inherit set, we cannot read
3425 * all child counters from atomic context.
3427 WARN_ON_ONCE(event->attr.inherit);
3430 * It must not have a pmu::count method, those are not
3433 WARN_ON_ONCE(event->pmu->count);
3436 * If the event is currently on this CPU, its either a per-task event,
3437 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
3440 if (event->oncpu == smp_processor_id())
3441 event->pmu->read(event);
3443 val = local64_read(&event->count);
3444 local_irq_restore(flags);
3449 static int perf_event_read(struct perf_event *event, bool group)
3451 int event_cpu, ret = 0;
3454 * If event is enabled and currently active on a CPU, update the
3455 * value in the event structure:
3457 event_cpu = READ_ONCE(event->oncpu);
3459 if (event->state == PERF_EVENT_STATE_ACTIVE &&
3460 !cpu_isolated(event_cpu)) {
3461 struct perf_read_data data = {
3467 if ((unsigned int)event_cpu >= nr_cpu_ids)
3469 if (!event->attr.exclude_idle ||
3470 !per_cpu(is_idle, event_cpu)) {
3471 smp_call_function_single(event_cpu,
3472 __perf_event_read, &data, 1);
3475 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3476 struct perf_event_context *ctx = event->ctx;
3477 unsigned long flags;
3479 raw_spin_lock_irqsave(&ctx->lock, flags);
3481 * may read while context is not active
3482 * (e.g., thread is blocked), in that case
3483 * we cannot update context time
3485 if (ctx->is_active) {
3486 update_context_time(ctx);
3487 update_cgrp_time_from_event(event);
3490 update_group_times(event);
3492 update_event_times(event);
3493 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3500 * Initialize the perf_event context in a task_struct:
3502 static void __perf_event_init_context(struct perf_event_context *ctx)
3504 raw_spin_lock_init(&ctx->lock);
3505 mutex_init(&ctx->mutex);
3506 INIT_LIST_HEAD(&ctx->active_ctx_list);
3507 INIT_LIST_HEAD(&ctx->pinned_groups);
3508 INIT_LIST_HEAD(&ctx->flexible_groups);
3509 INIT_LIST_HEAD(&ctx->event_list);
3510 atomic_set(&ctx->refcount, 1);
3511 INIT_DELAYED_WORK(&ctx->orphans_remove, orphans_remove_work);
3514 static struct perf_event_context *
3515 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3517 struct perf_event_context *ctx;
3519 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3523 __perf_event_init_context(ctx);
3526 get_task_struct(task);
3533 static struct task_struct *
3534 find_lively_task_by_vpid(pid_t vpid)
3536 struct task_struct *task;
3542 task = find_task_by_vpid(vpid);
3544 get_task_struct(task);
3548 return ERR_PTR(-ESRCH);
3554 * Returns a matching context with refcount and pincount.
3556 static struct perf_event_context *
3557 find_get_context(struct pmu *pmu, struct task_struct *task,
3558 struct perf_event *event)
3560 struct perf_event_context *ctx, *clone_ctx = NULL;
3561 struct perf_cpu_context *cpuctx;
3562 void *task_ctx_data = NULL;
3563 unsigned long flags;
3565 int cpu = event->cpu;
3568 /* Must be root to operate on a CPU event: */
3569 if (event->owner != EVENT_OWNER_KERNEL && perf_paranoid_cpu() &&
3570 !capable(CAP_SYS_ADMIN))
3571 return ERR_PTR(-EACCES);
3574 * We could be clever and allow to attach a event to an
3575 * offline CPU and activate it when the CPU comes up, but
3578 if (!cpu_online(cpu))
3579 return ERR_PTR(-ENODEV);
3581 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3590 ctxn = pmu->task_ctx_nr;
3594 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
3595 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
3596 if (!task_ctx_data) {
3603 ctx = perf_lock_task_context(task, ctxn, &flags);
3605 clone_ctx = unclone_ctx(ctx);
3608 if (task_ctx_data && !ctx->task_ctx_data) {
3609 ctx->task_ctx_data = task_ctx_data;
3610 task_ctx_data = NULL;
3612 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3617 ctx = alloc_perf_context(pmu, task);
3622 if (task_ctx_data) {
3623 ctx->task_ctx_data = task_ctx_data;
3624 task_ctx_data = NULL;
3628 mutex_lock(&task->perf_event_mutex);
3630 * If it has already passed perf_event_exit_task().
3631 * we must see PF_EXITING, it takes this mutex too.
3633 if (task->flags & PF_EXITING)
3635 else if (task->perf_event_ctxp[ctxn])
3640 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3642 mutex_unlock(&task->perf_event_mutex);
3644 if (unlikely(err)) {
3653 kfree(task_ctx_data);
3657 kfree(task_ctx_data);
3658 return ERR_PTR(err);
3661 static void perf_event_free_filter(struct perf_event *event);
3662 static void perf_event_free_bpf_prog(struct perf_event *event);
3664 static void free_event_rcu(struct rcu_head *head)
3666 struct perf_event *event;
3668 event = container_of(head, struct perf_event, rcu_head);
3670 put_pid_ns(event->ns);
3671 perf_event_free_filter(event);
3675 static void ring_buffer_attach(struct perf_event *event,
3676 struct ring_buffer *rb);
3678 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3683 if (is_cgroup_event(event))
3684 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3687 static void unaccount_event(struct perf_event *event)
3692 if (event->attach_state & PERF_ATTACH_TASK)
3693 static_key_slow_dec_deferred(&perf_sched_events);
3694 if (event->attr.mmap || event->attr.mmap_data)
3695 atomic_dec(&nr_mmap_events);
3696 if (event->attr.comm)
3697 atomic_dec(&nr_comm_events);
3698 if (event->attr.task)
3699 atomic_dec(&nr_task_events);
3700 if (event->attr.freq)
3701 atomic_dec(&nr_freq_events);
3702 if (event->attr.context_switch) {
3703 static_key_slow_dec_deferred(&perf_sched_events);
3704 atomic_dec(&nr_switch_events);
3706 if (is_cgroup_event(event))
3707 static_key_slow_dec_deferred(&perf_sched_events);
3708 if (has_branch_stack(event))
3709 static_key_slow_dec_deferred(&perf_sched_events);
3711 unaccount_event_cpu(event, event->cpu);
3715 * The following implement mutual exclusion of events on "exclusive" pmus
3716 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
3717 * at a time, so we disallow creating events that might conflict, namely:
3719 * 1) cpu-wide events in the presence of per-task events,
3720 * 2) per-task events in the presence of cpu-wide events,
3721 * 3) two matching events on the same context.
3723 * The former two cases are handled in the allocation path (perf_event_alloc(),
3724 * __free_event()), the latter -- before the first perf_install_in_context().
3726 static int exclusive_event_init(struct perf_event *event)
3728 struct pmu *pmu = event->pmu;
3730 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3734 * Prevent co-existence of per-task and cpu-wide events on the
3735 * same exclusive pmu.
3737 * Negative pmu::exclusive_cnt means there are cpu-wide
3738 * events on this "exclusive" pmu, positive means there are
3741 * Since this is called in perf_event_alloc() path, event::ctx
3742 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
3743 * to mean "per-task event", because unlike other attach states it
3744 * never gets cleared.
3746 if (event->attach_state & PERF_ATTACH_TASK) {
3747 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
3750 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
3757 static void exclusive_event_destroy(struct perf_event *event)
3759 struct pmu *pmu = event->pmu;
3761 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3764 /* see comment in exclusive_event_init() */
3765 if (event->attach_state & PERF_ATTACH_TASK)
3766 atomic_dec(&pmu->exclusive_cnt);
3768 atomic_inc(&pmu->exclusive_cnt);
3771 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
3773 if ((e1->pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) &&
3774 (e1->cpu == e2->cpu ||
3781 /* Called under the same ctx::mutex as perf_install_in_context() */
3782 static bool exclusive_event_installable(struct perf_event *event,
3783 struct perf_event_context *ctx)
3785 struct perf_event *iter_event;
3786 struct pmu *pmu = event->pmu;
3788 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3791 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
3792 if (exclusive_event_match(iter_event, event))
3799 static void __free_event(struct perf_event *event)
3801 if (!event->parent) {
3802 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3803 put_callchain_buffers();
3806 perf_event_free_bpf_prog(event);
3809 event->destroy(event);
3811 if (event->pmu->free_drv_configs)
3812 event->pmu->free_drv_configs(event);
3815 put_ctx(event->ctx);
3818 exclusive_event_destroy(event);
3819 module_put(event->pmu->module);
3822 call_rcu(&event->rcu_head, free_event_rcu);
3825 static void _free_event(struct perf_event *event)
3827 irq_work_sync(&event->pending);
3829 unaccount_event(event);
3833 * Can happen when we close an event with re-directed output.
3835 * Since we have a 0 refcount, perf_mmap_close() will skip
3836 * over us; possibly making our ring_buffer_put() the last.
3838 mutex_lock(&event->mmap_mutex);
3839 ring_buffer_attach(event, NULL);
3840 mutex_unlock(&event->mmap_mutex);
3843 if (is_cgroup_event(event))
3844 perf_detach_cgroup(event);
3846 __free_event(event);
3850 * Used to free events which have a known refcount of 1, such as in error paths
3851 * where the event isn't exposed yet and inherited events.
3853 static void free_event(struct perf_event *event)
3855 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3856 "unexpected event refcount: %ld; ptr=%p\n",
3857 atomic_long_read(&event->refcount), event)) {
3858 /* leak to avoid use-after-free */
3866 * Remove user event from the owner task.
3868 static void perf_remove_from_owner(struct perf_event *event)
3870 struct task_struct *owner;
3873 owner = ACCESS_ONCE(event->owner);
3875 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3876 * !owner it means the list deletion is complete and we can indeed
3877 * free this event, otherwise we need to serialize on
3878 * owner->perf_event_mutex.
3880 smp_read_barrier_depends();
3883 * Since delayed_put_task_struct() also drops the last
3884 * task reference we can safely take a new reference
3885 * while holding the rcu_read_lock().
3887 get_task_struct(owner);
3893 * If we're here through perf_event_exit_task() we're already
3894 * holding ctx->mutex which would be an inversion wrt. the
3895 * normal lock order.
3897 * However we can safely take this lock because its the child
3900 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
3903 * We have to re-check the event->owner field, if it is cleared
3904 * we raced with perf_event_exit_task(), acquiring the mutex
3905 * ensured they're done, and we can proceed with freeing the
3909 list_del_init(&event->owner_entry);
3910 mutex_unlock(&owner->perf_event_mutex);
3911 put_task_struct(owner);
3915 static void put_event(struct perf_event *event)
3917 struct perf_event_context *ctx;
3919 if (!atomic_long_dec_and_test(&event->refcount))
3922 if (!is_kernel_event(event))
3923 perf_remove_from_owner(event);
3926 * There are two ways this annotation is useful:
3928 * 1) there is a lock recursion from perf_event_exit_task
3929 * see the comment there.
3931 * 2) there is a lock-inversion with mmap_sem through
3932 * perf_read_group(), which takes faults while
3933 * holding ctx->mutex, however this is called after
3934 * the last filedesc died, so there is no possibility
3935 * to trigger the AB-BA case.
3937 ctx = perf_event_ctx_lock_nested(event, SINGLE_DEPTH_NESTING);
3938 WARN_ON_ONCE(ctx->parent_ctx);
3939 perf_remove_from_context(event, true);
3940 perf_event_ctx_unlock(event, ctx);
3945 int perf_event_release_kernel(struct perf_event *event)
3950 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3953 * Called when the last reference to the file is gone.
3955 static int perf_release(struct inode *inode, struct file *file)
3957 struct perf_event *event = file->private_data;
3960 * Event can be in state OFF because of a constraint check.
3961 * Change to ACTIVE so that it gets cleaned up correctly.
3963 if ((event->state == PERF_EVENT_STATE_OFF) &&
3964 event->attr.constraint_duplicate)
3965 event->state = PERF_EVENT_STATE_ACTIVE;
3966 put_event(file->private_data);
3971 * Remove all orphanes events from the context.
3973 static void orphans_remove_work(struct work_struct *work)
3975 struct perf_event_context *ctx;
3976 struct perf_event *event, *tmp;
3978 ctx = container_of(work, struct perf_event_context,
3979 orphans_remove.work);
3981 mutex_lock(&ctx->mutex);
3982 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) {
3983 struct perf_event *parent_event = event->parent;
3985 if (!is_orphaned_child(event))
3988 perf_remove_from_context(event, true);
3990 mutex_lock(&parent_event->child_mutex);
3991 list_del_init(&event->child_list);
3992 mutex_unlock(&parent_event->child_mutex);
3995 put_event(parent_event);
3998 raw_spin_lock_irq(&ctx->lock);
3999 ctx->orphans_remove_sched = false;
4000 raw_spin_unlock_irq(&ctx->lock);
4001 mutex_unlock(&ctx->mutex);
4006 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
4008 struct perf_event *child;
4014 mutex_lock(&event->child_mutex);
4016 (void)perf_event_read(event, false);
4017 total += perf_event_count(event);
4019 *enabled += event->total_time_enabled +
4020 atomic64_read(&event->child_total_time_enabled);
4021 *running += event->total_time_running +
4022 atomic64_read(&event->child_total_time_running);
4024 list_for_each_entry(child, &event->child_list, child_list) {
4025 (void)perf_event_read(child, false);
4026 total += perf_event_count(child);
4027 *enabled += child->total_time_enabled;
4028 *running += child->total_time_running;
4030 mutex_unlock(&event->child_mutex);
4034 EXPORT_SYMBOL_GPL(perf_event_read_value);
4036 static int __perf_read_group_add(struct perf_event *leader,
4037 u64 read_format, u64 *values)
4039 struct perf_event *sub;
4040 int n = 1; /* skip @nr */
4043 ret = perf_event_read(leader, true);
4048 * Since we co-schedule groups, {enabled,running} times of siblings
4049 * will be identical to those of the leader, so we only publish one
4052 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4053 values[n++] += leader->total_time_enabled +
4054 atomic64_read(&leader->child_total_time_enabled);
4057 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4058 values[n++] += leader->total_time_running +
4059 atomic64_read(&leader->child_total_time_running);
4063 * Write {count,id} tuples for every sibling.
4065 values[n++] += perf_event_count(leader);
4066 if (read_format & PERF_FORMAT_ID)
4067 values[n++] = primary_event_id(leader);
4069 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4070 values[n++] += perf_event_count(sub);
4071 if (read_format & PERF_FORMAT_ID)
4072 values[n++] = primary_event_id(sub);
4078 static int perf_read_group(struct perf_event *event,
4079 u64 read_format, char __user *buf)
4081 struct perf_event *leader = event->group_leader, *child;
4082 struct perf_event_context *ctx = leader->ctx;
4086 lockdep_assert_held(&ctx->mutex);
4088 values = kzalloc(event->read_size, GFP_KERNEL);
4092 values[0] = 1 + leader->nr_siblings;
4095 * By locking the child_mutex of the leader we effectively
4096 * lock the child list of all siblings.. XXX explain how.
4098 mutex_lock(&leader->child_mutex);
4100 ret = __perf_read_group_add(leader, read_format, values);
4104 list_for_each_entry(child, &leader->child_list, child_list) {
4105 ret = __perf_read_group_add(child, read_format, values);
4110 mutex_unlock(&leader->child_mutex);
4112 ret = event->read_size;
4113 if (copy_to_user(buf, values, event->read_size))
4118 mutex_unlock(&leader->child_mutex);
4124 static int perf_read_one(struct perf_event *event,
4125 u64 read_format, char __user *buf)
4127 u64 enabled, running;
4131 values[n++] = perf_event_read_value(event, &enabled, &running);
4132 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4133 values[n++] = enabled;
4134 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4135 values[n++] = running;
4136 if (read_format & PERF_FORMAT_ID)
4137 values[n++] = primary_event_id(event);
4139 if (copy_to_user(buf, values, n * sizeof(u64)))
4142 return n * sizeof(u64);
4145 static bool is_event_hup(struct perf_event *event)
4149 if (event->state != PERF_EVENT_STATE_EXIT)
4152 mutex_lock(&event->child_mutex);
4153 no_children = list_empty(&event->child_list);
4154 mutex_unlock(&event->child_mutex);
4159 * Read the performance event - simple non blocking version for now
4162 __perf_read(struct perf_event *event, char __user *buf, size_t count)
4164 u64 read_format = event->attr.read_format;
4168 * Return end-of-file for a read on a event that is in
4169 * error state (i.e. because it was pinned but it couldn't be
4170 * scheduled on to the CPU at some point).
4172 if (event->state == PERF_EVENT_STATE_ERROR)
4175 if (count < event->read_size)
4178 WARN_ON_ONCE(event->ctx->parent_ctx);
4179 if (read_format & PERF_FORMAT_GROUP)
4180 ret = perf_read_group(event, read_format, buf);
4182 ret = perf_read_one(event, read_format, buf);
4188 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
4190 struct perf_event *event = file->private_data;
4191 struct perf_event_context *ctx;
4194 ctx = perf_event_ctx_lock(event);
4195 ret = __perf_read(event, buf, count);
4196 perf_event_ctx_unlock(event, ctx);
4201 static unsigned int perf_poll(struct file *file, poll_table *wait)
4203 struct perf_event *event = file->private_data;
4204 struct ring_buffer *rb;
4205 unsigned int events = POLLHUP;
4207 poll_wait(file, &event->waitq, wait);
4209 if (is_event_hup(event))
4213 * Pin the event->rb by taking event->mmap_mutex; otherwise
4214 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
4216 mutex_lock(&event->mmap_mutex);
4219 events = atomic_xchg(&rb->poll, 0);
4220 mutex_unlock(&event->mmap_mutex);
4224 static void _perf_event_reset(struct perf_event *event)
4226 (void)perf_event_read(event, false);
4227 local64_set(&event->count, 0);
4228 perf_event_update_userpage(event);
4232 * Holding the top-level event's child_mutex means that any
4233 * descendant process that has inherited this event will block
4234 * in sync_child_event if it goes to exit, thus satisfying the
4235 * task existence requirements of perf_event_enable/disable.
4237 static void perf_event_for_each_child(struct perf_event *event,
4238 void (*func)(struct perf_event *))
4240 struct perf_event *child;
4242 WARN_ON_ONCE(event->ctx->parent_ctx);
4244 mutex_lock(&event->child_mutex);
4246 list_for_each_entry(child, &event->child_list, child_list)
4248 mutex_unlock(&event->child_mutex);
4251 static void perf_event_for_each(struct perf_event *event,
4252 void (*func)(struct perf_event *))
4254 struct perf_event_context *ctx = event->ctx;
4255 struct perf_event *sibling;
4257 lockdep_assert_held(&ctx->mutex);
4259 event = event->group_leader;
4261 perf_event_for_each_child(event, func);
4262 list_for_each_entry(sibling, &event->sibling_list, group_entry)
4263 perf_event_for_each_child(sibling, func);
4266 struct period_event {
4267 struct perf_event *event;
4271 static int __perf_event_period(void *info)
4273 struct period_event *pe = info;
4274 struct perf_event *event = pe->event;
4275 struct perf_event_context *ctx = event->ctx;
4276 u64 value = pe->value;
4279 raw_spin_lock(&ctx->lock);
4280 if (event->attr.freq) {
4281 event->attr.sample_freq = value;
4283 event->attr.sample_period = value;
4284 event->hw.sample_period = value;
4287 active = (event->state == PERF_EVENT_STATE_ACTIVE);
4289 perf_pmu_disable(ctx->pmu);
4290 event->pmu->stop(event, PERF_EF_UPDATE);
4293 local64_set(&event->hw.period_left, 0);
4296 event->pmu->start(event, PERF_EF_RELOAD);
4297 perf_pmu_enable(ctx->pmu);
4299 raw_spin_unlock(&ctx->lock);
4304 static int perf_event_period(struct perf_event *event, u64 __user *arg)
4306 struct period_event pe = { .event = event, };
4307 struct perf_event_context *ctx = event->ctx;
4308 struct task_struct *task;
4311 if (!is_sampling_event(event))
4314 if (copy_from_user(&value, arg, sizeof(value)))
4320 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
4327 cpu_function_call(event->cpu, __perf_event_period, &pe);
4332 if (!task_function_call(task, __perf_event_period, &pe))
4335 raw_spin_lock_irq(&ctx->lock);
4336 if (ctx->is_active) {
4337 raw_spin_unlock_irq(&ctx->lock);
4342 if (event->attr.freq) {
4343 event->attr.sample_freq = value;
4345 event->attr.sample_period = value;
4346 event->hw.sample_period = value;
4349 local64_set(&event->hw.period_left, 0);
4350 raw_spin_unlock_irq(&ctx->lock);
4355 static const struct file_operations perf_fops;
4357 static inline int perf_fget_light(int fd, struct fd *p)
4359 struct fd f = fdget(fd);
4363 if (f.file->f_op != &perf_fops) {
4371 static int perf_event_set_output(struct perf_event *event,
4372 struct perf_event *output_event);
4373 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
4374 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
4375 static int perf_event_drv_configs(struct perf_event *event,
4378 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
4380 void (*func)(struct perf_event *);
4384 case PERF_EVENT_IOC_ENABLE:
4385 func = _perf_event_enable;
4387 case PERF_EVENT_IOC_DISABLE:
4388 func = _perf_event_disable;
4390 case PERF_EVENT_IOC_RESET:
4391 func = _perf_event_reset;
4394 case PERF_EVENT_IOC_REFRESH:
4395 return _perf_event_refresh(event, arg);
4397 case PERF_EVENT_IOC_PERIOD:
4398 return perf_event_period(event, (u64 __user *)arg);
4400 case PERF_EVENT_IOC_ID:
4402 u64 id = primary_event_id(event);
4404 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
4409 case PERF_EVENT_IOC_SET_OUTPUT:
4413 struct perf_event *output_event;
4415 ret = perf_fget_light(arg, &output);
4418 output_event = output.file->private_data;
4419 ret = perf_event_set_output(event, output_event);
4422 ret = perf_event_set_output(event, NULL);
4427 case PERF_EVENT_IOC_SET_FILTER:
4428 return perf_event_set_filter(event, (void __user *)arg);
4430 case PERF_EVENT_IOC_SET_BPF:
4431 return perf_event_set_bpf_prog(event, arg);
4433 case PERF_EVENT_IOC_SET_DRV_CONFIGS:
4434 return perf_event_drv_configs(event, (void __user *)arg);
4440 if (flags & PERF_IOC_FLAG_GROUP)
4441 perf_event_for_each(event, func);
4443 perf_event_for_each_child(event, func);
4448 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4450 struct perf_event *event = file->private_data;
4451 struct perf_event_context *ctx;
4454 ctx = perf_event_ctx_lock(event);
4455 ret = _perf_ioctl(event, cmd, arg);
4456 perf_event_ctx_unlock(event, ctx);
4461 #ifdef CONFIG_COMPAT
4462 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
4465 switch (_IOC_NR(cmd)) {
4466 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
4467 case _IOC_NR(PERF_EVENT_IOC_ID):
4468 case _IOC_NR(PERF_EVENT_IOC_SET_DRV_CONFIGS):
4469 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
4470 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
4471 cmd &= ~IOCSIZE_MASK;
4472 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
4476 return perf_ioctl(file, cmd, arg);
4479 # define perf_compat_ioctl NULL
4482 int perf_event_task_enable(void)
4484 struct perf_event_context *ctx;
4485 struct perf_event *event;
4487 mutex_lock(¤t->perf_event_mutex);
4488 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4489 ctx = perf_event_ctx_lock(event);
4490 perf_event_for_each_child(event, _perf_event_enable);
4491 perf_event_ctx_unlock(event, ctx);
4493 mutex_unlock(¤t->perf_event_mutex);
4498 int perf_event_task_disable(void)
4500 struct perf_event_context *ctx;
4501 struct perf_event *event;
4503 mutex_lock(¤t->perf_event_mutex);
4504 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4505 ctx = perf_event_ctx_lock(event);
4506 perf_event_for_each_child(event, _perf_event_disable);
4507 perf_event_ctx_unlock(event, ctx);
4509 mutex_unlock(¤t->perf_event_mutex);
4514 static int perf_event_index(struct perf_event *event)
4516 if (event->hw.state & PERF_HES_STOPPED)
4519 if (event->state != PERF_EVENT_STATE_ACTIVE)
4522 return event->pmu->event_idx(event);
4525 static void calc_timer_values(struct perf_event *event,
4532 *now = perf_clock();
4533 ctx_time = event->shadow_ctx_time + *now;
4534 *enabled = ctx_time - event->tstamp_enabled;
4535 *running = ctx_time - event->tstamp_running;
4538 static void perf_event_init_userpage(struct perf_event *event)
4540 struct perf_event_mmap_page *userpg;
4541 struct ring_buffer *rb;
4544 rb = rcu_dereference(event->rb);
4548 userpg = rb->user_page;
4550 /* Allow new userspace to detect that bit 0 is deprecated */
4551 userpg->cap_bit0_is_deprecated = 1;
4552 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
4553 userpg->data_offset = PAGE_SIZE;
4554 userpg->data_size = perf_data_size(rb);
4560 void __weak arch_perf_update_userpage(
4561 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
4566 * Callers need to ensure there can be no nesting of this function, otherwise
4567 * the seqlock logic goes bad. We can not serialize this because the arch
4568 * code calls this from NMI context.
4570 void perf_event_update_userpage(struct perf_event *event)
4572 struct perf_event_mmap_page *userpg;
4573 struct ring_buffer *rb;
4574 u64 enabled, running, now;
4577 rb = rcu_dereference(event->rb);
4582 * compute total_time_enabled, total_time_running
4583 * based on snapshot values taken when the event
4584 * was last scheduled in.
4586 * we cannot simply called update_context_time()
4587 * because of locking issue as we can be called in
4590 calc_timer_values(event, &now, &enabled, &running);
4592 userpg = rb->user_page;
4594 * Disable preemption so as to not let the corresponding user-space
4595 * spin too long if we get preempted.
4600 userpg->index = perf_event_index(event);
4601 userpg->offset = perf_event_count(event);
4603 userpg->offset -= local64_read(&event->hw.prev_count);
4605 userpg->time_enabled = enabled +
4606 atomic64_read(&event->child_total_time_enabled);
4608 userpg->time_running = running +
4609 atomic64_read(&event->child_total_time_running);
4611 arch_perf_update_userpage(event, userpg, now);
4620 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
4622 struct perf_event *event = vma->vm_file->private_data;
4623 struct ring_buffer *rb;
4624 int ret = VM_FAULT_SIGBUS;
4626 if (vmf->flags & FAULT_FLAG_MKWRITE) {
4627 if (vmf->pgoff == 0)
4633 rb = rcu_dereference(event->rb);
4637 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
4640 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
4644 get_page(vmf->page);
4645 vmf->page->mapping = vma->vm_file->f_mapping;
4646 vmf->page->index = vmf->pgoff;
4655 static void ring_buffer_attach(struct perf_event *event,
4656 struct ring_buffer *rb)
4658 struct ring_buffer *old_rb = NULL;
4659 unsigned long flags;
4663 * Should be impossible, we set this when removing
4664 * event->rb_entry and wait/clear when adding event->rb_entry.
4666 WARN_ON_ONCE(event->rcu_pending);
4669 spin_lock_irqsave(&old_rb->event_lock, flags);
4670 list_del_rcu(&event->rb_entry);
4671 spin_unlock_irqrestore(&old_rb->event_lock, flags);
4673 event->rcu_batches = get_state_synchronize_rcu();
4674 event->rcu_pending = 1;
4678 if (event->rcu_pending) {
4679 cond_synchronize_rcu(event->rcu_batches);
4680 event->rcu_pending = 0;
4683 spin_lock_irqsave(&rb->event_lock, flags);
4684 list_add_rcu(&event->rb_entry, &rb->event_list);
4685 spin_unlock_irqrestore(&rb->event_lock, flags);
4688 rcu_assign_pointer(event->rb, rb);
4691 ring_buffer_put(old_rb);
4693 * Since we detached before setting the new rb, so that we
4694 * could attach the new rb, we could have missed a wakeup.
4697 wake_up_all(&event->waitq);
4701 static void ring_buffer_wakeup(struct perf_event *event)
4703 struct ring_buffer *rb;
4706 rb = rcu_dereference(event->rb);
4708 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
4709 wake_up_all(&event->waitq);
4714 struct ring_buffer *ring_buffer_get(struct perf_event *event)
4716 struct ring_buffer *rb;
4719 rb = rcu_dereference(event->rb);
4721 if (!atomic_inc_not_zero(&rb->refcount))
4729 void ring_buffer_put(struct ring_buffer *rb)
4731 if (!atomic_dec_and_test(&rb->refcount))
4734 WARN_ON_ONCE(!list_empty(&rb->event_list));
4736 call_rcu(&rb->rcu_head, rb_free_rcu);
4739 static void perf_mmap_open(struct vm_area_struct *vma)
4741 struct perf_event *event = vma->vm_file->private_data;
4743 atomic_inc(&event->mmap_count);
4744 atomic_inc(&event->rb->mmap_count);
4747 atomic_inc(&event->rb->aux_mmap_count);
4749 if (event->pmu->event_mapped)
4750 event->pmu->event_mapped(event);
4753 static void perf_pmu_output_stop(struct perf_event *event);
4756 * A buffer can be mmap()ed multiple times; either directly through the same
4757 * event, or through other events by use of perf_event_set_output().
4759 * In order to undo the VM accounting done by perf_mmap() we need to destroy
4760 * the buffer here, where we still have a VM context. This means we need
4761 * to detach all events redirecting to us.
4763 static void perf_mmap_close(struct vm_area_struct *vma)
4765 struct perf_event *event = vma->vm_file->private_data;
4767 struct ring_buffer *rb = ring_buffer_get(event);
4768 struct user_struct *mmap_user = rb->mmap_user;
4769 int mmap_locked = rb->mmap_locked;
4770 unsigned long size = perf_data_size(rb);
4772 if (event->pmu->event_unmapped)
4773 event->pmu->event_unmapped(event);
4776 * rb->aux_mmap_count will always drop before rb->mmap_count and
4777 * event->mmap_count, so it is ok to use event->mmap_mutex to
4778 * serialize with perf_mmap here.
4780 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
4781 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
4783 * Stop all AUX events that are writing to this buffer,
4784 * so that we can free its AUX pages and corresponding PMU
4785 * data. Note that after rb::aux_mmap_count dropped to zero,
4786 * they won't start any more (see perf_aux_output_begin()).
4788 perf_pmu_output_stop(event);
4790 /* now it's safe to free the pages */
4791 atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
4792 vma->vm_mm->pinned_vm -= rb->aux_mmap_locked;
4794 /* this has to be the last one */
4796 WARN_ON_ONCE(atomic_read(&rb->aux_refcount));
4798 mutex_unlock(&event->mmap_mutex);
4801 atomic_dec(&rb->mmap_count);
4803 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
4806 ring_buffer_attach(event, NULL);
4807 mutex_unlock(&event->mmap_mutex);
4809 /* If there's still other mmap()s of this buffer, we're done. */
4810 if (atomic_read(&rb->mmap_count))
4814 * No other mmap()s, detach from all other events that might redirect
4815 * into the now unreachable buffer. Somewhat complicated by the
4816 * fact that rb::event_lock otherwise nests inside mmap_mutex.
4820 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4821 if (!atomic_long_inc_not_zero(&event->refcount)) {
4823 * This event is en-route to free_event() which will
4824 * detach it and remove it from the list.
4830 mutex_lock(&event->mmap_mutex);
4832 * Check we didn't race with perf_event_set_output() which can
4833 * swizzle the rb from under us while we were waiting to
4834 * acquire mmap_mutex.
4836 * If we find a different rb; ignore this event, a next
4837 * iteration will no longer find it on the list. We have to
4838 * still restart the iteration to make sure we're not now
4839 * iterating the wrong list.
4841 if (event->rb == rb)
4842 ring_buffer_attach(event, NULL);
4844 mutex_unlock(&event->mmap_mutex);
4848 * Restart the iteration; either we're on the wrong list or
4849 * destroyed its integrity by doing a deletion.
4856 * It could be there's still a few 0-ref events on the list; they'll
4857 * get cleaned up by free_event() -- they'll also still have their
4858 * ref on the rb and will free it whenever they are done with it.
4860 * Aside from that, this buffer is 'fully' detached and unmapped,
4861 * undo the VM accounting.
4864 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4865 vma->vm_mm->pinned_vm -= mmap_locked;
4866 free_uid(mmap_user);
4869 ring_buffer_put(rb); /* could be last */
4872 static const struct vm_operations_struct perf_mmap_vmops = {
4873 .open = perf_mmap_open,
4874 .close = perf_mmap_close, /* non mergable */
4875 .fault = perf_mmap_fault,
4876 .page_mkwrite = perf_mmap_fault,
4879 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
4881 struct perf_event *event = file->private_data;
4882 unsigned long user_locked, user_lock_limit;
4883 struct user_struct *user = current_user();
4884 unsigned long locked, lock_limit;
4885 struct ring_buffer *rb = NULL;
4886 unsigned long vma_size;
4887 unsigned long nr_pages;
4888 long user_extra = 0, extra = 0;
4889 int ret = 0, flags = 0;
4892 * Don't allow mmap() of inherited per-task counters. This would
4893 * create a performance issue due to all children writing to the
4896 if (event->cpu == -1 && event->attr.inherit)
4899 if (!(vma->vm_flags & VM_SHARED))
4902 vma_size = vma->vm_end - vma->vm_start;
4904 if (vma->vm_pgoff == 0) {
4905 nr_pages = (vma_size / PAGE_SIZE) - 1;
4908 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
4909 * mapped, all subsequent mappings should have the same size
4910 * and offset. Must be above the normal perf buffer.
4912 u64 aux_offset, aux_size;
4917 nr_pages = vma_size / PAGE_SIZE;
4919 mutex_lock(&event->mmap_mutex);
4926 aux_offset = ACCESS_ONCE(rb->user_page->aux_offset);
4927 aux_size = ACCESS_ONCE(rb->user_page->aux_size);
4929 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
4932 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
4935 /* already mapped with a different offset */
4936 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
4939 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
4942 /* already mapped with a different size */
4943 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
4946 if (!is_power_of_2(nr_pages))
4949 if (!atomic_inc_not_zero(&rb->mmap_count))
4952 if (rb_has_aux(rb)) {
4953 atomic_inc(&rb->aux_mmap_count);
4958 atomic_set(&rb->aux_mmap_count, 1);
4959 user_extra = nr_pages;
4965 * If we have rb pages ensure they're a power-of-two number, so we
4966 * can do bitmasks instead of modulo.
4968 if (nr_pages != 0 && !is_power_of_2(nr_pages))
4971 if (vma_size != PAGE_SIZE * (1 + nr_pages))
4974 WARN_ON_ONCE(event->ctx->parent_ctx);
4976 mutex_lock(&event->mmap_mutex);
4978 if (event->rb->nr_pages != nr_pages) {
4983 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4985 * Raced against perf_mmap_close() through
4986 * perf_event_set_output(). Try again, hope for better
4989 mutex_unlock(&event->mmap_mutex);
4996 user_extra = nr_pages + 1;
4999 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
5002 * Increase the limit linearly with more CPUs:
5004 user_lock_limit *= num_online_cpus();
5006 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
5008 if (user_locked > user_lock_limit)
5009 extra = user_locked - user_lock_limit;
5011 lock_limit = rlimit(RLIMIT_MEMLOCK);
5012 lock_limit >>= PAGE_SHIFT;
5013 locked = vma->vm_mm->pinned_vm + extra;
5015 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
5016 !capable(CAP_IPC_LOCK)) {
5021 WARN_ON(!rb && event->rb);
5023 if (vma->vm_flags & VM_WRITE)
5024 flags |= RING_BUFFER_WRITABLE;
5027 rb = rb_alloc(nr_pages,
5028 event->attr.watermark ? event->attr.wakeup_watermark : 0,
5036 atomic_set(&rb->mmap_count, 1);
5037 rb->mmap_user = get_current_user();
5038 rb->mmap_locked = extra;
5040 ring_buffer_attach(event, rb);
5042 perf_event_init_userpage(event);
5043 perf_event_update_userpage(event);
5045 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
5046 event->attr.aux_watermark, flags);
5048 rb->aux_mmap_locked = extra;
5053 atomic_long_add(user_extra, &user->locked_vm);
5054 vma->vm_mm->pinned_vm += extra;
5056 atomic_inc(&event->mmap_count);
5058 atomic_dec(&rb->mmap_count);
5061 mutex_unlock(&event->mmap_mutex);
5064 * Since pinned accounting is per vm we cannot allow fork() to copy our
5067 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
5068 vma->vm_ops = &perf_mmap_vmops;
5070 if (event->pmu->event_mapped)
5071 event->pmu->event_mapped(event);
5076 static int perf_fasync(int fd, struct file *filp, int on)
5078 struct inode *inode = file_inode(filp);
5079 struct perf_event *event = filp->private_data;
5082 mutex_lock(&inode->i_mutex);
5083 retval = fasync_helper(fd, filp, on, &event->fasync);
5084 mutex_unlock(&inode->i_mutex);
5092 static const struct file_operations perf_fops = {
5093 .llseek = no_llseek,
5094 .release = perf_release,
5097 .unlocked_ioctl = perf_ioctl,
5098 .compat_ioctl = perf_compat_ioctl,
5100 .fasync = perf_fasync,
5106 * If there's data, ensure we set the poll() state and publish everything
5107 * to user-space before waking everybody up.
5110 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
5112 /* only the parent has fasync state */
5114 event = event->parent;
5115 return &event->fasync;
5118 void perf_event_wakeup(struct perf_event *event)
5120 ring_buffer_wakeup(event);
5122 if (event->pending_kill) {
5123 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
5124 event->pending_kill = 0;
5128 static void perf_pending_event(struct irq_work *entry)
5130 struct perf_event *event = container_of(entry,
5131 struct perf_event, pending);
5134 rctx = perf_swevent_get_recursion_context();
5136 * If we 'fail' here, that's OK, it means recursion is already disabled
5137 * and we won't recurse 'further'.
5140 if (event->pending_disable) {
5141 event->pending_disable = 0;
5142 __perf_event_disable(event);
5145 if (event->pending_wakeup) {
5146 event->pending_wakeup = 0;
5147 perf_event_wakeup(event);
5151 perf_swevent_put_recursion_context(rctx);
5155 * We assume there is only KVM supporting the callbacks.
5156 * Later on, we might change it to a list if there is
5157 * another virtualization implementation supporting the callbacks.
5159 struct perf_guest_info_callbacks *perf_guest_cbs;
5161 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5163 perf_guest_cbs = cbs;
5166 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
5168 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5170 perf_guest_cbs = NULL;
5173 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
5176 perf_output_sample_regs(struct perf_output_handle *handle,
5177 struct pt_regs *regs, u64 mask)
5181 for_each_set_bit(bit, (const unsigned long *) &mask,
5182 sizeof(mask) * BITS_PER_BYTE) {
5185 val = perf_reg_value(regs, bit);
5186 perf_output_put(handle, val);
5190 static void perf_sample_regs_user(struct perf_regs *regs_user,
5191 struct pt_regs *regs,
5192 struct pt_regs *regs_user_copy)
5194 if (user_mode(regs)) {
5195 regs_user->abi = perf_reg_abi(current);
5196 regs_user->regs = regs;
5197 } else if (!(current->flags & PF_KTHREAD)) {
5198 perf_get_regs_user(regs_user, regs, regs_user_copy);
5200 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
5201 regs_user->regs = NULL;
5205 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
5206 struct pt_regs *regs)
5208 regs_intr->regs = regs;
5209 regs_intr->abi = perf_reg_abi(current);
5214 * Get remaining task size from user stack pointer.
5216 * It'd be better to take stack vma map and limit this more
5217 * precisly, but there's no way to get it safely under interrupt,
5218 * so using TASK_SIZE as limit.
5220 static u64 perf_ustack_task_size(struct pt_regs *regs)
5222 unsigned long addr = perf_user_stack_pointer(regs);
5224 if (!addr || addr >= TASK_SIZE)
5227 return TASK_SIZE - addr;
5231 perf_sample_ustack_size(u16 stack_size, u16 header_size,
5232 struct pt_regs *regs)
5236 /* No regs, no stack pointer, no dump. */
5241 * Check if we fit in with the requested stack size into the:
5243 * If we don't, we limit the size to the TASK_SIZE.
5245 * - remaining sample size
5246 * If we don't, we customize the stack size to
5247 * fit in to the remaining sample size.
5250 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
5251 stack_size = min(stack_size, (u16) task_size);
5253 /* Current header size plus static size and dynamic size. */
5254 header_size += 2 * sizeof(u64);
5256 /* Do we fit in with the current stack dump size? */
5257 if ((u16) (header_size + stack_size) < header_size) {
5259 * If we overflow the maximum size for the sample,
5260 * we customize the stack dump size to fit in.
5262 stack_size = USHRT_MAX - header_size - sizeof(u64);
5263 stack_size = round_up(stack_size, sizeof(u64));
5270 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
5271 struct pt_regs *regs)
5273 /* Case of a kernel thread, nothing to dump */
5276 perf_output_put(handle, size);
5285 * - the size requested by user or the best one we can fit
5286 * in to the sample max size
5288 * - user stack dump data
5290 * - the actual dumped size
5294 perf_output_put(handle, dump_size);
5297 sp = perf_user_stack_pointer(regs);
5298 rem = __output_copy_user(handle, (void *) sp, dump_size);
5299 dyn_size = dump_size - rem;
5301 perf_output_skip(handle, rem);
5304 perf_output_put(handle, dyn_size);
5308 static void __perf_event_header__init_id(struct perf_event_header *header,
5309 struct perf_sample_data *data,
5310 struct perf_event *event)
5312 u64 sample_type = event->attr.sample_type;
5314 data->type = sample_type;
5315 header->size += event->id_header_size;
5317 if (sample_type & PERF_SAMPLE_TID) {
5318 /* namespace issues */
5319 data->tid_entry.pid = perf_event_pid(event, current);
5320 data->tid_entry.tid = perf_event_tid(event, current);
5323 if (sample_type & PERF_SAMPLE_TIME)
5324 data->time = perf_event_clock(event);
5326 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
5327 data->id = primary_event_id(event);
5329 if (sample_type & PERF_SAMPLE_STREAM_ID)
5330 data->stream_id = event->id;
5332 if (sample_type & PERF_SAMPLE_CPU) {
5333 data->cpu_entry.cpu = raw_smp_processor_id();
5334 data->cpu_entry.reserved = 0;
5338 void perf_event_header__init_id(struct perf_event_header *header,
5339 struct perf_sample_data *data,
5340 struct perf_event *event)
5342 if (event->attr.sample_id_all)
5343 __perf_event_header__init_id(header, data, event);
5346 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
5347 struct perf_sample_data *data)
5349 u64 sample_type = data->type;
5351 if (sample_type & PERF_SAMPLE_TID)
5352 perf_output_put(handle, data->tid_entry);
5354 if (sample_type & PERF_SAMPLE_TIME)
5355 perf_output_put(handle, data->time);
5357 if (sample_type & PERF_SAMPLE_ID)
5358 perf_output_put(handle, data->id);
5360 if (sample_type & PERF_SAMPLE_STREAM_ID)
5361 perf_output_put(handle, data->stream_id);
5363 if (sample_type & PERF_SAMPLE_CPU)
5364 perf_output_put(handle, data->cpu_entry);
5366 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5367 perf_output_put(handle, data->id);
5370 void perf_event__output_id_sample(struct perf_event *event,
5371 struct perf_output_handle *handle,
5372 struct perf_sample_data *sample)
5374 if (event->attr.sample_id_all)
5375 __perf_event__output_id_sample(handle, sample);
5378 static void perf_output_read_one(struct perf_output_handle *handle,
5379 struct perf_event *event,
5380 u64 enabled, u64 running)
5382 u64 read_format = event->attr.read_format;
5386 values[n++] = perf_event_count(event);
5387 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5388 values[n++] = enabled +
5389 atomic64_read(&event->child_total_time_enabled);
5391 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5392 values[n++] = running +
5393 atomic64_read(&event->child_total_time_running);
5395 if (read_format & PERF_FORMAT_ID)
5396 values[n++] = primary_event_id(event);
5398 __output_copy(handle, values, n * sizeof(u64));
5401 static void perf_output_read_group(struct perf_output_handle *handle,
5402 struct perf_event *event,
5403 u64 enabled, u64 running)
5405 struct perf_event *leader = event->group_leader, *sub;
5406 u64 read_format = event->attr.read_format;
5410 values[n++] = 1 + leader->nr_siblings;
5412 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5413 values[n++] = enabled;
5415 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5416 values[n++] = running;
5418 if ((leader != event) &&
5419 (leader->state == PERF_EVENT_STATE_ACTIVE))
5420 leader->pmu->read(leader);
5422 values[n++] = perf_event_count(leader);
5423 if (read_format & PERF_FORMAT_ID)
5424 values[n++] = primary_event_id(leader);
5426 __output_copy(handle, values, n * sizeof(u64));
5428 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
5431 if ((sub != event) &&
5432 (sub->state == PERF_EVENT_STATE_ACTIVE))
5433 sub->pmu->read(sub);
5435 values[n++] = perf_event_count(sub);
5436 if (read_format & PERF_FORMAT_ID)
5437 values[n++] = primary_event_id(sub);
5439 __output_copy(handle, values, n * sizeof(u64));
5443 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
5444 PERF_FORMAT_TOTAL_TIME_RUNNING)
5447 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
5449 * The problem is that its both hard and excessively expensive to iterate the
5450 * child list, not to mention that its impossible to IPI the children running
5451 * on another CPU, from interrupt/NMI context.
5453 static void perf_output_read(struct perf_output_handle *handle,
5454 struct perf_event *event)
5456 u64 enabled = 0, running = 0, now;
5457 u64 read_format = event->attr.read_format;
5460 * compute total_time_enabled, total_time_running
5461 * based on snapshot values taken when the event
5462 * was last scheduled in.
5464 * we cannot simply called update_context_time()
5465 * because of locking issue as we are called in
5468 if (read_format & PERF_FORMAT_TOTAL_TIMES)
5469 calc_timer_values(event, &now, &enabled, &running);
5471 if (event->attr.read_format & PERF_FORMAT_GROUP)
5472 perf_output_read_group(handle, event, enabled, running);
5474 perf_output_read_one(handle, event, enabled, running);
5477 void perf_output_sample(struct perf_output_handle *handle,
5478 struct perf_event_header *header,
5479 struct perf_sample_data *data,
5480 struct perf_event *event)
5482 u64 sample_type = data->type;
5484 perf_output_put(handle, *header);
5486 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5487 perf_output_put(handle, data->id);
5489 if (sample_type & PERF_SAMPLE_IP)
5490 perf_output_put(handle, data->ip);
5492 if (sample_type & PERF_SAMPLE_TID)
5493 perf_output_put(handle, data->tid_entry);
5495 if (sample_type & PERF_SAMPLE_TIME)
5496 perf_output_put(handle, data->time);
5498 if (sample_type & PERF_SAMPLE_ADDR)
5499 perf_output_put(handle, data->addr);
5501 if (sample_type & PERF_SAMPLE_ID)
5502 perf_output_put(handle, data->id);
5504 if (sample_type & PERF_SAMPLE_STREAM_ID)
5505 perf_output_put(handle, data->stream_id);
5507 if (sample_type & PERF_SAMPLE_CPU)
5508 perf_output_put(handle, data->cpu_entry);
5510 if (sample_type & PERF_SAMPLE_PERIOD)
5511 perf_output_put(handle, data->period);
5513 if (sample_type & PERF_SAMPLE_READ)
5514 perf_output_read(handle, event);
5516 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5517 if (data->callchain) {
5520 if (data->callchain)
5521 size += data->callchain->nr;
5523 size *= sizeof(u64);
5525 __output_copy(handle, data->callchain, size);
5528 perf_output_put(handle, nr);
5532 if (sample_type & PERF_SAMPLE_RAW) {
5534 u32 raw_size = data->raw->size;
5535 u32 real_size = round_up(raw_size + sizeof(u32),
5536 sizeof(u64)) - sizeof(u32);
5539 perf_output_put(handle, real_size);
5540 __output_copy(handle, data->raw->data, raw_size);
5541 if (real_size - raw_size)
5542 __output_copy(handle, &zero, real_size - raw_size);
5548 .size = sizeof(u32),
5551 perf_output_put(handle, raw);
5555 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5556 if (data->br_stack) {
5559 size = data->br_stack->nr
5560 * sizeof(struct perf_branch_entry);
5562 perf_output_put(handle, data->br_stack->nr);
5563 perf_output_copy(handle, data->br_stack->entries, size);
5566 * we always store at least the value of nr
5569 perf_output_put(handle, nr);
5573 if (sample_type & PERF_SAMPLE_REGS_USER) {
5574 u64 abi = data->regs_user.abi;
5577 * If there are no regs to dump, notice it through
5578 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5580 perf_output_put(handle, abi);
5583 u64 mask = event->attr.sample_regs_user;
5584 perf_output_sample_regs(handle,
5585 data->regs_user.regs,
5590 if (sample_type & PERF_SAMPLE_STACK_USER) {
5591 perf_output_sample_ustack(handle,
5592 data->stack_user_size,
5593 data->regs_user.regs);
5596 if (sample_type & PERF_SAMPLE_WEIGHT)
5597 perf_output_put(handle, data->weight);
5599 if (sample_type & PERF_SAMPLE_DATA_SRC)
5600 perf_output_put(handle, data->data_src.val);
5602 if (sample_type & PERF_SAMPLE_TRANSACTION)
5603 perf_output_put(handle, data->txn);
5605 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5606 u64 abi = data->regs_intr.abi;
5608 * If there are no regs to dump, notice it through
5609 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5611 perf_output_put(handle, abi);
5614 u64 mask = event->attr.sample_regs_intr;
5616 perf_output_sample_regs(handle,
5617 data->regs_intr.regs,
5622 if (!event->attr.watermark) {
5623 int wakeup_events = event->attr.wakeup_events;
5625 if (wakeup_events) {
5626 struct ring_buffer *rb = handle->rb;
5627 int events = local_inc_return(&rb->events);
5629 if (events >= wakeup_events) {
5630 local_sub(wakeup_events, &rb->events);
5631 local_inc(&rb->wakeup);
5637 void perf_prepare_sample(struct perf_event_header *header,
5638 struct perf_sample_data *data,
5639 struct perf_event *event,
5640 struct pt_regs *regs)
5642 u64 sample_type = event->attr.sample_type;
5644 header->type = PERF_RECORD_SAMPLE;
5645 header->size = sizeof(*header) + event->header_size;
5648 header->misc |= perf_misc_flags(regs);
5650 __perf_event_header__init_id(header, data, event);
5652 if (sample_type & PERF_SAMPLE_IP)
5653 data->ip = perf_instruction_pointer(regs);
5655 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5658 data->callchain = perf_callchain(event, regs);
5660 if (data->callchain)
5661 size += data->callchain->nr;
5663 header->size += size * sizeof(u64);
5666 if (sample_type & PERF_SAMPLE_RAW) {
5667 int size = sizeof(u32);
5670 size += data->raw->size;
5672 size += sizeof(u32);
5674 header->size += round_up(size, sizeof(u64));
5677 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5678 int size = sizeof(u64); /* nr */
5679 if (data->br_stack) {
5680 size += data->br_stack->nr
5681 * sizeof(struct perf_branch_entry);
5683 header->size += size;
5686 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
5687 perf_sample_regs_user(&data->regs_user, regs,
5688 &data->regs_user_copy);
5690 if (sample_type & PERF_SAMPLE_REGS_USER) {
5691 /* regs dump ABI info */
5692 int size = sizeof(u64);
5694 if (data->regs_user.regs) {
5695 u64 mask = event->attr.sample_regs_user;
5696 size += hweight64(mask) * sizeof(u64);
5699 header->size += size;
5702 if (sample_type & PERF_SAMPLE_STACK_USER) {
5704 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
5705 * processed as the last one or have additional check added
5706 * in case new sample type is added, because we could eat
5707 * up the rest of the sample size.
5709 u16 stack_size = event->attr.sample_stack_user;
5710 u16 size = sizeof(u64);
5712 stack_size = perf_sample_ustack_size(stack_size, header->size,
5713 data->regs_user.regs);
5716 * If there is something to dump, add space for the dump
5717 * itself and for the field that tells the dynamic size,
5718 * which is how many have been actually dumped.
5721 size += sizeof(u64) + stack_size;
5723 data->stack_user_size = stack_size;
5724 header->size += size;
5727 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5728 /* regs dump ABI info */
5729 int size = sizeof(u64);
5731 perf_sample_regs_intr(&data->regs_intr, regs);
5733 if (data->regs_intr.regs) {
5734 u64 mask = event->attr.sample_regs_intr;
5736 size += hweight64(mask) * sizeof(u64);
5739 header->size += size;
5743 void perf_event_output(struct perf_event *event,
5744 struct perf_sample_data *data,
5745 struct pt_regs *regs)
5747 struct perf_output_handle handle;
5748 struct perf_event_header header;
5750 /* protect the callchain buffers */
5753 perf_prepare_sample(&header, data, event, regs);
5755 if (perf_output_begin(&handle, event, header.size))
5758 perf_output_sample(&handle, &header, data, event);
5760 perf_output_end(&handle);
5770 struct perf_read_event {
5771 struct perf_event_header header;
5778 perf_event_read_event(struct perf_event *event,
5779 struct task_struct *task)
5781 struct perf_output_handle handle;
5782 struct perf_sample_data sample;
5783 struct perf_read_event read_event = {
5785 .type = PERF_RECORD_READ,
5787 .size = sizeof(read_event) + event->read_size,
5789 .pid = perf_event_pid(event, task),
5790 .tid = perf_event_tid(event, task),
5794 perf_event_header__init_id(&read_event.header, &sample, event);
5795 ret = perf_output_begin(&handle, event, read_event.header.size);
5799 perf_output_put(&handle, read_event);
5800 perf_output_read(&handle, event);
5801 perf_event__output_id_sample(event, &handle, &sample);
5803 perf_output_end(&handle);
5806 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
5809 perf_event_aux_ctx(struct perf_event_context *ctx,
5810 perf_event_aux_output_cb output,
5813 struct perf_event *event;
5815 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5816 if (event->state < PERF_EVENT_STATE_INACTIVE)
5818 if (!event_filter_match(event))
5820 output(event, data);
5825 perf_event_aux_task_ctx(perf_event_aux_output_cb output, void *data,
5826 struct perf_event_context *task_ctx)
5830 perf_event_aux_ctx(task_ctx, output, data);
5836 perf_event_aux(perf_event_aux_output_cb output, void *data,
5837 struct perf_event_context *task_ctx)
5839 struct perf_cpu_context *cpuctx;
5840 struct perf_event_context *ctx;
5845 * If we have task_ctx != NULL we only notify
5846 * the task context itself. The task_ctx is set
5847 * only for EXIT events before releasing task
5851 perf_event_aux_task_ctx(output, data, task_ctx);
5856 list_for_each_entry_rcu(pmu, &pmus, entry) {
5857 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
5858 if (cpuctx->unique_pmu != pmu)
5860 perf_event_aux_ctx(&cpuctx->ctx, output, data);
5861 ctxn = pmu->task_ctx_nr;
5864 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
5866 perf_event_aux_ctx(ctx, output, data);
5868 put_cpu_ptr(pmu->pmu_cpu_context);
5873 struct remote_output {
5874 struct ring_buffer *rb;
5878 static void __perf_event_output_stop(struct perf_event *event, void *data)
5880 struct perf_event *parent = event->parent;
5881 struct remote_output *ro = data;
5882 struct ring_buffer *rb = ro->rb;
5884 if (!has_aux(event))
5891 * In case of inheritance, it will be the parent that links to the
5892 * ring-buffer, but it will be the child that's actually using it:
5894 if (rcu_dereference(parent->rb) == rb)
5895 ro->err = __perf_event_stop(event);
5898 static int __perf_pmu_output_stop(void *info)
5900 struct perf_event *event = info;
5901 struct pmu *pmu = event->pmu;
5902 struct perf_cpu_context *cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
5903 struct remote_output ro = {
5908 perf_event_aux_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro);
5909 if (cpuctx->task_ctx)
5910 perf_event_aux_ctx(cpuctx->task_ctx, __perf_event_output_stop,
5917 static void perf_pmu_output_stop(struct perf_event *event)
5919 struct perf_event *iter;
5924 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
5926 * For per-CPU events, we need to make sure that neither they
5927 * nor their children are running; for cpu==-1 events it's
5928 * sufficient to stop the event itself if it's active, since
5929 * it can't have children.
5933 cpu = READ_ONCE(iter->oncpu);
5938 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
5939 if (err == -EAGAIN) {
5948 * task tracking -- fork/exit
5950 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
5953 struct perf_task_event {
5954 struct task_struct *task;
5955 struct perf_event_context *task_ctx;
5958 struct perf_event_header header;
5968 static int perf_event_task_match(struct perf_event *event)
5970 return event->attr.comm || event->attr.mmap ||
5971 event->attr.mmap2 || event->attr.mmap_data ||
5975 static void perf_event_task_output(struct perf_event *event,
5978 struct perf_task_event *task_event = data;
5979 struct perf_output_handle handle;
5980 struct perf_sample_data sample;
5981 struct task_struct *task = task_event->task;
5982 int ret, size = task_event->event_id.header.size;
5984 if (!perf_event_task_match(event))
5987 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
5989 ret = perf_output_begin(&handle, event,
5990 task_event->event_id.header.size);
5994 task_event->event_id.pid = perf_event_pid(event, task);
5995 task_event->event_id.ppid = perf_event_pid(event, current);
5997 task_event->event_id.tid = perf_event_tid(event, task);
5998 task_event->event_id.ptid = perf_event_tid(event, current);
6000 task_event->event_id.time = perf_event_clock(event);
6002 perf_output_put(&handle, task_event->event_id);
6004 perf_event__output_id_sample(event, &handle, &sample);
6006 perf_output_end(&handle);
6008 task_event->event_id.header.size = size;
6011 static void perf_event_task(struct task_struct *task,
6012 struct perf_event_context *task_ctx,
6015 struct perf_task_event task_event;
6017 if (!atomic_read(&nr_comm_events) &&
6018 !atomic_read(&nr_mmap_events) &&
6019 !atomic_read(&nr_task_events))
6022 task_event = (struct perf_task_event){
6024 .task_ctx = task_ctx,
6027 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
6029 .size = sizeof(task_event.event_id),
6039 perf_event_aux(perf_event_task_output,
6044 void perf_event_fork(struct task_struct *task)
6046 perf_event_task(task, NULL, 1);
6053 struct perf_comm_event {
6054 struct task_struct *task;
6059 struct perf_event_header header;
6066 static int perf_event_comm_match(struct perf_event *event)
6068 return event->attr.comm;
6071 static void perf_event_comm_output(struct perf_event *event,
6074 struct perf_comm_event *comm_event = data;
6075 struct perf_output_handle handle;
6076 struct perf_sample_data sample;
6077 int size = comm_event->event_id.header.size;
6080 if (!perf_event_comm_match(event))
6083 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
6084 ret = perf_output_begin(&handle, event,
6085 comm_event->event_id.header.size);
6090 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
6091 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
6093 perf_output_put(&handle, comm_event->event_id);
6094 __output_copy(&handle, comm_event->comm,
6095 comm_event->comm_size);
6097 perf_event__output_id_sample(event, &handle, &sample);
6099 perf_output_end(&handle);
6101 comm_event->event_id.header.size = size;
6104 static void perf_event_comm_event(struct perf_comm_event *comm_event)
6106 char comm[TASK_COMM_LEN];
6109 memset(comm, 0, sizeof(comm));
6110 strlcpy(comm, comm_event->task->comm, sizeof(comm));
6111 size = ALIGN(strlen(comm)+1, sizeof(u64));
6113 comm_event->comm = comm;
6114 comm_event->comm_size = size;
6116 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
6118 perf_event_aux(perf_event_comm_output,
6123 void perf_event_comm(struct task_struct *task, bool exec)
6125 struct perf_comm_event comm_event;
6127 if (!atomic_read(&nr_comm_events))
6130 comm_event = (struct perf_comm_event){
6136 .type = PERF_RECORD_COMM,
6137 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
6145 perf_event_comm_event(&comm_event);
6152 struct perf_mmap_event {
6153 struct vm_area_struct *vma;
6155 const char *file_name;
6163 struct perf_event_header header;
6173 static int perf_event_mmap_match(struct perf_event *event,
6176 struct perf_mmap_event *mmap_event = data;
6177 struct vm_area_struct *vma = mmap_event->vma;
6178 int executable = vma->vm_flags & VM_EXEC;
6180 return (!executable && event->attr.mmap_data) ||
6181 (executable && (event->attr.mmap || event->attr.mmap2));
6184 static void perf_event_mmap_output(struct perf_event *event,
6187 struct perf_mmap_event *mmap_event = data;
6188 struct perf_output_handle handle;
6189 struct perf_sample_data sample;
6190 int size = mmap_event->event_id.header.size;
6191 u32 type = mmap_event->event_id.header.type;
6194 if (!perf_event_mmap_match(event, data))
6197 if (event->attr.mmap2) {
6198 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
6199 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
6200 mmap_event->event_id.header.size += sizeof(mmap_event->min);
6201 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
6202 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
6203 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
6204 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
6207 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
6208 ret = perf_output_begin(&handle, event,
6209 mmap_event->event_id.header.size);
6213 mmap_event->event_id.pid = perf_event_pid(event, current);
6214 mmap_event->event_id.tid = perf_event_tid(event, current);
6216 perf_output_put(&handle, mmap_event->event_id);
6218 if (event->attr.mmap2) {
6219 perf_output_put(&handle, mmap_event->maj);
6220 perf_output_put(&handle, mmap_event->min);
6221 perf_output_put(&handle, mmap_event->ino);
6222 perf_output_put(&handle, mmap_event->ino_generation);
6223 perf_output_put(&handle, mmap_event->prot);
6224 perf_output_put(&handle, mmap_event->flags);
6227 __output_copy(&handle, mmap_event->file_name,
6228 mmap_event->file_size);
6230 perf_event__output_id_sample(event, &handle, &sample);
6232 perf_output_end(&handle);
6234 mmap_event->event_id.header.size = size;
6235 mmap_event->event_id.header.type = type;
6238 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
6240 struct vm_area_struct *vma = mmap_event->vma;
6241 struct file *file = vma->vm_file;
6242 int maj = 0, min = 0;
6243 u64 ino = 0, gen = 0;
6244 u32 prot = 0, flags = 0;
6250 if (vma->vm_flags & VM_READ)
6252 if (vma->vm_flags & VM_WRITE)
6254 if (vma->vm_flags & VM_EXEC)
6257 if (vma->vm_flags & VM_MAYSHARE)
6260 flags = MAP_PRIVATE;
6262 if (vma->vm_flags & VM_DENYWRITE)
6263 flags |= MAP_DENYWRITE;
6264 if (vma->vm_flags & VM_MAYEXEC)
6265 flags |= MAP_EXECUTABLE;
6266 if (vma->vm_flags & VM_LOCKED)
6267 flags |= MAP_LOCKED;
6268 if (vma->vm_flags & VM_HUGETLB)
6269 flags |= MAP_HUGETLB;
6272 struct inode *inode;
6275 buf = kmalloc(PATH_MAX, GFP_KERNEL);
6281 * d_path() works from the end of the rb backwards, so we
6282 * need to add enough zero bytes after the string to handle
6283 * the 64bit alignment we do later.
6285 name = file_path(file, buf, PATH_MAX - sizeof(u64));
6290 inode = file_inode(vma->vm_file);
6291 dev = inode->i_sb->s_dev;
6293 gen = inode->i_generation;
6299 if (vma->vm_ops && vma->vm_ops->name) {
6300 name = (char *) vma->vm_ops->name(vma);
6305 name = (char *)arch_vma_name(vma);
6309 if (vma->vm_start <= vma->vm_mm->start_brk &&
6310 vma->vm_end >= vma->vm_mm->brk) {
6314 if (vma->vm_start <= vma->vm_mm->start_stack &&
6315 vma->vm_end >= vma->vm_mm->start_stack) {
6325 strlcpy(tmp, name, sizeof(tmp));
6329 * Since our buffer works in 8 byte units we need to align our string
6330 * size to a multiple of 8. However, we must guarantee the tail end is
6331 * zero'd out to avoid leaking random bits to userspace.
6333 size = strlen(name)+1;
6334 while (!IS_ALIGNED(size, sizeof(u64)))
6335 name[size++] = '\0';
6337 mmap_event->file_name = name;
6338 mmap_event->file_size = size;
6339 mmap_event->maj = maj;
6340 mmap_event->min = min;
6341 mmap_event->ino = ino;
6342 mmap_event->ino_generation = gen;
6343 mmap_event->prot = prot;
6344 mmap_event->flags = flags;
6346 if (!(vma->vm_flags & VM_EXEC))
6347 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
6349 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
6351 perf_event_aux(perf_event_mmap_output,
6358 void perf_event_mmap(struct vm_area_struct *vma)
6360 struct perf_mmap_event mmap_event;
6362 if (!atomic_read(&nr_mmap_events))
6365 mmap_event = (struct perf_mmap_event){
6371 .type = PERF_RECORD_MMAP,
6372 .misc = PERF_RECORD_MISC_USER,
6377 .start = vma->vm_start,
6378 .len = vma->vm_end - vma->vm_start,
6379 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
6381 /* .maj (attr_mmap2 only) */
6382 /* .min (attr_mmap2 only) */
6383 /* .ino (attr_mmap2 only) */
6384 /* .ino_generation (attr_mmap2 only) */
6385 /* .prot (attr_mmap2 only) */
6386 /* .flags (attr_mmap2 only) */
6389 perf_event_mmap_event(&mmap_event);
6392 void perf_event_aux_event(struct perf_event *event, unsigned long head,
6393 unsigned long size, u64 flags)
6395 struct perf_output_handle handle;
6396 struct perf_sample_data sample;
6397 struct perf_aux_event {
6398 struct perf_event_header header;
6404 .type = PERF_RECORD_AUX,
6406 .size = sizeof(rec),
6414 perf_event_header__init_id(&rec.header, &sample, event);
6415 ret = perf_output_begin(&handle, event, rec.header.size);
6420 perf_output_put(&handle, rec);
6421 perf_event__output_id_sample(event, &handle, &sample);
6423 perf_output_end(&handle);
6427 * Lost/dropped samples logging
6429 void perf_log_lost_samples(struct perf_event *event, u64 lost)
6431 struct perf_output_handle handle;
6432 struct perf_sample_data sample;
6436 struct perf_event_header header;
6438 } lost_samples_event = {
6440 .type = PERF_RECORD_LOST_SAMPLES,
6442 .size = sizeof(lost_samples_event),
6447 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
6449 ret = perf_output_begin(&handle, event,
6450 lost_samples_event.header.size);
6454 perf_output_put(&handle, lost_samples_event);
6455 perf_event__output_id_sample(event, &handle, &sample);
6456 perf_output_end(&handle);
6460 * context_switch tracking
6463 struct perf_switch_event {
6464 struct task_struct *task;
6465 struct task_struct *next_prev;
6468 struct perf_event_header header;
6474 static int perf_event_switch_match(struct perf_event *event)
6476 return event->attr.context_switch;
6479 static void perf_event_switch_output(struct perf_event *event, void *data)
6481 struct perf_switch_event *se = data;
6482 struct perf_output_handle handle;
6483 struct perf_sample_data sample;
6486 if (!perf_event_switch_match(event))
6489 /* Only CPU-wide events are allowed to see next/prev pid/tid */
6490 if (event->ctx->task) {
6491 se->event_id.header.type = PERF_RECORD_SWITCH;
6492 se->event_id.header.size = sizeof(se->event_id.header);
6494 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
6495 se->event_id.header.size = sizeof(se->event_id);
6496 se->event_id.next_prev_pid =
6497 perf_event_pid(event, se->next_prev);
6498 se->event_id.next_prev_tid =
6499 perf_event_tid(event, se->next_prev);
6502 perf_event_header__init_id(&se->event_id.header, &sample, event);
6504 ret = perf_output_begin(&handle, event, se->event_id.header.size);
6508 if (event->ctx->task)
6509 perf_output_put(&handle, se->event_id.header);
6511 perf_output_put(&handle, se->event_id);
6513 perf_event__output_id_sample(event, &handle, &sample);
6515 perf_output_end(&handle);
6518 static void perf_event_switch(struct task_struct *task,
6519 struct task_struct *next_prev, bool sched_in)
6521 struct perf_switch_event switch_event;
6523 /* N.B. caller checks nr_switch_events != 0 */
6525 switch_event = (struct perf_switch_event){
6527 .next_prev = next_prev,
6531 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
6534 /* .next_prev_pid */
6535 /* .next_prev_tid */
6539 perf_event_aux(perf_event_switch_output,
6545 * IRQ throttle logging
6548 static void perf_log_throttle(struct perf_event *event, int enable)
6550 struct perf_output_handle handle;
6551 struct perf_sample_data sample;
6555 struct perf_event_header header;
6559 } throttle_event = {
6561 .type = PERF_RECORD_THROTTLE,
6563 .size = sizeof(throttle_event),
6565 .time = perf_event_clock(event),
6566 .id = primary_event_id(event),
6567 .stream_id = event->id,
6571 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
6573 perf_event_header__init_id(&throttle_event.header, &sample, event);
6575 ret = perf_output_begin(&handle, event,
6576 throttle_event.header.size);
6580 perf_output_put(&handle, throttle_event);
6581 perf_event__output_id_sample(event, &handle, &sample);
6582 perf_output_end(&handle);
6585 static void perf_log_itrace_start(struct perf_event *event)
6587 struct perf_output_handle handle;
6588 struct perf_sample_data sample;
6589 struct perf_aux_event {
6590 struct perf_event_header header;
6597 event = event->parent;
6599 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
6600 event->hw.itrace_started)
6603 rec.header.type = PERF_RECORD_ITRACE_START;
6604 rec.header.misc = 0;
6605 rec.header.size = sizeof(rec);
6606 rec.pid = perf_event_pid(event, current);
6607 rec.tid = perf_event_tid(event, current);
6609 perf_event_header__init_id(&rec.header, &sample, event);
6610 ret = perf_output_begin(&handle, event, rec.header.size);
6615 perf_output_put(&handle, rec);
6616 perf_event__output_id_sample(event, &handle, &sample);
6618 perf_output_end(&handle);
6622 * Generic event overflow handling, sampling.
6625 static int __perf_event_overflow(struct perf_event *event,
6626 int throttle, struct perf_sample_data *data,
6627 struct pt_regs *regs)
6629 int events = atomic_read(&event->event_limit);
6630 struct hw_perf_event *hwc = &event->hw;
6635 * Non-sampling counters might still use the PMI to fold short
6636 * hardware counters, ignore those.
6638 if (unlikely(!is_sampling_event(event)))
6641 seq = __this_cpu_read(perf_throttled_seq);
6642 if (seq != hwc->interrupts_seq) {
6643 hwc->interrupts_seq = seq;
6644 hwc->interrupts = 1;
6647 if (unlikely(throttle
6648 && hwc->interrupts >= max_samples_per_tick)) {
6649 __this_cpu_inc(perf_throttled_count);
6650 hwc->interrupts = MAX_INTERRUPTS;
6651 perf_log_throttle(event, 0);
6652 tick_nohz_full_kick();
6657 if (event->attr.freq) {
6658 u64 now = perf_clock();
6659 s64 delta = now - hwc->freq_time_stamp;
6661 hwc->freq_time_stamp = now;
6663 if (delta > 0 && delta < 2*TICK_NSEC)
6664 perf_adjust_period(event, delta, hwc->last_period, true);
6668 * XXX event_limit might not quite work as expected on inherited
6672 event->pending_kill = POLL_IN;
6673 if (events && atomic_dec_and_test(&event->event_limit)) {
6675 event->pending_kill = POLL_HUP;
6676 event->pending_disable = 1;
6677 irq_work_queue(&event->pending);
6680 if (event->overflow_handler)
6681 event->overflow_handler(event, data, regs);
6683 perf_event_output(event, data, regs);
6685 if (*perf_event_fasync(event) && event->pending_kill) {
6686 event->pending_wakeup = 1;
6687 irq_work_queue(&event->pending);
6693 int perf_event_overflow(struct perf_event *event,
6694 struct perf_sample_data *data,
6695 struct pt_regs *regs)
6697 return __perf_event_overflow(event, 1, data, regs);
6701 * Generic software event infrastructure
6704 struct swevent_htable {
6705 struct swevent_hlist *swevent_hlist;
6706 struct mutex hlist_mutex;
6709 /* Recursion avoidance in each contexts */
6710 int recursion[PERF_NR_CONTEXTS];
6713 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
6716 * We directly increment event->count and keep a second value in
6717 * event->hw.period_left to count intervals. This period event
6718 * is kept in the range [-sample_period, 0] so that we can use the
6722 u64 perf_swevent_set_period(struct perf_event *event)
6724 struct hw_perf_event *hwc = &event->hw;
6725 u64 period = hwc->last_period;
6729 hwc->last_period = hwc->sample_period;
6732 old = val = local64_read(&hwc->period_left);
6736 nr = div64_u64(period + val, period);
6737 offset = nr * period;
6739 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
6745 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
6746 struct perf_sample_data *data,
6747 struct pt_regs *regs)
6749 struct hw_perf_event *hwc = &event->hw;
6753 overflow = perf_swevent_set_period(event);
6755 if (hwc->interrupts == MAX_INTERRUPTS)
6758 for (; overflow; overflow--) {
6759 if (__perf_event_overflow(event, throttle,
6762 * We inhibit the overflow from happening when
6763 * hwc->interrupts == MAX_INTERRUPTS.
6771 static void perf_swevent_event(struct perf_event *event, u64 nr,
6772 struct perf_sample_data *data,
6773 struct pt_regs *regs)
6775 struct hw_perf_event *hwc = &event->hw;
6777 local64_add(nr, &event->count);
6782 if (!is_sampling_event(event))
6785 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
6787 return perf_swevent_overflow(event, 1, data, regs);
6789 data->period = event->hw.last_period;
6791 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
6792 return perf_swevent_overflow(event, 1, data, regs);
6794 if (local64_add_negative(nr, &hwc->period_left))
6797 perf_swevent_overflow(event, 0, data, regs);
6800 static int perf_exclude_event(struct perf_event *event,
6801 struct pt_regs *regs)
6803 if (event->hw.state & PERF_HES_STOPPED)
6807 if (event->attr.exclude_user && user_mode(regs))
6810 if (event->attr.exclude_kernel && !user_mode(regs))
6817 static int perf_swevent_match(struct perf_event *event,
6818 enum perf_type_id type,
6820 struct perf_sample_data *data,
6821 struct pt_regs *regs)
6823 if (event->attr.type != type)
6826 if (event->attr.config != event_id)
6829 if (perf_exclude_event(event, regs))
6835 static inline u64 swevent_hash(u64 type, u32 event_id)
6837 u64 val = event_id | (type << 32);
6839 return hash_64(val, SWEVENT_HLIST_BITS);
6842 static inline struct hlist_head *
6843 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
6845 u64 hash = swevent_hash(type, event_id);
6847 return &hlist->heads[hash];
6850 /* For the read side: events when they trigger */
6851 static inline struct hlist_head *
6852 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
6854 struct swevent_hlist *hlist;
6856 hlist = rcu_dereference(swhash->swevent_hlist);
6860 return __find_swevent_head(hlist, type, event_id);
6863 /* For the event head insertion and removal in the hlist */
6864 static inline struct hlist_head *
6865 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
6867 struct swevent_hlist *hlist;
6868 u32 event_id = event->attr.config;
6869 u64 type = event->attr.type;
6872 * Event scheduling is always serialized against hlist allocation
6873 * and release. Which makes the protected version suitable here.
6874 * The context lock guarantees that.
6876 hlist = rcu_dereference_protected(swhash->swevent_hlist,
6877 lockdep_is_held(&event->ctx->lock));
6881 return __find_swevent_head(hlist, type, event_id);
6884 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
6886 struct perf_sample_data *data,
6887 struct pt_regs *regs)
6889 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6890 struct perf_event *event;
6891 struct hlist_head *head;
6894 head = find_swevent_head_rcu(swhash, type, event_id);
6898 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6899 if (perf_swevent_match(event, type, event_id, data, regs))
6900 perf_swevent_event(event, nr, data, regs);
6906 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
6908 int perf_swevent_get_recursion_context(void)
6910 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6912 return get_recursion_context(swhash->recursion);
6914 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
6916 inline void perf_swevent_put_recursion_context(int rctx)
6918 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6920 put_recursion_context(swhash->recursion, rctx);
6923 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6925 struct perf_sample_data data;
6927 if (WARN_ON_ONCE(!regs))
6930 perf_sample_data_init(&data, addr, 0);
6931 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
6934 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6938 preempt_disable_notrace();
6939 rctx = perf_swevent_get_recursion_context();
6940 if (unlikely(rctx < 0))
6943 ___perf_sw_event(event_id, nr, regs, addr);
6945 perf_swevent_put_recursion_context(rctx);
6947 preempt_enable_notrace();
6950 static void perf_swevent_read(struct perf_event *event)
6954 static int perf_swevent_add(struct perf_event *event, int flags)
6956 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6957 struct hw_perf_event *hwc = &event->hw;
6958 struct hlist_head *head;
6960 if (is_sampling_event(event)) {
6961 hwc->last_period = hwc->sample_period;
6962 perf_swevent_set_period(event);
6965 hwc->state = !(flags & PERF_EF_START);
6967 head = find_swevent_head(swhash, event);
6968 if (WARN_ON_ONCE(!head))
6971 hlist_add_head_rcu(&event->hlist_entry, head);
6972 perf_event_update_userpage(event);
6977 static void perf_swevent_del(struct perf_event *event, int flags)
6979 hlist_del_rcu(&event->hlist_entry);
6982 static void perf_swevent_start(struct perf_event *event, int flags)
6984 event->hw.state = 0;
6987 static void perf_swevent_stop(struct perf_event *event, int flags)
6989 event->hw.state = PERF_HES_STOPPED;
6992 /* Deref the hlist from the update side */
6993 static inline struct swevent_hlist *
6994 swevent_hlist_deref(struct swevent_htable *swhash)
6996 return rcu_dereference_protected(swhash->swevent_hlist,
6997 lockdep_is_held(&swhash->hlist_mutex));
7000 static void swevent_hlist_release(struct swevent_htable *swhash)
7002 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
7007 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
7008 kfree_rcu(hlist, rcu_head);
7011 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
7013 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7015 mutex_lock(&swhash->hlist_mutex);
7017 if (!--swhash->hlist_refcount)
7018 swevent_hlist_release(swhash);
7020 mutex_unlock(&swhash->hlist_mutex);
7023 static void swevent_hlist_put(struct perf_event *event)
7027 for_each_possible_cpu(cpu)
7028 swevent_hlist_put_cpu(event, cpu);
7031 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
7033 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7036 mutex_lock(&swhash->hlist_mutex);
7037 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
7038 struct swevent_hlist *hlist;
7040 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
7045 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7047 swhash->hlist_refcount++;
7049 mutex_unlock(&swhash->hlist_mutex);
7054 static int swevent_hlist_get(struct perf_event *event)
7057 int cpu, failed_cpu;
7060 for_each_possible_cpu(cpu) {
7061 err = swevent_hlist_get_cpu(event, cpu);
7071 for_each_possible_cpu(cpu) {
7072 if (cpu == failed_cpu)
7074 swevent_hlist_put_cpu(event, cpu);
7081 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
7083 static void sw_perf_event_destroy(struct perf_event *event)
7085 u64 event_id = event->attr.config;
7087 WARN_ON(event->parent);
7089 static_key_slow_dec(&perf_swevent_enabled[event_id]);
7090 swevent_hlist_put(event);
7093 static int perf_swevent_init(struct perf_event *event)
7095 u64 event_id = event->attr.config;
7097 if (event->attr.type != PERF_TYPE_SOFTWARE)
7101 * no branch sampling for software events
7103 if (has_branch_stack(event))
7107 case PERF_COUNT_SW_CPU_CLOCK:
7108 case PERF_COUNT_SW_TASK_CLOCK:
7115 if (event_id >= PERF_COUNT_SW_MAX)
7118 if (!event->parent) {
7121 err = swevent_hlist_get(event);
7125 static_key_slow_inc(&perf_swevent_enabled[event_id]);
7126 event->destroy = sw_perf_event_destroy;
7132 static struct pmu perf_swevent = {
7133 .task_ctx_nr = perf_sw_context,
7135 .capabilities = PERF_PMU_CAP_NO_NMI,
7137 .event_init = perf_swevent_init,
7138 .add = perf_swevent_add,
7139 .del = perf_swevent_del,
7140 .start = perf_swevent_start,
7141 .stop = perf_swevent_stop,
7142 .read = perf_swevent_read,
7144 .events_across_hotplug = 1,
7147 #ifdef CONFIG_EVENT_TRACING
7149 static int perf_tp_filter_match(struct perf_event *event,
7150 struct perf_sample_data *data)
7152 void *record = data->raw->data;
7154 /* only top level events have filters set */
7156 event = event->parent;
7158 if (likely(!event->filter) || filter_match_preds(event->filter, record))
7163 static int perf_tp_event_match(struct perf_event *event,
7164 struct perf_sample_data *data,
7165 struct pt_regs *regs)
7167 if (event->hw.state & PERF_HES_STOPPED)
7170 * All tracepoints are from kernel-space.
7172 if (event->attr.exclude_kernel)
7175 if (!perf_tp_filter_match(event, data))
7181 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
7182 struct pt_regs *regs, struct hlist_head *head, int rctx,
7183 struct task_struct *task)
7185 struct perf_sample_data data;
7186 struct perf_event *event;
7188 struct perf_raw_record raw = {
7193 perf_sample_data_init(&data, addr, 0);
7196 hlist_for_each_entry_rcu(event, head, hlist_entry) {
7197 if (perf_tp_event_match(event, &data, regs))
7198 perf_swevent_event(event, count, &data, regs);
7202 * If we got specified a target task, also iterate its context and
7203 * deliver this event there too.
7205 if (task && task != current) {
7206 struct perf_event_context *ctx;
7207 struct trace_entry *entry = record;
7210 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
7214 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7215 if (event->cpu != smp_processor_id())
7217 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7219 if (event->attr.config != entry->type)
7221 if (perf_tp_event_match(event, &data, regs))
7222 perf_swevent_event(event, count, &data, regs);
7228 perf_swevent_put_recursion_context(rctx);
7230 EXPORT_SYMBOL_GPL(perf_tp_event);
7232 static void tp_perf_event_destroy(struct perf_event *event)
7234 perf_trace_destroy(event);
7237 static int perf_tp_event_init(struct perf_event *event)
7241 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7245 * no branch sampling for tracepoint events
7247 if (has_branch_stack(event))
7250 err = perf_trace_init(event);
7254 event->destroy = tp_perf_event_destroy;
7259 static struct pmu perf_tracepoint = {
7260 .task_ctx_nr = perf_sw_context,
7262 .event_init = perf_tp_event_init,
7263 .add = perf_trace_add,
7264 .del = perf_trace_del,
7265 .start = perf_swevent_start,
7266 .stop = perf_swevent_stop,
7267 .read = perf_swevent_read,
7269 .events_across_hotplug = 1,
7272 static inline void perf_tp_register(void)
7274 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
7277 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7282 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7285 filter_str = strndup_user(arg, PAGE_SIZE);
7286 if (IS_ERR(filter_str))
7287 return PTR_ERR(filter_str);
7289 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
7295 static void perf_event_free_filter(struct perf_event *event)
7297 ftrace_profile_free_filter(event);
7300 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7302 struct bpf_prog *prog;
7304 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7307 if (event->tp_event->prog)
7310 if (!(event->tp_event->flags & TRACE_EVENT_FL_UKPROBE))
7311 /* bpf programs can only be attached to u/kprobes */
7314 prog = bpf_prog_get(prog_fd);
7316 return PTR_ERR(prog);
7318 if (prog->type != BPF_PROG_TYPE_KPROBE) {
7319 /* valid fd, but invalid bpf program type */
7324 event->tp_event->prog = prog;
7325 event->tp_event->bpf_prog_owner = event;
7330 static void perf_event_free_bpf_prog(struct perf_event *event)
7332 struct bpf_prog *prog;
7334 if (!event->tp_event)
7337 prog = event->tp_event->prog;
7338 if (prog && event->tp_event->bpf_prog_owner == event) {
7339 event->tp_event->prog = NULL;
7346 static inline void perf_tp_register(void)
7350 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7355 static void perf_event_free_filter(struct perf_event *event)
7359 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7364 static void perf_event_free_bpf_prog(struct perf_event *event)
7367 #endif /* CONFIG_EVENT_TRACING */
7369 #ifdef CONFIG_HAVE_HW_BREAKPOINT
7370 void perf_bp_event(struct perf_event *bp, void *data)
7372 struct perf_sample_data sample;
7373 struct pt_regs *regs = data;
7375 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
7377 if (!bp->hw.state && !perf_exclude_event(bp, regs))
7378 perf_swevent_event(bp, 1, &sample, regs);
7382 static int perf_event_drv_configs(struct perf_event *event,
7385 if (!event->pmu->get_drv_configs)
7388 return event->pmu->get_drv_configs(event, arg);
7392 * hrtimer based swevent callback
7395 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
7397 enum hrtimer_restart ret = HRTIMER_RESTART;
7398 struct perf_sample_data data;
7399 struct pt_regs *regs;
7400 struct perf_event *event;
7403 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
7405 if (event->state != PERF_EVENT_STATE_ACTIVE)
7406 return HRTIMER_NORESTART;
7408 event->pmu->read(event);
7410 perf_sample_data_init(&data, 0, event->hw.last_period);
7411 regs = get_irq_regs();
7413 if (regs && !perf_exclude_event(event, regs)) {
7414 if (!(event->attr.exclude_idle && is_idle_task(current)))
7415 if (__perf_event_overflow(event, 1, &data, regs))
7416 ret = HRTIMER_NORESTART;
7419 period = max_t(u64, 10000, event->hw.sample_period);
7420 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
7425 static void perf_swevent_start_hrtimer(struct perf_event *event)
7427 struct hw_perf_event *hwc = &event->hw;
7430 if (!is_sampling_event(event))
7433 period = local64_read(&hwc->period_left);
7438 local64_set(&hwc->period_left, 0);
7440 period = max_t(u64, 10000, hwc->sample_period);
7442 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
7443 HRTIMER_MODE_REL_PINNED);
7446 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
7448 struct hw_perf_event *hwc = &event->hw;
7450 if (is_sampling_event(event)) {
7451 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
7452 local64_set(&hwc->period_left, ktime_to_ns(remaining));
7454 hrtimer_cancel(&hwc->hrtimer);
7458 static void perf_swevent_init_hrtimer(struct perf_event *event)
7460 struct hw_perf_event *hwc = &event->hw;
7462 if (!is_sampling_event(event))
7465 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7466 hwc->hrtimer.function = perf_swevent_hrtimer;
7469 * Since hrtimers have a fixed rate, we can do a static freq->period
7470 * mapping and avoid the whole period adjust feedback stuff.
7472 if (event->attr.freq) {
7473 long freq = event->attr.sample_freq;
7475 event->attr.sample_period = NSEC_PER_SEC / freq;
7476 hwc->sample_period = event->attr.sample_period;
7477 local64_set(&hwc->period_left, hwc->sample_period);
7478 hwc->last_period = hwc->sample_period;
7479 event->attr.freq = 0;
7484 * Software event: cpu wall time clock
7487 static void cpu_clock_event_update(struct perf_event *event)
7492 now = local_clock();
7493 prev = local64_xchg(&event->hw.prev_count, now);
7494 local64_add(now - prev, &event->count);
7497 static void cpu_clock_event_start(struct perf_event *event, int flags)
7499 local64_set(&event->hw.prev_count, local_clock());
7500 perf_swevent_start_hrtimer(event);
7503 static void cpu_clock_event_stop(struct perf_event *event, int flags)
7505 perf_swevent_cancel_hrtimer(event);
7506 cpu_clock_event_update(event);
7509 static int cpu_clock_event_add(struct perf_event *event, int flags)
7511 if (flags & PERF_EF_START)
7512 cpu_clock_event_start(event, flags);
7513 perf_event_update_userpage(event);
7518 static void cpu_clock_event_del(struct perf_event *event, int flags)
7520 cpu_clock_event_stop(event, flags);
7523 static void cpu_clock_event_read(struct perf_event *event)
7525 cpu_clock_event_update(event);
7528 static int cpu_clock_event_init(struct perf_event *event)
7530 if (event->attr.type != PERF_TYPE_SOFTWARE)
7533 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
7537 * no branch sampling for software events
7539 if (has_branch_stack(event))
7542 perf_swevent_init_hrtimer(event);
7547 static struct pmu perf_cpu_clock = {
7548 .task_ctx_nr = perf_sw_context,
7550 .capabilities = PERF_PMU_CAP_NO_NMI,
7552 .event_init = cpu_clock_event_init,
7553 .add = cpu_clock_event_add,
7554 .del = cpu_clock_event_del,
7555 .start = cpu_clock_event_start,
7556 .stop = cpu_clock_event_stop,
7557 .read = cpu_clock_event_read,
7559 .events_across_hotplug = 1,
7563 * Software event: task time clock
7566 static void task_clock_event_update(struct perf_event *event, u64 now)
7571 prev = local64_xchg(&event->hw.prev_count, now);
7573 local64_add(delta, &event->count);
7576 static void task_clock_event_start(struct perf_event *event, int flags)
7578 local64_set(&event->hw.prev_count, event->ctx->time);
7579 perf_swevent_start_hrtimer(event);
7582 static void task_clock_event_stop(struct perf_event *event, int flags)
7584 perf_swevent_cancel_hrtimer(event);
7585 task_clock_event_update(event, event->ctx->time);
7588 static int task_clock_event_add(struct perf_event *event, int flags)
7590 if (flags & PERF_EF_START)
7591 task_clock_event_start(event, flags);
7592 perf_event_update_userpage(event);
7597 static void task_clock_event_del(struct perf_event *event, int flags)
7599 task_clock_event_stop(event, PERF_EF_UPDATE);
7602 static void task_clock_event_read(struct perf_event *event)
7604 u64 now = perf_clock();
7605 u64 delta = now - event->ctx->timestamp;
7606 u64 time = event->ctx->time + delta;
7608 task_clock_event_update(event, time);
7611 static int task_clock_event_init(struct perf_event *event)
7613 if (event->attr.type != PERF_TYPE_SOFTWARE)
7616 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
7620 * no branch sampling for software events
7622 if (has_branch_stack(event))
7625 perf_swevent_init_hrtimer(event);
7630 static struct pmu perf_task_clock = {
7631 .task_ctx_nr = perf_sw_context,
7633 .capabilities = PERF_PMU_CAP_NO_NMI,
7635 .event_init = task_clock_event_init,
7636 .add = task_clock_event_add,
7637 .del = task_clock_event_del,
7638 .start = task_clock_event_start,
7639 .stop = task_clock_event_stop,
7640 .read = task_clock_event_read,
7642 .events_across_hotplug = 1,
7645 static void perf_pmu_nop_void(struct pmu *pmu)
7649 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
7653 static int perf_pmu_nop_int(struct pmu *pmu)
7658 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
7660 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
7662 __this_cpu_write(nop_txn_flags, flags);
7664 if (flags & ~PERF_PMU_TXN_ADD)
7667 perf_pmu_disable(pmu);
7670 static int perf_pmu_commit_txn(struct pmu *pmu)
7672 unsigned int flags = __this_cpu_read(nop_txn_flags);
7674 __this_cpu_write(nop_txn_flags, 0);
7676 if (flags & ~PERF_PMU_TXN_ADD)
7679 perf_pmu_enable(pmu);
7683 static void perf_pmu_cancel_txn(struct pmu *pmu)
7685 unsigned int flags = __this_cpu_read(nop_txn_flags);
7687 __this_cpu_write(nop_txn_flags, 0);
7689 if (flags & ~PERF_PMU_TXN_ADD)
7692 perf_pmu_enable(pmu);
7695 static int perf_event_idx_default(struct perf_event *event)
7701 * Ensures all contexts with the same task_ctx_nr have the same
7702 * pmu_cpu_context too.
7704 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
7711 list_for_each_entry(pmu, &pmus, entry) {
7712 if (pmu->task_ctx_nr == ctxn)
7713 return pmu->pmu_cpu_context;
7719 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
7723 for_each_possible_cpu(cpu) {
7724 struct perf_cpu_context *cpuctx;
7726 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7728 if (cpuctx->unique_pmu == old_pmu)
7729 cpuctx->unique_pmu = pmu;
7733 static void free_pmu_context(struct pmu *pmu)
7737 mutex_lock(&pmus_lock);
7739 * Like a real lame refcount.
7741 list_for_each_entry(i, &pmus, entry) {
7742 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
7743 update_pmu_context(i, pmu);
7748 free_percpu(pmu->pmu_cpu_context);
7750 mutex_unlock(&pmus_lock);
7752 static struct idr pmu_idr;
7755 type_show(struct device *dev, struct device_attribute *attr, char *page)
7757 struct pmu *pmu = dev_get_drvdata(dev);
7759 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
7761 static DEVICE_ATTR_RO(type);
7764 perf_event_mux_interval_ms_show(struct device *dev,
7765 struct device_attribute *attr,
7768 struct pmu *pmu = dev_get_drvdata(dev);
7770 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
7773 static DEFINE_MUTEX(mux_interval_mutex);
7776 perf_event_mux_interval_ms_store(struct device *dev,
7777 struct device_attribute *attr,
7778 const char *buf, size_t count)
7780 struct pmu *pmu = dev_get_drvdata(dev);
7781 int timer, cpu, ret;
7783 ret = kstrtoint(buf, 0, &timer);
7790 /* same value, noting to do */
7791 if (timer == pmu->hrtimer_interval_ms)
7794 mutex_lock(&mux_interval_mutex);
7795 pmu->hrtimer_interval_ms = timer;
7797 /* update all cpuctx for this PMU */
7799 for_each_online_cpu(cpu) {
7800 struct perf_cpu_context *cpuctx;
7801 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7802 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
7804 cpu_function_call(cpu,
7805 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
7808 mutex_unlock(&mux_interval_mutex);
7812 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
7814 static struct attribute *pmu_dev_attrs[] = {
7815 &dev_attr_type.attr,
7816 &dev_attr_perf_event_mux_interval_ms.attr,
7819 ATTRIBUTE_GROUPS(pmu_dev);
7821 static int pmu_bus_running;
7822 static struct bus_type pmu_bus = {
7823 .name = "event_source",
7824 .dev_groups = pmu_dev_groups,
7827 static void pmu_dev_release(struct device *dev)
7832 static int pmu_dev_alloc(struct pmu *pmu)
7836 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
7840 pmu->dev->groups = pmu->attr_groups;
7841 device_initialize(pmu->dev);
7842 ret = dev_set_name(pmu->dev, "%s", pmu->name);
7846 dev_set_drvdata(pmu->dev, pmu);
7847 pmu->dev->bus = &pmu_bus;
7848 pmu->dev->release = pmu_dev_release;
7849 ret = device_add(pmu->dev);
7857 put_device(pmu->dev);
7861 static struct lock_class_key cpuctx_mutex;
7862 static struct lock_class_key cpuctx_lock;
7864 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
7868 mutex_lock(&pmus_lock);
7870 pmu->pmu_disable_count = alloc_percpu(int);
7871 if (!pmu->pmu_disable_count)
7880 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
7888 if (pmu_bus_running) {
7889 ret = pmu_dev_alloc(pmu);
7895 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
7896 if (pmu->pmu_cpu_context)
7897 goto got_cpu_context;
7900 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
7901 if (!pmu->pmu_cpu_context)
7904 for_each_possible_cpu(cpu) {
7905 struct perf_cpu_context *cpuctx;
7907 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7908 __perf_event_init_context(&cpuctx->ctx);
7909 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
7910 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
7911 cpuctx->ctx.pmu = pmu;
7913 __perf_mux_hrtimer_init(cpuctx, cpu);
7915 cpuctx->unique_pmu = pmu;
7919 if (!pmu->start_txn) {
7920 if (pmu->pmu_enable) {
7922 * If we have pmu_enable/pmu_disable calls, install
7923 * transaction stubs that use that to try and batch
7924 * hardware accesses.
7926 pmu->start_txn = perf_pmu_start_txn;
7927 pmu->commit_txn = perf_pmu_commit_txn;
7928 pmu->cancel_txn = perf_pmu_cancel_txn;
7930 pmu->start_txn = perf_pmu_nop_txn;
7931 pmu->commit_txn = perf_pmu_nop_int;
7932 pmu->cancel_txn = perf_pmu_nop_void;
7936 if (!pmu->pmu_enable) {
7937 pmu->pmu_enable = perf_pmu_nop_void;
7938 pmu->pmu_disable = perf_pmu_nop_void;
7941 if (!pmu->event_idx)
7942 pmu->event_idx = perf_event_idx_default;
7944 list_add_rcu(&pmu->entry, &pmus);
7945 atomic_set(&pmu->exclusive_cnt, 0);
7948 mutex_unlock(&pmus_lock);
7953 device_del(pmu->dev);
7954 put_device(pmu->dev);
7957 if (pmu->type >= PERF_TYPE_MAX)
7958 idr_remove(&pmu_idr, pmu->type);
7961 free_percpu(pmu->pmu_disable_count);
7964 EXPORT_SYMBOL_GPL(perf_pmu_register);
7966 void perf_pmu_unregister(struct pmu *pmu)
7968 mutex_lock(&pmus_lock);
7969 list_del_rcu(&pmu->entry);
7970 mutex_unlock(&pmus_lock);
7973 * We dereference the pmu list under both SRCU and regular RCU, so
7974 * synchronize against both of those.
7976 synchronize_srcu(&pmus_srcu);
7979 free_percpu(pmu->pmu_disable_count);
7980 if (pmu->type >= PERF_TYPE_MAX)
7981 idr_remove(&pmu_idr, pmu->type);
7982 device_del(pmu->dev);
7983 put_device(pmu->dev);
7984 free_pmu_context(pmu);
7986 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
7988 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
7990 struct perf_event_context *ctx = NULL;
7993 if (!try_module_get(pmu->module))
7996 if (event->group_leader != event) {
7998 * This ctx->mutex can nest when we're called through
7999 * inheritance. See the perf_event_ctx_lock_nested() comment.
8001 ctx = perf_event_ctx_lock_nested(event->group_leader,
8002 SINGLE_DEPTH_NESTING);
8007 ret = pmu->event_init(event);
8010 perf_event_ctx_unlock(event->group_leader, ctx);
8013 module_put(pmu->module);
8018 static struct pmu *perf_init_event(struct perf_event *event)
8020 struct pmu *pmu = NULL;
8024 idx = srcu_read_lock(&pmus_srcu);
8027 pmu = idr_find(&pmu_idr, event->attr.type);
8030 ret = perf_try_init_event(pmu, event);
8036 list_for_each_entry_rcu(pmu, &pmus, entry) {
8037 ret = perf_try_init_event(pmu, event);
8041 if (ret != -ENOENT) {
8046 pmu = ERR_PTR(-ENOENT);
8048 srcu_read_unlock(&pmus_srcu, idx);
8053 static void account_event_cpu(struct perf_event *event, int cpu)
8058 if (is_cgroup_event(event))
8059 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
8062 static void account_event(struct perf_event *event)
8067 if (event->attach_state & PERF_ATTACH_TASK)
8068 static_key_slow_inc(&perf_sched_events.key);
8069 if (event->attr.mmap || event->attr.mmap_data)
8070 atomic_inc(&nr_mmap_events);
8071 if (event->attr.comm)
8072 atomic_inc(&nr_comm_events);
8073 if (event->attr.task)
8074 atomic_inc(&nr_task_events);
8075 if (event->attr.freq) {
8076 if (atomic_inc_return(&nr_freq_events) == 1)
8077 tick_nohz_full_kick_all();
8079 if (event->attr.context_switch) {
8080 atomic_inc(&nr_switch_events);
8081 static_key_slow_inc(&perf_sched_events.key);
8083 if (has_branch_stack(event))
8084 static_key_slow_inc(&perf_sched_events.key);
8085 if (is_cgroup_event(event))
8086 static_key_slow_inc(&perf_sched_events.key);
8088 account_event_cpu(event, event->cpu);
8092 * Allocate and initialize a event structure
8094 static struct perf_event *
8095 perf_event_alloc(struct perf_event_attr *attr, int cpu,
8096 struct task_struct *task,
8097 struct perf_event *group_leader,
8098 struct perf_event *parent_event,
8099 perf_overflow_handler_t overflow_handler,
8100 void *context, int cgroup_fd)
8103 struct perf_event *event;
8104 struct hw_perf_event *hwc;
8107 if ((unsigned)cpu >= nr_cpu_ids) {
8108 if (!task || cpu != -1)
8109 return ERR_PTR(-EINVAL);
8112 event = kzalloc(sizeof(*event), GFP_KERNEL);
8114 return ERR_PTR(-ENOMEM);
8117 * Single events are their own group leaders, with an
8118 * empty sibling list:
8121 group_leader = event;
8123 mutex_init(&event->group_leader_mutex);
8124 mutex_init(&event->child_mutex);
8125 INIT_LIST_HEAD(&event->child_list);
8127 INIT_LIST_HEAD(&event->group_entry);
8128 INIT_LIST_HEAD(&event->event_entry);
8129 INIT_LIST_HEAD(&event->sibling_list);
8130 INIT_LIST_HEAD(&event->rb_entry);
8131 INIT_LIST_HEAD(&event->active_entry);
8132 INIT_LIST_HEAD(&event->drv_configs);
8133 INIT_HLIST_NODE(&event->hlist_entry);
8136 init_waitqueue_head(&event->waitq);
8137 init_irq_work(&event->pending, perf_pending_event);
8139 mutex_init(&event->mmap_mutex);
8141 atomic_long_set(&event->refcount, 1);
8143 event->attr = *attr;
8144 event->group_leader = group_leader;
8148 event->parent = parent_event;
8150 event->ns = get_pid_ns(task_active_pid_ns(current));
8151 event->id = atomic64_inc_return(&perf_event_id);
8153 event->state = PERF_EVENT_STATE_INACTIVE;
8156 event->attach_state = PERF_ATTACH_TASK;
8158 * XXX pmu::event_init needs to know what task to account to
8159 * and we cannot use the ctx information because we need the
8160 * pmu before we get a ctx.
8162 event->hw.target = task;
8165 event->clock = &local_clock;
8167 event->clock = parent_event->clock;
8169 if (!overflow_handler && parent_event) {
8170 overflow_handler = parent_event->overflow_handler;
8171 context = parent_event->overflow_handler_context;
8174 event->overflow_handler = overflow_handler;
8175 event->overflow_handler_context = context;
8177 perf_event__state_init(event);
8182 hwc->sample_period = attr->sample_period;
8183 if (attr->freq && attr->sample_freq)
8184 hwc->sample_period = 1;
8185 hwc->last_period = hwc->sample_period;
8187 local64_set(&hwc->period_left, hwc->sample_period);
8190 * We currently do not support PERF_SAMPLE_READ on inherited events.
8191 * See perf_output_read().
8193 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
8196 if (!has_branch_stack(event))
8197 event->attr.branch_sample_type = 0;
8199 if (cgroup_fd != -1) {
8200 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
8205 pmu = perf_init_event(event);
8208 else if (IS_ERR(pmu)) {
8213 err = exclusive_event_init(event);
8217 if (!event->parent) {
8218 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
8219 err = get_callchain_buffers();
8225 /* symmetric to unaccount_event() in _free_event() */
8226 account_event(event);
8231 exclusive_event_destroy(event);
8235 event->destroy(event);
8236 module_put(pmu->module);
8238 if (is_cgroup_event(event))
8239 perf_detach_cgroup(event);
8241 put_pid_ns(event->ns);
8244 return ERR_PTR(err);
8247 static int perf_copy_attr(struct perf_event_attr __user *uattr,
8248 struct perf_event_attr *attr)
8253 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
8257 * zero the full structure, so that a short copy will be nice.
8259 memset(attr, 0, sizeof(*attr));
8261 ret = get_user(size, &uattr->size);
8265 if (size > PAGE_SIZE) /* silly large */
8268 if (!size) /* abi compat */
8269 size = PERF_ATTR_SIZE_VER0;
8271 if (size < PERF_ATTR_SIZE_VER0)
8275 * If we're handed a bigger struct than we know of,
8276 * ensure all the unknown bits are 0 - i.e. new
8277 * user-space does not rely on any kernel feature
8278 * extensions we dont know about yet.
8280 if (size > sizeof(*attr)) {
8281 unsigned char __user *addr;
8282 unsigned char __user *end;
8285 addr = (void __user *)uattr + sizeof(*attr);
8286 end = (void __user *)uattr + size;
8288 for (; addr < end; addr++) {
8289 ret = get_user(val, addr);
8295 size = sizeof(*attr);
8298 ret = copy_from_user(attr, uattr, size);
8302 if (attr->__reserved_1)
8305 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
8308 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
8311 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
8312 u64 mask = attr->branch_sample_type;
8314 /* only using defined bits */
8315 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
8318 /* at least one branch bit must be set */
8319 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
8322 /* propagate priv level, when not set for branch */
8323 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
8325 /* exclude_kernel checked on syscall entry */
8326 if (!attr->exclude_kernel)
8327 mask |= PERF_SAMPLE_BRANCH_KERNEL;
8329 if (!attr->exclude_user)
8330 mask |= PERF_SAMPLE_BRANCH_USER;
8332 if (!attr->exclude_hv)
8333 mask |= PERF_SAMPLE_BRANCH_HV;
8335 * adjust user setting (for HW filter setup)
8337 attr->branch_sample_type = mask;
8339 /* privileged levels capture (kernel, hv): check permissions */
8340 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
8341 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8345 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
8346 ret = perf_reg_validate(attr->sample_regs_user);
8351 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
8352 if (!arch_perf_have_user_stack_dump())
8356 * We have __u32 type for the size, but so far
8357 * we can only use __u16 as maximum due to the
8358 * __u16 sample size limit.
8360 if (attr->sample_stack_user >= USHRT_MAX)
8362 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
8366 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
8367 ret = perf_reg_validate(attr->sample_regs_intr);
8372 put_user(sizeof(*attr), &uattr->size);
8378 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
8380 struct ring_buffer *rb = NULL;
8386 /* don't allow circular references */
8387 if (event == output_event)
8391 * Don't allow cross-cpu buffers
8393 if (output_event->cpu != event->cpu)
8397 * If its not a per-cpu rb, it must be the same task.
8399 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
8403 * Mixing clocks in the same buffer is trouble you don't need.
8405 if (output_event->clock != event->clock)
8409 * If both events generate aux data, they must be on the same PMU
8411 if (has_aux(event) && has_aux(output_event) &&
8412 event->pmu != output_event->pmu)
8416 mutex_lock(&event->mmap_mutex);
8417 /* Can't redirect output if we've got an active mmap() */
8418 if (atomic_read(&event->mmap_count))
8422 /* get the rb we want to redirect to */
8423 rb = ring_buffer_get(output_event);
8428 ring_buffer_attach(event, rb);
8432 mutex_unlock(&event->mmap_mutex);
8438 static void mutex_lock_double(struct mutex *a, struct mutex *b)
8444 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
8447 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
8449 bool nmi_safe = false;
8452 case CLOCK_MONOTONIC:
8453 event->clock = &ktime_get_mono_fast_ns;
8457 case CLOCK_MONOTONIC_RAW:
8458 event->clock = &ktime_get_raw_fast_ns;
8462 case CLOCK_REALTIME:
8463 event->clock = &ktime_get_real_ns;
8466 case CLOCK_BOOTTIME:
8467 event->clock = &ktime_get_boot_ns;
8471 event->clock = &ktime_get_tai_ns;
8478 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
8485 * Variation on perf_event_ctx_lock_nested(), except we take two context
8488 static struct perf_event_context *
8489 __perf_event_ctx_lock_double(struct perf_event *group_leader,
8490 struct perf_event_context *ctx)
8492 struct perf_event_context *gctx;
8496 gctx = READ_ONCE(group_leader->ctx);
8497 if (!atomic_inc_not_zero(&gctx->refcount)) {
8503 mutex_lock_double(&gctx->mutex, &ctx->mutex);
8505 if (group_leader->ctx != gctx) {
8506 mutex_unlock(&ctx->mutex);
8507 mutex_unlock(&gctx->mutex);
8516 * sys_perf_event_open - open a performance event, associate it to a task/cpu
8518 * @attr_uptr: event_id type attributes for monitoring/sampling
8521 * @group_fd: group leader event fd
8523 SYSCALL_DEFINE5(perf_event_open,
8524 struct perf_event_attr __user *, attr_uptr,
8525 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
8527 struct perf_event *group_leader = NULL, *output_event = NULL;
8528 struct perf_event *event, *sibling;
8529 struct perf_event_attr attr;
8530 struct perf_event_context *ctx, *uninitialized_var(gctx);
8531 struct file *event_file = NULL;
8532 struct fd group = {NULL, 0};
8533 struct task_struct *task = NULL;
8538 int f_flags = O_RDWR;
8541 /* for future expandability... */
8542 if (flags & ~PERF_FLAG_ALL)
8545 if (perf_paranoid_any() && !capable(CAP_SYS_ADMIN))
8548 err = perf_copy_attr(attr_uptr, &attr);
8552 if (attr.constraint_duplicate || attr.__reserved_1)
8555 if (!attr.exclude_kernel) {
8556 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8561 if (attr.sample_freq > sysctl_perf_event_sample_rate)
8564 if (attr.sample_period & (1ULL << 63))
8569 * In cgroup mode, the pid argument is used to pass the fd
8570 * opened to the cgroup directory in cgroupfs. The cpu argument
8571 * designates the cpu on which to monitor threads from that
8574 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
8577 if (flags & PERF_FLAG_FD_CLOEXEC)
8578 f_flags |= O_CLOEXEC;
8580 event_fd = get_unused_fd_flags(f_flags);
8584 if (group_fd != -1) {
8585 err = perf_fget_light(group_fd, &group);
8588 group_leader = group.file->private_data;
8589 if (flags & PERF_FLAG_FD_OUTPUT)
8590 output_event = group_leader;
8591 if (flags & PERF_FLAG_FD_NO_GROUP)
8592 group_leader = NULL;
8596 * Take the group_leader's group_leader_mutex before observing
8597 * anything in the group leader that leads to changes in ctx,
8598 * many of which may be changing on another thread.
8599 * In particular, we want to take this lock before deciding
8600 * whether we need to move_group.
8603 mutex_lock(&group_leader->group_leader_mutex);
8605 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
8606 task = find_lively_task_by_vpid(pid);
8608 err = PTR_ERR(task);
8613 if (task && group_leader &&
8614 group_leader->attr.inherit != attr.inherit) {
8622 err = mutex_lock_interruptible(&task->signal->cred_guard_mutex);
8627 * Reuse ptrace permission checks for now.
8629 * We must hold cred_guard_mutex across this and any potential
8630 * perf_install_in_context() call for this new event to
8631 * serialize against exec() altering our credentials (and the
8632 * perf_event_exit_task() that could imply).
8635 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
8639 if (flags & PERF_FLAG_PID_CGROUP)
8642 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
8643 NULL, NULL, cgroup_fd);
8644 if (IS_ERR(event)) {
8645 err = PTR_ERR(event);
8649 if (is_sampling_event(event)) {
8650 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
8657 * Special case software events and allow them to be part of
8658 * any hardware group.
8662 if (attr.use_clockid) {
8663 err = perf_event_set_clock(event, attr.clockid);
8669 (is_software_event(event) != is_software_event(group_leader))) {
8670 if (is_software_event(event)) {
8672 * If event and group_leader are not both a software
8673 * event, and event is, then group leader is not.
8675 * Allow the addition of software events to !software
8676 * groups, this is safe because software events never
8679 pmu = group_leader->pmu;
8680 } else if (is_software_event(group_leader) &&
8681 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
8683 * In case the group is a pure software group, and we
8684 * try to add a hardware event, move the whole group to
8685 * the hardware context.
8692 * Get the target context (task or percpu):
8694 ctx = find_get_context(pmu, task, event);
8700 if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
8706 * Look up the group leader (we will attach this event to it):
8712 * Do not allow a recursive hierarchy (this new sibling
8713 * becoming part of another group-sibling):
8715 if (group_leader->group_leader != group_leader)
8718 /* All events in a group should have the same clock */
8719 if (group_leader->clock != event->clock)
8723 * Make sure we're both events for the same CPU;
8724 * grouping events for different CPUs is broken; since
8725 * you can never concurrently schedule them anyhow.
8727 if (group_leader->cpu != event->cpu)
8731 * Make sure we're both on the same task, or both
8734 if (group_leader->ctx->task != ctx->task)
8738 * Do not allow to attach to a group in a different task
8739 * or CPU context. If we're moving SW events, we'll fix
8740 * this up later, so allow that.
8742 if (!move_group && group_leader->ctx != ctx)
8746 * Only a group leader can be exclusive or pinned
8748 if (attr.exclusive || attr.pinned)
8753 err = perf_event_set_output(event, output_event);
8758 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
8760 if (IS_ERR(event_file)) {
8761 err = PTR_ERR(event_file);
8767 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
8770 * Check if we raced against another sys_perf_event_open() call
8771 * moving the software group underneath us.
8773 if (!(group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
8775 * If someone moved the group out from under us, check
8776 * if this new event wound up on the same ctx, if so
8777 * its the regular !move_group case, otherwise fail.
8783 perf_event_ctx_unlock(group_leader, gctx);
8788 mutex_lock(&ctx->mutex);
8791 if (!perf_event_validate_size(event)) {
8797 * Must be under the same ctx::mutex as perf_install_in_context(),
8798 * because we need to serialize with concurrent event creation.
8800 if (!exclusive_event_installable(event, ctx)) {
8801 /* exclusive and group stuff are assumed mutually exclusive */
8802 WARN_ON_ONCE(move_group);
8808 WARN_ON_ONCE(ctx->parent_ctx);
8811 * This is the point on no return; we cannot fail hereafter. This is
8812 * where we start modifying current state.
8817 * See perf_event_ctx_lock() for comments on the details
8818 * of swizzling perf_event::ctx.
8820 perf_remove_from_context(group_leader, false);
8822 list_for_each_entry(sibling, &group_leader->sibling_list,
8824 perf_remove_from_context(sibling, false);
8829 * Wait for everybody to stop referencing the events through
8830 * the old lists, before installing it on new lists.
8835 * Install the group siblings before the group leader.
8837 * Because a group leader will try and install the entire group
8838 * (through the sibling list, which is still in-tact), we can
8839 * end up with siblings installed in the wrong context.
8841 * By installing siblings first we NO-OP because they're not
8842 * reachable through the group lists.
8844 list_for_each_entry(sibling, &group_leader->sibling_list,
8846 perf_event__state_init(sibling);
8847 perf_install_in_context(ctx, sibling, sibling->cpu);
8852 * Removing from the context ends up with disabled
8853 * event. What we want here is event in the initial
8854 * startup state, ready to be add into new context.
8856 perf_event__state_init(group_leader);
8857 perf_install_in_context(ctx, group_leader, group_leader->cpu);
8861 * Now that all events are installed in @ctx, nothing
8862 * references @gctx anymore, so drop the last reference we have
8869 * Precalculate sample_data sizes; do while holding ctx::mutex such
8870 * that we're serialized against further additions and before
8871 * perf_install_in_context() which is the point the event is active and
8872 * can use these values.
8874 perf_event__header_size(event);
8875 perf_event__id_header_size(event);
8877 perf_install_in_context(ctx, event, event->cpu);
8878 perf_unpin_context(ctx);
8881 perf_event_ctx_unlock(group_leader, gctx);
8882 mutex_unlock(&ctx->mutex);
8884 mutex_unlock(&group_leader->group_leader_mutex);
8887 mutex_unlock(&task->signal->cred_guard_mutex);
8888 put_task_struct(task);
8893 event->owner = current;
8895 mutex_lock(¤t->perf_event_mutex);
8896 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
8897 mutex_unlock(¤t->perf_event_mutex);
8900 * Drop the reference on the group_event after placing the
8901 * new event on the sibling_list. This ensures destruction
8902 * of the group leader will find the pointer to itself in
8903 * perf_group_detach().
8906 fd_install(event_fd, event_file);
8911 perf_event_ctx_unlock(group_leader, gctx);
8912 mutex_unlock(&ctx->mutex);
8916 perf_unpin_context(ctx);
8920 * If event_file is set, the fput() above will have called ->release()
8921 * and that will take care of freeing the event.
8927 mutex_unlock(&task->signal->cred_guard_mutex);
8932 put_task_struct(task);
8935 mutex_unlock(&group_leader->group_leader_mutex);
8938 put_unused_fd(event_fd);
8943 * perf_event_create_kernel_counter
8945 * @attr: attributes of the counter to create
8946 * @cpu: cpu in which the counter is bound
8947 * @task: task to profile (NULL for percpu)
8950 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
8951 struct task_struct *task,
8952 perf_overflow_handler_t overflow_handler,
8955 struct perf_event_context *ctx;
8956 struct perf_event *event;
8960 * Get the target context (task or percpu):
8963 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
8964 overflow_handler, context, -1);
8965 if (IS_ERR(event)) {
8966 err = PTR_ERR(event);
8970 /* Mark owner so we could distinguish it from user events. */
8971 event->owner = EVENT_OWNER_KERNEL;
8973 ctx = find_get_context(event->pmu, task, event);
8979 WARN_ON_ONCE(ctx->parent_ctx);
8980 mutex_lock(&ctx->mutex);
8981 if (!exclusive_event_installable(event, ctx)) {
8982 mutex_unlock(&ctx->mutex);
8983 perf_unpin_context(ctx);
8989 perf_install_in_context(ctx, event, event->cpu);
8990 perf_unpin_context(ctx);
8991 mutex_unlock(&ctx->mutex);
8998 return ERR_PTR(err);
9000 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
9002 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
9004 struct perf_event_context *src_ctx;
9005 struct perf_event_context *dst_ctx;
9006 struct perf_event *event, *tmp;
9009 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
9010 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
9013 * See perf_event_ctx_lock() for comments on the details
9014 * of swizzling perf_event::ctx.
9016 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
9017 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
9019 perf_remove_from_context(event, false);
9020 unaccount_event_cpu(event, src_cpu);
9022 list_add(&event->migrate_entry, &events);
9026 * Wait for the events to quiesce before re-instating them.
9031 * Re-instate events in 2 passes.
9033 * Skip over group leaders and only install siblings on this first
9034 * pass, siblings will not get enabled without a leader, however a
9035 * leader will enable its siblings, even if those are still on the old
9038 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
9039 if (event->group_leader == event)
9042 list_del(&event->migrate_entry);
9043 if (event->state >= PERF_EVENT_STATE_OFF)
9044 event->state = PERF_EVENT_STATE_INACTIVE;
9045 account_event_cpu(event, dst_cpu);
9046 perf_install_in_context(dst_ctx, event, dst_cpu);
9051 * Once all the siblings are setup properly, install the group leaders
9054 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
9055 list_del(&event->migrate_entry);
9056 if (event->state >= PERF_EVENT_STATE_OFF)
9057 event->state = PERF_EVENT_STATE_INACTIVE;
9058 account_event_cpu(event, dst_cpu);
9059 perf_install_in_context(dst_ctx, event, dst_cpu);
9062 mutex_unlock(&dst_ctx->mutex);
9063 mutex_unlock(&src_ctx->mutex);
9065 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
9067 static void sync_child_event(struct perf_event *child_event,
9068 struct task_struct *child)
9070 struct perf_event *parent_event = child_event->parent;
9073 if (child_event->attr.inherit_stat)
9074 perf_event_read_event(child_event, child);
9076 child_val = perf_event_count(child_event);
9079 * Add back the child's count to the parent's count:
9081 atomic64_add(child_val, &parent_event->child_count);
9082 atomic64_add(child_event->total_time_enabled,
9083 &parent_event->child_total_time_enabled);
9084 atomic64_add(child_event->total_time_running,
9085 &parent_event->child_total_time_running);
9088 * Remove this event from the parent's list
9090 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
9091 mutex_lock(&parent_event->child_mutex);
9092 list_del_init(&child_event->child_list);
9093 mutex_unlock(&parent_event->child_mutex);
9096 * Make sure user/parent get notified, that we just
9099 perf_event_wakeup(parent_event);
9102 * Release the parent event, if this was the last
9105 put_event(parent_event);
9109 __perf_event_exit_task(struct perf_event *child_event,
9110 struct perf_event_context *child_ctx,
9111 struct task_struct *child)
9114 * Do not destroy the 'original' grouping; because of the context
9115 * switch optimization the original events could've ended up in a
9116 * random child task.
9118 * If we were to destroy the original group, all group related
9119 * operations would cease to function properly after this random
9122 * Do destroy all inherited groups, we don't care about those
9123 * and being thorough is better.
9125 perf_remove_from_context(child_event, !!child_event->parent);
9128 * It can happen that the parent exits first, and has events
9129 * that are still around due to the child reference. These
9130 * events need to be zapped.
9132 if (child_event->parent) {
9133 sync_child_event(child_event, child);
9134 free_event(child_event);
9136 child_event->state = PERF_EVENT_STATE_EXIT;
9137 perf_event_wakeup(child_event);
9141 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
9143 struct perf_event *child_event, *next;
9144 struct perf_event_context *child_ctx, *clone_ctx = NULL;
9145 unsigned long flags;
9147 if (likely(!child->perf_event_ctxp[ctxn]))
9150 local_irq_save(flags);
9152 * We can't reschedule here because interrupts are disabled,
9153 * and either child is current or it is a task that can't be
9154 * scheduled, so we are now safe from rescheduling changing
9157 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
9160 * Take the context lock here so that if find_get_context is
9161 * reading child->perf_event_ctxp, we wait until it has
9162 * incremented the context's refcount before we do put_ctx below.
9164 raw_spin_lock(&child_ctx->lock);
9165 task_ctx_sched_out(child_ctx);
9166 child->perf_event_ctxp[ctxn] = NULL;
9169 * If this context is a clone; unclone it so it can't get
9170 * swapped to another process while we're removing all
9171 * the events from it.
9173 clone_ctx = unclone_ctx(child_ctx);
9174 update_context_time(child_ctx);
9175 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
9181 * Report the task dead after unscheduling the events so that we
9182 * won't get any samples after PERF_RECORD_EXIT. We can however still
9183 * get a few PERF_RECORD_READ events.
9185 perf_event_task(child, child_ctx, 0);
9188 * We can recurse on the same lock type through:
9190 * __perf_event_exit_task()
9191 * sync_child_event()
9193 * mutex_lock(&ctx->mutex)
9195 * But since its the parent context it won't be the same instance.
9197 mutex_lock(&child_ctx->mutex);
9199 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
9200 __perf_event_exit_task(child_event, child_ctx, child);
9202 mutex_unlock(&child_ctx->mutex);
9208 * When a child task exits, feed back event values to parent events.
9210 * Can be called with cred_guard_mutex held when called from
9211 * install_exec_creds().
9213 void perf_event_exit_task(struct task_struct *child)
9215 struct perf_event *event, *tmp;
9218 mutex_lock(&child->perf_event_mutex);
9219 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
9221 list_del_init(&event->owner_entry);
9224 * Ensure the list deletion is visible before we clear
9225 * the owner, closes a race against perf_release() where
9226 * we need to serialize on the owner->perf_event_mutex.
9229 event->owner = NULL;
9231 mutex_unlock(&child->perf_event_mutex);
9233 for_each_task_context_nr(ctxn)
9234 perf_event_exit_task_context(child, ctxn);
9237 * The perf_event_exit_task_context calls perf_event_task
9238 * with child's task_ctx, which generates EXIT events for
9239 * child contexts and sets child->perf_event_ctxp[] to NULL.
9240 * At this point we need to send EXIT events to cpu contexts.
9242 perf_event_task(child, NULL, 0);
9245 static void perf_free_event(struct perf_event *event,
9246 struct perf_event_context *ctx)
9248 struct perf_event *parent = event->parent;
9250 if (WARN_ON_ONCE(!parent))
9253 mutex_lock(&parent->child_mutex);
9254 list_del_init(&event->child_list);
9255 mutex_unlock(&parent->child_mutex);
9259 raw_spin_lock_irq(&ctx->lock);
9260 perf_group_detach(event);
9261 list_del_event(event, ctx);
9262 raw_spin_unlock_irq(&ctx->lock);
9267 * Free an unexposed, unused context as created by inheritance by
9268 * perf_event_init_task below, used by fork() in case of fail.
9270 * Not all locks are strictly required, but take them anyway to be nice and
9271 * help out with the lockdep assertions.
9273 void perf_event_free_task(struct task_struct *task)
9275 struct perf_event_context *ctx;
9276 struct perf_event *event, *tmp;
9279 for_each_task_context_nr(ctxn) {
9280 ctx = task->perf_event_ctxp[ctxn];
9284 mutex_lock(&ctx->mutex);
9286 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
9288 perf_free_event(event, ctx);
9290 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
9292 perf_free_event(event, ctx);
9294 if (!list_empty(&ctx->pinned_groups) ||
9295 !list_empty(&ctx->flexible_groups))
9298 mutex_unlock(&ctx->mutex);
9304 void perf_event_delayed_put(struct task_struct *task)
9308 for_each_task_context_nr(ctxn)
9309 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
9312 struct perf_event *perf_event_get(unsigned int fd)
9316 struct perf_event *event;
9318 err = perf_fget_light(fd, &f);
9320 return ERR_PTR(err);
9322 event = f.file->private_data;
9323 atomic_long_inc(&event->refcount);
9329 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
9332 return ERR_PTR(-EINVAL);
9334 return &event->attr;
9338 * inherit a event from parent task to child task:
9340 static struct perf_event *
9341 inherit_event(struct perf_event *parent_event,
9342 struct task_struct *parent,
9343 struct perf_event_context *parent_ctx,
9344 struct task_struct *child,
9345 struct perf_event *group_leader,
9346 struct perf_event_context *child_ctx)
9348 enum perf_event_active_state parent_state = parent_event->state;
9349 struct perf_event *child_event;
9350 unsigned long flags;
9353 * Instead of creating recursive hierarchies of events,
9354 * we link inherited events back to the original parent,
9355 * which has a filp for sure, which we use as the reference
9358 if (parent_event->parent)
9359 parent_event = parent_event->parent;
9361 child_event = perf_event_alloc(&parent_event->attr,
9364 group_leader, parent_event,
9366 if (IS_ERR(child_event))
9369 if (is_orphaned_event(parent_event) ||
9370 !atomic_long_inc_not_zero(&parent_event->refcount)) {
9371 free_event(child_event);
9378 * Make the child state follow the state of the parent event,
9379 * not its attr.disabled bit. We hold the parent's mutex,
9380 * so we won't race with perf_event_{en, dis}able_family.
9382 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
9383 child_event->state = PERF_EVENT_STATE_INACTIVE;
9385 child_event->state = PERF_EVENT_STATE_OFF;
9387 if (parent_event->attr.freq) {
9388 u64 sample_period = parent_event->hw.sample_period;
9389 struct hw_perf_event *hwc = &child_event->hw;
9391 hwc->sample_period = sample_period;
9392 hwc->last_period = sample_period;
9394 local64_set(&hwc->period_left, sample_period);
9397 child_event->ctx = child_ctx;
9398 child_event->overflow_handler = parent_event->overflow_handler;
9399 child_event->overflow_handler_context
9400 = parent_event->overflow_handler_context;
9403 * Precalculate sample_data sizes
9405 perf_event__header_size(child_event);
9406 perf_event__id_header_size(child_event);
9409 * Link it up in the child's context:
9411 raw_spin_lock_irqsave(&child_ctx->lock, flags);
9412 add_event_to_ctx(child_event, child_ctx);
9413 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
9416 * Link this into the parent event's child list
9418 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
9419 mutex_lock(&parent_event->child_mutex);
9420 list_add_tail(&child_event->child_list, &parent_event->child_list);
9421 mutex_unlock(&parent_event->child_mutex);
9426 static int inherit_group(struct perf_event *parent_event,
9427 struct task_struct *parent,
9428 struct perf_event_context *parent_ctx,
9429 struct task_struct *child,
9430 struct perf_event_context *child_ctx)
9432 struct perf_event *leader;
9433 struct perf_event *sub;
9434 struct perf_event *child_ctr;
9436 leader = inherit_event(parent_event, parent, parent_ctx,
9437 child, NULL, child_ctx);
9439 return PTR_ERR(leader);
9440 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
9441 child_ctr = inherit_event(sub, parent, parent_ctx,
9442 child, leader, child_ctx);
9443 if (IS_ERR(child_ctr))
9444 return PTR_ERR(child_ctr);
9450 inherit_task_group(struct perf_event *event, struct task_struct *parent,
9451 struct perf_event_context *parent_ctx,
9452 struct task_struct *child, int ctxn,
9456 struct perf_event_context *child_ctx;
9458 if (!event->attr.inherit) {
9463 child_ctx = child->perf_event_ctxp[ctxn];
9466 * This is executed from the parent task context, so
9467 * inherit events that have been marked for cloning.
9468 * First allocate and initialize a context for the
9472 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
9476 child->perf_event_ctxp[ctxn] = child_ctx;
9479 ret = inherit_group(event, parent, parent_ctx,
9489 * Initialize the perf_event context in task_struct
9491 static int perf_event_init_context(struct task_struct *child, int ctxn)
9493 struct perf_event_context *child_ctx, *parent_ctx;
9494 struct perf_event_context *cloned_ctx;
9495 struct perf_event *event;
9496 struct task_struct *parent = current;
9497 int inherited_all = 1;
9498 unsigned long flags;
9501 if (likely(!parent->perf_event_ctxp[ctxn]))
9505 * If the parent's context is a clone, pin it so it won't get
9508 parent_ctx = perf_pin_task_context(parent, ctxn);
9513 * No need to check if parent_ctx != NULL here; since we saw
9514 * it non-NULL earlier, the only reason for it to become NULL
9515 * is if we exit, and since we're currently in the middle of
9516 * a fork we can't be exiting at the same time.
9520 * Lock the parent list. No need to lock the child - not PID
9521 * hashed yet and not running, so nobody can access it.
9523 mutex_lock(&parent_ctx->mutex);
9526 * We dont have to disable NMIs - we are only looking at
9527 * the list, not manipulating it:
9529 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
9530 ret = inherit_task_group(event, parent, parent_ctx,
9531 child, ctxn, &inherited_all);
9537 * We can't hold ctx->lock when iterating the ->flexible_group list due
9538 * to allocations, but we need to prevent rotation because
9539 * rotate_ctx() will change the list from interrupt context.
9541 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9542 parent_ctx->rotate_disable = 1;
9543 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9545 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
9546 ret = inherit_task_group(event, parent, parent_ctx,
9547 child, ctxn, &inherited_all);
9552 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9553 parent_ctx->rotate_disable = 0;
9555 child_ctx = child->perf_event_ctxp[ctxn];
9557 if (child_ctx && inherited_all) {
9559 * Mark the child context as a clone of the parent
9560 * context, or of whatever the parent is a clone of.
9562 * Note that if the parent is a clone, the holding of
9563 * parent_ctx->lock avoids it from being uncloned.
9565 cloned_ctx = parent_ctx->parent_ctx;
9567 child_ctx->parent_ctx = cloned_ctx;
9568 child_ctx->parent_gen = parent_ctx->parent_gen;
9570 child_ctx->parent_ctx = parent_ctx;
9571 child_ctx->parent_gen = parent_ctx->generation;
9573 get_ctx(child_ctx->parent_ctx);
9576 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9578 mutex_unlock(&parent_ctx->mutex);
9580 perf_unpin_context(parent_ctx);
9581 put_ctx(parent_ctx);
9587 * Initialize the perf_event context in task_struct
9589 int perf_event_init_task(struct task_struct *child)
9593 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
9594 mutex_init(&child->perf_event_mutex);
9595 INIT_LIST_HEAD(&child->perf_event_list);
9597 for_each_task_context_nr(ctxn) {
9598 ret = perf_event_init_context(child, ctxn);
9600 perf_event_free_task(child);
9608 static void __init perf_event_init_all_cpus(void)
9610 struct swevent_htable *swhash;
9613 for_each_possible_cpu(cpu) {
9614 swhash = &per_cpu(swevent_htable, cpu);
9615 mutex_init(&swhash->hlist_mutex);
9616 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
9620 static void perf_event_init_cpu(int cpu)
9622 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9624 mutex_lock(&swhash->hlist_mutex);
9625 if (swhash->hlist_refcount > 0) {
9626 struct swevent_hlist *hlist;
9628 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
9630 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9632 mutex_unlock(&swhash->hlist_mutex);
9635 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
9636 static void __perf_event_exit_context(void *__info)
9638 struct remove_event re = { .detach_group = true };
9639 struct perf_event_context *ctx = __info;
9642 list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
9643 __perf_remove_from_context(&re);
9647 static void __perf_event_stop_swclock(void *__info)
9649 struct perf_event_context *ctx = __info;
9650 struct perf_event *event, *tmp;
9652 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) {
9653 if (event->attr.config == PERF_COUNT_SW_CPU_CLOCK &&
9654 event->attr.type == PERF_TYPE_SOFTWARE)
9655 cpu_clock_event_stop(event, 0);
9659 static void perf_event_exit_cpu_context(int cpu)
9661 struct perf_cpu_context *cpuctx;
9662 struct perf_event_context *ctx;
9663 unsigned long flags;
9667 idx = srcu_read_lock(&pmus_srcu);
9668 list_for_each_entry_rcu(pmu, &pmus, entry) {
9669 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
9672 /* Cancel the mux hrtimer to avoid CPU migration */
9673 if (pmu->task_ctx_nr != perf_sw_context) {
9674 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
9675 hrtimer_cancel(&cpuctx->hrtimer);
9676 cpuctx->hrtimer_active = 0;
9677 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock,
9681 mutex_lock(&ctx->mutex);
9683 * If keeping events across hotplugging is supported, do not
9684 * remove the event list, but keep it alive across CPU hotplug.
9685 * The context is exited via an fd close path when userspace
9686 * is done and the target CPU is online. If software clock
9687 * event is active, then stop hrtimer associated with it.
9688 * Start the timer when the CPU comes back online.
9690 if (!pmu->events_across_hotplug)
9691 smp_call_function_single(cpu, __perf_event_exit_context,
9694 smp_call_function_single(cpu, __perf_event_stop_swclock,
9696 mutex_unlock(&ctx->mutex);
9698 srcu_read_unlock(&pmus_srcu, idx);
9701 static void perf_event_start_swclock(int cpu)
9703 struct perf_event_context *ctx;
9706 struct perf_event *event, *tmp;
9708 idx = srcu_read_lock(&pmus_srcu);
9709 list_for_each_entry_rcu(pmu, &pmus, entry) {
9710 if (pmu->events_across_hotplug) {
9711 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
9712 list_for_each_entry_safe(event, tmp, &ctx->event_list,
9714 if (event->attr.config ==
9715 PERF_COUNT_SW_CPU_CLOCK &&
9716 event->attr.type == PERF_TYPE_SOFTWARE)
9717 cpu_clock_event_start(event, 0);
9721 srcu_read_unlock(&pmus_srcu, idx);
9724 static void perf_event_exit_cpu(int cpu)
9726 perf_event_exit_cpu_context(cpu);
9729 static inline void perf_event_exit_cpu(int cpu) { }
9730 static inline void perf_event_start_swclock(int cpu) { }
9734 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
9738 for_each_online_cpu(cpu)
9739 perf_event_exit_cpu(cpu);
9745 * Run the perf reboot notifier at the very last possible moment so that
9746 * the generic watchdog code runs as long as possible.
9748 static struct notifier_block perf_reboot_notifier = {
9749 .notifier_call = perf_reboot,
9750 .priority = INT_MIN,
9754 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
9756 unsigned int cpu = (long)hcpu;
9758 switch (action & ~CPU_TASKS_FROZEN) {
9760 case CPU_UP_PREPARE:
9761 case CPU_DOWN_FAILED:
9762 perf_event_init_cpu(cpu);
9765 case CPU_UP_CANCELED:
9766 case CPU_DOWN_PREPARE:
9767 perf_event_exit_cpu(cpu);
9771 perf_event_start_swclock(cpu);
9781 static int event_idle_notif(struct notifier_block *nb, unsigned long action,
9786 __this_cpu_write(is_idle, true);
9789 __this_cpu_write(is_idle, false);
9796 static struct notifier_block perf_event_idle_nb = {
9797 .notifier_call = event_idle_notif,
9800 void __init perf_event_init(void)
9806 perf_event_init_all_cpus();
9807 init_srcu_struct(&pmus_srcu);
9808 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
9809 perf_pmu_register(&perf_cpu_clock, NULL, -1);
9810 perf_pmu_register(&perf_task_clock, NULL, -1);
9812 perf_cpu_notifier(perf_cpu_notify);
9813 idle_notifier_register(&perf_event_idle_nb);
9814 register_reboot_notifier(&perf_reboot_notifier);
9816 ret = init_hw_breakpoint();
9817 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
9819 /* do not patch jump label more than once per second */
9820 jump_label_rate_limit(&perf_sched_events, HZ);
9823 * Build time assertion that we keep the data_head at the intended
9824 * location. IOW, validation we got the __reserved[] size right.
9826 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
9830 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
9833 struct perf_pmu_events_attr *pmu_attr =
9834 container_of(attr, struct perf_pmu_events_attr, attr);
9836 if (pmu_attr->event_str)
9837 return sprintf(page, "%s\n", pmu_attr->event_str);
9842 static int __init perf_event_sysfs_init(void)
9847 mutex_lock(&pmus_lock);
9849 ret = bus_register(&pmu_bus);
9853 list_for_each_entry(pmu, &pmus, entry) {
9854 if (!pmu->name || pmu->type < 0)
9857 ret = pmu_dev_alloc(pmu);
9858 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
9860 pmu_bus_running = 1;
9864 mutex_unlock(&pmus_lock);
9868 device_initcall(perf_event_sysfs_init);
9870 #ifdef CONFIG_CGROUP_PERF
9871 static struct cgroup_subsys_state *
9872 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
9874 struct perf_cgroup *jc;
9876 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
9878 return ERR_PTR(-ENOMEM);
9880 jc->info = alloc_percpu(struct perf_cgroup_info);
9883 return ERR_PTR(-ENOMEM);
9889 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
9891 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
9893 free_percpu(jc->info);
9897 static int __perf_cgroup_move(void *info)
9899 struct task_struct *task = info;
9901 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
9906 static void perf_cgroup_attach(struct cgroup_taskset *tset)
9908 struct task_struct *task;
9909 struct cgroup_subsys_state *css;
9911 cgroup_taskset_for_each(task, css, tset)
9912 task_function_call(task, __perf_cgroup_move, task);
9915 struct cgroup_subsys perf_event_cgrp_subsys = {
9916 .css_alloc = perf_cgroup_css_alloc,
9917 .css_free = perf_cgroup_css_free,
9918 .attach = perf_cgroup_attach,
9920 #endif /* CONFIG_CGROUP_PERF */