ALSA: seq: Fix copy_from_user() call inside lock
[linux/fpc-iii.git] / kernel / events / core.c
blob9b12efcefdf78a9955d53fe73d1a8e436f3d390e
1 /*
2 * Performance events core code:
4 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
5 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
6 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
7 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
9 * For licensing details see kernel-base/COPYING
12 #include <linux/fs.h>
13 #include <linux/mm.h>
14 #include <linux/cpu.h>
15 #include <linux/smp.h>
16 #include <linux/idr.h>
17 #include <linux/file.h>
18 #include <linux/poll.h>
19 #include <linux/slab.h>
20 #include <linux/hash.h>
21 #include <linux/tick.h>
22 #include <linux/sysfs.h>
23 #include <linux/dcache.h>
24 #include <linux/percpu.h>
25 #include <linux/ptrace.h>
26 #include <linux/reboot.h>
27 #include <linux/vmstat.h>
28 #include <linux/device.h>
29 #include <linux/export.h>
30 #include <linux/vmalloc.h>
31 #include <linux/hardirq.h>
32 #include <linux/rculist.h>
33 #include <linux/uaccess.h>
34 #include <linux/syscalls.h>
35 #include <linux/anon_inodes.h>
36 #include <linux/kernel_stat.h>
37 #include <linux/perf_event.h>
38 #include <linux/ftrace_event.h>
39 #include <linux/hw_breakpoint.h>
40 #include <linux/mm_types.h>
41 #include <linux/cgroup.h>
42 #include <linux/module.h>
43 #include <linux/mman.h>
44 #include <linux/compat.h>
46 #include "internal.h"
48 #include <asm/irq_regs.h>
50 static struct workqueue_struct *perf_wq;
52 struct remote_function_call {
53 struct task_struct *p;
54 int (*func)(void *info);
55 void *info;
56 int ret;
59 static void remote_function(void *data)
61 struct remote_function_call *tfc = data;
62 struct task_struct *p = tfc->p;
64 if (p) {
65 tfc->ret = -EAGAIN;
66 if (task_cpu(p) != smp_processor_id() || !task_curr(p))
67 return;
70 tfc->ret = tfc->func(tfc->info);
73 /**
74 * task_function_call - call a function on the cpu on which a task runs
75 * @p: the task to evaluate
76 * @func: the function to be called
77 * @info: the function call argument
79 * Calls the function @func when the task is currently running. This might
80 * be on the current CPU, which just calls the function directly
82 * returns: @func return value, or
83 * -ESRCH - when the process isn't running
84 * -EAGAIN - when the process moved away
86 static int
87 task_function_call(struct task_struct *p, int (*func) (void *info), void *info)
89 struct remote_function_call data = {
90 .p = p,
91 .func = func,
92 .info = info,
93 .ret = -ESRCH, /* No such (running) process */
96 if (task_curr(p))
97 smp_call_function_single(task_cpu(p), remote_function, &data, 1);
99 return data.ret;
103 * cpu_function_call - call a function on the cpu
104 * @func: the function to be called
105 * @info: the function call argument
107 * Calls the function @func on the remote cpu.
109 * returns: @func return value or -ENXIO when the cpu is offline
111 static int cpu_function_call(int cpu, int (*func) (void *info), void *info)
113 struct remote_function_call data = {
114 .p = NULL,
115 .func = func,
116 .info = info,
117 .ret = -ENXIO, /* No such CPU */
120 smp_call_function_single(cpu, remote_function, &data, 1);
122 return data.ret;
125 #define EVENT_OWNER_KERNEL ((void *) -1)
127 static bool is_kernel_event(struct perf_event *event)
129 return event->owner == EVENT_OWNER_KERNEL;
132 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
133 PERF_FLAG_FD_OUTPUT |\
134 PERF_FLAG_PID_CGROUP |\
135 PERF_FLAG_FD_CLOEXEC)
138 * branch priv levels that need permission checks
140 #define PERF_SAMPLE_BRANCH_PERM_PLM \
141 (PERF_SAMPLE_BRANCH_KERNEL |\
142 PERF_SAMPLE_BRANCH_HV)
144 enum event_type_t {
145 EVENT_FLEXIBLE = 0x1,
146 EVENT_PINNED = 0x2,
147 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
151 * perf_sched_events : >0 events exist
152 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
154 struct static_key_deferred perf_sched_events __read_mostly;
155 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
156 static DEFINE_PER_CPU(atomic_t, perf_branch_stack_events);
158 static atomic_t nr_mmap_events __read_mostly;
159 static atomic_t nr_comm_events __read_mostly;
160 static atomic_t nr_task_events __read_mostly;
161 static atomic_t nr_freq_events __read_mostly;
163 static LIST_HEAD(pmus);
164 static DEFINE_MUTEX(pmus_lock);
165 static struct srcu_struct pmus_srcu;
168 * perf event paranoia level:
169 * -1 - not paranoid at all
170 * 0 - disallow raw tracepoint access for unpriv
171 * 1 - disallow cpu events for unpriv
172 * 2 - disallow kernel profiling for unpriv
174 int sysctl_perf_event_paranoid __read_mostly = 1;
176 /* Minimum for 512 kiB + 1 user control page */
177 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
180 * max perf event sample rate
182 #define DEFAULT_MAX_SAMPLE_RATE 100000
183 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
184 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
186 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
188 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
189 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
191 static int perf_sample_allowed_ns __read_mostly =
192 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
194 void update_perf_cpu_limits(void)
196 u64 tmp = perf_sample_period_ns;
198 tmp *= sysctl_perf_cpu_time_max_percent;
199 do_div(tmp, 100);
200 ACCESS_ONCE(perf_sample_allowed_ns) = tmp;
203 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
205 int perf_proc_update_handler(struct ctl_table *table, int write,
206 void __user *buffer, size_t *lenp,
207 loff_t *ppos)
209 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
211 if (ret || !write)
212 return ret;
214 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
215 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
216 update_perf_cpu_limits();
218 return 0;
221 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
223 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
224 void __user *buffer, size_t *lenp,
225 loff_t *ppos)
227 int ret = proc_dointvec(table, write, buffer, lenp, ppos);
229 if (ret || !write)
230 return ret;
232 update_perf_cpu_limits();
234 return 0;
238 * perf samples are done in some very critical code paths (NMIs).
239 * If they take too much CPU time, the system can lock up and not
240 * get any real work done. This will drop the sample rate when
241 * we detect that events are taking too long.
243 #define NR_ACCUMULATED_SAMPLES 128
244 static DEFINE_PER_CPU(u64, running_sample_length);
246 static void perf_duration_warn(struct irq_work *w)
248 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
249 u64 avg_local_sample_len;
250 u64 local_samples_len;
252 local_samples_len = __this_cpu_read(running_sample_length);
253 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
255 printk_ratelimited(KERN_WARNING
256 "perf interrupt took too long (%lld > %lld), lowering "
257 "kernel.perf_event_max_sample_rate to %d\n",
258 avg_local_sample_len, allowed_ns >> 1,
259 sysctl_perf_event_sample_rate);
262 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
264 void perf_sample_event_took(u64 sample_len_ns)
266 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
267 u64 avg_local_sample_len;
268 u64 local_samples_len;
270 if (allowed_ns == 0)
271 return;
273 /* decay the counter by 1 average sample */
274 local_samples_len = __this_cpu_read(running_sample_length);
275 local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES;
276 local_samples_len += sample_len_ns;
277 __this_cpu_write(running_sample_length, local_samples_len);
280 * note: this will be biased artifically low until we have
281 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
282 * from having to maintain a count.
284 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
286 if (avg_local_sample_len <= allowed_ns)
287 return;
289 if (max_samples_per_tick <= 1)
290 return;
292 max_samples_per_tick = DIV_ROUND_UP(max_samples_per_tick, 2);
293 sysctl_perf_event_sample_rate = max_samples_per_tick * HZ;
294 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
296 update_perf_cpu_limits();
298 if (!irq_work_queue(&perf_duration_work)) {
299 early_printk("perf interrupt took too long (%lld > %lld), lowering "
300 "kernel.perf_event_max_sample_rate to %d\n",
301 avg_local_sample_len, allowed_ns >> 1,
302 sysctl_perf_event_sample_rate);
306 static atomic64_t perf_event_id;
308 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
309 enum event_type_t event_type);
311 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
312 enum event_type_t event_type,
313 struct task_struct *task);
315 static void update_context_time(struct perf_event_context *ctx);
316 static u64 perf_event_time(struct perf_event *event);
318 void __weak perf_event_print_debug(void) { }
320 extern __weak const char *perf_pmu_name(void)
322 return "pmu";
325 static inline u64 perf_clock(void)
327 return local_clock();
330 static inline struct perf_cpu_context *
331 __get_cpu_context(struct perf_event_context *ctx)
333 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
336 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
337 struct perf_event_context *ctx)
339 raw_spin_lock(&cpuctx->ctx.lock);
340 if (ctx)
341 raw_spin_lock(&ctx->lock);
344 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
345 struct perf_event_context *ctx)
347 if (ctx)
348 raw_spin_unlock(&ctx->lock);
349 raw_spin_unlock(&cpuctx->ctx.lock);
352 #ifdef CONFIG_CGROUP_PERF
355 * perf_cgroup_info keeps track of time_enabled for a cgroup.
356 * This is a per-cpu dynamically allocated data structure.
358 struct perf_cgroup_info {
359 u64 time;
360 u64 timestamp;
363 struct perf_cgroup {
364 struct cgroup_subsys_state css;
365 struct perf_cgroup_info __percpu *info;
369 * Must ensure cgroup is pinned (css_get) before calling
370 * this function. In other words, we cannot call this function
371 * if there is no cgroup event for the current CPU context.
373 static inline struct perf_cgroup *
374 perf_cgroup_from_task(struct task_struct *task)
376 return container_of(task_css(task, perf_event_cgrp_id),
377 struct perf_cgroup, css);
380 static inline bool
381 perf_cgroup_match(struct perf_event *event)
383 struct perf_event_context *ctx = event->ctx;
384 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
386 /* @event doesn't care about cgroup */
387 if (!event->cgrp)
388 return true;
390 /* wants specific cgroup scope but @cpuctx isn't associated with any */
391 if (!cpuctx->cgrp)
392 return false;
395 * Cgroup scoping is recursive. An event enabled for a cgroup is
396 * also enabled for all its descendant cgroups. If @cpuctx's
397 * cgroup is a descendant of @event's (the test covers identity
398 * case), it's a match.
400 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
401 event->cgrp->css.cgroup);
404 static inline void perf_detach_cgroup(struct perf_event *event)
406 css_put(&event->cgrp->css);
407 event->cgrp = NULL;
410 static inline int is_cgroup_event(struct perf_event *event)
412 return event->cgrp != NULL;
415 static inline u64 perf_cgroup_event_time(struct perf_event *event)
417 struct perf_cgroup_info *t;
419 t = per_cpu_ptr(event->cgrp->info, event->cpu);
420 return t->time;
423 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
425 struct perf_cgroup_info *info;
426 u64 now;
428 now = perf_clock();
430 info = this_cpu_ptr(cgrp->info);
432 info->time += now - info->timestamp;
433 info->timestamp = now;
436 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
438 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
439 if (cgrp_out)
440 __update_cgrp_time(cgrp_out);
443 static inline void update_cgrp_time_from_event(struct perf_event *event)
445 struct perf_cgroup *cgrp;
448 * ensure we access cgroup data only when needed and
449 * when we know the cgroup is pinned (css_get)
451 if (!is_cgroup_event(event))
452 return;
454 cgrp = perf_cgroup_from_task(current);
456 * Do not update time when cgroup is not active
458 if (cgrp == event->cgrp)
459 __update_cgrp_time(event->cgrp);
462 static inline void
463 perf_cgroup_set_timestamp(struct task_struct *task,
464 struct perf_event_context *ctx)
466 struct perf_cgroup *cgrp;
467 struct perf_cgroup_info *info;
470 * ctx->lock held by caller
471 * ensure we do not access cgroup data
472 * unless we have the cgroup pinned (css_get)
474 if (!task || !ctx->nr_cgroups)
475 return;
477 cgrp = perf_cgroup_from_task(task);
478 info = this_cpu_ptr(cgrp->info);
479 info->timestamp = ctx->timestamp;
482 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
483 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
486 * reschedule events based on the cgroup constraint of task.
488 * mode SWOUT : schedule out everything
489 * mode SWIN : schedule in based on cgroup for next
491 void perf_cgroup_switch(struct task_struct *task, int mode)
493 struct perf_cpu_context *cpuctx;
494 struct pmu *pmu;
495 unsigned long flags;
498 * disable interrupts to avoid geting nr_cgroup
499 * changes via __perf_event_disable(). Also
500 * avoids preemption.
502 local_irq_save(flags);
505 * we reschedule only in the presence of cgroup
506 * constrained events.
508 rcu_read_lock();
510 list_for_each_entry_rcu(pmu, &pmus, entry) {
511 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
512 if (cpuctx->unique_pmu != pmu)
513 continue; /* ensure we process each cpuctx once */
516 * perf_cgroup_events says at least one
517 * context on this CPU has cgroup events.
519 * ctx->nr_cgroups reports the number of cgroup
520 * events for a context.
522 if (cpuctx->ctx.nr_cgroups > 0) {
523 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
524 perf_pmu_disable(cpuctx->ctx.pmu);
526 if (mode & PERF_CGROUP_SWOUT) {
527 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
529 * must not be done before ctxswout due
530 * to event_filter_match() in event_sched_out()
532 cpuctx->cgrp = NULL;
535 if (mode & PERF_CGROUP_SWIN) {
536 WARN_ON_ONCE(cpuctx->cgrp);
538 * set cgrp before ctxsw in to allow
539 * event_filter_match() to not have to pass
540 * task around
542 cpuctx->cgrp = perf_cgroup_from_task(task);
543 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
545 perf_pmu_enable(cpuctx->ctx.pmu);
546 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
550 rcu_read_unlock();
552 local_irq_restore(flags);
555 static inline void perf_cgroup_sched_out(struct task_struct *task,
556 struct task_struct *next)
558 struct perf_cgroup *cgrp1;
559 struct perf_cgroup *cgrp2 = NULL;
562 * we come here when we know perf_cgroup_events > 0
564 cgrp1 = perf_cgroup_from_task(task);
567 * next is NULL when called from perf_event_enable_on_exec()
568 * that will systematically cause a cgroup_switch()
570 if (next)
571 cgrp2 = perf_cgroup_from_task(next);
574 * only schedule out current cgroup events if we know
575 * that we are switching to a different cgroup. Otherwise,
576 * do no touch the cgroup events.
578 if (cgrp1 != cgrp2)
579 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
582 static inline void perf_cgroup_sched_in(struct task_struct *prev,
583 struct task_struct *task)
585 struct perf_cgroup *cgrp1;
586 struct perf_cgroup *cgrp2 = NULL;
589 * we come here when we know perf_cgroup_events > 0
591 cgrp1 = perf_cgroup_from_task(task);
593 /* prev can never be NULL */
594 cgrp2 = perf_cgroup_from_task(prev);
597 * only need to schedule in cgroup events if we are changing
598 * cgroup during ctxsw. Cgroup events were not scheduled
599 * out of ctxsw out if that was not the case.
601 if (cgrp1 != cgrp2)
602 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
605 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
606 struct perf_event_attr *attr,
607 struct perf_event *group_leader)
609 struct perf_cgroup *cgrp;
610 struct cgroup_subsys_state *css;
611 struct fd f = fdget(fd);
612 int ret = 0;
614 if (!f.file)
615 return -EBADF;
617 css = css_tryget_online_from_dir(f.file->f_dentry,
618 &perf_event_cgrp_subsys);
619 if (IS_ERR(css)) {
620 ret = PTR_ERR(css);
621 goto out;
624 cgrp = container_of(css, struct perf_cgroup, css);
625 event->cgrp = cgrp;
628 * all events in a group must monitor
629 * the same cgroup because a task belongs
630 * to only one perf cgroup at a time
632 if (group_leader && group_leader->cgrp != cgrp) {
633 perf_detach_cgroup(event);
634 ret = -EINVAL;
636 out:
637 fdput(f);
638 return ret;
641 static inline void
642 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
644 struct perf_cgroup_info *t;
645 t = per_cpu_ptr(event->cgrp->info, event->cpu);
646 event->shadow_ctx_time = now - t->timestamp;
649 static inline void
650 perf_cgroup_defer_enabled(struct perf_event *event)
653 * when the current task's perf cgroup does not match
654 * the event's, we need to remember to call the
655 * perf_mark_enable() function the first time a task with
656 * a matching perf cgroup is scheduled in.
658 if (is_cgroup_event(event) && !perf_cgroup_match(event))
659 event->cgrp_defer_enabled = 1;
662 static inline void
663 perf_cgroup_mark_enabled(struct perf_event *event,
664 struct perf_event_context *ctx)
666 struct perf_event *sub;
667 u64 tstamp = perf_event_time(event);
669 if (!event->cgrp_defer_enabled)
670 return;
672 event->cgrp_defer_enabled = 0;
674 event->tstamp_enabled = tstamp - event->total_time_enabled;
675 list_for_each_entry(sub, &event->sibling_list, group_entry) {
676 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
677 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
678 sub->cgrp_defer_enabled = 0;
682 #else /* !CONFIG_CGROUP_PERF */
684 static inline bool
685 perf_cgroup_match(struct perf_event *event)
687 return true;
690 static inline void perf_detach_cgroup(struct perf_event *event)
693 static inline int is_cgroup_event(struct perf_event *event)
695 return 0;
698 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
700 return 0;
703 static inline void update_cgrp_time_from_event(struct perf_event *event)
707 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
711 static inline void perf_cgroup_sched_out(struct task_struct *task,
712 struct task_struct *next)
716 static inline void perf_cgroup_sched_in(struct task_struct *prev,
717 struct task_struct *task)
721 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
722 struct perf_event_attr *attr,
723 struct perf_event *group_leader)
725 return -EINVAL;
728 static inline void
729 perf_cgroup_set_timestamp(struct task_struct *task,
730 struct perf_event_context *ctx)
734 void
735 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
739 static inline void
740 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
744 static inline u64 perf_cgroup_event_time(struct perf_event *event)
746 return 0;
749 static inline void
750 perf_cgroup_defer_enabled(struct perf_event *event)
754 static inline void
755 perf_cgroup_mark_enabled(struct perf_event *event,
756 struct perf_event_context *ctx)
759 #endif
762 * set default to be dependent on timer tick just
763 * like original code
765 #define PERF_CPU_HRTIMER (1000 / HZ)
767 * function must be called with interrupts disbled
769 static enum hrtimer_restart perf_cpu_hrtimer_handler(struct hrtimer *hr)
771 struct perf_cpu_context *cpuctx;
772 enum hrtimer_restart ret = HRTIMER_NORESTART;
773 int rotations = 0;
775 WARN_ON(!irqs_disabled());
777 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
779 rotations = perf_rotate_context(cpuctx);
782 * arm timer if needed
784 if (rotations) {
785 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
786 ret = HRTIMER_RESTART;
789 return ret;
792 /* CPU is going down */
793 void perf_cpu_hrtimer_cancel(int cpu)
795 struct perf_cpu_context *cpuctx;
796 struct pmu *pmu;
797 unsigned long flags;
799 if (WARN_ON(cpu != smp_processor_id()))
800 return;
802 local_irq_save(flags);
804 rcu_read_lock();
806 list_for_each_entry_rcu(pmu, &pmus, entry) {
807 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
809 if (pmu->task_ctx_nr == perf_sw_context)
810 continue;
812 hrtimer_cancel(&cpuctx->hrtimer);
815 rcu_read_unlock();
817 local_irq_restore(flags);
820 static void __perf_cpu_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
822 struct hrtimer *hr = &cpuctx->hrtimer;
823 struct pmu *pmu = cpuctx->ctx.pmu;
824 int timer;
826 /* no multiplexing needed for SW PMU */
827 if (pmu->task_ctx_nr == perf_sw_context)
828 return;
831 * check default is sane, if not set then force to
832 * default interval (1/tick)
834 timer = pmu->hrtimer_interval_ms;
835 if (timer < 1)
836 timer = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
838 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
840 hrtimer_init(hr, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
841 hr->function = perf_cpu_hrtimer_handler;
844 static void perf_cpu_hrtimer_restart(struct perf_cpu_context *cpuctx)
846 struct hrtimer *hr = &cpuctx->hrtimer;
847 struct pmu *pmu = cpuctx->ctx.pmu;
849 /* not for SW PMU */
850 if (pmu->task_ctx_nr == perf_sw_context)
851 return;
853 if (hrtimer_active(hr))
854 return;
856 if (!hrtimer_callback_running(hr))
857 __hrtimer_start_range_ns(hr, cpuctx->hrtimer_interval,
858 0, HRTIMER_MODE_REL_PINNED, 0);
861 void perf_pmu_disable(struct pmu *pmu)
863 int *count = this_cpu_ptr(pmu->pmu_disable_count);
864 if (!(*count)++)
865 pmu->pmu_disable(pmu);
868 void perf_pmu_enable(struct pmu *pmu)
870 int *count = this_cpu_ptr(pmu->pmu_disable_count);
871 if (!--(*count))
872 pmu->pmu_enable(pmu);
875 static DEFINE_PER_CPU(struct list_head, rotation_list);
878 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
879 * because they're strictly cpu affine and rotate_start is called with IRQs
880 * disabled, while rotate_context is called from IRQ context.
882 static void perf_pmu_rotate_start(struct pmu *pmu)
884 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
885 struct list_head *head = this_cpu_ptr(&rotation_list);
887 WARN_ON(!irqs_disabled());
889 if (list_empty(&cpuctx->rotation_list))
890 list_add(&cpuctx->rotation_list, head);
893 static void get_ctx(struct perf_event_context *ctx)
895 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
898 static void put_ctx(struct perf_event_context *ctx)
900 if (atomic_dec_and_test(&ctx->refcount)) {
901 if (ctx->parent_ctx)
902 put_ctx(ctx->parent_ctx);
903 if (ctx->task)
904 put_task_struct(ctx->task);
905 kfree_rcu(ctx, rcu_head);
910 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
911 * perf_pmu_migrate_context() we need some magic.
913 * Those places that change perf_event::ctx will hold both
914 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
916 * Lock ordering is by mutex address. There is one other site where
917 * perf_event_context::mutex nests and that is put_event(). But remember that
918 * that is a parent<->child context relation, and migration does not affect
919 * children, therefore these two orderings should not interact.
921 * The change in perf_event::ctx does not affect children (as claimed above)
922 * because the sys_perf_event_open() case will install a new event and break
923 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
924 * concerned with cpuctx and that doesn't have children.
926 * The places that change perf_event::ctx will issue:
928 * perf_remove_from_context();
929 * synchronize_rcu();
930 * perf_install_in_context();
932 * to affect the change. The remove_from_context() + synchronize_rcu() should
933 * quiesce the event, after which we can install it in the new location. This
934 * means that only external vectors (perf_fops, prctl) can perturb the event
935 * while in transit. Therefore all such accessors should also acquire
936 * perf_event_context::mutex to serialize against this.
938 * However; because event->ctx can change while we're waiting to acquire
939 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
940 * function.
942 * Lock order:
943 * task_struct::perf_event_mutex
944 * perf_event_context::mutex
945 * perf_event_context::lock
946 * perf_event::child_mutex;
947 * perf_event::mmap_mutex
948 * mmap_sem
950 static struct perf_event_context *perf_event_ctx_lock(struct perf_event *event)
952 struct perf_event_context *ctx;
954 again:
955 rcu_read_lock();
956 ctx = ACCESS_ONCE(event->ctx);
957 if (!atomic_inc_not_zero(&ctx->refcount)) {
958 rcu_read_unlock();
959 goto again;
961 rcu_read_unlock();
963 mutex_lock(&ctx->mutex);
964 if (event->ctx != ctx) {
965 mutex_unlock(&ctx->mutex);
966 put_ctx(ctx);
967 goto again;
970 return ctx;
973 static void perf_event_ctx_unlock(struct perf_event *event,
974 struct perf_event_context *ctx)
976 mutex_unlock(&ctx->mutex);
977 put_ctx(ctx);
981 * This must be done under the ctx->lock, such as to serialize against
982 * context_equiv(), therefore we cannot call put_ctx() since that might end up
983 * calling scheduler related locks and ctx->lock nests inside those.
985 static __must_check struct perf_event_context *
986 unclone_ctx(struct perf_event_context *ctx)
988 struct perf_event_context *parent_ctx = ctx->parent_ctx;
990 lockdep_assert_held(&ctx->lock);
992 if (parent_ctx)
993 ctx->parent_ctx = NULL;
994 ctx->generation++;
996 return parent_ctx;
999 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1002 * only top level events have the pid namespace they were created in
1004 if (event->parent)
1005 event = event->parent;
1007 return task_tgid_nr_ns(p, event->ns);
1010 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1013 * only top level events have the pid namespace they were created in
1015 if (event->parent)
1016 event = event->parent;
1018 return task_pid_nr_ns(p, event->ns);
1022 * If we inherit events we want to return the parent event id
1023 * to userspace.
1025 static u64 primary_event_id(struct perf_event *event)
1027 u64 id = event->id;
1029 if (event->parent)
1030 id = event->parent->id;
1032 return id;
1036 * Get the perf_event_context for a task and lock it.
1037 * This has to cope with with the fact that until it is locked,
1038 * the context could get moved to another task.
1040 static struct perf_event_context *
1041 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1043 struct perf_event_context *ctx;
1045 retry:
1047 * One of the few rules of preemptible RCU is that one cannot do
1048 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1049 * part of the read side critical section was preemptible -- see
1050 * rcu_read_unlock_special().
1052 * Since ctx->lock nests under rq->lock we must ensure the entire read
1053 * side critical section is non-preemptible.
1055 preempt_disable();
1056 rcu_read_lock();
1057 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1058 if (ctx) {
1060 * If this context is a clone of another, it might
1061 * get swapped for another underneath us by
1062 * perf_event_task_sched_out, though the
1063 * rcu_read_lock() protects us from any context
1064 * getting freed. Lock the context and check if it
1065 * got swapped before we could get the lock, and retry
1066 * if so. If we locked the right context, then it
1067 * can't get swapped on us any more.
1069 raw_spin_lock_irqsave(&ctx->lock, *flags);
1070 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1071 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
1072 rcu_read_unlock();
1073 preempt_enable();
1074 goto retry;
1077 if (!atomic_inc_not_zero(&ctx->refcount)) {
1078 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
1079 ctx = NULL;
1082 rcu_read_unlock();
1083 preempt_enable();
1084 return ctx;
1088 * Get the context for a task and increment its pin_count so it
1089 * can't get swapped to another task. This also increments its
1090 * reference count so that the context can't get freed.
1092 static struct perf_event_context *
1093 perf_pin_task_context(struct task_struct *task, int ctxn)
1095 struct perf_event_context *ctx;
1096 unsigned long flags;
1098 ctx = perf_lock_task_context(task, ctxn, &flags);
1099 if (ctx) {
1100 ++ctx->pin_count;
1101 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1103 return ctx;
1106 static void perf_unpin_context(struct perf_event_context *ctx)
1108 unsigned long flags;
1110 raw_spin_lock_irqsave(&ctx->lock, flags);
1111 --ctx->pin_count;
1112 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1116 * Update the record of the current time in a context.
1118 static void update_context_time(struct perf_event_context *ctx)
1120 u64 now = perf_clock();
1122 ctx->time += now - ctx->timestamp;
1123 ctx->timestamp = now;
1126 static u64 perf_event_time(struct perf_event *event)
1128 struct perf_event_context *ctx = event->ctx;
1130 if (is_cgroup_event(event))
1131 return perf_cgroup_event_time(event);
1133 return ctx ? ctx->time : 0;
1137 * Update the total_time_enabled and total_time_running fields for a event.
1138 * The caller of this function needs to hold the ctx->lock.
1140 static void update_event_times(struct perf_event *event)
1142 struct perf_event_context *ctx = event->ctx;
1143 u64 run_end;
1145 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1146 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1147 return;
1149 * in cgroup mode, time_enabled represents
1150 * the time the event was enabled AND active
1151 * tasks were in the monitored cgroup. This is
1152 * independent of the activity of the context as
1153 * there may be a mix of cgroup and non-cgroup events.
1155 * That is why we treat cgroup events differently
1156 * here.
1158 if (is_cgroup_event(event))
1159 run_end = perf_cgroup_event_time(event);
1160 else if (ctx->is_active)
1161 run_end = ctx->time;
1162 else
1163 run_end = event->tstamp_stopped;
1165 event->total_time_enabled = run_end - event->tstamp_enabled;
1167 if (event->state == PERF_EVENT_STATE_INACTIVE)
1168 run_end = event->tstamp_stopped;
1169 else
1170 run_end = perf_event_time(event);
1172 event->total_time_running = run_end - event->tstamp_running;
1177 * Update total_time_enabled and total_time_running for all events in a group.
1179 static void update_group_times(struct perf_event *leader)
1181 struct perf_event *event;
1183 update_event_times(leader);
1184 list_for_each_entry(event, &leader->sibling_list, group_entry)
1185 update_event_times(event);
1188 static struct list_head *
1189 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1191 if (event->attr.pinned)
1192 return &ctx->pinned_groups;
1193 else
1194 return &ctx->flexible_groups;
1198 * Add a event from the lists for its context.
1199 * Must be called with ctx->mutex and ctx->lock held.
1201 static void
1202 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1204 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1205 event->attach_state |= PERF_ATTACH_CONTEXT;
1208 * If we're a stand alone event or group leader, we go to the context
1209 * list, group events are kept attached to the group so that
1210 * perf_group_detach can, at all times, locate all siblings.
1212 if (event->group_leader == event) {
1213 struct list_head *list;
1215 if (is_software_event(event))
1216 event->group_flags |= PERF_GROUP_SOFTWARE;
1218 list = ctx_group_list(event, ctx);
1219 list_add_tail(&event->group_entry, list);
1222 if (is_cgroup_event(event))
1223 ctx->nr_cgroups++;
1225 if (has_branch_stack(event))
1226 ctx->nr_branch_stack++;
1228 list_add_rcu(&event->event_entry, &ctx->event_list);
1229 if (!ctx->nr_events)
1230 perf_pmu_rotate_start(ctx->pmu);
1231 ctx->nr_events++;
1232 if (event->attr.inherit_stat)
1233 ctx->nr_stat++;
1235 ctx->generation++;
1239 * Initialize event state based on the perf_event_attr::disabled.
1241 static inline void perf_event__state_init(struct perf_event *event)
1243 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1244 PERF_EVENT_STATE_INACTIVE;
1248 * Called at perf_event creation and when events are attached/detached from a
1249 * group.
1251 static void perf_event__read_size(struct perf_event *event)
1253 int entry = sizeof(u64); /* value */
1254 int size = 0;
1255 int nr = 1;
1257 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1258 size += sizeof(u64);
1260 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1261 size += sizeof(u64);
1263 if (event->attr.read_format & PERF_FORMAT_ID)
1264 entry += sizeof(u64);
1266 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1267 nr += event->group_leader->nr_siblings;
1268 size += sizeof(u64);
1271 size += entry * nr;
1272 event->read_size = size;
1275 static void perf_event__header_size(struct perf_event *event)
1277 struct perf_sample_data *data;
1278 u64 sample_type = event->attr.sample_type;
1279 u16 size = 0;
1281 perf_event__read_size(event);
1283 if (sample_type & PERF_SAMPLE_IP)
1284 size += sizeof(data->ip);
1286 if (sample_type & PERF_SAMPLE_ADDR)
1287 size += sizeof(data->addr);
1289 if (sample_type & PERF_SAMPLE_PERIOD)
1290 size += sizeof(data->period);
1292 if (sample_type & PERF_SAMPLE_WEIGHT)
1293 size += sizeof(data->weight);
1295 if (sample_type & PERF_SAMPLE_READ)
1296 size += event->read_size;
1298 if (sample_type & PERF_SAMPLE_DATA_SRC)
1299 size += sizeof(data->data_src.val);
1301 if (sample_type & PERF_SAMPLE_TRANSACTION)
1302 size += sizeof(data->txn);
1304 event->header_size = size;
1307 static void perf_event__id_header_size(struct perf_event *event)
1309 struct perf_sample_data *data;
1310 u64 sample_type = event->attr.sample_type;
1311 u16 size = 0;
1313 if (sample_type & PERF_SAMPLE_TID)
1314 size += sizeof(data->tid_entry);
1316 if (sample_type & PERF_SAMPLE_TIME)
1317 size += sizeof(data->time);
1319 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1320 size += sizeof(data->id);
1322 if (sample_type & PERF_SAMPLE_ID)
1323 size += sizeof(data->id);
1325 if (sample_type & PERF_SAMPLE_STREAM_ID)
1326 size += sizeof(data->stream_id);
1328 if (sample_type & PERF_SAMPLE_CPU)
1329 size += sizeof(data->cpu_entry);
1331 event->id_header_size = size;
1334 static void perf_group_attach(struct perf_event *event)
1336 struct perf_event *group_leader = event->group_leader, *pos;
1339 * We can have double attach due to group movement in perf_event_open.
1341 if (event->attach_state & PERF_ATTACH_GROUP)
1342 return;
1344 event->attach_state |= PERF_ATTACH_GROUP;
1346 if (group_leader == event)
1347 return;
1349 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1350 !is_software_event(event))
1351 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1353 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1354 group_leader->nr_siblings++;
1356 perf_event__header_size(group_leader);
1358 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1359 perf_event__header_size(pos);
1363 * Remove a event from the lists for its context.
1364 * Must be called with ctx->mutex and ctx->lock held.
1366 static void
1367 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1369 struct perf_cpu_context *cpuctx;
1371 * We can have double detach due to exit/hot-unplug + close.
1373 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1374 return;
1376 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1378 if (is_cgroup_event(event)) {
1379 ctx->nr_cgroups--;
1380 cpuctx = __get_cpu_context(ctx);
1382 * if there are no more cgroup events
1383 * then cler cgrp to avoid stale pointer
1384 * in update_cgrp_time_from_cpuctx()
1386 if (!ctx->nr_cgroups)
1387 cpuctx->cgrp = NULL;
1390 if (has_branch_stack(event))
1391 ctx->nr_branch_stack--;
1393 ctx->nr_events--;
1394 if (event->attr.inherit_stat)
1395 ctx->nr_stat--;
1397 list_del_rcu(&event->event_entry);
1399 if (event->group_leader == event)
1400 list_del_init(&event->group_entry);
1402 update_group_times(event);
1405 * If event was in error state, then keep it
1406 * that way, otherwise bogus counts will be
1407 * returned on read(). The only way to get out
1408 * of error state is by explicit re-enabling
1409 * of the event
1411 if (event->state > PERF_EVENT_STATE_OFF)
1412 event->state = PERF_EVENT_STATE_OFF;
1414 ctx->generation++;
1417 static void perf_group_detach(struct perf_event *event)
1419 struct perf_event *sibling, *tmp;
1420 struct list_head *list = NULL;
1423 * We can have double detach due to exit/hot-unplug + close.
1425 if (!(event->attach_state & PERF_ATTACH_GROUP))
1426 return;
1428 event->attach_state &= ~PERF_ATTACH_GROUP;
1431 * If this is a sibling, remove it from its group.
1433 if (event->group_leader != event) {
1434 list_del_init(&event->group_entry);
1435 event->group_leader->nr_siblings--;
1436 goto out;
1439 if (!list_empty(&event->group_entry))
1440 list = &event->group_entry;
1443 * If this was a group event with sibling events then
1444 * upgrade the siblings to singleton events by adding them
1445 * to whatever list we are on.
1447 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1448 if (list)
1449 list_move_tail(&sibling->group_entry, list);
1450 sibling->group_leader = sibling;
1452 /* Inherit group flags from the previous leader */
1453 sibling->group_flags = event->group_flags;
1456 out:
1457 perf_event__header_size(event->group_leader);
1459 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1460 perf_event__header_size(tmp);
1464 * User event without the task.
1466 static bool is_orphaned_event(struct perf_event *event)
1468 return event && !is_kernel_event(event) && !event->owner;
1472 * Event has a parent but parent's task finished and it's
1473 * alive only because of children holding refference.
1475 static bool is_orphaned_child(struct perf_event *event)
1477 return is_orphaned_event(event->parent);
1480 static void orphans_remove_work(struct work_struct *work);
1482 static void schedule_orphans_remove(struct perf_event_context *ctx)
1484 if (!ctx->task || ctx->orphans_remove_sched || !perf_wq)
1485 return;
1487 if (queue_delayed_work(perf_wq, &ctx->orphans_remove, 1)) {
1488 get_ctx(ctx);
1489 ctx->orphans_remove_sched = true;
1493 static int __init perf_workqueue_init(void)
1495 perf_wq = create_singlethread_workqueue("perf");
1496 WARN(!perf_wq, "failed to create perf workqueue\n");
1497 return perf_wq ? 0 : -1;
1500 core_initcall(perf_workqueue_init);
1502 static inline int
1503 event_filter_match(struct perf_event *event)
1505 return (event->cpu == -1 || event->cpu == smp_processor_id())
1506 && perf_cgroup_match(event);
1509 static void
1510 event_sched_out(struct perf_event *event,
1511 struct perf_cpu_context *cpuctx,
1512 struct perf_event_context *ctx)
1514 u64 tstamp = perf_event_time(event);
1515 u64 delta;
1517 * An event which could not be activated because of
1518 * filter mismatch still needs to have its timings
1519 * maintained, otherwise bogus information is return
1520 * via read() for time_enabled, time_running:
1522 if (event->state == PERF_EVENT_STATE_INACTIVE
1523 && !event_filter_match(event)) {
1524 delta = tstamp - event->tstamp_stopped;
1525 event->tstamp_running += delta;
1526 event->tstamp_stopped = tstamp;
1529 if (event->state != PERF_EVENT_STATE_ACTIVE)
1530 return;
1532 perf_pmu_disable(event->pmu);
1534 event->state = PERF_EVENT_STATE_INACTIVE;
1535 if (event->pending_disable) {
1536 event->pending_disable = 0;
1537 event->state = PERF_EVENT_STATE_OFF;
1539 event->tstamp_stopped = tstamp;
1540 event->pmu->del(event, 0);
1541 event->oncpu = -1;
1543 if (!is_software_event(event))
1544 cpuctx->active_oncpu--;
1545 ctx->nr_active--;
1546 if (event->attr.freq && event->attr.sample_freq)
1547 ctx->nr_freq--;
1548 if (event->attr.exclusive || !cpuctx->active_oncpu)
1549 cpuctx->exclusive = 0;
1551 if (is_orphaned_child(event))
1552 schedule_orphans_remove(ctx);
1554 perf_pmu_enable(event->pmu);
1557 static void
1558 group_sched_out(struct perf_event *group_event,
1559 struct perf_cpu_context *cpuctx,
1560 struct perf_event_context *ctx)
1562 struct perf_event *event;
1563 int state = group_event->state;
1565 event_sched_out(group_event, cpuctx, ctx);
1568 * Schedule out siblings (if any):
1570 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1571 event_sched_out(event, cpuctx, ctx);
1573 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1574 cpuctx->exclusive = 0;
1577 struct remove_event {
1578 struct perf_event *event;
1579 bool detach_group;
1583 * Cross CPU call to remove a performance event
1585 * We disable the event on the hardware level first. After that we
1586 * remove it from the context list.
1588 static int __perf_remove_from_context(void *info)
1590 struct remove_event *re = info;
1591 struct perf_event *event = re->event;
1592 struct perf_event_context *ctx = event->ctx;
1593 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1595 raw_spin_lock(&ctx->lock);
1596 event_sched_out(event, cpuctx, ctx);
1597 if (re->detach_group)
1598 perf_group_detach(event);
1599 list_del_event(event, ctx);
1600 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1601 ctx->is_active = 0;
1602 cpuctx->task_ctx = NULL;
1604 raw_spin_unlock(&ctx->lock);
1606 return 0;
1611 * Remove the event from a task's (or a CPU's) list of events.
1613 * CPU events are removed with a smp call. For task events we only
1614 * call when the task is on a CPU.
1616 * If event->ctx is a cloned context, callers must make sure that
1617 * every task struct that event->ctx->task could possibly point to
1618 * remains valid. This is OK when called from perf_release since
1619 * that only calls us on the top-level context, which can't be a clone.
1620 * When called from perf_event_exit_task, it's OK because the
1621 * context has been detached from its task.
1623 static void perf_remove_from_context(struct perf_event *event, bool detach_group)
1625 struct perf_event_context *ctx = event->ctx;
1626 struct task_struct *task = ctx->task;
1627 struct remove_event re = {
1628 .event = event,
1629 .detach_group = detach_group,
1632 lockdep_assert_held(&ctx->mutex);
1634 if (!task) {
1636 * Per cpu events are removed via an smp call. The removal can
1637 * fail if the CPU is currently offline, but in that case we
1638 * already called __perf_remove_from_context from
1639 * perf_event_exit_cpu.
1641 cpu_function_call(event->cpu, __perf_remove_from_context, &re);
1642 return;
1645 retry:
1646 if (!task_function_call(task, __perf_remove_from_context, &re))
1647 return;
1649 raw_spin_lock_irq(&ctx->lock);
1651 * If we failed to find a running task, but find the context active now
1652 * that we've acquired the ctx->lock, retry.
1654 if (ctx->is_active) {
1655 raw_spin_unlock_irq(&ctx->lock);
1657 * Reload the task pointer, it might have been changed by
1658 * a concurrent perf_event_context_sched_out().
1660 task = ctx->task;
1661 goto retry;
1665 * Since the task isn't running, its safe to remove the event, us
1666 * holding the ctx->lock ensures the task won't get scheduled in.
1668 if (detach_group)
1669 perf_group_detach(event);
1670 list_del_event(event, ctx);
1671 raw_spin_unlock_irq(&ctx->lock);
1675 * Cross CPU call to disable a performance event
1677 int __perf_event_disable(void *info)
1679 struct perf_event *event = info;
1680 struct perf_event_context *ctx = event->ctx;
1681 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1684 * If this is a per-task event, need to check whether this
1685 * event's task is the current task on this cpu.
1687 * Can trigger due to concurrent perf_event_context_sched_out()
1688 * flipping contexts around.
1690 if (ctx->task && cpuctx->task_ctx != ctx)
1691 return -EINVAL;
1693 raw_spin_lock(&ctx->lock);
1696 * If the event is on, turn it off.
1697 * If it is in error state, leave it in error state.
1699 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1700 update_context_time(ctx);
1701 update_cgrp_time_from_event(event);
1702 update_group_times(event);
1703 if (event == event->group_leader)
1704 group_sched_out(event, cpuctx, ctx);
1705 else
1706 event_sched_out(event, cpuctx, ctx);
1707 event->state = PERF_EVENT_STATE_OFF;
1710 raw_spin_unlock(&ctx->lock);
1712 return 0;
1716 * Disable a event.
1718 * If event->ctx is a cloned context, callers must make sure that
1719 * every task struct that event->ctx->task could possibly point to
1720 * remains valid. This condition is satisifed when called through
1721 * perf_event_for_each_child or perf_event_for_each because they
1722 * hold the top-level event's child_mutex, so any descendant that
1723 * goes to exit will block in sync_child_event.
1724 * When called from perf_pending_event it's OK because event->ctx
1725 * is the current context on this CPU and preemption is disabled,
1726 * hence we can't get into perf_event_task_sched_out for this context.
1728 static void _perf_event_disable(struct perf_event *event)
1730 struct perf_event_context *ctx = event->ctx;
1731 struct task_struct *task = ctx->task;
1733 if (!task) {
1735 * Disable the event on the cpu that it's on
1737 cpu_function_call(event->cpu, __perf_event_disable, event);
1738 return;
1741 retry:
1742 if (!task_function_call(task, __perf_event_disable, event))
1743 return;
1745 raw_spin_lock_irq(&ctx->lock);
1747 * If the event is still active, we need to retry the cross-call.
1749 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1750 raw_spin_unlock_irq(&ctx->lock);
1752 * Reload the task pointer, it might have been changed by
1753 * a concurrent perf_event_context_sched_out().
1755 task = ctx->task;
1756 goto retry;
1760 * Since we have the lock this context can't be scheduled
1761 * in, so we can change the state safely.
1763 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1764 update_group_times(event);
1765 event->state = PERF_EVENT_STATE_OFF;
1767 raw_spin_unlock_irq(&ctx->lock);
1771 * Strictly speaking kernel users cannot create groups and therefore this
1772 * interface does not need the perf_event_ctx_lock() magic.
1774 void perf_event_disable(struct perf_event *event)
1776 struct perf_event_context *ctx;
1778 ctx = perf_event_ctx_lock(event);
1779 _perf_event_disable(event);
1780 perf_event_ctx_unlock(event, ctx);
1782 EXPORT_SYMBOL_GPL(perf_event_disable);
1784 static void perf_set_shadow_time(struct perf_event *event,
1785 struct perf_event_context *ctx,
1786 u64 tstamp)
1789 * use the correct time source for the time snapshot
1791 * We could get by without this by leveraging the
1792 * fact that to get to this function, the caller
1793 * has most likely already called update_context_time()
1794 * and update_cgrp_time_xx() and thus both timestamp
1795 * are identical (or very close). Given that tstamp is,
1796 * already adjusted for cgroup, we could say that:
1797 * tstamp - ctx->timestamp
1798 * is equivalent to
1799 * tstamp - cgrp->timestamp.
1801 * Then, in perf_output_read(), the calculation would
1802 * work with no changes because:
1803 * - event is guaranteed scheduled in
1804 * - no scheduled out in between
1805 * - thus the timestamp would be the same
1807 * But this is a bit hairy.
1809 * So instead, we have an explicit cgroup call to remain
1810 * within the time time source all along. We believe it
1811 * is cleaner and simpler to understand.
1813 if (is_cgroup_event(event))
1814 perf_cgroup_set_shadow_time(event, tstamp);
1815 else
1816 event->shadow_ctx_time = tstamp - ctx->timestamp;
1819 #define MAX_INTERRUPTS (~0ULL)
1821 static void perf_log_throttle(struct perf_event *event, int enable);
1823 static int
1824 event_sched_in(struct perf_event *event,
1825 struct perf_cpu_context *cpuctx,
1826 struct perf_event_context *ctx)
1828 u64 tstamp = perf_event_time(event);
1829 int ret = 0;
1831 lockdep_assert_held(&ctx->lock);
1833 if (event->state <= PERF_EVENT_STATE_OFF)
1834 return 0;
1836 event->state = PERF_EVENT_STATE_ACTIVE;
1837 event->oncpu = smp_processor_id();
1840 * Unthrottle events, since we scheduled we might have missed several
1841 * ticks already, also for a heavily scheduling task there is little
1842 * guarantee it'll get a tick in a timely manner.
1844 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1845 perf_log_throttle(event, 1);
1846 event->hw.interrupts = 0;
1850 * The new state must be visible before we turn it on in the hardware:
1852 smp_wmb();
1854 perf_pmu_disable(event->pmu);
1856 if (event->pmu->add(event, PERF_EF_START)) {
1857 event->state = PERF_EVENT_STATE_INACTIVE;
1858 event->oncpu = -1;
1859 ret = -EAGAIN;
1860 goto out;
1863 event->tstamp_running += tstamp - event->tstamp_stopped;
1865 perf_set_shadow_time(event, ctx, tstamp);
1867 if (!is_software_event(event))
1868 cpuctx->active_oncpu++;
1869 ctx->nr_active++;
1870 if (event->attr.freq && event->attr.sample_freq)
1871 ctx->nr_freq++;
1873 if (event->attr.exclusive)
1874 cpuctx->exclusive = 1;
1876 if (is_orphaned_child(event))
1877 schedule_orphans_remove(ctx);
1879 out:
1880 perf_pmu_enable(event->pmu);
1882 return ret;
1885 static int
1886 group_sched_in(struct perf_event *group_event,
1887 struct perf_cpu_context *cpuctx,
1888 struct perf_event_context *ctx)
1890 struct perf_event *event, *partial_group = NULL;
1891 struct pmu *pmu = ctx->pmu;
1892 u64 now = ctx->time;
1893 bool simulate = false;
1895 if (group_event->state == PERF_EVENT_STATE_OFF)
1896 return 0;
1898 pmu->start_txn(pmu);
1900 if (event_sched_in(group_event, cpuctx, ctx)) {
1901 pmu->cancel_txn(pmu);
1902 perf_cpu_hrtimer_restart(cpuctx);
1903 return -EAGAIN;
1907 * Schedule in siblings as one group (if any):
1909 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1910 if (event_sched_in(event, cpuctx, ctx)) {
1911 partial_group = event;
1912 goto group_error;
1916 if (!pmu->commit_txn(pmu))
1917 return 0;
1919 group_error:
1921 * Groups can be scheduled in as one unit only, so undo any
1922 * partial group before returning:
1923 * The events up to the failed event are scheduled out normally,
1924 * tstamp_stopped will be updated.
1926 * The failed events and the remaining siblings need to have
1927 * their timings updated as if they had gone thru event_sched_in()
1928 * and event_sched_out(). This is required to get consistent timings
1929 * across the group. This also takes care of the case where the group
1930 * could never be scheduled by ensuring tstamp_stopped is set to mark
1931 * the time the event was actually stopped, such that time delta
1932 * calculation in update_event_times() is correct.
1934 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1935 if (event == partial_group)
1936 simulate = true;
1938 if (simulate) {
1939 event->tstamp_running += now - event->tstamp_stopped;
1940 event->tstamp_stopped = now;
1941 } else {
1942 event_sched_out(event, cpuctx, ctx);
1945 event_sched_out(group_event, cpuctx, ctx);
1947 pmu->cancel_txn(pmu);
1949 perf_cpu_hrtimer_restart(cpuctx);
1951 return -EAGAIN;
1955 * Work out whether we can put this event group on the CPU now.
1957 static int group_can_go_on(struct perf_event *event,
1958 struct perf_cpu_context *cpuctx,
1959 int can_add_hw)
1962 * Groups consisting entirely of software events can always go on.
1964 if (event->group_flags & PERF_GROUP_SOFTWARE)
1965 return 1;
1967 * If an exclusive group is already on, no other hardware
1968 * events can go on.
1970 if (cpuctx->exclusive)
1971 return 0;
1973 * If this group is exclusive and there are already
1974 * events on the CPU, it can't go on.
1976 if (event->attr.exclusive && cpuctx->active_oncpu)
1977 return 0;
1979 * Otherwise, try to add it if all previous groups were able
1980 * to go on.
1982 return can_add_hw;
1985 static void add_event_to_ctx(struct perf_event *event,
1986 struct perf_event_context *ctx)
1988 u64 tstamp = perf_event_time(event);
1990 list_add_event(event, ctx);
1991 perf_group_attach(event);
1992 event->tstamp_enabled = tstamp;
1993 event->tstamp_running = tstamp;
1994 event->tstamp_stopped = tstamp;
1997 static void task_ctx_sched_out(struct perf_event_context *ctx);
1998 static void
1999 ctx_sched_in(struct perf_event_context *ctx,
2000 struct perf_cpu_context *cpuctx,
2001 enum event_type_t event_type,
2002 struct task_struct *task);
2004 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2005 struct perf_event_context *ctx,
2006 struct task_struct *task)
2008 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2009 if (ctx)
2010 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2011 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2012 if (ctx)
2013 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2017 * Cross CPU call to install and enable a performance event
2019 * Must be called with ctx->mutex held
2021 static int __perf_install_in_context(void *info)
2023 struct perf_event *event = info;
2024 struct perf_event_context *ctx = event->ctx;
2025 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2026 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2027 struct task_struct *task = current;
2029 perf_ctx_lock(cpuctx, task_ctx);
2030 perf_pmu_disable(cpuctx->ctx.pmu);
2033 * If there was an active task_ctx schedule it out.
2035 if (task_ctx)
2036 task_ctx_sched_out(task_ctx);
2039 * If the context we're installing events in is not the
2040 * active task_ctx, flip them.
2042 if (ctx->task && task_ctx != ctx) {
2043 if (task_ctx)
2044 raw_spin_unlock(&task_ctx->lock);
2045 raw_spin_lock(&ctx->lock);
2046 task_ctx = ctx;
2049 if (task_ctx) {
2050 cpuctx->task_ctx = task_ctx;
2051 task = task_ctx->task;
2054 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
2056 update_context_time(ctx);
2058 * update cgrp time only if current cgrp
2059 * matches event->cgrp. Must be done before
2060 * calling add_event_to_ctx()
2062 update_cgrp_time_from_event(event);
2064 add_event_to_ctx(event, ctx);
2067 * Schedule everything back in
2069 perf_event_sched_in(cpuctx, task_ctx, task);
2071 perf_pmu_enable(cpuctx->ctx.pmu);
2072 perf_ctx_unlock(cpuctx, task_ctx);
2074 return 0;
2078 * Attach a performance event to a context
2080 * First we add the event to the list with the hardware enable bit
2081 * in event->hw_config cleared.
2083 * If the event is attached to a task which is on a CPU we use a smp
2084 * call to enable it in the task context. The task might have been
2085 * scheduled away, but we check this in the smp call again.
2087 static void
2088 perf_install_in_context(struct perf_event_context *ctx,
2089 struct perf_event *event,
2090 int cpu)
2092 struct task_struct *task = ctx->task;
2094 lockdep_assert_held(&ctx->mutex);
2096 event->ctx = ctx;
2097 if (event->cpu != -1)
2098 event->cpu = cpu;
2100 if (!task) {
2102 * Per cpu events are installed via an smp call and
2103 * the install is always successful.
2105 cpu_function_call(cpu, __perf_install_in_context, event);
2106 return;
2109 retry:
2110 if (!task_function_call(task, __perf_install_in_context, event))
2111 return;
2113 raw_spin_lock_irq(&ctx->lock);
2115 * If we failed to find a running task, but find the context active now
2116 * that we've acquired the ctx->lock, retry.
2118 if (ctx->is_active) {
2119 raw_spin_unlock_irq(&ctx->lock);
2121 * Reload the task pointer, it might have been changed by
2122 * a concurrent perf_event_context_sched_out().
2124 task = ctx->task;
2125 goto retry;
2129 * Since the task isn't running, its safe to add the event, us holding
2130 * the ctx->lock ensures the task won't get scheduled in.
2132 add_event_to_ctx(event, ctx);
2133 raw_spin_unlock_irq(&ctx->lock);
2137 * Put a event into inactive state and update time fields.
2138 * Enabling the leader of a group effectively enables all
2139 * the group members that aren't explicitly disabled, so we
2140 * have to update their ->tstamp_enabled also.
2141 * Note: this works for group members as well as group leaders
2142 * since the non-leader members' sibling_lists will be empty.
2144 static void __perf_event_mark_enabled(struct perf_event *event)
2146 struct perf_event *sub;
2147 u64 tstamp = perf_event_time(event);
2149 event->state = PERF_EVENT_STATE_INACTIVE;
2150 event->tstamp_enabled = tstamp - event->total_time_enabled;
2151 list_for_each_entry(sub, &event->sibling_list, group_entry) {
2152 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2153 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2158 * Cross CPU call to enable a performance event
2160 static int __perf_event_enable(void *info)
2162 struct perf_event *event = info;
2163 struct perf_event_context *ctx = event->ctx;
2164 struct perf_event *leader = event->group_leader;
2165 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2166 int err;
2169 * There's a time window between 'ctx->is_active' check
2170 * in perf_event_enable function and this place having:
2171 * - IRQs on
2172 * - ctx->lock unlocked
2174 * where the task could be killed and 'ctx' deactivated
2175 * by perf_event_exit_task.
2177 if (!ctx->is_active)
2178 return -EINVAL;
2180 raw_spin_lock(&ctx->lock);
2181 update_context_time(ctx);
2183 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2184 goto unlock;
2187 * set current task's cgroup time reference point
2189 perf_cgroup_set_timestamp(current, ctx);
2191 __perf_event_mark_enabled(event);
2193 if (!event_filter_match(event)) {
2194 if (is_cgroup_event(event))
2195 perf_cgroup_defer_enabled(event);
2196 goto unlock;
2200 * If the event is in a group and isn't the group leader,
2201 * then don't put it on unless the group is on.
2203 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
2204 goto unlock;
2206 if (!group_can_go_on(event, cpuctx, 1)) {
2207 err = -EEXIST;
2208 } else {
2209 if (event == leader)
2210 err = group_sched_in(event, cpuctx, ctx);
2211 else
2212 err = event_sched_in(event, cpuctx, ctx);
2215 if (err) {
2217 * If this event can't go on and it's part of a
2218 * group, then the whole group has to come off.
2220 if (leader != event) {
2221 group_sched_out(leader, cpuctx, ctx);
2222 perf_cpu_hrtimer_restart(cpuctx);
2224 if (leader->attr.pinned) {
2225 update_group_times(leader);
2226 leader->state = PERF_EVENT_STATE_ERROR;
2230 unlock:
2231 raw_spin_unlock(&ctx->lock);
2233 return 0;
2237 * Enable a event.
2239 * If event->ctx is a cloned context, callers must make sure that
2240 * every task struct that event->ctx->task could possibly point to
2241 * remains valid. This condition is satisfied when called through
2242 * perf_event_for_each_child or perf_event_for_each as described
2243 * for perf_event_disable.
2245 static void _perf_event_enable(struct perf_event *event)
2247 struct perf_event_context *ctx = event->ctx;
2248 struct task_struct *task = ctx->task;
2250 if (!task) {
2252 * Enable the event on the cpu that it's on
2254 cpu_function_call(event->cpu, __perf_event_enable, event);
2255 return;
2258 raw_spin_lock_irq(&ctx->lock);
2259 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2260 goto out;
2263 * If the event is in error state, clear that first.
2264 * That way, if we see the event in error state below, we
2265 * know that it has gone back into error state, as distinct
2266 * from the task having been scheduled away before the
2267 * cross-call arrived.
2269 if (event->state == PERF_EVENT_STATE_ERROR)
2270 event->state = PERF_EVENT_STATE_OFF;
2272 retry:
2273 if (!ctx->is_active) {
2274 __perf_event_mark_enabled(event);
2275 goto out;
2278 raw_spin_unlock_irq(&ctx->lock);
2280 if (!task_function_call(task, __perf_event_enable, event))
2281 return;
2283 raw_spin_lock_irq(&ctx->lock);
2286 * If the context is active and the event is still off,
2287 * we need to retry the cross-call.
2289 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
2291 * task could have been flipped by a concurrent
2292 * perf_event_context_sched_out()
2294 task = ctx->task;
2295 goto retry;
2298 out:
2299 raw_spin_unlock_irq(&ctx->lock);
2303 * See perf_event_disable();
2305 void perf_event_enable(struct perf_event *event)
2307 struct perf_event_context *ctx;
2309 ctx = perf_event_ctx_lock(event);
2310 _perf_event_enable(event);
2311 perf_event_ctx_unlock(event, ctx);
2313 EXPORT_SYMBOL_GPL(perf_event_enable);
2315 static int _perf_event_refresh(struct perf_event *event, int refresh)
2318 * not supported on inherited events
2320 if (event->attr.inherit || !is_sampling_event(event))
2321 return -EINVAL;
2323 atomic_add(refresh, &event->event_limit);
2324 _perf_event_enable(event);
2326 return 0;
2330 * See perf_event_disable()
2332 int perf_event_refresh(struct perf_event *event, int refresh)
2334 struct perf_event_context *ctx;
2335 int ret;
2337 ctx = perf_event_ctx_lock(event);
2338 ret = _perf_event_refresh(event, refresh);
2339 perf_event_ctx_unlock(event, ctx);
2341 return ret;
2343 EXPORT_SYMBOL_GPL(perf_event_refresh);
2345 static void ctx_sched_out(struct perf_event_context *ctx,
2346 struct perf_cpu_context *cpuctx,
2347 enum event_type_t event_type)
2349 struct perf_event *event;
2350 int is_active = ctx->is_active;
2352 ctx->is_active &= ~event_type;
2353 if (likely(!ctx->nr_events))
2354 return;
2356 update_context_time(ctx);
2357 update_cgrp_time_from_cpuctx(cpuctx);
2358 if (!ctx->nr_active)
2359 return;
2361 perf_pmu_disable(ctx->pmu);
2362 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2363 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2364 group_sched_out(event, cpuctx, ctx);
2367 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2368 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2369 group_sched_out(event, cpuctx, ctx);
2371 perf_pmu_enable(ctx->pmu);
2375 * Test whether two contexts are equivalent, i.e. whether they have both been
2376 * cloned from the same version of the same context.
2378 * Equivalence is measured using a generation number in the context that is
2379 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2380 * and list_del_event().
2382 static int context_equiv(struct perf_event_context *ctx1,
2383 struct perf_event_context *ctx2)
2385 lockdep_assert_held(&ctx1->lock);
2386 lockdep_assert_held(&ctx2->lock);
2388 /* Pinning disables the swap optimization */
2389 if (ctx1->pin_count || ctx2->pin_count)
2390 return 0;
2392 /* If ctx1 is the parent of ctx2 */
2393 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2394 return 1;
2396 /* If ctx2 is the parent of ctx1 */
2397 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2398 return 1;
2401 * If ctx1 and ctx2 have the same parent; we flatten the parent
2402 * hierarchy, see perf_event_init_context().
2404 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2405 ctx1->parent_gen == ctx2->parent_gen)
2406 return 1;
2408 /* Unmatched */
2409 return 0;
2412 static void __perf_event_sync_stat(struct perf_event *event,
2413 struct perf_event *next_event)
2415 u64 value;
2417 if (!event->attr.inherit_stat)
2418 return;
2421 * Update the event value, we cannot use perf_event_read()
2422 * because we're in the middle of a context switch and have IRQs
2423 * disabled, which upsets smp_call_function_single(), however
2424 * we know the event must be on the current CPU, therefore we
2425 * don't need to use it.
2427 switch (event->state) {
2428 case PERF_EVENT_STATE_ACTIVE:
2429 event->pmu->read(event);
2430 /* fall-through */
2432 case PERF_EVENT_STATE_INACTIVE:
2433 update_event_times(event);
2434 break;
2436 default:
2437 break;
2441 * In order to keep per-task stats reliable we need to flip the event
2442 * values when we flip the contexts.
2444 value = local64_read(&next_event->count);
2445 value = local64_xchg(&event->count, value);
2446 local64_set(&next_event->count, value);
2448 swap(event->total_time_enabled, next_event->total_time_enabled);
2449 swap(event->total_time_running, next_event->total_time_running);
2452 * Since we swizzled the values, update the user visible data too.
2454 perf_event_update_userpage(event);
2455 perf_event_update_userpage(next_event);
2458 static void perf_event_sync_stat(struct perf_event_context *ctx,
2459 struct perf_event_context *next_ctx)
2461 struct perf_event *event, *next_event;
2463 if (!ctx->nr_stat)
2464 return;
2466 update_context_time(ctx);
2468 event = list_first_entry(&ctx->event_list,
2469 struct perf_event, event_entry);
2471 next_event = list_first_entry(&next_ctx->event_list,
2472 struct perf_event, event_entry);
2474 while (&event->event_entry != &ctx->event_list &&
2475 &next_event->event_entry != &next_ctx->event_list) {
2477 __perf_event_sync_stat(event, next_event);
2479 event = list_next_entry(event, event_entry);
2480 next_event = list_next_entry(next_event, event_entry);
2484 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2485 struct task_struct *next)
2487 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2488 struct perf_event_context *next_ctx;
2489 struct perf_event_context *parent, *next_parent;
2490 struct perf_cpu_context *cpuctx;
2491 int do_switch = 1;
2493 if (likely(!ctx))
2494 return;
2496 cpuctx = __get_cpu_context(ctx);
2497 if (!cpuctx->task_ctx)
2498 return;
2500 rcu_read_lock();
2501 next_ctx = next->perf_event_ctxp[ctxn];
2502 if (!next_ctx)
2503 goto unlock;
2505 parent = rcu_dereference(ctx->parent_ctx);
2506 next_parent = rcu_dereference(next_ctx->parent_ctx);
2508 /* If neither context have a parent context; they cannot be clones. */
2509 if (!parent && !next_parent)
2510 goto unlock;
2512 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2514 * Looks like the two contexts are clones, so we might be
2515 * able to optimize the context switch. We lock both
2516 * contexts and check that they are clones under the
2517 * lock (including re-checking that neither has been
2518 * uncloned in the meantime). It doesn't matter which
2519 * order we take the locks because no other cpu could
2520 * be trying to lock both of these tasks.
2522 raw_spin_lock(&ctx->lock);
2523 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2524 if (context_equiv(ctx, next_ctx)) {
2526 * XXX do we need a memory barrier of sorts
2527 * wrt to rcu_dereference() of perf_event_ctxp
2529 task->perf_event_ctxp[ctxn] = next_ctx;
2530 next->perf_event_ctxp[ctxn] = ctx;
2531 ctx->task = next;
2532 next_ctx->task = task;
2533 do_switch = 0;
2535 perf_event_sync_stat(ctx, next_ctx);
2537 raw_spin_unlock(&next_ctx->lock);
2538 raw_spin_unlock(&ctx->lock);
2540 unlock:
2541 rcu_read_unlock();
2543 if (do_switch) {
2544 raw_spin_lock(&ctx->lock);
2545 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2546 cpuctx->task_ctx = NULL;
2547 raw_spin_unlock(&ctx->lock);
2551 #define for_each_task_context_nr(ctxn) \
2552 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2555 * Called from scheduler to remove the events of the current task,
2556 * with interrupts disabled.
2558 * We stop each event and update the event value in event->count.
2560 * This does not protect us against NMI, but disable()
2561 * sets the disabled bit in the control field of event _before_
2562 * accessing the event control register. If a NMI hits, then it will
2563 * not restart the event.
2565 void __perf_event_task_sched_out(struct task_struct *task,
2566 struct task_struct *next)
2568 int ctxn;
2570 for_each_task_context_nr(ctxn)
2571 perf_event_context_sched_out(task, ctxn, next);
2574 * if cgroup events exist on this CPU, then we need
2575 * to check if we have to switch out PMU state.
2576 * cgroup event are system-wide mode only
2578 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2579 perf_cgroup_sched_out(task, next);
2582 static void task_ctx_sched_out(struct perf_event_context *ctx)
2584 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2586 if (!cpuctx->task_ctx)
2587 return;
2589 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2590 return;
2592 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2593 cpuctx->task_ctx = NULL;
2597 * Called with IRQs disabled
2599 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2600 enum event_type_t event_type)
2602 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2605 static void
2606 ctx_pinned_sched_in(struct perf_event_context *ctx,
2607 struct perf_cpu_context *cpuctx)
2609 struct perf_event *event;
2611 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2612 if (event->state <= PERF_EVENT_STATE_OFF)
2613 continue;
2614 if (!event_filter_match(event))
2615 continue;
2617 /* may need to reset tstamp_enabled */
2618 if (is_cgroup_event(event))
2619 perf_cgroup_mark_enabled(event, ctx);
2621 if (group_can_go_on(event, cpuctx, 1))
2622 group_sched_in(event, cpuctx, ctx);
2625 * If this pinned group hasn't been scheduled,
2626 * put it in error state.
2628 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2629 update_group_times(event);
2630 event->state = PERF_EVENT_STATE_ERROR;
2635 static void
2636 ctx_flexible_sched_in(struct perf_event_context *ctx,
2637 struct perf_cpu_context *cpuctx)
2639 struct perf_event *event;
2640 int can_add_hw = 1;
2642 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2643 /* Ignore events in OFF or ERROR state */
2644 if (event->state <= PERF_EVENT_STATE_OFF)
2645 continue;
2647 * Listen to the 'cpu' scheduling filter constraint
2648 * of events:
2650 if (!event_filter_match(event))
2651 continue;
2653 /* may need to reset tstamp_enabled */
2654 if (is_cgroup_event(event))
2655 perf_cgroup_mark_enabled(event, ctx);
2657 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2658 if (group_sched_in(event, cpuctx, ctx))
2659 can_add_hw = 0;
2664 static void
2665 ctx_sched_in(struct perf_event_context *ctx,
2666 struct perf_cpu_context *cpuctx,
2667 enum event_type_t event_type,
2668 struct task_struct *task)
2670 u64 now;
2671 int is_active = ctx->is_active;
2673 ctx->is_active |= event_type;
2674 if (likely(!ctx->nr_events))
2675 return;
2677 now = perf_clock();
2678 ctx->timestamp = now;
2679 perf_cgroup_set_timestamp(task, ctx);
2681 * First go through the list and put on any pinned groups
2682 * in order to give them the best chance of going on.
2684 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2685 ctx_pinned_sched_in(ctx, cpuctx);
2687 /* Then walk through the lower prio flexible groups */
2688 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2689 ctx_flexible_sched_in(ctx, cpuctx);
2692 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2693 enum event_type_t event_type,
2694 struct task_struct *task)
2696 struct perf_event_context *ctx = &cpuctx->ctx;
2698 ctx_sched_in(ctx, cpuctx, event_type, task);
2701 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2702 struct task_struct *task)
2704 struct perf_cpu_context *cpuctx;
2706 cpuctx = __get_cpu_context(ctx);
2707 if (cpuctx->task_ctx == ctx)
2708 return;
2710 perf_ctx_lock(cpuctx, ctx);
2711 perf_pmu_disable(ctx->pmu);
2713 * We want to keep the following priority order:
2714 * cpu pinned (that don't need to move), task pinned,
2715 * cpu flexible, task flexible.
2717 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2719 if (ctx->nr_events)
2720 cpuctx->task_ctx = ctx;
2722 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2724 perf_pmu_enable(ctx->pmu);
2725 perf_ctx_unlock(cpuctx, ctx);
2728 * Since these rotations are per-cpu, we need to ensure the
2729 * cpu-context we got scheduled on is actually rotating.
2731 perf_pmu_rotate_start(ctx->pmu);
2735 * When sampling the branck stack in system-wide, it may be necessary
2736 * to flush the stack on context switch. This happens when the branch
2737 * stack does not tag its entries with the pid of the current task.
2738 * Otherwise it becomes impossible to associate a branch entry with a
2739 * task. This ambiguity is more likely to appear when the branch stack
2740 * supports priv level filtering and the user sets it to monitor only
2741 * at the user level (which could be a useful measurement in system-wide
2742 * mode). In that case, the risk is high of having a branch stack with
2743 * branch from multiple tasks. Flushing may mean dropping the existing
2744 * entries or stashing them somewhere in the PMU specific code layer.
2746 * This function provides the context switch callback to the lower code
2747 * layer. It is invoked ONLY when there is at least one system-wide context
2748 * with at least one active event using taken branch sampling.
2750 static void perf_branch_stack_sched_in(struct task_struct *prev,
2751 struct task_struct *task)
2753 struct perf_cpu_context *cpuctx;
2754 struct pmu *pmu;
2755 unsigned long flags;
2757 /* no need to flush branch stack if not changing task */
2758 if (prev == task)
2759 return;
2761 local_irq_save(flags);
2763 rcu_read_lock();
2765 list_for_each_entry_rcu(pmu, &pmus, entry) {
2766 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2769 * check if the context has at least one
2770 * event using PERF_SAMPLE_BRANCH_STACK
2772 if (cpuctx->ctx.nr_branch_stack > 0
2773 && pmu->flush_branch_stack) {
2775 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2777 perf_pmu_disable(pmu);
2779 pmu->flush_branch_stack();
2781 perf_pmu_enable(pmu);
2783 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2787 rcu_read_unlock();
2789 local_irq_restore(flags);
2793 * Called from scheduler to add the events of the current task
2794 * with interrupts disabled.
2796 * We restore the event value and then enable it.
2798 * This does not protect us against NMI, but enable()
2799 * sets the enabled bit in the control field of event _before_
2800 * accessing the event control register. If a NMI hits, then it will
2801 * keep the event running.
2803 void __perf_event_task_sched_in(struct task_struct *prev,
2804 struct task_struct *task)
2806 struct perf_event_context *ctx;
2807 int ctxn;
2809 for_each_task_context_nr(ctxn) {
2810 ctx = task->perf_event_ctxp[ctxn];
2811 if (likely(!ctx))
2812 continue;
2814 perf_event_context_sched_in(ctx, task);
2817 * if cgroup events exist on this CPU, then we need
2818 * to check if we have to switch in PMU state.
2819 * cgroup event are system-wide mode only
2821 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2822 perf_cgroup_sched_in(prev, task);
2824 /* check for system-wide branch_stack events */
2825 if (atomic_read(this_cpu_ptr(&perf_branch_stack_events)))
2826 perf_branch_stack_sched_in(prev, task);
2829 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2831 u64 frequency = event->attr.sample_freq;
2832 u64 sec = NSEC_PER_SEC;
2833 u64 divisor, dividend;
2835 int count_fls, nsec_fls, frequency_fls, sec_fls;
2837 count_fls = fls64(count);
2838 nsec_fls = fls64(nsec);
2839 frequency_fls = fls64(frequency);
2840 sec_fls = 30;
2843 * We got @count in @nsec, with a target of sample_freq HZ
2844 * the target period becomes:
2846 * @count * 10^9
2847 * period = -------------------
2848 * @nsec * sample_freq
2853 * Reduce accuracy by one bit such that @a and @b converge
2854 * to a similar magnitude.
2856 #define REDUCE_FLS(a, b) \
2857 do { \
2858 if (a##_fls > b##_fls) { \
2859 a >>= 1; \
2860 a##_fls--; \
2861 } else { \
2862 b >>= 1; \
2863 b##_fls--; \
2865 } while (0)
2868 * Reduce accuracy until either term fits in a u64, then proceed with
2869 * the other, so that finally we can do a u64/u64 division.
2871 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2872 REDUCE_FLS(nsec, frequency);
2873 REDUCE_FLS(sec, count);
2876 if (count_fls + sec_fls > 64) {
2877 divisor = nsec * frequency;
2879 while (count_fls + sec_fls > 64) {
2880 REDUCE_FLS(count, sec);
2881 divisor >>= 1;
2884 dividend = count * sec;
2885 } else {
2886 dividend = count * sec;
2888 while (nsec_fls + frequency_fls > 64) {
2889 REDUCE_FLS(nsec, frequency);
2890 dividend >>= 1;
2893 divisor = nsec * frequency;
2896 if (!divisor)
2897 return dividend;
2899 return div64_u64(dividend, divisor);
2902 static DEFINE_PER_CPU(int, perf_throttled_count);
2903 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2905 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2907 struct hw_perf_event *hwc = &event->hw;
2908 s64 period, sample_period;
2909 s64 delta;
2911 period = perf_calculate_period(event, nsec, count);
2913 delta = (s64)(period - hwc->sample_period);
2914 delta = (delta + 7) / 8; /* low pass filter */
2916 sample_period = hwc->sample_period + delta;
2918 if (!sample_period)
2919 sample_period = 1;
2921 hwc->sample_period = sample_period;
2923 if (local64_read(&hwc->period_left) > 8*sample_period) {
2924 if (disable)
2925 event->pmu->stop(event, PERF_EF_UPDATE);
2927 local64_set(&hwc->period_left, 0);
2929 if (disable)
2930 event->pmu->start(event, PERF_EF_RELOAD);
2935 * combine freq adjustment with unthrottling to avoid two passes over the
2936 * events. At the same time, make sure, having freq events does not change
2937 * the rate of unthrottling as that would introduce bias.
2939 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
2940 int needs_unthr)
2942 struct perf_event *event;
2943 struct hw_perf_event *hwc;
2944 u64 now, period = TICK_NSEC;
2945 s64 delta;
2948 * only need to iterate over all events iff:
2949 * - context have events in frequency mode (needs freq adjust)
2950 * - there are events to unthrottle on this cpu
2952 if (!(ctx->nr_freq || needs_unthr))
2953 return;
2955 raw_spin_lock(&ctx->lock);
2956 perf_pmu_disable(ctx->pmu);
2958 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
2959 if (event->state != PERF_EVENT_STATE_ACTIVE)
2960 continue;
2962 if (!event_filter_match(event))
2963 continue;
2965 perf_pmu_disable(event->pmu);
2967 hwc = &event->hw;
2969 if (hwc->interrupts == MAX_INTERRUPTS) {
2970 hwc->interrupts = 0;
2971 perf_log_throttle(event, 1);
2972 event->pmu->start(event, 0);
2975 if (!event->attr.freq || !event->attr.sample_freq)
2976 goto next;
2979 * stop the event and update event->count
2981 event->pmu->stop(event, PERF_EF_UPDATE);
2983 now = local64_read(&event->count);
2984 delta = now - hwc->freq_count_stamp;
2985 hwc->freq_count_stamp = now;
2988 * restart the event
2989 * reload only if value has changed
2990 * we have stopped the event so tell that
2991 * to perf_adjust_period() to avoid stopping it
2992 * twice.
2994 if (delta > 0)
2995 perf_adjust_period(event, period, delta, false);
2997 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
2998 next:
2999 perf_pmu_enable(event->pmu);
3002 perf_pmu_enable(ctx->pmu);
3003 raw_spin_unlock(&ctx->lock);
3007 * Round-robin a context's events:
3009 static void rotate_ctx(struct perf_event_context *ctx)
3012 * Rotate the first entry last of non-pinned groups. Rotation might be
3013 * disabled by the inheritance code.
3015 if (!ctx->rotate_disable)
3016 list_rotate_left(&ctx->flexible_groups);
3020 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
3021 * because they're strictly cpu affine and rotate_start is called with IRQs
3022 * disabled, while rotate_context is called from IRQ context.
3024 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
3026 struct perf_event_context *ctx = NULL;
3027 int rotate = 0, remove = 1;
3029 if (cpuctx->ctx.nr_events) {
3030 remove = 0;
3031 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
3032 rotate = 1;
3035 ctx = cpuctx->task_ctx;
3036 if (ctx && ctx->nr_events) {
3037 remove = 0;
3038 if (ctx->nr_events != ctx->nr_active)
3039 rotate = 1;
3042 if (!rotate)
3043 goto done;
3045 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3046 perf_pmu_disable(cpuctx->ctx.pmu);
3048 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3049 if (ctx)
3050 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
3052 rotate_ctx(&cpuctx->ctx);
3053 if (ctx)
3054 rotate_ctx(ctx);
3056 perf_event_sched_in(cpuctx, ctx, current);
3058 perf_pmu_enable(cpuctx->ctx.pmu);
3059 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3060 done:
3061 if (remove)
3062 list_del_init(&cpuctx->rotation_list);
3064 return rotate;
3067 #ifdef CONFIG_NO_HZ_FULL
3068 bool perf_event_can_stop_tick(void)
3070 if (atomic_read(&nr_freq_events) ||
3071 __this_cpu_read(perf_throttled_count))
3072 return false;
3073 else
3074 return true;
3076 #endif
3078 void perf_event_task_tick(void)
3080 struct list_head *head = this_cpu_ptr(&rotation_list);
3081 struct perf_cpu_context *cpuctx, *tmp;
3082 struct perf_event_context *ctx;
3083 int throttled;
3085 WARN_ON(!irqs_disabled());
3087 __this_cpu_inc(perf_throttled_seq);
3088 throttled = __this_cpu_xchg(perf_throttled_count, 0);
3090 list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) {
3091 ctx = &cpuctx->ctx;
3092 perf_adjust_freq_unthr_context(ctx, throttled);
3094 ctx = cpuctx->task_ctx;
3095 if (ctx)
3096 perf_adjust_freq_unthr_context(ctx, throttled);
3100 static int event_enable_on_exec(struct perf_event *event,
3101 struct perf_event_context *ctx)
3103 if (!event->attr.enable_on_exec)
3104 return 0;
3106 event->attr.enable_on_exec = 0;
3107 if (event->state >= PERF_EVENT_STATE_INACTIVE)
3108 return 0;
3110 __perf_event_mark_enabled(event);
3112 return 1;
3116 * Enable all of a task's events that have been marked enable-on-exec.
3117 * This expects task == current.
3119 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
3121 struct perf_event_context *clone_ctx = NULL;
3122 struct perf_event *event;
3123 unsigned long flags;
3124 int enabled = 0;
3125 int ret;
3127 local_irq_save(flags);
3128 if (!ctx || !ctx->nr_events)
3129 goto out;
3132 * We must ctxsw out cgroup events to avoid conflict
3133 * when invoking perf_task_event_sched_in() later on
3134 * in this function. Otherwise we end up trying to
3135 * ctxswin cgroup events which are already scheduled
3136 * in.
3138 perf_cgroup_sched_out(current, NULL);
3140 raw_spin_lock(&ctx->lock);
3141 task_ctx_sched_out(ctx);
3143 list_for_each_entry(event, &ctx->event_list, event_entry) {
3144 ret = event_enable_on_exec(event, ctx);
3145 if (ret)
3146 enabled = 1;
3150 * Unclone this context if we enabled any event.
3152 if (enabled)
3153 clone_ctx = unclone_ctx(ctx);
3155 raw_spin_unlock(&ctx->lock);
3158 * Also calls ctxswin for cgroup events, if any:
3160 perf_event_context_sched_in(ctx, ctx->task);
3161 out:
3162 local_irq_restore(flags);
3164 if (clone_ctx)
3165 put_ctx(clone_ctx);
3168 void perf_event_exec(void)
3170 struct perf_event_context *ctx;
3171 int ctxn;
3173 rcu_read_lock();
3174 for_each_task_context_nr(ctxn) {
3175 ctx = current->perf_event_ctxp[ctxn];
3176 if (!ctx)
3177 continue;
3179 perf_event_enable_on_exec(ctx);
3181 rcu_read_unlock();
3185 * Cross CPU call to read the hardware event
3187 static void __perf_event_read(void *info)
3189 struct perf_event *event = info;
3190 struct perf_event_context *ctx = event->ctx;
3191 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3194 * If this is a task context, we need to check whether it is
3195 * the current task context of this cpu. If not it has been
3196 * scheduled out before the smp call arrived. In that case
3197 * event->count would have been updated to a recent sample
3198 * when the event was scheduled out.
3200 if (ctx->task && cpuctx->task_ctx != ctx)
3201 return;
3203 raw_spin_lock(&ctx->lock);
3204 if (ctx->is_active) {
3205 update_context_time(ctx);
3206 update_cgrp_time_from_event(event);
3208 update_event_times(event);
3209 if (event->state == PERF_EVENT_STATE_ACTIVE)
3210 event->pmu->read(event);
3211 raw_spin_unlock(&ctx->lock);
3214 static inline u64 perf_event_count(struct perf_event *event)
3216 return local64_read(&event->count) + atomic64_read(&event->child_count);
3219 static u64 perf_event_read(struct perf_event *event)
3222 * If event is enabled and currently active on a CPU, update the
3223 * value in the event structure:
3225 if (event->state == PERF_EVENT_STATE_ACTIVE) {
3226 smp_call_function_single(event->oncpu,
3227 __perf_event_read, event, 1);
3228 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3229 struct perf_event_context *ctx = event->ctx;
3230 unsigned long flags;
3232 raw_spin_lock_irqsave(&ctx->lock, flags);
3234 * may read while context is not active
3235 * (e.g., thread is blocked), in that case
3236 * we cannot update context time
3238 if (ctx->is_active) {
3239 update_context_time(ctx);
3240 update_cgrp_time_from_event(event);
3242 update_event_times(event);
3243 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3246 return perf_event_count(event);
3250 * Initialize the perf_event context in a task_struct:
3252 static void __perf_event_init_context(struct perf_event_context *ctx)
3254 raw_spin_lock_init(&ctx->lock);
3255 mutex_init(&ctx->mutex);
3256 INIT_LIST_HEAD(&ctx->pinned_groups);
3257 INIT_LIST_HEAD(&ctx->flexible_groups);
3258 INIT_LIST_HEAD(&ctx->event_list);
3259 atomic_set(&ctx->refcount, 1);
3260 INIT_DELAYED_WORK(&ctx->orphans_remove, orphans_remove_work);
3263 static struct perf_event_context *
3264 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3266 struct perf_event_context *ctx;
3268 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3269 if (!ctx)
3270 return NULL;
3272 __perf_event_init_context(ctx);
3273 if (task) {
3274 ctx->task = task;
3275 get_task_struct(task);
3277 ctx->pmu = pmu;
3279 return ctx;
3282 static struct task_struct *
3283 find_lively_task_by_vpid(pid_t vpid)
3285 struct task_struct *task;
3286 int err;
3288 rcu_read_lock();
3289 if (!vpid)
3290 task = current;
3291 else
3292 task = find_task_by_vpid(vpid);
3293 if (task)
3294 get_task_struct(task);
3295 rcu_read_unlock();
3297 if (!task)
3298 return ERR_PTR(-ESRCH);
3300 /* Reuse ptrace permission checks for now. */
3301 err = -EACCES;
3302 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
3303 goto errout;
3305 return task;
3306 errout:
3307 put_task_struct(task);
3308 return ERR_PTR(err);
3313 * Returns a matching context with refcount and pincount.
3315 static struct perf_event_context *
3316 find_get_context(struct pmu *pmu, struct task_struct *task, int cpu)
3318 struct perf_event_context *ctx, *clone_ctx = NULL;
3319 struct perf_cpu_context *cpuctx;
3320 unsigned long flags;
3321 int ctxn, err;
3323 if (!task) {
3324 /* Must be root to operate on a CPU event: */
3325 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3326 return ERR_PTR(-EACCES);
3329 * We could be clever and allow to attach a event to an
3330 * offline CPU and activate it when the CPU comes up, but
3331 * that's for later.
3333 if (!cpu_online(cpu))
3334 return ERR_PTR(-ENODEV);
3336 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3337 ctx = &cpuctx->ctx;
3338 get_ctx(ctx);
3339 ++ctx->pin_count;
3341 return ctx;
3344 err = -EINVAL;
3345 ctxn = pmu->task_ctx_nr;
3346 if (ctxn < 0)
3347 goto errout;
3349 retry:
3350 ctx = perf_lock_task_context(task, ctxn, &flags);
3351 if (ctx) {
3352 clone_ctx = unclone_ctx(ctx);
3353 ++ctx->pin_count;
3354 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3356 if (clone_ctx)
3357 put_ctx(clone_ctx);
3358 } else {
3359 ctx = alloc_perf_context(pmu, task);
3360 err = -ENOMEM;
3361 if (!ctx)
3362 goto errout;
3364 err = 0;
3365 mutex_lock(&task->perf_event_mutex);
3367 * If it has already passed perf_event_exit_task().
3368 * we must see PF_EXITING, it takes this mutex too.
3370 if (task->flags & PF_EXITING)
3371 err = -ESRCH;
3372 else if (task->perf_event_ctxp[ctxn])
3373 err = -EAGAIN;
3374 else {
3375 get_ctx(ctx);
3376 ++ctx->pin_count;
3377 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3379 mutex_unlock(&task->perf_event_mutex);
3381 if (unlikely(err)) {
3382 put_ctx(ctx);
3384 if (err == -EAGAIN)
3385 goto retry;
3386 goto errout;
3390 return ctx;
3392 errout:
3393 return ERR_PTR(err);
3396 static void perf_event_free_filter(struct perf_event *event);
3398 static void free_event_rcu(struct rcu_head *head)
3400 struct perf_event *event;
3402 event = container_of(head, struct perf_event, rcu_head);
3403 if (event->ns)
3404 put_pid_ns(event->ns);
3405 perf_event_free_filter(event);
3406 kfree(event);
3409 static void ring_buffer_put(struct ring_buffer *rb);
3410 static void ring_buffer_attach(struct perf_event *event,
3411 struct ring_buffer *rb);
3413 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3415 if (event->parent)
3416 return;
3418 if (has_branch_stack(event)) {
3419 if (!(event->attach_state & PERF_ATTACH_TASK))
3420 atomic_dec(&per_cpu(perf_branch_stack_events, cpu));
3422 if (is_cgroup_event(event))
3423 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3426 static void unaccount_event(struct perf_event *event)
3428 if (event->parent)
3429 return;
3431 if (event->attach_state & PERF_ATTACH_TASK)
3432 static_key_slow_dec_deferred(&perf_sched_events);
3433 if (event->attr.mmap || event->attr.mmap_data)
3434 atomic_dec(&nr_mmap_events);
3435 if (event->attr.comm)
3436 atomic_dec(&nr_comm_events);
3437 if (event->attr.task)
3438 atomic_dec(&nr_task_events);
3439 if (event->attr.freq)
3440 atomic_dec(&nr_freq_events);
3441 if (is_cgroup_event(event))
3442 static_key_slow_dec_deferred(&perf_sched_events);
3443 if (has_branch_stack(event))
3444 static_key_slow_dec_deferred(&perf_sched_events);
3446 unaccount_event_cpu(event, event->cpu);
3449 static void __free_event(struct perf_event *event)
3451 if (!event->parent) {
3452 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3453 put_callchain_buffers();
3456 if (event->destroy)
3457 event->destroy(event);
3459 if (event->ctx)
3460 put_ctx(event->ctx);
3462 if (event->pmu)
3463 module_put(event->pmu->module);
3465 call_rcu(&event->rcu_head, free_event_rcu);
3468 static void _free_event(struct perf_event *event)
3470 irq_work_sync(&event->pending);
3472 unaccount_event(event);
3474 if (event->rb) {
3476 * Can happen when we close an event with re-directed output.
3478 * Since we have a 0 refcount, perf_mmap_close() will skip
3479 * over us; possibly making our ring_buffer_put() the last.
3481 mutex_lock(&event->mmap_mutex);
3482 ring_buffer_attach(event, NULL);
3483 mutex_unlock(&event->mmap_mutex);
3486 if (is_cgroup_event(event))
3487 perf_detach_cgroup(event);
3489 __free_event(event);
3493 * Used to free events which have a known refcount of 1, such as in error paths
3494 * where the event isn't exposed yet and inherited events.
3496 static void free_event(struct perf_event *event)
3498 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3499 "unexpected event refcount: %ld; ptr=%p\n",
3500 atomic_long_read(&event->refcount), event)) {
3501 /* leak to avoid use-after-free */
3502 return;
3505 _free_event(event);
3509 * Remove user event from the owner task.
3511 static void perf_remove_from_owner(struct perf_event *event)
3513 struct task_struct *owner;
3515 rcu_read_lock();
3516 owner = ACCESS_ONCE(event->owner);
3518 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3519 * !owner it means the list deletion is complete and we can indeed
3520 * free this event, otherwise we need to serialize on
3521 * owner->perf_event_mutex.
3523 smp_read_barrier_depends();
3524 if (owner) {
3526 * Since delayed_put_task_struct() also drops the last
3527 * task reference we can safely take a new reference
3528 * while holding the rcu_read_lock().
3530 get_task_struct(owner);
3532 rcu_read_unlock();
3534 if (owner) {
3536 * If we're here through perf_event_exit_task() we're already
3537 * holding ctx->mutex which would be an inversion wrt. the
3538 * normal lock order.
3540 * However we can safely take this lock because its the child
3541 * ctx->mutex.
3543 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
3546 * We have to re-check the event->owner field, if it is cleared
3547 * we raced with perf_event_exit_task(), acquiring the mutex
3548 * ensured they're done, and we can proceed with freeing the
3549 * event.
3551 if (event->owner)
3552 list_del_init(&event->owner_entry);
3553 mutex_unlock(&owner->perf_event_mutex);
3554 put_task_struct(owner);
3559 * Called when the last reference to the file is gone.
3561 static void put_event(struct perf_event *event)
3563 struct perf_event_context *ctx = event->ctx;
3565 if (!atomic_long_dec_and_test(&event->refcount))
3566 return;
3568 if (!is_kernel_event(event))
3569 perf_remove_from_owner(event);
3571 WARN_ON_ONCE(ctx->parent_ctx);
3573 * There are two ways this annotation is useful:
3575 * 1) there is a lock recursion from perf_event_exit_task
3576 * see the comment there.
3578 * 2) there is a lock-inversion with mmap_sem through
3579 * perf_event_read_group(), which takes faults while
3580 * holding ctx->mutex, however this is called after
3581 * the last filedesc died, so there is no possibility
3582 * to trigger the AB-BA case.
3584 mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
3585 perf_remove_from_context(event, true);
3586 mutex_unlock(&ctx->mutex);
3588 _free_event(event);
3591 int perf_event_release_kernel(struct perf_event *event)
3593 put_event(event);
3594 return 0;
3596 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3598 static int perf_release(struct inode *inode, struct file *file)
3600 put_event(file->private_data);
3601 return 0;
3605 * Remove all orphanes events from the context.
3607 static void orphans_remove_work(struct work_struct *work)
3609 struct perf_event_context *ctx;
3610 struct perf_event *event, *tmp;
3612 ctx = container_of(work, struct perf_event_context,
3613 orphans_remove.work);
3615 mutex_lock(&ctx->mutex);
3616 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) {
3617 struct perf_event *parent_event = event->parent;
3619 if (!is_orphaned_child(event))
3620 continue;
3622 perf_remove_from_context(event, true);
3624 mutex_lock(&parent_event->child_mutex);
3625 list_del_init(&event->child_list);
3626 mutex_unlock(&parent_event->child_mutex);
3628 free_event(event);
3629 put_event(parent_event);
3632 raw_spin_lock_irq(&ctx->lock);
3633 ctx->orphans_remove_sched = false;
3634 raw_spin_unlock_irq(&ctx->lock);
3635 mutex_unlock(&ctx->mutex);
3637 put_ctx(ctx);
3640 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3642 struct perf_event *child;
3643 u64 total = 0;
3645 *enabled = 0;
3646 *running = 0;
3648 mutex_lock(&event->child_mutex);
3649 total += perf_event_read(event);
3650 *enabled += event->total_time_enabled +
3651 atomic64_read(&event->child_total_time_enabled);
3652 *running += event->total_time_running +
3653 atomic64_read(&event->child_total_time_running);
3655 list_for_each_entry(child, &event->child_list, child_list) {
3656 total += perf_event_read(child);
3657 *enabled += child->total_time_enabled;
3658 *running += child->total_time_running;
3660 mutex_unlock(&event->child_mutex);
3662 return total;
3664 EXPORT_SYMBOL_GPL(perf_event_read_value);
3666 static int perf_event_read_group(struct perf_event *event,
3667 u64 read_format, char __user *buf)
3669 struct perf_event *leader = event->group_leader, *sub;
3670 struct perf_event_context *ctx = leader->ctx;
3671 int n = 0, size = 0, ret;
3672 u64 count, enabled, running;
3673 u64 values[5];
3675 lockdep_assert_held(&ctx->mutex);
3677 count = perf_event_read_value(leader, &enabled, &running);
3679 values[n++] = 1 + leader->nr_siblings;
3680 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3681 values[n++] = enabled;
3682 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3683 values[n++] = running;
3684 values[n++] = count;
3685 if (read_format & PERF_FORMAT_ID)
3686 values[n++] = primary_event_id(leader);
3688 size = n * sizeof(u64);
3690 if (copy_to_user(buf, values, size))
3691 return -EFAULT;
3693 ret = size;
3695 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3696 n = 0;
3698 values[n++] = perf_event_read_value(sub, &enabled, &running);
3699 if (read_format & PERF_FORMAT_ID)
3700 values[n++] = primary_event_id(sub);
3702 size = n * sizeof(u64);
3704 if (copy_to_user(buf + ret, values, size)) {
3705 return -EFAULT;
3708 ret += size;
3711 return ret;
3714 static int perf_event_read_one(struct perf_event *event,
3715 u64 read_format, char __user *buf)
3717 u64 enabled, running;
3718 u64 values[4];
3719 int n = 0;
3721 values[n++] = perf_event_read_value(event, &enabled, &running);
3722 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3723 values[n++] = enabled;
3724 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3725 values[n++] = running;
3726 if (read_format & PERF_FORMAT_ID)
3727 values[n++] = primary_event_id(event);
3729 if (copy_to_user(buf, values, n * sizeof(u64)))
3730 return -EFAULT;
3732 return n * sizeof(u64);
3735 static bool is_event_hup(struct perf_event *event)
3737 bool no_children;
3739 if (event->state != PERF_EVENT_STATE_EXIT)
3740 return false;
3742 mutex_lock(&event->child_mutex);
3743 no_children = list_empty(&event->child_list);
3744 mutex_unlock(&event->child_mutex);
3745 return no_children;
3749 * Read the performance event - simple non blocking version for now
3751 static ssize_t
3752 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
3754 u64 read_format = event->attr.read_format;
3755 int ret;
3758 * Return end-of-file for a read on a event that is in
3759 * error state (i.e. because it was pinned but it couldn't be
3760 * scheduled on to the CPU at some point).
3762 if (event->state == PERF_EVENT_STATE_ERROR)
3763 return 0;
3765 if (count < event->read_size)
3766 return -ENOSPC;
3768 WARN_ON_ONCE(event->ctx->parent_ctx);
3769 if (read_format & PERF_FORMAT_GROUP)
3770 ret = perf_event_read_group(event, read_format, buf);
3771 else
3772 ret = perf_event_read_one(event, read_format, buf);
3774 return ret;
3777 static ssize_t
3778 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
3780 struct perf_event *event = file->private_data;
3781 struct perf_event_context *ctx;
3782 int ret;
3784 ctx = perf_event_ctx_lock(event);
3785 ret = perf_read_hw(event, buf, count);
3786 perf_event_ctx_unlock(event, ctx);
3788 return ret;
3791 static unsigned int perf_poll(struct file *file, poll_table *wait)
3793 struct perf_event *event = file->private_data;
3794 struct ring_buffer *rb;
3795 unsigned int events = POLLHUP;
3797 poll_wait(file, &event->waitq, wait);
3799 if (is_event_hup(event))
3800 return events;
3803 * Pin the event->rb by taking event->mmap_mutex; otherwise
3804 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
3806 mutex_lock(&event->mmap_mutex);
3807 rb = event->rb;
3808 if (rb)
3809 events = atomic_xchg(&rb->poll, 0);
3810 mutex_unlock(&event->mmap_mutex);
3811 return events;
3814 static void _perf_event_reset(struct perf_event *event)
3816 (void)perf_event_read(event);
3817 local64_set(&event->count, 0);
3818 perf_event_update_userpage(event);
3822 * Holding the top-level event's child_mutex means that any
3823 * descendant process that has inherited this event will block
3824 * in sync_child_event if it goes to exit, thus satisfying the
3825 * task existence requirements of perf_event_enable/disable.
3827 static void perf_event_for_each_child(struct perf_event *event,
3828 void (*func)(struct perf_event *))
3830 struct perf_event *child;
3832 WARN_ON_ONCE(event->ctx->parent_ctx);
3834 mutex_lock(&event->child_mutex);
3835 func(event);
3836 list_for_each_entry(child, &event->child_list, child_list)
3837 func(child);
3838 mutex_unlock(&event->child_mutex);
3841 static void perf_event_for_each(struct perf_event *event,
3842 void (*func)(struct perf_event *))
3844 struct perf_event_context *ctx = event->ctx;
3845 struct perf_event *sibling;
3847 lockdep_assert_held(&ctx->mutex);
3849 event = event->group_leader;
3851 perf_event_for_each_child(event, func);
3852 list_for_each_entry(sibling, &event->sibling_list, group_entry)
3853 perf_event_for_each_child(sibling, func);
3856 struct period_event {
3857 struct perf_event *event;
3858 u64 value;
3861 static int __perf_event_period(void *info)
3863 struct period_event *pe = info;
3864 struct perf_event *event = pe->event;
3865 struct perf_event_context *ctx = event->ctx;
3866 u64 value = pe->value;
3867 bool active;
3869 raw_spin_lock(&ctx->lock);
3870 if (event->attr.freq) {
3871 event->attr.sample_freq = value;
3872 } else {
3873 event->attr.sample_period = value;
3874 event->hw.sample_period = value;
3877 active = (event->state == PERF_EVENT_STATE_ACTIVE);
3878 if (active) {
3879 perf_pmu_disable(ctx->pmu);
3880 event->pmu->stop(event, PERF_EF_UPDATE);
3883 local64_set(&event->hw.period_left, 0);
3885 if (active) {
3886 event->pmu->start(event, PERF_EF_RELOAD);
3887 perf_pmu_enable(ctx->pmu);
3889 raw_spin_unlock(&ctx->lock);
3891 return 0;
3894 static int perf_event_period(struct perf_event *event, u64 __user *arg)
3896 struct period_event pe = { .event = event, };
3897 struct perf_event_context *ctx = event->ctx;
3898 struct task_struct *task;
3899 u64 value;
3901 if (!is_sampling_event(event))
3902 return -EINVAL;
3904 if (copy_from_user(&value, arg, sizeof(value)))
3905 return -EFAULT;
3907 if (!value)
3908 return -EINVAL;
3910 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
3911 return -EINVAL;
3913 task = ctx->task;
3914 pe.value = value;
3916 if (!task) {
3917 cpu_function_call(event->cpu, __perf_event_period, &pe);
3918 return 0;
3921 retry:
3922 if (!task_function_call(task, __perf_event_period, &pe))
3923 return 0;
3925 raw_spin_lock_irq(&ctx->lock);
3926 if (ctx->is_active) {
3927 raw_spin_unlock_irq(&ctx->lock);
3928 task = ctx->task;
3929 goto retry;
3932 __perf_event_period(&pe);
3933 raw_spin_unlock_irq(&ctx->lock);
3935 return 0;
3938 static const struct file_operations perf_fops;
3940 static inline int perf_fget_light(int fd, struct fd *p)
3942 struct fd f = fdget(fd);
3943 if (!f.file)
3944 return -EBADF;
3946 if (f.file->f_op != &perf_fops) {
3947 fdput(f);
3948 return -EBADF;
3950 *p = f;
3951 return 0;
3954 static int perf_event_set_output(struct perf_event *event,
3955 struct perf_event *output_event);
3956 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
3958 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
3960 void (*func)(struct perf_event *);
3961 u32 flags = arg;
3963 switch (cmd) {
3964 case PERF_EVENT_IOC_ENABLE:
3965 func = _perf_event_enable;
3966 break;
3967 case PERF_EVENT_IOC_DISABLE:
3968 func = _perf_event_disable;
3969 break;
3970 case PERF_EVENT_IOC_RESET:
3971 func = _perf_event_reset;
3972 break;
3974 case PERF_EVENT_IOC_REFRESH:
3975 return _perf_event_refresh(event, arg);
3977 case PERF_EVENT_IOC_PERIOD:
3978 return perf_event_period(event, (u64 __user *)arg);
3980 case PERF_EVENT_IOC_ID:
3982 u64 id = primary_event_id(event);
3984 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
3985 return -EFAULT;
3986 return 0;
3989 case PERF_EVENT_IOC_SET_OUTPUT:
3991 int ret;
3992 if (arg != -1) {
3993 struct perf_event *output_event;
3994 struct fd output;
3995 ret = perf_fget_light(arg, &output);
3996 if (ret)
3997 return ret;
3998 output_event = output.file->private_data;
3999 ret = perf_event_set_output(event, output_event);
4000 fdput(output);
4001 } else {
4002 ret = perf_event_set_output(event, NULL);
4004 return ret;
4007 case PERF_EVENT_IOC_SET_FILTER:
4008 return perf_event_set_filter(event, (void __user *)arg);
4010 default:
4011 return -ENOTTY;
4014 if (flags & PERF_IOC_FLAG_GROUP)
4015 perf_event_for_each(event, func);
4016 else
4017 perf_event_for_each_child(event, func);
4019 return 0;
4022 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4024 struct perf_event *event = file->private_data;
4025 struct perf_event_context *ctx;
4026 long ret;
4028 ctx = perf_event_ctx_lock(event);
4029 ret = _perf_ioctl(event, cmd, arg);
4030 perf_event_ctx_unlock(event, ctx);
4032 return ret;
4035 #ifdef CONFIG_COMPAT
4036 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
4037 unsigned long arg)
4039 switch (_IOC_NR(cmd)) {
4040 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
4041 case _IOC_NR(PERF_EVENT_IOC_ID):
4042 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
4043 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
4044 cmd &= ~IOCSIZE_MASK;
4045 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
4047 break;
4049 return perf_ioctl(file, cmd, arg);
4051 #else
4052 # define perf_compat_ioctl NULL
4053 #endif
4055 int perf_event_task_enable(void)
4057 struct perf_event_context *ctx;
4058 struct perf_event *event;
4060 mutex_lock(&current->perf_event_mutex);
4061 list_for_each_entry(event, &current->perf_event_list, owner_entry) {
4062 ctx = perf_event_ctx_lock(event);
4063 perf_event_for_each_child(event, _perf_event_enable);
4064 perf_event_ctx_unlock(event, ctx);
4066 mutex_unlock(&current->perf_event_mutex);
4068 return 0;
4071 int perf_event_task_disable(void)
4073 struct perf_event_context *ctx;
4074 struct perf_event *event;
4076 mutex_lock(&current->perf_event_mutex);
4077 list_for_each_entry(event, &current->perf_event_list, owner_entry) {
4078 ctx = perf_event_ctx_lock(event);
4079 perf_event_for_each_child(event, _perf_event_disable);
4080 perf_event_ctx_unlock(event, ctx);
4082 mutex_unlock(&current->perf_event_mutex);
4084 return 0;
4087 static int perf_event_index(struct perf_event *event)
4089 if (event->hw.state & PERF_HES_STOPPED)
4090 return 0;
4092 if (event->state != PERF_EVENT_STATE_ACTIVE)
4093 return 0;
4095 return event->pmu->event_idx(event);
4098 static void calc_timer_values(struct perf_event *event,
4099 u64 *now,
4100 u64 *enabled,
4101 u64 *running)
4103 u64 ctx_time;
4105 *now = perf_clock();
4106 ctx_time = event->shadow_ctx_time + *now;
4107 *enabled = ctx_time - event->tstamp_enabled;
4108 *running = ctx_time - event->tstamp_running;
4111 static void perf_event_init_userpage(struct perf_event *event)
4113 struct perf_event_mmap_page *userpg;
4114 struct ring_buffer *rb;
4116 rcu_read_lock();
4117 rb = rcu_dereference(event->rb);
4118 if (!rb)
4119 goto unlock;
4121 userpg = rb->user_page;
4123 /* Allow new userspace to detect that bit 0 is deprecated */
4124 userpg->cap_bit0_is_deprecated = 1;
4125 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
4127 unlock:
4128 rcu_read_unlock();
4131 void __weak arch_perf_update_userpage(struct perf_event_mmap_page *userpg, u64 now)
4136 * Callers need to ensure there can be no nesting of this function, otherwise
4137 * the seqlock logic goes bad. We can not serialize this because the arch
4138 * code calls this from NMI context.
4140 void perf_event_update_userpage(struct perf_event *event)
4142 struct perf_event_mmap_page *userpg;
4143 struct ring_buffer *rb;
4144 u64 enabled, running, now;
4146 rcu_read_lock();
4147 rb = rcu_dereference(event->rb);
4148 if (!rb)
4149 goto unlock;
4152 * compute total_time_enabled, total_time_running
4153 * based on snapshot values taken when the event
4154 * was last scheduled in.
4156 * we cannot simply called update_context_time()
4157 * because of locking issue as we can be called in
4158 * NMI context
4160 calc_timer_values(event, &now, &enabled, &running);
4162 userpg = rb->user_page;
4164 * Disable preemption so as to not let the corresponding user-space
4165 * spin too long if we get preempted.
4167 preempt_disable();
4168 ++userpg->lock;
4169 barrier();
4170 userpg->index = perf_event_index(event);
4171 userpg->offset = perf_event_count(event);
4172 if (userpg->index)
4173 userpg->offset -= local64_read(&event->hw.prev_count);
4175 userpg->time_enabled = enabled +
4176 atomic64_read(&event->child_total_time_enabled);
4178 userpg->time_running = running +
4179 atomic64_read(&event->child_total_time_running);
4181 arch_perf_update_userpage(userpg, now);
4183 barrier();
4184 ++userpg->lock;
4185 preempt_enable();
4186 unlock:
4187 rcu_read_unlock();
4190 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
4192 struct perf_event *event = vma->vm_file->private_data;
4193 struct ring_buffer *rb;
4194 int ret = VM_FAULT_SIGBUS;
4196 if (vmf->flags & FAULT_FLAG_MKWRITE) {
4197 if (vmf->pgoff == 0)
4198 ret = 0;
4199 return ret;
4202 rcu_read_lock();
4203 rb = rcu_dereference(event->rb);
4204 if (!rb)
4205 goto unlock;
4207 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
4208 goto unlock;
4210 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
4211 if (!vmf->page)
4212 goto unlock;
4214 get_page(vmf->page);
4215 vmf->page->mapping = vma->vm_file->f_mapping;
4216 vmf->page->index = vmf->pgoff;
4218 ret = 0;
4219 unlock:
4220 rcu_read_unlock();
4222 return ret;
4225 static void ring_buffer_attach(struct perf_event *event,
4226 struct ring_buffer *rb)
4228 struct ring_buffer *old_rb = NULL;
4229 unsigned long flags;
4231 if (event->rb) {
4233 * Should be impossible, we set this when removing
4234 * event->rb_entry and wait/clear when adding event->rb_entry.
4236 WARN_ON_ONCE(event->rcu_pending);
4238 old_rb = event->rb;
4239 spin_lock_irqsave(&old_rb->event_lock, flags);
4240 list_del_rcu(&event->rb_entry);
4241 spin_unlock_irqrestore(&old_rb->event_lock, flags);
4243 event->rcu_batches = get_state_synchronize_rcu();
4244 event->rcu_pending = 1;
4247 if (rb) {
4248 if (event->rcu_pending) {
4249 cond_synchronize_rcu(event->rcu_batches);
4250 event->rcu_pending = 0;
4253 spin_lock_irqsave(&rb->event_lock, flags);
4254 list_add_rcu(&event->rb_entry, &rb->event_list);
4255 spin_unlock_irqrestore(&rb->event_lock, flags);
4258 rcu_assign_pointer(event->rb, rb);
4260 if (old_rb) {
4261 ring_buffer_put(old_rb);
4263 * Since we detached before setting the new rb, so that we
4264 * could attach the new rb, we could have missed a wakeup.
4265 * Provide it now.
4267 wake_up_all(&event->waitq);
4271 static void ring_buffer_wakeup(struct perf_event *event)
4273 struct ring_buffer *rb;
4275 rcu_read_lock();
4276 rb = rcu_dereference(event->rb);
4277 if (rb) {
4278 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
4279 wake_up_all(&event->waitq);
4281 rcu_read_unlock();
4284 static void rb_free_rcu(struct rcu_head *rcu_head)
4286 struct ring_buffer *rb;
4288 rb = container_of(rcu_head, struct ring_buffer, rcu_head);
4289 rb_free(rb);
4292 static struct ring_buffer *ring_buffer_get(struct perf_event *event)
4294 struct ring_buffer *rb;
4296 rcu_read_lock();
4297 rb = rcu_dereference(event->rb);
4298 if (rb) {
4299 if (!atomic_inc_not_zero(&rb->refcount))
4300 rb = NULL;
4302 rcu_read_unlock();
4304 return rb;
4307 static void ring_buffer_put(struct ring_buffer *rb)
4309 if (!atomic_dec_and_test(&rb->refcount))
4310 return;
4312 WARN_ON_ONCE(!list_empty(&rb->event_list));
4314 call_rcu(&rb->rcu_head, rb_free_rcu);
4317 static void perf_mmap_open(struct vm_area_struct *vma)
4319 struct perf_event *event = vma->vm_file->private_data;
4321 atomic_inc(&event->mmap_count);
4322 atomic_inc(&event->rb->mmap_count);
4326 * A buffer can be mmap()ed multiple times; either directly through the same
4327 * event, or through other events by use of perf_event_set_output().
4329 * In order to undo the VM accounting done by perf_mmap() we need to destroy
4330 * the buffer here, where we still have a VM context. This means we need
4331 * to detach all events redirecting to us.
4333 static void perf_mmap_close(struct vm_area_struct *vma)
4335 struct perf_event *event = vma->vm_file->private_data;
4337 struct ring_buffer *rb = ring_buffer_get(event);
4338 struct user_struct *mmap_user = rb->mmap_user;
4339 int mmap_locked = rb->mmap_locked;
4340 unsigned long size = perf_data_size(rb);
4342 atomic_dec(&rb->mmap_count);
4344 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
4345 goto out_put;
4347 ring_buffer_attach(event, NULL);
4348 mutex_unlock(&event->mmap_mutex);
4350 /* If there's still other mmap()s of this buffer, we're done. */
4351 if (atomic_read(&rb->mmap_count))
4352 goto out_put;
4355 * No other mmap()s, detach from all other events that might redirect
4356 * into the now unreachable buffer. Somewhat complicated by the
4357 * fact that rb::event_lock otherwise nests inside mmap_mutex.
4359 again:
4360 rcu_read_lock();
4361 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4362 if (!atomic_long_inc_not_zero(&event->refcount)) {
4364 * This event is en-route to free_event() which will
4365 * detach it and remove it from the list.
4367 continue;
4369 rcu_read_unlock();
4371 mutex_lock(&event->mmap_mutex);
4373 * Check we didn't race with perf_event_set_output() which can
4374 * swizzle the rb from under us while we were waiting to
4375 * acquire mmap_mutex.
4377 * If we find a different rb; ignore this event, a next
4378 * iteration will no longer find it on the list. We have to
4379 * still restart the iteration to make sure we're not now
4380 * iterating the wrong list.
4382 if (event->rb == rb)
4383 ring_buffer_attach(event, NULL);
4385 mutex_unlock(&event->mmap_mutex);
4386 put_event(event);
4389 * Restart the iteration; either we're on the wrong list or
4390 * destroyed its integrity by doing a deletion.
4392 goto again;
4394 rcu_read_unlock();
4397 * It could be there's still a few 0-ref events on the list; they'll
4398 * get cleaned up by free_event() -- they'll also still have their
4399 * ref on the rb and will free it whenever they are done with it.
4401 * Aside from that, this buffer is 'fully' detached and unmapped,
4402 * undo the VM accounting.
4405 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4406 vma->vm_mm->pinned_vm -= mmap_locked;
4407 free_uid(mmap_user);
4409 out_put:
4410 ring_buffer_put(rb); /* could be last */
4413 static const struct vm_operations_struct perf_mmap_vmops = {
4414 .open = perf_mmap_open,
4415 .close = perf_mmap_close,
4416 .fault = perf_mmap_fault,
4417 .page_mkwrite = perf_mmap_fault,
4420 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
4422 struct perf_event *event = file->private_data;
4423 unsigned long user_locked, user_lock_limit;
4424 struct user_struct *user = current_user();
4425 unsigned long locked, lock_limit;
4426 struct ring_buffer *rb;
4427 unsigned long vma_size;
4428 unsigned long nr_pages;
4429 long user_extra, extra;
4430 int ret = 0, flags = 0;
4433 * Don't allow mmap() of inherited per-task counters. This would
4434 * create a performance issue due to all children writing to the
4435 * same rb.
4437 if (event->cpu == -1 && event->attr.inherit)
4438 return -EINVAL;
4440 if (!(vma->vm_flags & VM_SHARED))
4441 return -EINVAL;
4443 vma_size = vma->vm_end - vma->vm_start;
4444 nr_pages = (vma_size / PAGE_SIZE) - 1;
4447 * If we have rb pages ensure they're a power-of-two number, so we
4448 * can do bitmasks instead of modulo.
4450 if (nr_pages != 0 && !is_power_of_2(nr_pages))
4451 return -EINVAL;
4453 if (vma_size != PAGE_SIZE * (1 + nr_pages))
4454 return -EINVAL;
4456 if (vma->vm_pgoff != 0)
4457 return -EINVAL;
4459 WARN_ON_ONCE(event->ctx->parent_ctx);
4460 again:
4461 mutex_lock(&event->mmap_mutex);
4462 if (event->rb) {
4463 if (event->rb->nr_pages != nr_pages) {
4464 ret = -EINVAL;
4465 goto unlock;
4468 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4470 * Raced against perf_mmap_close() through
4471 * perf_event_set_output(). Try again, hope for better
4472 * luck.
4474 mutex_unlock(&event->mmap_mutex);
4475 goto again;
4478 goto unlock;
4481 user_extra = nr_pages + 1;
4482 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
4485 * Increase the limit linearly with more CPUs:
4487 user_lock_limit *= num_online_cpus();
4489 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
4491 extra = 0;
4492 if (user_locked > user_lock_limit)
4493 extra = user_locked - user_lock_limit;
4495 lock_limit = rlimit(RLIMIT_MEMLOCK);
4496 lock_limit >>= PAGE_SHIFT;
4497 locked = vma->vm_mm->pinned_vm + extra;
4499 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
4500 !capable(CAP_IPC_LOCK)) {
4501 ret = -EPERM;
4502 goto unlock;
4505 WARN_ON(event->rb);
4507 if (vma->vm_flags & VM_WRITE)
4508 flags |= RING_BUFFER_WRITABLE;
4510 rb = rb_alloc(nr_pages,
4511 event->attr.watermark ? event->attr.wakeup_watermark : 0,
4512 event->cpu, flags);
4514 if (!rb) {
4515 ret = -ENOMEM;
4516 goto unlock;
4519 atomic_set(&rb->mmap_count, 1);
4520 rb->mmap_locked = extra;
4521 rb->mmap_user = get_current_user();
4523 atomic_long_add(user_extra, &user->locked_vm);
4524 vma->vm_mm->pinned_vm += extra;
4526 ring_buffer_attach(event, rb);
4528 perf_event_init_userpage(event);
4529 perf_event_update_userpage(event);
4531 unlock:
4532 if (!ret)
4533 atomic_inc(&event->mmap_count);
4534 mutex_unlock(&event->mmap_mutex);
4537 * Since pinned accounting is per vm we cannot allow fork() to copy our
4538 * vma.
4540 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
4541 vma->vm_ops = &perf_mmap_vmops;
4543 return ret;
4546 static int perf_fasync(int fd, struct file *filp, int on)
4548 struct inode *inode = file_inode(filp);
4549 struct perf_event *event = filp->private_data;
4550 int retval;
4552 mutex_lock(&inode->i_mutex);
4553 retval = fasync_helper(fd, filp, on, &event->fasync);
4554 mutex_unlock(&inode->i_mutex);
4556 if (retval < 0)
4557 return retval;
4559 return 0;
4562 static const struct file_operations perf_fops = {
4563 .llseek = no_llseek,
4564 .release = perf_release,
4565 .read = perf_read,
4566 .poll = perf_poll,
4567 .unlocked_ioctl = perf_ioctl,
4568 .compat_ioctl = perf_compat_ioctl,
4569 .mmap = perf_mmap,
4570 .fasync = perf_fasync,
4574 * Perf event wakeup
4576 * If there's data, ensure we set the poll() state and publish everything
4577 * to user-space before waking everybody up.
4580 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
4582 /* only the parent has fasync state */
4583 if (event->parent)
4584 event = event->parent;
4585 return &event->fasync;
4588 void perf_event_wakeup(struct perf_event *event)
4590 ring_buffer_wakeup(event);
4592 if (event->pending_kill) {
4593 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
4594 event->pending_kill = 0;
4598 static void perf_pending_event(struct irq_work *entry)
4600 struct perf_event *event = container_of(entry,
4601 struct perf_event, pending);
4602 int rctx;
4604 rctx = perf_swevent_get_recursion_context();
4606 * If we 'fail' here, that's OK, it means recursion is already disabled
4607 * and we won't recurse 'further'.
4610 if (event->pending_disable) {
4611 event->pending_disable = 0;
4612 __perf_event_disable(event);
4615 if (event->pending_wakeup) {
4616 event->pending_wakeup = 0;
4617 perf_event_wakeup(event);
4620 if (rctx >= 0)
4621 perf_swevent_put_recursion_context(rctx);
4625 * We assume there is only KVM supporting the callbacks.
4626 * Later on, we might change it to a list if there is
4627 * another virtualization implementation supporting the callbacks.
4629 struct perf_guest_info_callbacks *perf_guest_cbs;
4631 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4633 perf_guest_cbs = cbs;
4634 return 0;
4636 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
4638 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4640 perf_guest_cbs = NULL;
4641 return 0;
4643 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
4645 static void
4646 perf_output_sample_regs(struct perf_output_handle *handle,
4647 struct pt_regs *regs, u64 mask)
4649 int bit;
4651 for_each_set_bit(bit, (const unsigned long *) &mask,
4652 sizeof(mask) * BITS_PER_BYTE) {
4653 u64 val;
4655 val = perf_reg_value(regs, bit);
4656 perf_output_put(handle, val);
4660 static void perf_sample_regs_user(struct perf_regs_user *regs_user,
4661 struct pt_regs *regs)
4663 if (!user_mode(regs)) {
4664 if (current->mm)
4665 regs = task_pt_regs(current);
4666 else
4667 regs = NULL;
4670 if (regs) {
4671 regs_user->regs = regs;
4672 regs_user->abi = perf_reg_abi(current);
4677 * Get remaining task size from user stack pointer.
4679 * It'd be better to take stack vma map and limit this more
4680 * precisly, but there's no way to get it safely under interrupt,
4681 * so using TASK_SIZE as limit.
4683 static u64 perf_ustack_task_size(struct pt_regs *regs)
4685 unsigned long addr = perf_user_stack_pointer(regs);
4687 if (!addr || addr >= TASK_SIZE)
4688 return 0;
4690 return TASK_SIZE - addr;
4693 static u16
4694 perf_sample_ustack_size(u16 stack_size, u16 header_size,
4695 struct pt_regs *regs)
4697 u64 task_size;
4699 /* No regs, no stack pointer, no dump. */
4700 if (!regs)
4701 return 0;
4704 * Check if we fit in with the requested stack size into the:
4705 * - TASK_SIZE
4706 * If we don't, we limit the size to the TASK_SIZE.
4708 * - remaining sample size
4709 * If we don't, we customize the stack size to
4710 * fit in to the remaining sample size.
4713 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
4714 stack_size = min(stack_size, (u16) task_size);
4716 /* Current header size plus static size and dynamic size. */
4717 header_size += 2 * sizeof(u64);
4719 /* Do we fit in with the current stack dump size? */
4720 if ((u16) (header_size + stack_size) < header_size) {
4722 * If we overflow the maximum size for the sample,
4723 * we customize the stack dump size to fit in.
4725 stack_size = USHRT_MAX - header_size - sizeof(u64);
4726 stack_size = round_up(stack_size, sizeof(u64));
4729 return stack_size;
4732 static void
4733 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
4734 struct pt_regs *regs)
4736 /* Case of a kernel thread, nothing to dump */
4737 if (!regs) {
4738 u64 size = 0;
4739 perf_output_put(handle, size);
4740 } else {
4741 unsigned long sp;
4742 unsigned int rem;
4743 u64 dyn_size;
4746 * We dump:
4747 * static size
4748 * - the size requested by user or the best one we can fit
4749 * in to the sample max size
4750 * data
4751 * - user stack dump data
4752 * dynamic size
4753 * - the actual dumped size
4756 /* Static size. */
4757 perf_output_put(handle, dump_size);
4759 /* Data. */
4760 sp = perf_user_stack_pointer(regs);
4761 rem = __output_copy_user(handle, (void *) sp, dump_size);
4762 dyn_size = dump_size - rem;
4764 perf_output_skip(handle, rem);
4766 /* Dynamic size. */
4767 perf_output_put(handle, dyn_size);
4771 static void __perf_event_header__init_id(struct perf_event_header *header,
4772 struct perf_sample_data *data,
4773 struct perf_event *event)
4775 u64 sample_type = event->attr.sample_type;
4777 data->type = sample_type;
4778 header->size += event->id_header_size;
4780 if (sample_type & PERF_SAMPLE_TID) {
4781 /* namespace issues */
4782 data->tid_entry.pid = perf_event_pid(event, current);
4783 data->tid_entry.tid = perf_event_tid(event, current);
4786 if (sample_type & PERF_SAMPLE_TIME)
4787 data->time = perf_clock();
4789 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
4790 data->id = primary_event_id(event);
4792 if (sample_type & PERF_SAMPLE_STREAM_ID)
4793 data->stream_id = event->id;
4795 if (sample_type & PERF_SAMPLE_CPU) {
4796 data->cpu_entry.cpu = raw_smp_processor_id();
4797 data->cpu_entry.reserved = 0;
4801 void perf_event_header__init_id(struct perf_event_header *header,
4802 struct perf_sample_data *data,
4803 struct perf_event *event)
4805 if (event->attr.sample_id_all)
4806 __perf_event_header__init_id(header, data, event);
4809 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
4810 struct perf_sample_data *data)
4812 u64 sample_type = data->type;
4814 if (sample_type & PERF_SAMPLE_TID)
4815 perf_output_put(handle, data->tid_entry);
4817 if (sample_type & PERF_SAMPLE_TIME)
4818 perf_output_put(handle, data->time);
4820 if (sample_type & PERF_SAMPLE_ID)
4821 perf_output_put(handle, data->id);
4823 if (sample_type & PERF_SAMPLE_STREAM_ID)
4824 perf_output_put(handle, data->stream_id);
4826 if (sample_type & PERF_SAMPLE_CPU)
4827 perf_output_put(handle, data->cpu_entry);
4829 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4830 perf_output_put(handle, data->id);
4833 void perf_event__output_id_sample(struct perf_event *event,
4834 struct perf_output_handle *handle,
4835 struct perf_sample_data *sample)
4837 if (event->attr.sample_id_all)
4838 __perf_event__output_id_sample(handle, sample);
4841 static void perf_output_read_one(struct perf_output_handle *handle,
4842 struct perf_event *event,
4843 u64 enabled, u64 running)
4845 u64 read_format = event->attr.read_format;
4846 u64 values[4];
4847 int n = 0;
4849 values[n++] = perf_event_count(event);
4850 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4851 values[n++] = enabled +
4852 atomic64_read(&event->child_total_time_enabled);
4854 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4855 values[n++] = running +
4856 atomic64_read(&event->child_total_time_running);
4858 if (read_format & PERF_FORMAT_ID)
4859 values[n++] = primary_event_id(event);
4861 __output_copy(handle, values, n * sizeof(u64));
4865 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
4867 static void perf_output_read_group(struct perf_output_handle *handle,
4868 struct perf_event *event,
4869 u64 enabled, u64 running)
4871 struct perf_event *leader = event->group_leader, *sub;
4872 u64 read_format = event->attr.read_format;
4873 u64 values[5];
4874 int n = 0;
4876 values[n++] = 1 + leader->nr_siblings;
4878 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4879 values[n++] = enabled;
4881 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4882 values[n++] = running;
4884 if (leader != event)
4885 leader->pmu->read(leader);
4887 values[n++] = perf_event_count(leader);
4888 if (read_format & PERF_FORMAT_ID)
4889 values[n++] = primary_event_id(leader);
4891 __output_copy(handle, values, n * sizeof(u64));
4893 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4894 n = 0;
4896 if ((sub != event) &&
4897 (sub->state == PERF_EVENT_STATE_ACTIVE))
4898 sub->pmu->read(sub);
4900 values[n++] = perf_event_count(sub);
4901 if (read_format & PERF_FORMAT_ID)
4902 values[n++] = primary_event_id(sub);
4904 __output_copy(handle, values, n * sizeof(u64));
4908 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
4909 PERF_FORMAT_TOTAL_TIME_RUNNING)
4911 static void perf_output_read(struct perf_output_handle *handle,
4912 struct perf_event *event)
4914 u64 enabled = 0, running = 0, now;
4915 u64 read_format = event->attr.read_format;
4918 * compute total_time_enabled, total_time_running
4919 * based on snapshot values taken when the event
4920 * was last scheduled in.
4922 * we cannot simply called update_context_time()
4923 * because of locking issue as we are called in
4924 * NMI context
4926 if (read_format & PERF_FORMAT_TOTAL_TIMES)
4927 calc_timer_values(event, &now, &enabled, &running);
4929 if (event->attr.read_format & PERF_FORMAT_GROUP)
4930 perf_output_read_group(handle, event, enabled, running);
4931 else
4932 perf_output_read_one(handle, event, enabled, running);
4935 void perf_output_sample(struct perf_output_handle *handle,
4936 struct perf_event_header *header,
4937 struct perf_sample_data *data,
4938 struct perf_event *event)
4940 u64 sample_type = data->type;
4942 perf_output_put(handle, *header);
4944 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4945 perf_output_put(handle, data->id);
4947 if (sample_type & PERF_SAMPLE_IP)
4948 perf_output_put(handle, data->ip);
4950 if (sample_type & PERF_SAMPLE_TID)
4951 perf_output_put(handle, data->tid_entry);
4953 if (sample_type & PERF_SAMPLE_TIME)
4954 perf_output_put(handle, data->time);
4956 if (sample_type & PERF_SAMPLE_ADDR)
4957 perf_output_put(handle, data->addr);
4959 if (sample_type & PERF_SAMPLE_ID)
4960 perf_output_put(handle, data->id);
4962 if (sample_type & PERF_SAMPLE_STREAM_ID)
4963 perf_output_put(handle, data->stream_id);
4965 if (sample_type & PERF_SAMPLE_CPU)
4966 perf_output_put(handle, data->cpu_entry);
4968 if (sample_type & PERF_SAMPLE_PERIOD)
4969 perf_output_put(handle, data->period);
4971 if (sample_type & PERF_SAMPLE_READ)
4972 perf_output_read(handle, event);
4974 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4975 if (data->callchain) {
4976 int size = 1;
4978 if (data->callchain)
4979 size += data->callchain->nr;
4981 size *= sizeof(u64);
4983 __output_copy(handle, data->callchain, size);
4984 } else {
4985 u64 nr = 0;
4986 perf_output_put(handle, nr);
4990 if (sample_type & PERF_SAMPLE_RAW) {
4991 if (data->raw) {
4992 perf_output_put(handle, data->raw->size);
4993 __output_copy(handle, data->raw->data,
4994 data->raw->size);
4995 } else {
4996 struct {
4997 u32 size;
4998 u32 data;
4999 } raw = {
5000 .size = sizeof(u32),
5001 .data = 0,
5003 perf_output_put(handle, raw);
5007 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5008 if (data->br_stack) {
5009 size_t size;
5011 size = data->br_stack->nr
5012 * sizeof(struct perf_branch_entry);
5014 perf_output_put(handle, data->br_stack->nr);
5015 perf_output_copy(handle, data->br_stack->entries, size);
5016 } else {
5018 * we always store at least the value of nr
5020 u64 nr = 0;
5021 perf_output_put(handle, nr);
5025 if (sample_type & PERF_SAMPLE_REGS_USER) {
5026 u64 abi = data->regs_user.abi;
5029 * If there are no regs to dump, notice it through
5030 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5032 perf_output_put(handle, abi);
5034 if (abi) {
5035 u64 mask = event->attr.sample_regs_user;
5036 perf_output_sample_regs(handle,
5037 data->regs_user.regs,
5038 mask);
5042 if (sample_type & PERF_SAMPLE_STACK_USER) {
5043 perf_output_sample_ustack(handle,
5044 data->stack_user_size,
5045 data->regs_user.regs);
5048 if (sample_type & PERF_SAMPLE_WEIGHT)
5049 perf_output_put(handle, data->weight);
5051 if (sample_type & PERF_SAMPLE_DATA_SRC)
5052 perf_output_put(handle, data->data_src.val);
5054 if (sample_type & PERF_SAMPLE_TRANSACTION)
5055 perf_output_put(handle, data->txn);
5057 if (!event->attr.watermark) {
5058 int wakeup_events = event->attr.wakeup_events;
5060 if (wakeup_events) {
5061 struct ring_buffer *rb = handle->rb;
5062 int events = local_inc_return(&rb->events);
5064 if (events >= wakeup_events) {
5065 local_sub(wakeup_events, &rb->events);
5066 local_inc(&rb->wakeup);
5072 void perf_prepare_sample(struct perf_event_header *header,
5073 struct perf_sample_data *data,
5074 struct perf_event *event,
5075 struct pt_regs *regs)
5077 u64 sample_type = event->attr.sample_type;
5079 header->type = PERF_RECORD_SAMPLE;
5080 header->size = sizeof(*header) + event->header_size;
5082 header->misc = 0;
5083 header->misc |= perf_misc_flags(regs);
5085 __perf_event_header__init_id(header, data, event);
5087 if (sample_type & PERF_SAMPLE_IP)
5088 data->ip = perf_instruction_pointer(regs);
5090 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5091 int size = 1;
5093 data->callchain = perf_callchain(event, regs);
5095 if (data->callchain)
5096 size += data->callchain->nr;
5098 header->size += size * sizeof(u64);
5101 if (sample_type & PERF_SAMPLE_RAW) {
5102 int size = sizeof(u32);
5104 if (data->raw)
5105 size += data->raw->size;
5106 else
5107 size += sizeof(u32);
5109 WARN_ON_ONCE(size & (sizeof(u64)-1));
5110 header->size += size;
5113 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5114 int size = sizeof(u64); /* nr */
5115 if (data->br_stack) {
5116 size += data->br_stack->nr
5117 * sizeof(struct perf_branch_entry);
5119 header->size += size;
5122 if (sample_type & PERF_SAMPLE_REGS_USER) {
5123 /* regs dump ABI info */
5124 int size = sizeof(u64);
5126 perf_sample_regs_user(&data->regs_user, regs);
5128 if (data->regs_user.regs) {
5129 u64 mask = event->attr.sample_regs_user;
5130 size += hweight64(mask) * sizeof(u64);
5133 header->size += size;
5136 if (sample_type & PERF_SAMPLE_STACK_USER) {
5138 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
5139 * processed as the last one or have additional check added
5140 * in case new sample type is added, because we could eat
5141 * up the rest of the sample size.
5143 struct perf_regs_user *uregs = &data->regs_user;
5144 u16 stack_size = event->attr.sample_stack_user;
5145 u16 size = sizeof(u64);
5147 if (!uregs->abi)
5148 perf_sample_regs_user(uregs, regs);
5150 stack_size = perf_sample_ustack_size(stack_size, header->size,
5151 uregs->regs);
5154 * If there is something to dump, add space for the dump
5155 * itself and for the field that tells the dynamic size,
5156 * which is how many have been actually dumped.
5158 if (stack_size)
5159 size += sizeof(u64) + stack_size;
5161 data->stack_user_size = stack_size;
5162 header->size += size;
5166 static void perf_event_output(struct perf_event *event,
5167 struct perf_sample_data *data,
5168 struct pt_regs *regs)
5170 struct perf_output_handle handle;
5171 struct perf_event_header header;
5173 /* protect the callchain buffers */
5174 rcu_read_lock();
5176 perf_prepare_sample(&header, data, event, regs);
5178 if (perf_output_begin(&handle, event, header.size))
5179 goto exit;
5181 perf_output_sample(&handle, &header, data, event);
5183 perf_output_end(&handle);
5185 exit:
5186 rcu_read_unlock();
5190 * read event_id
5193 struct perf_read_event {
5194 struct perf_event_header header;
5196 u32 pid;
5197 u32 tid;
5200 static void
5201 perf_event_read_event(struct perf_event *event,
5202 struct task_struct *task)
5204 struct perf_output_handle handle;
5205 struct perf_sample_data sample;
5206 struct perf_read_event read_event = {
5207 .header = {
5208 .type = PERF_RECORD_READ,
5209 .misc = 0,
5210 .size = sizeof(read_event) + event->read_size,
5212 .pid = perf_event_pid(event, task),
5213 .tid = perf_event_tid(event, task),
5215 int ret;
5217 perf_event_header__init_id(&read_event.header, &sample, event);
5218 ret = perf_output_begin(&handle, event, read_event.header.size);
5219 if (ret)
5220 return;
5222 perf_output_put(&handle, read_event);
5223 perf_output_read(&handle, event);
5224 perf_event__output_id_sample(event, &handle, &sample);
5226 perf_output_end(&handle);
5229 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
5231 static void
5232 perf_event_aux_ctx(struct perf_event_context *ctx,
5233 perf_event_aux_output_cb output,
5234 void *data)
5236 struct perf_event *event;
5238 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5239 if (event->state < PERF_EVENT_STATE_INACTIVE)
5240 continue;
5241 if (!event_filter_match(event))
5242 continue;
5243 output(event, data);
5247 static void
5248 perf_event_aux(perf_event_aux_output_cb output, void *data,
5249 struct perf_event_context *task_ctx)
5251 struct perf_cpu_context *cpuctx;
5252 struct perf_event_context *ctx;
5253 struct pmu *pmu;
5254 int ctxn;
5256 rcu_read_lock();
5257 list_for_each_entry_rcu(pmu, &pmus, entry) {
5258 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
5259 if (cpuctx->unique_pmu != pmu)
5260 goto next;
5261 perf_event_aux_ctx(&cpuctx->ctx, output, data);
5262 if (task_ctx)
5263 goto next;
5264 ctxn = pmu->task_ctx_nr;
5265 if (ctxn < 0)
5266 goto next;
5267 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
5268 if (ctx)
5269 perf_event_aux_ctx(ctx, output, data);
5270 next:
5271 put_cpu_ptr(pmu->pmu_cpu_context);
5274 if (task_ctx) {
5275 preempt_disable();
5276 perf_event_aux_ctx(task_ctx, output, data);
5277 preempt_enable();
5279 rcu_read_unlock();
5283 * task tracking -- fork/exit
5285 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
5288 struct perf_task_event {
5289 struct task_struct *task;
5290 struct perf_event_context *task_ctx;
5292 struct {
5293 struct perf_event_header header;
5295 u32 pid;
5296 u32 ppid;
5297 u32 tid;
5298 u32 ptid;
5299 u64 time;
5300 } event_id;
5303 static int perf_event_task_match(struct perf_event *event)
5305 return event->attr.comm || event->attr.mmap ||
5306 event->attr.mmap2 || event->attr.mmap_data ||
5307 event->attr.task;
5310 static void perf_event_task_output(struct perf_event *event,
5311 void *data)
5313 struct perf_task_event *task_event = data;
5314 struct perf_output_handle handle;
5315 struct perf_sample_data sample;
5316 struct task_struct *task = task_event->task;
5317 int ret, size = task_event->event_id.header.size;
5319 if (!perf_event_task_match(event))
5320 return;
5322 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
5324 ret = perf_output_begin(&handle, event,
5325 task_event->event_id.header.size);
5326 if (ret)
5327 goto out;
5329 task_event->event_id.pid = perf_event_pid(event, task);
5330 task_event->event_id.ppid = perf_event_pid(event, current);
5332 task_event->event_id.tid = perf_event_tid(event, task);
5333 task_event->event_id.ptid = perf_event_tid(event, current);
5335 perf_output_put(&handle, task_event->event_id);
5337 perf_event__output_id_sample(event, &handle, &sample);
5339 perf_output_end(&handle);
5340 out:
5341 task_event->event_id.header.size = size;
5344 static void perf_event_task(struct task_struct *task,
5345 struct perf_event_context *task_ctx,
5346 int new)
5348 struct perf_task_event task_event;
5350 if (!atomic_read(&nr_comm_events) &&
5351 !atomic_read(&nr_mmap_events) &&
5352 !atomic_read(&nr_task_events))
5353 return;
5355 task_event = (struct perf_task_event){
5356 .task = task,
5357 .task_ctx = task_ctx,
5358 .event_id = {
5359 .header = {
5360 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
5361 .misc = 0,
5362 .size = sizeof(task_event.event_id),
5364 /* .pid */
5365 /* .ppid */
5366 /* .tid */
5367 /* .ptid */
5368 .time = perf_clock(),
5372 perf_event_aux(perf_event_task_output,
5373 &task_event,
5374 task_ctx);
5377 void perf_event_fork(struct task_struct *task)
5379 perf_event_task(task, NULL, 1);
5383 * comm tracking
5386 struct perf_comm_event {
5387 struct task_struct *task;
5388 char *comm;
5389 int comm_size;
5391 struct {
5392 struct perf_event_header header;
5394 u32 pid;
5395 u32 tid;
5396 } event_id;
5399 static int perf_event_comm_match(struct perf_event *event)
5401 return event->attr.comm;
5404 static void perf_event_comm_output(struct perf_event *event,
5405 void *data)
5407 struct perf_comm_event *comm_event = data;
5408 struct perf_output_handle handle;
5409 struct perf_sample_data sample;
5410 int size = comm_event->event_id.header.size;
5411 int ret;
5413 if (!perf_event_comm_match(event))
5414 return;
5416 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
5417 ret = perf_output_begin(&handle, event,
5418 comm_event->event_id.header.size);
5420 if (ret)
5421 goto out;
5423 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
5424 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
5426 perf_output_put(&handle, comm_event->event_id);
5427 __output_copy(&handle, comm_event->comm,
5428 comm_event->comm_size);
5430 perf_event__output_id_sample(event, &handle, &sample);
5432 perf_output_end(&handle);
5433 out:
5434 comm_event->event_id.header.size = size;
5437 static void perf_event_comm_event(struct perf_comm_event *comm_event)
5439 char comm[TASK_COMM_LEN];
5440 unsigned int size;
5442 memset(comm, 0, sizeof(comm));
5443 strlcpy(comm, comm_event->task->comm, sizeof(comm));
5444 size = ALIGN(strlen(comm)+1, sizeof(u64));
5446 comm_event->comm = comm;
5447 comm_event->comm_size = size;
5449 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
5451 perf_event_aux(perf_event_comm_output,
5452 comm_event,
5453 NULL);
5456 void perf_event_comm(struct task_struct *task, bool exec)
5458 struct perf_comm_event comm_event;
5460 if (!atomic_read(&nr_comm_events))
5461 return;
5463 comm_event = (struct perf_comm_event){
5464 .task = task,
5465 /* .comm */
5466 /* .comm_size */
5467 .event_id = {
5468 .header = {
5469 .type = PERF_RECORD_COMM,
5470 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
5471 /* .size */
5473 /* .pid */
5474 /* .tid */
5478 perf_event_comm_event(&comm_event);
5482 * mmap tracking
5485 struct perf_mmap_event {
5486 struct vm_area_struct *vma;
5488 const char *file_name;
5489 int file_size;
5490 int maj, min;
5491 u64 ino;
5492 u64 ino_generation;
5493 u32 prot, flags;
5495 struct {
5496 struct perf_event_header header;
5498 u32 pid;
5499 u32 tid;
5500 u64 start;
5501 u64 len;
5502 u64 pgoff;
5503 } event_id;
5506 static int perf_event_mmap_match(struct perf_event *event,
5507 void *data)
5509 struct perf_mmap_event *mmap_event = data;
5510 struct vm_area_struct *vma = mmap_event->vma;
5511 int executable = vma->vm_flags & VM_EXEC;
5513 return (!executable && event->attr.mmap_data) ||
5514 (executable && (event->attr.mmap || event->attr.mmap2));
5517 static void perf_event_mmap_output(struct perf_event *event,
5518 void *data)
5520 struct perf_mmap_event *mmap_event = data;
5521 struct perf_output_handle handle;
5522 struct perf_sample_data sample;
5523 int size = mmap_event->event_id.header.size;
5524 int ret;
5526 if (!perf_event_mmap_match(event, data))
5527 return;
5529 if (event->attr.mmap2) {
5530 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
5531 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
5532 mmap_event->event_id.header.size += sizeof(mmap_event->min);
5533 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
5534 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
5535 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
5536 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
5539 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
5540 ret = perf_output_begin(&handle, event,
5541 mmap_event->event_id.header.size);
5542 if (ret)
5543 goto out;
5545 mmap_event->event_id.pid = perf_event_pid(event, current);
5546 mmap_event->event_id.tid = perf_event_tid(event, current);
5548 perf_output_put(&handle, mmap_event->event_id);
5550 if (event->attr.mmap2) {
5551 perf_output_put(&handle, mmap_event->maj);
5552 perf_output_put(&handle, mmap_event->min);
5553 perf_output_put(&handle, mmap_event->ino);
5554 perf_output_put(&handle, mmap_event->ino_generation);
5555 perf_output_put(&handle, mmap_event->prot);
5556 perf_output_put(&handle, mmap_event->flags);
5559 __output_copy(&handle, mmap_event->file_name,
5560 mmap_event->file_size);
5562 perf_event__output_id_sample(event, &handle, &sample);
5564 perf_output_end(&handle);
5565 out:
5566 mmap_event->event_id.header.size = size;
5569 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
5571 struct vm_area_struct *vma = mmap_event->vma;
5572 struct file *file = vma->vm_file;
5573 int maj = 0, min = 0;
5574 u64 ino = 0, gen = 0;
5575 u32 prot = 0, flags = 0;
5576 unsigned int size;
5577 char tmp[16];
5578 char *buf = NULL;
5579 char *name;
5581 if (file) {
5582 struct inode *inode;
5583 dev_t dev;
5585 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5586 if (!buf) {
5587 name = "//enomem";
5588 goto cpy_name;
5591 * d_path() works from the end of the rb backwards, so we
5592 * need to add enough zero bytes after the string to handle
5593 * the 64bit alignment we do later.
5595 name = d_path(&file->f_path, buf, PATH_MAX - sizeof(u64));
5596 if (IS_ERR(name)) {
5597 name = "//toolong";
5598 goto cpy_name;
5600 inode = file_inode(vma->vm_file);
5601 dev = inode->i_sb->s_dev;
5602 ino = inode->i_ino;
5603 gen = inode->i_generation;
5604 maj = MAJOR(dev);
5605 min = MINOR(dev);
5607 if (vma->vm_flags & VM_READ)
5608 prot |= PROT_READ;
5609 if (vma->vm_flags & VM_WRITE)
5610 prot |= PROT_WRITE;
5611 if (vma->vm_flags & VM_EXEC)
5612 prot |= PROT_EXEC;
5614 if (vma->vm_flags & VM_MAYSHARE)
5615 flags = MAP_SHARED;
5616 else
5617 flags = MAP_PRIVATE;
5619 if (vma->vm_flags & VM_DENYWRITE)
5620 flags |= MAP_DENYWRITE;
5621 if (vma->vm_flags & VM_MAYEXEC)
5622 flags |= MAP_EXECUTABLE;
5623 if (vma->vm_flags & VM_LOCKED)
5624 flags |= MAP_LOCKED;
5625 if (vma->vm_flags & VM_HUGETLB)
5626 flags |= MAP_HUGETLB;
5628 goto got_name;
5629 } else {
5630 if (vma->vm_ops && vma->vm_ops->name) {
5631 name = (char *) vma->vm_ops->name(vma);
5632 if (name)
5633 goto cpy_name;
5636 name = (char *)arch_vma_name(vma);
5637 if (name)
5638 goto cpy_name;
5640 if (vma->vm_start <= vma->vm_mm->start_brk &&
5641 vma->vm_end >= vma->vm_mm->brk) {
5642 name = "[heap]";
5643 goto cpy_name;
5645 if (vma->vm_start <= vma->vm_mm->start_stack &&
5646 vma->vm_end >= vma->vm_mm->start_stack) {
5647 name = "[stack]";
5648 goto cpy_name;
5651 name = "//anon";
5652 goto cpy_name;
5655 cpy_name:
5656 strlcpy(tmp, name, sizeof(tmp));
5657 name = tmp;
5658 got_name:
5660 * Since our buffer works in 8 byte units we need to align our string
5661 * size to a multiple of 8. However, we must guarantee the tail end is
5662 * zero'd out to avoid leaking random bits to userspace.
5664 size = strlen(name)+1;
5665 while (!IS_ALIGNED(size, sizeof(u64)))
5666 name[size++] = '\0';
5668 mmap_event->file_name = name;
5669 mmap_event->file_size = size;
5670 mmap_event->maj = maj;
5671 mmap_event->min = min;
5672 mmap_event->ino = ino;
5673 mmap_event->ino_generation = gen;
5674 mmap_event->prot = prot;
5675 mmap_event->flags = flags;
5677 if (!(vma->vm_flags & VM_EXEC))
5678 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
5680 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
5682 perf_event_aux(perf_event_mmap_output,
5683 mmap_event,
5684 NULL);
5686 kfree(buf);
5689 void perf_event_mmap(struct vm_area_struct *vma)
5691 struct perf_mmap_event mmap_event;
5693 if (!atomic_read(&nr_mmap_events))
5694 return;
5696 mmap_event = (struct perf_mmap_event){
5697 .vma = vma,
5698 /* .file_name */
5699 /* .file_size */
5700 .event_id = {
5701 .header = {
5702 .type = PERF_RECORD_MMAP,
5703 .misc = PERF_RECORD_MISC_USER,
5704 /* .size */
5706 /* .pid */
5707 /* .tid */
5708 .start = vma->vm_start,
5709 .len = vma->vm_end - vma->vm_start,
5710 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
5712 /* .maj (attr_mmap2 only) */
5713 /* .min (attr_mmap2 only) */
5714 /* .ino (attr_mmap2 only) */
5715 /* .ino_generation (attr_mmap2 only) */
5716 /* .prot (attr_mmap2 only) */
5717 /* .flags (attr_mmap2 only) */
5720 perf_event_mmap_event(&mmap_event);
5724 * IRQ throttle logging
5727 static void perf_log_throttle(struct perf_event *event, int enable)
5729 struct perf_output_handle handle;
5730 struct perf_sample_data sample;
5731 int ret;
5733 struct {
5734 struct perf_event_header header;
5735 u64 time;
5736 u64 id;
5737 u64 stream_id;
5738 } throttle_event = {
5739 .header = {
5740 .type = PERF_RECORD_THROTTLE,
5741 .misc = 0,
5742 .size = sizeof(throttle_event),
5744 .time = perf_clock(),
5745 .id = primary_event_id(event),
5746 .stream_id = event->id,
5749 if (enable)
5750 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
5752 perf_event_header__init_id(&throttle_event.header, &sample, event);
5754 ret = perf_output_begin(&handle, event,
5755 throttle_event.header.size);
5756 if (ret)
5757 return;
5759 perf_output_put(&handle, throttle_event);
5760 perf_event__output_id_sample(event, &handle, &sample);
5761 perf_output_end(&handle);
5765 * Generic event overflow handling, sampling.
5768 static int __perf_event_overflow(struct perf_event *event,
5769 int throttle, struct perf_sample_data *data,
5770 struct pt_regs *regs)
5772 int events = atomic_read(&event->event_limit);
5773 struct hw_perf_event *hwc = &event->hw;
5774 u64 seq;
5775 int ret = 0;
5778 * Non-sampling counters might still use the PMI to fold short
5779 * hardware counters, ignore those.
5781 if (unlikely(!is_sampling_event(event)))
5782 return 0;
5784 seq = __this_cpu_read(perf_throttled_seq);
5785 if (seq != hwc->interrupts_seq) {
5786 hwc->interrupts_seq = seq;
5787 hwc->interrupts = 1;
5788 } else {
5789 hwc->interrupts++;
5790 if (unlikely(throttle
5791 && hwc->interrupts >= max_samples_per_tick)) {
5792 __this_cpu_inc(perf_throttled_count);
5793 hwc->interrupts = MAX_INTERRUPTS;
5794 perf_log_throttle(event, 0);
5795 tick_nohz_full_kick();
5796 ret = 1;
5800 if (event->attr.freq) {
5801 u64 now = perf_clock();
5802 s64 delta = now - hwc->freq_time_stamp;
5804 hwc->freq_time_stamp = now;
5806 if (delta > 0 && delta < 2*TICK_NSEC)
5807 perf_adjust_period(event, delta, hwc->last_period, true);
5811 * XXX event_limit might not quite work as expected on inherited
5812 * events
5815 event->pending_kill = POLL_IN;
5816 if (events && atomic_dec_and_test(&event->event_limit)) {
5817 ret = 1;
5818 event->pending_kill = POLL_HUP;
5819 event->pending_disable = 1;
5820 irq_work_queue(&event->pending);
5823 if (event->overflow_handler)
5824 event->overflow_handler(event, data, regs);
5825 else
5826 perf_event_output(event, data, regs);
5828 if (*perf_event_fasync(event) && event->pending_kill) {
5829 event->pending_wakeup = 1;
5830 irq_work_queue(&event->pending);
5833 return ret;
5836 int perf_event_overflow(struct perf_event *event,
5837 struct perf_sample_data *data,
5838 struct pt_regs *regs)
5840 return __perf_event_overflow(event, 1, data, regs);
5844 * Generic software event infrastructure
5847 struct swevent_htable {
5848 struct swevent_hlist *swevent_hlist;
5849 struct mutex hlist_mutex;
5850 int hlist_refcount;
5852 /* Recursion avoidance in each contexts */
5853 int recursion[PERF_NR_CONTEXTS];
5856 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
5859 * We directly increment event->count and keep a second value in
5860 * event->hw.period_left to count intervals. This period event
5861 * is kept in the range [-sample_period, 0] so that we can use the
5862 * sign as trigger.
5865 u64 perf_swevent_set_period(struct perf_event *event)
5867 struct hw_perf_event *hwc = &event->hw;
5868 u64 period = hwc->last_period;
5869 u64 nr, offset;
5870 s64 old, val;
5872 hwc->last_period = hwc->sample_period;
5874 again:
5875 old = val = local64_read(&hwc->period_left);
5876 if (val < 0)
5877 return 0;
5879 nr = div64_u64(period + val, period);
5880 offset = nr * period;
5881 val -= offset;
5882 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
5883 goto again;
5885 return nr;
5888 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
5889 struct perf_sample_data *data,
5890 struct pt_regs *regs)
5892 struct hw_perf_event *hwc = &event->hw;
5893 int throttle = 0;
5895 if (!overflow)
5896 overflow = perf_swevent_set_period(event);
5898 if (hwc->interrupts == MAX_INTERRUPTS)
5899 return;
5901 for (; overflow; overflow--) {
5902 if (__perf_event_overflow(event, throttle,
5903 data, regs)) {
5905 * We inhibit the overflow from happening when
5906 * hwc->interrupts == MAX_INTERRUPTS.
5908 break;
5910 throttle = 1;
5914 static void perf_swevent_event(struct perf_event *event, u64 nr,
5915 struct perf_sample_data *data,
5916 struct pt_regs *regs)
5918 struct hw_perf_event *hwc = &event->hw;
5920 local64_add(nr, &event->count);
5922 if (!regs)
5923 return;
5925 if (!is_sampling_event(event))
5926 return;
5928 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
5929 data->period = nr;
5930 return perf_swevent_overflow(event, 1, data, regs);
5931 } else
5932 data->period = event->hw.last_period;
5934 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
5935 return perf_swevent_overflow(event, 1, data, regs);
5937 if (local64_add_negative(nr, &hwc->period_left))
5938 return;
5940 perf_swevent_overflow(event, 0, data, regs);
5943 static int perf_exclude_event(struct perf_event *event,
5944 struct pt_regs *regs)
5946 if (event->hw.state & PERF_HES_STOPPED)
5947 return 1;
5949 if (regs) {
5950 if (event->attr.exclude_user && user_mode(regs))
5951 return 1;
5953 if (event->attr.exclude_kernel && !user_mode(regs))
5954 return 1;
5957 return 0;
5960 static int perf_swevent_match(struct perf_event *event,
5961 enum perf_type_id type,
5962 u32 event_id,
5963 struct perf_sample_data *data,
5964 struct pt_regs *regs)
5966 if (event->attr.type != type)
5967 return 0;
5969 if (event->attr.config != event_id)
5970 return 0;
5972 if (perf_exclude_event(event, regs))
5973 return 0;
5975 return 1;
5978 static inline u64 swevent_hash(u64 type, u32 event_id)
5980 u64 val = event_id | (type << 32);
5982 return hash_64(val, SWEVENT_HLIST_BITS);
5985 static inline struct hlist_head *
5986 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
5988 u64 hash = swevent_hash(type, event_id);
5990 return &hlist->heads[hash];
5993 /* For the read side: events when they trigger */
5994 static inline struct hlist_head *
5995 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
5997 struct swevent_hlist *hlist;
5999 hlist = rcu_dereference(swhash->swevent_hlist);
6000 if (!hlist)
6001 return NULL;
6003 return __find_swevent_head(hlist, type, event_id);
6006 /* For the event head insertion and removal in the hlist */
6007 static inline struct hlist_head *
6008 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
6010 struct swevent_hlist *hlist;
6011 u32 event_id = event->attr.config;
6012 u64 type = event->attr.type;
6015 * Event scheduling is always serialized against hlist allocation
6016 * and release. Which makes the protected version suitable here.
6017 * The context lock guarantees that.
6019 hlist = rcu_dereference_protected(swhash->swevent_hlist,
6020 lockdep_is_held(&event->ctx->lock));
6021 if (!hlist)
6022 return NULL;
6024 return __find_swevent_head(hlist, type, event_id);
6027 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
6028 u64 nr,
6029 struct perf_sample_data *data,
6030 struct pt_regs *regs)
6032 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6033 struct perf_event *event;
6034 struct hlist_head *head;
6036 rcu_read_lock();
6037 head = find_swevent_head_rcu(swhash, type, event_id);
6038 if (!head)
6039 goto end;
6041 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6042 if (perf_swevent_match(event, type, event_id, data, regs))
6043 perf_swevent_event(event, nr, data, regs);
6045 end:
6046 rcu_read_unlock();
6049 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
6051 int perf_swevent_get_recursion_context(void)
6053 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6055 return get_recursion_context(swhash->recursion);
6057 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
6059 inline void perf_swevent_put_recursion_context(int rctx)
6061 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6063 put_recursion_context(swhash->recursion, rctx);
6066 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6068 struct perf_sample_data data;
6070 if (WARN_ON_ONCE(!regs))
6071 return;
6073 perf_sample_data_init(&data, addr, 0);
6074 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
6077 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6079 int rctx;
6081 preempt_disable_notrace();
6082 rctx = perf_swevent_get_recursion_context();
6083 if (unlikely(rctx < 0))
6084 goto fail;
6086 ___perf_sw_event(event_id, nr, regs, addr);
6088 perf_swevent_put_recursion_context(rctx);
6089 fail:
6090 preempt_enable_notrace();
6093 static void perf_swevent_read(struct perf_event *event)
6097 static int perf_swevent_add(struct perf_event *event, int flags)
6099 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6100 struct hw_perf_event *hwc = &event->hw;
6101 struct hlist_head *head;
6103 if (is_sampling_event(event)) {
6104 hwc->last_period = hwc->sample_period;
6105 perf_swevent_set_period(event);
6108 hwc->state = !(flags & PERF_EF_START);
6110 head = find_swevent_head(swhash, event);
6111 if (WARN_ON_ONCE(!head))
6112 return -EINVAL;
6114 hlist_add_head_rcu(&event->hlist_entry, head);
6116 return 0;
6119 static void perf_swevent_del(struct perf_event *event, int flags)
6121 hlist_del_rcu(&event->hlist_entry);
6124 static void perf_swevent_start(struct perf_event *event, int flags)
6126 event->hw.state = 0;
6129 static void perf_swevent_stop(struct perf_event *event, int flags)
6131 event->hw.state = PERF_HES_STOPPED;
6134 /* Deref the hlist from the update side */
6135 static inline struct swevent_hlist *
6136 swevent_hlist_deref(struct swevent_htable *swhash)
6138 return rcu_dereference_protected(swhash->swevent_hlist,
6139 lockdep_is_held(&swhash->hlist_mutex));
6142 static void swevent_hlist_release(struct swevent_htable *swhash)
6144 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
6146 if (!hlist)
6147 return;
6149 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
6150 kfree_rcu(hlist, rcu_head);
6153 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
6155 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6157 mutex_lock(&swhash->hlist_mutex);
6159 if (!--swhash->hlist_refcount)
6160 swevent_hlist_release(swhash);
6162 mutex_unlock(&swhash->hlist_mutex);
6165 static void swevent_hlist_put(struct perf_event *event)
6167 int cpu;
6169 for_each_possible_cpu(cpu)
6170 swevent_hlist_put_cpu(event, cpu);
6173 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
6175 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6176 int err = 0;
6178 mutex_lock(&swhash->hlist_mutex);
6179 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
6180 struct swevent_hlist *hlist;
6182 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
6183 if (!hlist) {
6184 err = -ENOMEM;
6185 goto exit;
6187 rcu_assign_pointer(swhash->swevent_hlist, hlist);
6189 swhash->hlist_refcount++;
6190 exit:
6191 mutex_unlock(&swhash->hlist_mutex);
6193 return err;
6196 static int swevent_hlist_get(struct perf_event *event)
6198 int err;
6199 int cpu, failed_cpu;
6201 get_online_cpus();
6202 for_each_possible_cpu(cpu) {
6203 err = swevent_hlist_get_cpu(event, cpu);
6204 if (err) {
6205 failed_cpu = cpu;
6206 goto fail;
6209 put_online_cpus();
6211 return 0;
6212 fail:
6213 for_each_possible_cpu(cpu) {
6214 if (cpu == failed_cpu)
6215 break;
6216 swevent_hlist_put_cpu(event, cpu);
6219 put_online_cpus();
6220 return err;
6223 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
6225 static void sw_perf_event_destroy(struct perf_event *event)
6227 u64 event_id = event->attr.config;
6229 WARN_ON(event->parent);
6231 static_key_slow_dec(&perf_swevent_enabled[event_id]);
6232 swevent_hlist_put(event);
6235 static int perf_swevent_init(struct perf_event *event)
6237 u64 event_id = event->attr.config;
6239 if (event->attr.type != PERF_TYPE_SOFTWARE)
6240 return -ENOENT;
6243 * no branch sampling for software events
6245 if (has_branch_stack(event))
6246 return -EOPNOTSUPP;
6248 switch (event_id) {
6249 case PERF_COUNT_SW_CPU_CLOCK:
6250 case PERF_COUNT_SW_TASK_CLOCK:
6251 return -ENOENT;
6253 default:
6254 break;
6257 if (event_id >= PERF_COUNT_SW_MAX)
6258 return -ENOENT;
6260 if (!event->parent) {
6261 int err;
6263 err = swevent_hlist_get(event);
6264 if (err)
6265 return err;
6267 static_key_slow_inc(&perf_swevent_enabled[event_id]);
6268 event->destroy = sw_perf_event_destroy;
6271 return 0;
6274 static struct pmu perf_swevent = {
6275 .task_ctx_nr = perf_sw_context,
6277 .event_init = perf_swevent_init,
6278 .add = perf_swevent_add,
6279 .del = perf_swevent_del,
6280 .start = perf_swevent_start,
6281 .stop = perf_swevent_stop,
6282 .read = perf_swevent_read,
6285 #ifdef CONFIG_EVENT_TRACING
6287 static int perf_tp_filter_match(struct perf_event *event,
6288 struct perf_sample_data *data)
6290 void *record = data->raw->data;
6292 if (likely(!event->filter) || filter_match_preds(event->filter, record))
6293 return 1;
6294 return 0;
6297 static int perf_tp_event_match(struct perf_event *event,
6298 struct perf_sample_data *data,
6299 struct pt_regs *regs)
6301 if (event->hw.state & PERF_HES_STOPPED)
6302 return 0;
6304 * All tracepoints are from kernel-space.
6306 if (event->attr.exclude_kernel)
6307 return 0;
6309 if (!perf_tp_filter_match(event, data))
6310 return 0;
6312 return 1;
6315 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
6316 struct pt_regs *regs, struct hlist_head *head, int rctx,
6317 struct task_struct *task)
6319 struct perf_sample_data data;
6320 struct perf_event *event;
6322 struct perf_raw_record raw = {
6323 .size = entry_size,
6324 .data = record,
6327 perf_sample_data_init(&data, addr, 0);
6328 data.raw = &raw;
6330 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6331 if (perf_tp_event_match(event, &data, regs))
6332 perf_swevent_event(event, count, &data, regs);
6336 * If we got specified a target task, also iterate its context and
6337 * deliver this event there too.
6339 if (task && task != current) {
6340 struct perf_event_context *ctx;
6341 struct trace_entry *entry = record;
6343 rcu_read_lock();
6344 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
6345 if (!ctx)
6346 goto unlock;
6348 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
6349 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6350 continue;
6351 if (event->attr.config != entry->type)
6352 continue;
6353 if (perf_tp_event_match(event, &data, regs))
6354 perf_swevent_event(event, count, &data, regs);
6356 unlock:
6357 rcu_read_unlock();
6360 perf_swevent_put_recursion_context(rctx);
6362 EXPORT_SYMBOL_GPL(perf_tp_event);
6364 static void tp_perf_event_destroy(struct perf_event *event)
6366 perf_trace_destroy(event);
6369 static int perf_tp_event_init(struct perf_event *event)
6371 int err;
6373 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6374 return -ENOENT;
6377 * no branch sampling for tracepoint events
6379 if (has_branch_stack(event))
6380 return -EOPNOTSUPP;
6382 err = perf_trace_init(event);
6383 if (err)
6384 return err;
6386 event->destroy = tp_perf_event_destroy;
6388 return 0;
6391 static struct pmu perf_tracepoint = {
6392 .task_ctx_nr = perf_sw_context,
6394 .event_init = perf_tp_event_init,
6395 .add = perf_trace_add,
6396 .del = perf_trace_del,
6397 .start = perf_swevent_start,
6398 .stop = perf_swevent_stop,
6399 .read = perf_swevent_read,
6402 static inline void perf_tp_register(void)
6404 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
6407 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
6409 char *filter_str;
6410 int ret;
6412 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6413 return -EINVAL;
6415 filter_str = strndup_user(arg, PAGE_SIZE);
6416 if (IS_ERR(filter_str))
6417 return PTR_ERR(filter_str);
6419 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
6421 kfree(filter_str);
6422 return ret;
6425 static void perf_event_free_filter(struct perf_event *event)
6427 ftrace_profile_free_filter(event);
6430 #else
6432 static inline void perf_tp_register(void)
6436 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
6438 return -ENOENT;
6441 static void perf_event_free_filter(struct perf_event *event)
6445 #endif /* CONFIG_EVENT_TRACING */
6447 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6448 void perf_bp_event(struct perf_event *bp, void *data)
6450 struct perf_sample_data sample;
6451 struct pt_regs *regs = data;
6453 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
6455 if (!bp->hw.state && !perf_exclude_event(bp, regs))
6456 perf_swevent_event(bp, 1, &sample, regs);
6458 #endif
6461 * hrtimer based swevent callback
6464 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
6466 enum hrtimer_restart ret = HRTIMER_RESTART;
6467 struct perf_sample_data data;
6468 struct pt_regs *regs;
6469 struct perf_event *event;
6470 u64 period;
6472 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
6474 if (event->state != PERF_EVENT_STATE_ACTIVE)
6475 return HRTIMER_NORESTART;
6477 event->pmu->read(event);
6479 perf_sample_data_init(&data, 0, event->hw.last_period);
6480 regs = get_irq_regs();
6482 if (regs && !perf_exclude_event(event, regs)) {
6483 if (!(event->attr.exclude_idle && is_idle_task(current)))
6484 if (__perf_event_overflow(event, 1, &data, regs))
6485 ret = HRTIMER_NORESTART;
6488 period = max_t(u64, 10000, event->hw.sample_period);
6489 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
6491 return ret;
6494 static void perf_swevent_start_hrtimer(struct perf_event *event)
6496 struct hw_perf_event *hwc = &event->hw;
6497 s64 period;
6499 if (!is_sampling_event(event))
6500 return;
6502 period = local64_read(&hwc->period_left);
6503 if (period) {
6504 if (period < 0)
6505 period = 10000;
6507 local64_set(&hwc->period_left, 0);
6508 } else {
6509 period = max_t(u64, 10000, hwc->sample_period);
6511 __hrtimer_start_range_ns(&hwc->hrtimer,
6512 ns_to_ktime(period), 0,
6513 HRTIMER_MODE_REL_PINNED, 0);
6516 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
6518 struct hw_perf_event *hwc = &event->hw;
6520 if (is_sampling_event(event)) {
6521 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
6522 local64_set(&hwc->period_left, ktime_to_ns(remaining));
6524 hrtimer_cancel(&hwc->hrtimer);
6528 static void perf_swevent_init_hrtimer(struct perf_event *event)
6530 struct hw_perf_event *hwc = &event->hw;
6532 if (!is_sampling_event(event))
6533 return;
6535 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6536 hwc->hrtimer.function = perf_swevent_hrtimer;
6539 * Since hrtimers have a fixed rate, we can do a static freq->period
6540 * mapping and avoid the whole period adjust feedback stuff.
6542 if (event->attr.freq) {
6543 long freq = event->attr.sample_freq;
6545 event->attr.sample_period = NSEC_PER_SEC / freq;
6546 hwc->sample_period = event->attr.sample_period;
6547 local64_set(&hwc->period_left, hwc->sample_period);
6548 hwc->last_period = hwc->sample_period;
6549 event->attr.freq = 0;
6554 * Software event: cpu wall time clock
6557 static void cpu_clock_event_update(struct perf_event *event)
6559 s64 prev;
6560 u64 now;
6562 now = local_clock();
6563 prev = local64_xchg(&event->hw.prev_count, now);
6564 local64_add(now - prev, &event->count);
6567 static void cpu_clock_event_start(struct perf_event *event, int flags)
6569 local64_set(&event->hw.prev_count, local_clock());
6570 perf_swevent_start_hrtimer(event);
6573 static void cpu_clock_event_stop(struct perf_event *event, int flags)
6575 perf_swevent_cancel_hrtimer(event);
6576 cpu_clock_event_update(event);
6579 static int cpu_clock_event_add(struct perf_event *event, int flags)
6581 if (flags & PERF_EF_START)
6582 cpu_clock_event_start(event, flags);
6584 return 0;
6587 static void cpu_clock_event_del(struct perf_event *event, int flags)
6589 cpu_clock_event_stop(event, flags);
6592 static void cpu_clock_event_read(struct perf_event *event)
6594 cpu_clock_event_update(event);
6597 static int cpu_clock_event_init(struct perf_event *event)
6599 if (event->attr.type != PERF_TYPE_SOFTWARE)
6600 return -ENOENT;
6602 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
6603 return -ENOENT;
6606 * no branch sampling for software events
6608 if (has_branch_stack(event))
6609 return -EOPNOTSUPP;
6611 perf_swevent_init_hrtimer(event);
6613 return 0;
6616 static struct pmu perf_cpu_clock = {
6617 .task_ctx_nr = perf_sw_context,
6619 .event_init = cpu_clock_event_init,
6620 .add = cpu_clock_event_add,
6621 .del = cpu_clock_event_del,
6622 .start = cpu_clock_event_start,
6623 .stop = cpu_clock_event_stop,
6624 .read = cpu_clock_event_read,
6628 * Software event: task time clock
6631 static void task_clock_event_update(struct perf_event *event, u64 now)
6633 u64 prev;
6634 s64 delta;
6636 prev = local64_xchg(&event->hw.prev_count, now);
6637 delta = now - prev;
6638 local64_add(delta, &event->count);
6641 static void task_clock_event_start(struct perf_event *event, int flags)
6643 local64_set(&event->hw.prev_count, event->ctx->time);
6644 perf_swevent_start_hrtimer(event);
6647 static void task_clock_event_stop(struct perf_event *event, int flags)
6649 perf_swevent_cancel_hrtimer(event);
6650 task_clock_event_update(event, event->ctx->time);
6653 static int task_clock_event_add(struct perf_event *event, int flags)
6655 if (flags & PERF_EF_START)
6656 task_clock_event_start(event, flags);
6658 return 0;
6661 static void task_clock_event_del(struct perf_event *event, int flags)
6663 task_clock_event_stop(event, PERF_EF_UPDATE);
6666 static void task_clock_event_read(struct perf_event *event)
6668 u64 now = perf_clock();
6669 u64 delta = now - event->ctx->timestamp;
6670 u64 time = event->ctx->time + delta;
6672 task_clock_event_update(event, time);
6675 static int task_clock_event_init(struct perf_event *event)
6677 if (event->attr.type != PERF_TYPE_SOFTWARE)
6678 return -ENOENT;
6680 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
6681 return -ENOENT;
6684 * no branch sampling for software events
6686 if (has_branch_stack(event))
6687 return -EOPNOTSUPP;
6689 perf_swevent_init_hrtimer(event);
6691 return 0;
6694 static struct pmu perf_task_clock = {
6695 .task_ctx_nr = perf_sw_context,
6697 .event_init = task_clock_event_init,
6698 .add = task_clock_event_add,
6699 .del = task_clock_event_del,
6700 .start = task_clock_event_start,
6701 .stop = task_clock_event_stop,
6702 .read = task_clock_event_read,
6705 static void perf_pmu_nop_void(struct pmu *pmu)
6709 static int perf_pmu_nop_int(struct pmu *pmu)
6711 return 0;
6714 static void perf_pmu_start_txn(struct pmu *pmu)
6716 perf_pmu_disable(pmu);
6719 static int perf_pmu_commit_txn(struct pmu *pmu)
6721 perf_pmu_enable(pmu);
6722 return 0;
6725 static void perf_pmu_cancel_txn(struct pmu *pmu)
6727 perf_pmu_enable(pmu);
6730 static int perf_event_idx_default(struct perf_event *event)
6732 return 0;
6736 * Ensures all contexts with the same task_ctx_nr have the same
6737 * pmu_cpu_context too.
6739 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
6741 struct pmu *pmu;
6743 if (ctxn < 0)
6744 return NULL;
6746 list_for_each_entry(pmu, &pmus, entry) {
6747 if (pmu->task_ctx_nr == ctxn)
6748 return pmu->pmu_cpu_context;
6751 return NULL;
6754 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
6756 int cpu;
6758 for_each_possible_cpu(cpu) {
6759 struct perf_cpu_context *cpuctx;
6761 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6763 if (cpuctx->unique_pmu == old_pmu)
6764 cpuctx->unique_pmu = pmu;
6768 static void free_pmu_context(struct pmu *pmu)
6770 struct pmu *i;
6772 mutex_lock(&pmus_lock);
6774 * Like a real lame refcount.
6776 list_for_each_entry(i, &pmus, entry) {
6777 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
6778 update_pmu_context(i, pmu);
6779 goto out;
6783 free_percpu(pmu->pmu_cpu_context);
6784 out:
6785 mutex_unlock(&pmus_lock);
6787 static struct idr pmu_idr;
6789 static ssize_t
6790 type_show(struct device *dev, struct device_attribute *attr, char *page)
6792 struct pmu *pmu = dev_get_drvdata(dev);
6794 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
6796 static DEVICE_ATTR_RO(type);
6798 static ssize_t
6799 perf_event_mux_interval_ms_show(struct device *dev,
6800 struct device_attribute *attr,
6801 char *page)
6803 struct pmu *pmu = dev_get_drvdata(dev);
6805 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
6808 static ssize_t
6809 perf_event_mux_interval_ms_store(struct device *dev,
6810 struct device_attribute *attr,
6811 const char *buf, size_t count)
6813 struct pmu *pmu = dev_get_drvdata(dev);
6814 int timer, cpu, ret;
6816 ret = kstrtoint(buf, 0, &timer);
6817 if (ret)
6818 return ret;
6820 if (timer < 1)
6821 return -EINVAL;
6823 /* same value, noting to do */
6824 if (timer == pmu->hrtimer_interval_ms)
6825 return count;
6827 pmu->hrtimer_interval_ms = timer;
6829 /* update all cpuctx for this PMU */
6830 for_each_possible_cpu(cpu) {
6831 struct perf_cpu_context *cpuctx;
6832 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6833 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
6835 if (hrtimer_active(&cpuctx->hrtimer))
6836 hrtimer_forward_now(&cpuctx->hrtimer, cpuctx->hrtimer_interval);
6839 return count;
6841 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
6843 static struct attribute *pmu_dev_attrs[] = {
6844 &dev_attr_type.attr,
6845 &dev_attr_perf_event_mux_interval_ms.attr,
6846 NULL,
6848 ATTRIBUTE_GROUPS(pmu_dev);
6850 static int pmu_bus_running;
6851 static struct bus_type pmu_bus = {
6852 .name = "event_source",
6853 .dev_groups = pmu_dev_groups,
6856 static void pmu_dev_release(struct device *dev)
6858 kfree(dev);
6861 static int pmu_dev_alloc(struct pmu *pmu)
6863 int ret = -ENOMEM;
6865 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
6866 if (!pmu->dev)
6867 goto out;
6869 pmu->dev->groups = pmu->attr_groups;
6870 device_initialize(pmu->dev);
6871 ret = dev_set_name(pmu->dev, "%s", pmu->name);
6872 if (ret)
6873 goto free_dev;
6875 dev_set_drvdata(pmu->dev, pmu);
6876 pmu->dev->bus = &pmu_bus;
6877 pmu->dev->release = pmu_dev_release;
6878 ret = device_add(pmu->dev);
6879 if (ret)
6880 goto free_dev;
6882 out:
6883 return ret;
6885 free_dev:
6886 put_device(pmu->dev);
6887 goto out;
6890 static struct lock_class_key cpuctx_mutex;
6891 static struct lock_class_key cpuctx_lock;
6893 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
6895 int cpu, ret;
6897 mutex_lock(&pmus_lock);
6898 ret = -ENOMEM;
6899 pmu->pmu_disable_count = alloc_percpu(int);
6900 if (!pmu->pmu_disable_count)
6901 goto unlock;
6903 pmu->type = -1;
6904 if (!name)
6905 goto skip_type;
6906 pmu->name = name;
6908 if (type < 0) {
6909 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
6910 if (type < 0) {
6911 ret = type;
6912 goto free_pdc;
6915 pmu->type = type;
6917 if (pmu_bus_running) {
6918 ret = pmu_dev_alloc(pmu);
6919 if (ret)
6920 goto free_idr;
6923 skip_type:
6924 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
6925 if (pmu->pmu_cpu_context)
6926 goto got_cpu_context;
6928 ret = -ENOMEM;
6929 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
6930 if (!pmu->pmu_cpu_context)
6931 goto free_dev;
6933 for_each_possible_cpu(cpu) {
6934 struct perf_cpu_context *cpuctx;
6936 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6937 __perf_event_init_context(&cpuctx->ctx);
6938 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
6939 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
6940 cpuctx->ctx.pmu = pmu;
6942 __perf_cpu_hrtimer_init(cpuctx, cpu);
6944 INIT_LIST_HEAD(&cpuctx->rotation_list);
6945 cpuctx->unique_pmu = pmu;
6948 got_cpu_context:
6949 if (!pmu->start_txn) {
6950 if (pmu->pmu_enable) {
6952 * If we have pmu_enable/pmu_disable calls, install
6953 * transaction stubs that use that to try and batch
6954 * hardware accesses.
6956 pmu->start_txn = perf_pmu_start_txn;
6957 pmu->commit_txn = perf_pmu_commit_txn;
6958 pmu->cancel_txn = perf_pmu_cancel_txn;
6959 } else {
6960 pmu->start_txn = perf_pmu_nop_void;
6961 pmu->commit_txn = perf_pmu_nop_int;
6962 pmu->cancel_txn = perf_pmu_nop_void;
6966 if (!pmu->pmu_enable) {
6967 pmu->pmu_enable = perf_pmu_nop_void;
6968 pmu->pmu_disable = perf_pmu_nop_void;
6971 if (!pmu->event_idx)
6972 pmu->event_idx = perf_event_idx_default;
6974 list_add_rcu(&pmu->entry, &pmus);
6975 ret = 0;
6976 unlock:
6977 mutex_unlock(&pmus_lock);
6979 return ret;
6981 free_dev:
6982 device_del(pmu->dev);
6983 put_device(pmu->dev);
6985 free_idr:
6986 if (pmu->type >= PERF_TYPE_MAX)
6987 idr_remove(&pmu_idr, pmu->type);
6989 free_pdc:
6990 free_percpu(pmu->pmu_disable_count);
6991 goto unlock;
6993 EXPORT_SYMBOL_GPL(perf_pmu_register);
6995 void perf_pmu_unregister(struct pmu *pmu)
6997 mutex_lock(&pmus_lock);
6998 list_del_rcu(&pmu->entry);
6999 mutex_unlock(&pmus_lock);
7002 * We dereference the pmu list under both SRCU and regular RCU, so
7003 * synchronize against both of those.
7005 synchronize_srcu(&pmus_srcu);
7006 synchronize_rcu();
7008 free_percpu(pmu->pmu_disable_count);
7009 if (pmu->type >= PERF_TYPE_MAX)
7010 idr_remove(&pmu_idr, pmu->type);
7011 device_del(pmu->dev);
7012 put_device(pmu->dev);
7013 free_pmu_context(pmu);
7015 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
7017 struct pmu *perf_init_event(struct perf_event *event)
7019 struct pmu *pmu = NULL;
7020 int idx;
7021 int ret;
7023 idx = srcu_read_lock(&pmus_srcu);
7025 rcu_read_lock();
7026 pmu = idr_find(&pmu_idr, event->attr.type);
7027 rcu_read_unlock();
7028 if (pmu) {
7029 if (!try_module_get(pmu->module)) {
7030 pmu = ERR_PTR(-ENODEV);
7031 goto unlock;
7033 event->pmu = pmu;
7034 ret = pmu->event_init(event);
7035 if (ret)
7036 pmu = ERR_PTR(ret);
7037 goto unlock;
7040 list_for_each_entry_rcu(pmu, &pmus, entry) {
7041 if (!try_module_get(pmu->module)) {
7042 pmu = ERR_PTR(-ENODEV);
7043 goto unlock;
7045 event->pmu = pmu;
7046 ret = pmu->event_init(event);
7047 if (!ret)
7048 goto unlock;
7050 if (ret != -ENOENT) {
7051 pmu = ERR_PTR(ret);
7052 goto unlock;
7055 pmu = ERR_PTR(-ENOENT);
7056 unlock:
7057 srcu_read_unlock(&pmus_srcu, idx);
7059 return pmu;
7062 static void account_event_cpu(struct perf_event *event, int cpu)
7064 if (event->parent)
7065 return;
7067 if (has_branch_stack(event)) {
7068 if (!(event->attach_state & PERF_ATTACH_TASK))
7069 atomic_inc(&per_cpu(perf_branch_stack_events, cpu));
7071 if (is_cgroup_event(event))
7072 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
7075 static void account_event(struct perf_event *event)
7077 if (event->parent)
7078 return;
7080 if (event->attach_state & PERF_ATTACH_TASK)
7081 static_key_slow_inc(&perf_sched_events.key);
7082 if (event->attr.mmap || event->attr.mmap_data)
7083 atomic_inc(&nr_mmap_events);
7084 if (event->attr.comm)
7085 atomic_inc(&nr_comm_events);
7086 if (event->attr.task)
7087 atomic_inc(&nr_task_events);
7088 if (event->attr.freq) {
7089 if (atomic_inc_return(&nr_freq_events) == 1)
7090 tick_nohz_full_kick_all();
7092 if (has_branch_stack(event))
7093 static_key_slow_inc(&perf_sched_events.key);
7094 if (is_cgroup_event(event))
7095 static_key_slow_inc(&perf_sched_events.key);
7097 account_event_cpu(event, event->cpu);
7101 * Allocate and initialize a event structure
7103 static struct perf_event *
7104 perf_event_alloc(struct perf_event_attr *attr, int cpu,
7105 struct task_struct *task,
7106 struct perf_event *group_leader,
7107 struct perf_event *parent_event,
7108 perf_overflow_handler_t overflow_handler,
7109 void *context)
7111 struct pmu *pmu;
7112 struct perf_event *event;
7113 struct hw_perf_event *hwc;
7114 long err = -EINVAL;
7116 if ((unsigned)cpu >= nr_cpu_ids) {
7117 if (!task || cpu != -1)
7118 return ERR_PTR(-EINVAL);
7121 event = kzalloc(sizeof(*event), GFP_KERNEL);
7122 if (!event)
7123 return ERR_PTR(-ENOMEM);
7126 * Single events are their own group leaders, with an
7127 * empty sibling list:
7129 if (!group_leader)
7130 group_leader = event;
7132 mutex_init(&event->child_mutex);
7133 INIT_LIST_HEAD(&event->child_list);
7135 INIT_LIST_HEAD(&event->group_entry);
7136 INIT_LIST_HEAD(&event->event_entry);
7137 INIT_LIST_HEAD(&event->sibling_list);
7138 INIT_LIST_HEAD(&event->rb_entry);
7139 INIT_LIST_HEAD(&event->active_entry);
7140 INIT_HLIST_NODE(&event->hlist_entry);
7143 init_waitqueue_head(&event->waitq);
7144 init_irq_work(&event->pending, perf_pending_event);
7146 mutex_init(&event->mmap_mutex);
7148 atomic_long_set(&event->refcount, 1);
7149 event->cpu = cpu;
7150 event->attr = *attr;
7151 event->group_leader = group_leader;
7152 event->pmu = NULL;
7153 event->oncpu = -1;
7155 event->parent = parent_event;
7157 event->ns = get_pid_ns(task_active_pid_ns(current));
7158 event->id = atomic64_inc_return(&perf_event_id);
7160 event->state = PERF_EVENT_STATE_INACTIVE;
7162 if (task) {
7163 event->attach_state = PERF_ATTACH_TASK;
7165 if (attr->type == PERF_TYPE_TRACEPOINT)
7166 event->hw.tp_target = task;
7167 #ifdef CONFIG_HAVE_HW_BREAKPOINT
7169 * hw_breakpoint is a bit difficult here..
7171 else if (attr->type == PERF_TYPE_BREAKPOINT)
7172 event->hw.bp_target = task;
7173 #endif
7176 if (!overflow_handler && parent_event) {
7177 overflow_handler = parent_event->overflow_handler;
7178 context = parent_event->overflow_handler_context;
7181 event->overflow_handler = overflow_handler;
7182 event->overflow_handler_context = context;
7184 perf_event__state_init(event);
7186 pmu = NULL;
7188 hwc = &event->hw;
7189 hwc->sample_period = attr->sample_period;
7190 if (attr->freq && attr->sample_freq)
7191 hwc->sample_period = 1;
7192 hwc->last_period = hwc->sample_period;
7194 local64_set(&hwc->period_left, hwc->sample_period);
7197 * we currently do not support PERF_FORMAT_GROUP on inherited events
7199 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
7200 goto err_ns;
7202 pmu = perf_init_event(event);
7203 if (!pmu)
7204 goto err_ns;
7205 else if (IS_ERR(pmu)) {
7206 err = PTR_ERR(pmu);
7207 goto err_ns;
7210 if (!event->parent) {
7211 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
7212 err = get_callchain_buffers();
7213 if (err)
7214 goto err_pmu;
7218 return event;
7220 err_pmu:
7221 if (event->destroy)
7222 event->destroy(event);
7223 module_put(pmu->module);
7224 err_ns:
7225 if (event->ns)
7226 put_pid_ns(event->ns);
7227 kfree(event);
7229 return ERR_PTR(err);
7232 static int perf_copy_attr(struct perf_event_attr __user *uattr,
7233 struct perf_event_attr *attr)
7235 u32 size;
7236 int ret;
7238 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
7239 return -EFAULT;
7242 * zero the full structure, so that a short copy will be nice.
7244 memset(attr, 0, sizeof(*attr));
7246 ret = get_user(size, &uattr->size);
7247 if (ret)
7248 return ret;
7250 if (size > PAGE_SIZE) /* silly large */
7251 goto err_size;
7253 if (!size) /* abi compat */
7254 size = PERF_ATTR_SIZE_VER0;
7256 if (size < PERF_ATTR_SIZE_VER0)
7257 goto err_size;
7260 * If we're handed a bigger struct than we know of,
7261 * ensure all the unknown bits are 0 - i.e. new
7262 * user-space does not rely on any kernel feature
7263 * extensions we dont know about yet.
7265 if (size > sizeof(*attr)) {
7266 unsigned char __user *addr;
7267 unsigned char __user *end;
7268 unsigned char val;
7270 addr = (void __user *)uattr + sizeof(*attr);
7271 end = (void __user *)uattr + size;
7273 for (; addr < end; addr++) {
7274 ret = get_user(val, addr);
7275 if (ret)
7276 return ret;
7277 if (val)
7278 goto err_size;
7280 size = sizeof(*attr);
7283 ret = copy_from_user(attr, uattr, size);
7284 if (ret)
7285 return -EFAULT;
7287 if (attr->__reserved_1)
7288 return -EINVAL;
7290 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
7291 return -EINVAL;
7293 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
7294 return -EINVAL;
7296 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
7297 u64 mask = attr->branch_sample_type;
7299 /* only using defined bits */
7300 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
7301 return -EINVAL;
7303 /* at least one branch bit must be set */
7304 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
7305 return -EINVAL;
7307 /* propagate priv level, when not set for branch */
7308 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
7310 /* exclude_kernel checked on syscall entry */
7311 if (!attr->exclude_kernel)
7312 mask |= PERF_SAMPLE_BRANCH_KERNEL;
7314 if (!attr->exclude_user)
7315 mask |= PERF_SAMPLE_BRANCH_USER;
7317 if (!attr->exclude_hv)
7318 mask |= PERF_SAMPLE_BRANCH_HV;
7320 * adjust user setting (for HW filter setup)
7322 attr->branch_sample_type = mask;
7324 /* privileged levels capture (kernel, hv): check permissions */
7325 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
7326 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
7327 return -EACCES;
7330 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
7331 ret = perf_reg_validate(attr->sample_regs_user);
7332 if (ret)
7333 return ret;
7336 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
7337 if (!arch_perf_have_user_stack_dump())
7338 return -ENOSYS;
7341 * We have __u32 type for the size, but so far
7342 * we can only use __u16 as maximum due to the
7343 * __u16 sample size limit.
7345 if (attr->sample_stack_user >= USHRT_MAX)
7346 ret = -EINVAL;
7347 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
7348 ret = -EINVAL;
7351 out:
7352 return ret;
7354 err_size:
7355 put_user(sizeof(*attr), &uattr->size);
7356 ret = -E2BIG;
7357 goto out;
7360 static int
7361 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
7363 struct ring_buffer *rb = NULL;
7364 int ret = -EINVAL;
7366 if (!output_event)
7367 goto set;
7369 /* don't allow circular references */
7370 if (event == output_event)
7371 goto out;
7374 * Don't allow cross-cpu buffers
7376 if (output_event->cpu != event->cpu)
7377 goto out;
7380 * If its not a per-cpu rb, it must be the same task.
7382 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
7383 goto out;
7385 set:
7386 mutex_lock(&event->mmap_mutex);
7387 /* Can't redirect output if we've got an active mmap() */
7388 if (atomic_read(&event->mmap_count))
7389 goto unlock;
7391 if (output_event) {
7392 /* get the rb we want to redirect to */
7393 rb = ring_buffer_get(output_event);
7394 if (!rb)
7395 goto unlock;
7398 ring_buffer_attach(event, rb);
7400 ret = 0;
7401 unlock:
7402 mutex_unlock(&event->mmap_mutex);
7404 out:
7405 return ret;
7408 static void mutex_lock_double(struct mutex *a, struct mutex *b)
7410 if (b < a)
7411 swap(a, b);
7413 mutex_lock(a);
7414 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
7418 * sys_perf_event_open - open a performance event, associate it to a task/cpu
7420 * @attr_uptr: event_id type attributes for monitoring/sampling
7421 * @pid: target pid
7422 * @cpu: target cpu
7423 * @group_fd: group leader event fd
7425 SYSCALL_DEFINE5(perf_event_open,
7426 struct perf_event_attr __user *, attr_uptr,
7427 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
7429 struct perf_event *group_leader = NULL, *output_event = NULL;
7430 struct perf_event *event, *sibling;
7431 struct perf_event_attr attr;
7432 struct perf_event_context *ctx, *uninitialized_var(gctx);
7433 struct file *event_file = NULL;
7434 struct fd group = {NULL, 0};
7435 struct task_struct *task = NULL;
7436 struct pmu *pmu;
7437 int event_fd;
7438 int move_group = 0;
7439 int err;
7440 int f_flags = O_RDWR;
7442 /* for future expandability... */
7443 if (flags & ~PERF_FLAG_ALL)
7444 return -EINVAL;
7446 err = perf_copy_attr(attr_uptr, &attr);
7447 if (err)
7448 return err;
7450 if (!attr.exclude_kernel) {
7451 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
7452 return -EACCES;
7455 if (attr.freq) {
7456 if (attr.sample_freq > sysctl_perf_event_sample_rate)
7457 return -EINVAL;
7458 } else {
7459 if (attr.sample_period & (1ULL << 63))
7460 return -EINVAL;
7464 * In cgroup mode, the pid argument is used to pass the fd
7465 * opened to the cgroup directory in cgroupfs. The cpu argument
7466 * designates the cpu on which to monitor threads from that
7467 * cgroup.
7469 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
7470 return -EINVAL;
7472 if (flags & PERF_FLAG_FD_CLOEXEC)
7473 f_flags |= O_CLOEXEC;
7475 event_fd = get_unused_fd_flags(f_flags);
7476 if (event_fd < 0)
7477 return event_fd;
7479 if (group_fd != -1) {
7480 err = perf_fget_light(group_fd, &group);
7481 if (err)
7482 goto err_fd;
7483 group_leader = group.file->private_data;
7484 if (flags & PERF_FLAG_FD_OUTPUT)
7485 output_event = group_leader;
7486 if (flags & PERF_FLAG_FD_NO_GROUP)
7487 group_leader = NULL;
7490 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
7491 task = find_lively_task_by_vpid(pid);
7492 if (IS_ERR(task)) {
7493 err = PTR_ERR(task);
7494 goto err_group_fd;
7498 if (task && group_leader &&
7499 group_leader->attr.inherit != attr.inherit) {
7500 err = -EINVAL;
7501 goto err_task;
7504 get_online_cpus();
7506 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
7507 NULL, NULL);
7508 if (IS_ERR(event)) {
7509 err = PTR_ERR(event);
7510 goto err_cpus;
7513 if (flags & PERF_FLAG_PID_CGROUP) {
7514 err = perf_cgroup_connect(pid, event, &attr, group_leader);
7515 if (err) {
7516 __free_event(event);
7517 goto err_cpus;
7521 if (is_sampling_event(event)) {
7522 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
7523 err = -ENOTSUPP;
7524 goto err_alloc;
7528 account_event(event);
7531 * Special case software events and allow them to be part of
7532 * any hardware group.
7534 pmu = event->pmu;
7536 if (group_leader &&
7537 (is_software_event(event) != is_software_event(group_leader))) {
7538 if (is_software_event(event)) {
7540 * If event and group_leader are not both a software
7541 * event, and event is, then group leader is not.
7543 * Allow the addition of software events to !software
7544 * groups, this is safe because software events never
7545 * fail to schedule.
7547 pmu = group_leader->pmu;
7548 } else if (is_software_event(group_leader) &&
7549 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
7551 * In case the group is a pure software group, and we
7552 * try to add a hardware event, move the whole group to
7553 * the hardware context.
7555 move_group = 1;
7560 * Get the target context (task or percpu):
7562 ctx = find_get_context(pmu, task, event->cpu);
7563 if (IS_ERR(ctx)) {
7564 err = PTR_ERR(ctx);
7565 goto err_alloc;
7568 if (task) {
7569 put_task_struct(task);
7570 task = NULL;
7574 * Look up the group leader (we will attach this event to it):
7576 if (group_leader) {
7577 err = -EINVAL;
7580 * Do not allow a recursive hierarchy (this new sibling
7581 * becoming part of another group-sibling):
7583 if (group_leader->group_leader != group_leader)
7584 goto err_context;
7586 * Make sure we're both events for the same CPU;
7587 * grouping events for different CPUs is broken; since
7588 * you can never concurrently schedule them anyhow.
7590 if (group_leader->cpu != event->cpu)
7591 goto err_context;
7594 * Make sure we're both on the same task, or both
7595 * per-CPU events.
7597 if (group_leader->ctx->task != ctx->task)
7598 goto err_context;
7601 * Do not allow to attach to a group in a different task
7602 * or CPU context. If we're moving SW events, we'll fix
7603 * this up later, so allow that.
7605 if (!move_group && group_leader->ctx != ctx)
7606 goto err_context;
7609 * Only a group leader can be exclusive or pinned
7611 if (attr.exclusive || attr.pinned)
7612 goto err_context;
7615 if (output_event) {
7616 err = perf_event_set_output(event, output_event);
7617 if (err)
7618 goto err_context;
7621 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
7622 f_flags);
7623 if (IS_ERR(event_file)) {
7624 err = PTR_ERR(event_file);
7625 goto err_context;
7628 if (move_group) {
7629 gctx = group_leader->ctx;
7632 * See perf_event_ctx_lock() for comments on the details
7633 * of swizzling perf_event::ctx.
7635 mutex_lock_double(&gctx->mutex, &ctx->mutex);
7637 perf_remove_from_context(group_leader, false);
7640 * Removing from the context ends up with disabled
7641 * event. What we want here is event in the initial
7642 * startup state, ready to be add into new context.
7644 perf_event__state_init(group_leader);
7645 list_for_each_entry(sibling, &group_leader->sibling_list,
7646 group_entry) {
7647 perf_remove_from_context(sibling, false);
7648 perf_event__state_init(sibling);
7649 put_ctx(gctx);
7651 } else {
7652 mutex_lock(&ctx->mutex);
7655 WARN_ON_ONCE(ctx->parent_ctx);
7657 if (move_group) {
7659 * Wait for everybody to stop referencing the events through
7660 * the old lists, before installing it on new lists.
7662 synchronize_rcu();
7664 perf_install_in_context(ctx, group_leader, group_leader->cpu);
7665 get_ctx(ctx);
7666 list_for_each_entry(sibling, &group_leader->sibling_list,
7667 group_entry) {
7668 perf_install_in_context(ctx, sibling, sibling->cpu);
7669 get_ctx(ctx);
7673 perf_install_in_context(ctx, event, event->cpu);
7674 perf_unpin_context(ctx);
7676 if (move_group) {
7677 mutex_unlock(&gctx->mutex);
7678 put_ctx(gctx);
7680 mutex_unlock(&ctx->mutex);
7682 put_online_cpus();
7684 event->owner = current;
7686 mutex_lock(&current->perf_event_mutex);
7687 list_add_tail(&event->owner_entry, &current->perf_event_list);
7688 mutex_unlock(&current->perf_event_mutex);
7691 * Precalculate sample_data sizes
7693 perf_event__header_size(event);
7694 perf_event__id_header_size(event);
7697 * Drop the reference on the group_event after placing the
7698 * new event on the sibling_list. This ensures destruction
7699 * of the group leader will find the pointer to itself in
7700 * perf_group_detach().
7702 fdput(group);
7703 fd_install(event_fd, event_file);
7704 return event_fd;
7706 err_context:
7707 perf_unpin_context(ctx);
7708 put_ctx(ctx);
7709 err_alloc:
7710 free_event(event);
7711 err_cpus:
7712 put_online_cpus();
7713 err_task:
7714 if (task)
7715 put_task_struct(task);
7716 err_group_fd:
7717 fdput(group);
7718 err_fd:
7719 put_unused_fd(event_fd);
7720 return err;
7724 * perf_event_create_kernel_counter
7726 * @attr: attributes of the counter to create
7727 * @cpu: cpu in which the counter is bound
7728 * @task: task to profile (NULL for percpu)
7730 struct perf_event *
7731 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
7732 struct task_struct *task,
7733 perf_overflow_handler_t overflow_handler,
7734 void *context)
7736 struct perf_event_context *ctx;
7737 struct perf_event *event;
7738 int err;
7741 * Get the target context (task or percpu):
7744 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
7745 overflow_handler, context);
7746 if (IS_ERR(event)) {
7747 err = PTR_ERR(event);
7748 goto err;
7751 /* Mark owner so we could distinguish it from user events. */
7752 event->owner = EVENT_OWNER_KERNEL;
7754 account_event(event);
7756 ctx = find_get_context(event->pmu, task, cpu);
7757 if (IS_ERR(ctx)) {
7758 err = PTR_ERR(ctx);
7759 goto err_free;
7762 WARN_ON_ONCE(ctx->parent_ctx);
7763 mutex_lock(&ctx->mutex);
7764 perf_install_in_context(ctx, event, cpu);
7765 perf_unpin_context(ctx);
7766 mutex_unlock(&ctx->mutex);
7768 return event;
7770 err_free:
7771 free_event(event);
7772 err:
7773 return ERR_PTR(err);
7775 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
7777 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
7779 struct perf_event_context *src_ctx;
7780 struct perf_event_context *dst_ctx;
7781 struct perf_event *event, *tmp;
7782 LIST_HEAD(events);
7784 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
7785 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
7788 * See perf_event_ctx_lock() for comments on the details
7789 * of swizzling perf_event::ctx.
7791 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
7792 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
7793 event_entry) {
7794 perf_remove_from_context(event, false);
7795 unaccount_event_cpu(event, src_cpu);
7796 put_ctx(src_ctx);
7797 list_add(&event->migrate_entry, &events);
7800 synchronize_rcu();
7802 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
7803 list_del(&event->migrate_entry);
7804 if (event->state >= PERF_EVENT_STATE_OFF)
7805 event->state = PERF_EVENT_STATE_INACTIVE;
7806 account_event_cpu(event, dst_cpu);
7807 perf_install_in_context(dst_ctx, event, dst_cpu);
7808 get_ctx(dst_ctx);
7810 mutex_unlock(&dst_ctx->mutex);
7811 mutex_unlock(&src_ctx->mutex);
7813 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
7815 static void sync_child_event(struct perf_event *child_event,
7816 struct task_struct *child)
7818 struct perf_event *parent_event = child_event->parent;
7819 u64 child_val;
7821 if (child_event->attr.inherit_stat)
7822 perf_event_read_event(child_event, child);
7824 child_val = perf_event_count(child_event);
7827 * Add back the child's count to the parent's count:
7829 atomic64_add(child_val, &parent_event->child_count);
7830 atomic64_add(child_event->total_time_enabled,
7831 &parent_event->child_total_time_enabled);
7832 atomic64_add(child_event->total_time_running,
7833 &parent_event->child_total_time_running);
7836 * Remove this event from the parent's list
7838 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7839 mutex_lock(&parent_event->child_mutex);
7840 list_del_init(&child_event->child_list);
7841 mutex_unlock(&parent_event->child_mutex);
7844 * Make sure user/parent get notified, that we just
7845 * lost one event.
7847 perf_event_wakeup(parent_event);
7850 * Release the parent event, if this was the last
7851 * reference to it.
7853 put_event(parent_event);
7856 static void
7857 __perf_event_exit_task(struct perf_event *child_event,
7858 struct perf_event_context *child_ctx,
7859 struct task_struct *child)
7862 * Do not destroy the 'original' grouping; because of the context
7863 * switch optimization the original events could've ended up in a
7864 * random child task.
7866 * If we were to destroy the original group, all group related
7867 * operations would cease to function properly after this random
7868 * child dies.
7870 * Do destroy all inherited groups, we don't care about those
7871 * and being thorough is better.
7873 perf_remove_from_context(child_event, !!child_event->parent);
7876 * It can happen that the parent exits first, and has events
7877 * that are still around due to the child reference. These
7878 * events need to be zapped.
7880 if (child_event->parent) {
7881 sync_child_event(child_event, child);
7882 free_event(child_event);
7883 } else {
7884 child_event->state = PERF_EVENT_STATE_EXIT;
7885 perf_event_wakeup(child_event);
7889 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
7891 struct perf_event *child_event, *next;
7892 struct perf_event_context *child_ctx, *clone_ctx = NULL;
7893 unsigned long flags;
7895 if (likely(!child->perf_event_ctxp[ctxn])) {
7896 perf_event_task(child, NULL, 0);
7897 return;
7900 local_irq_save(flags);
7902 * We can't reschedule here because interrupts are disabled,
7903 * and either child is current or it is a task that can't be
7904 * scheduled, so we are now safe from rescheduling changing
7905 * our context.
7907 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
7910 * Take the context lock here so that if find_get_context is
7911 * reading child->perf_event_ctxp, we wait until it has
7912 * incremented the context's refcount before we do put_ctx below.
7914 raw_spin_lock(&child_ctx->lock);
7915 task_ctx_sched_out(child_ctx);
7916 child->perf_event_ctxp[ctxn] = NULL;
7919 * If this context is a clone; unclone it so it can't get
7920 * swapped to another process while we're removing all
7921 * the events from it.
7923 clone_ctx = unclone_ctx(child_ctx);
7924 update_context_time(child_ctx);
7925 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7927 if (clone_ctx)
7928 put_ctx(clone_ctx);
7931 * Report the task dead after unscheduling the events so that we
7932 * won't get any samples after PERF_RECORD_EXIT. We can however still
7933 * get a few PERF_RECORD_READ events.
7935 perf_event_task(child, child_ctx, 0);
7938 * We can recurse on the same lock type through:
7940 * __perf_event_exit_task()
7941 * sync_child_event()
7942 * put_event()
7943 * mutex_lock(&ctx->mutex)
7945 * But since its the parent context it won't be the same instance.
7947 mutex_lock(&child_ctx->mutex);
7949 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
7950 __perf_event_exit_task(child_event, child_ctx, child);
7952 mutex_unlock(&child_ctx->mutex);
7954 put_ctx(child_ctx);
7958 * When a child task exits, feed back event values to parent events.
7960 void perf_event_exit_task(struct task_struct *child)
7962 struct perf_event *event, *tmp;
7963 int ctxn;
7965 mutex_lock(&child->perf_event_mutex);
7966 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
7967 owner_entry) {
7968 list_del_init(&event->owner_entry);
7971 * Ensure the list deletion is visible before we clear
7972 * the owner, closes a race against perf_release() where
7973 * we need to serialize on the owner->perf_event_mutex.
7975 smp_wmb();
7976 event->owner = NULL;
7978 mutex_unlock(&child->perf_event_mutex);
7980 for_each_task_context_nr(ctxn)
7981 perf_event_exit_task_context(child, ctxn);
7984 static void perf_free_event(struct perf_event *event,
7985 struct perf_event_context *ctx)
7987 struct perf_event *parent = event->parent;
7989 if (WARN_ON_ONCE(!parent))
7990 return;
7992 mutex_lock(&parent->child_mutex);
7993 list_del_init(&event->child_list);
7994 mutex_unlock(&parent->child_mutex);
7996 put_event(parent);
7998 perf_group_detach(event);
7999 list_del_event(event, ctx);
8000 free_event(event);
8004 * free an unexposed, unused context as created by inheritance by
8005 * perf_event_init_task below, used by fork() in case of fail.
8007 void perf_event_free_task(struct task_struct *task)
8009 struct perf_event_context *ctx;
8010 struct perf_event *event, *tmp;
8011 int ctxn;
8013 for_each_task_context_nr(ctxn) {
8014 ctx = task->perf_event_ctxp[ctxn];
8015 if (!ctx)
8016 continue;
8018 mutex_lock(&ctx->mutex);
8019 again:
8020 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
8021 group_entry)
8022 perf_free_event(event, ctx);
8024 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
8025 group_entry)
8026 perf_free_event(event, ctx);
8028 if (!list_empty(&ctx->pinned_groups) ||
8029 !list_empty(&ctx->flexible_groups))
8030 goto again;
8032 mutex_unlock(&ctx->mutex);
8034 put_ctx(ctx);
8038 void perf_event_delayed_put(struct task_struct *task)
8040 int ctxn;
8042 for_each_task_context_nr(ctxn)
8043 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
8047 * inherit a event from parent task to child task:
8049 static struct perf_event *
8050 inherit_event(struct perf_event *parent_event,
8051 struct task_struct *parent,
8052 struct perf_event_context *parent_ctx,
8053 struct task_struct *child,
8054 struct perf_event *group_leader,
8055 struct perf_event_context *child_ctx)
8057 enum perf_event_active_state parent_state = parent_event->state;
8058 struct perf_event *child_event;
8059 unsigned long flags;
8062 * Instead of creating recursive hierarchies of events,
8063 * we link inherited events back to the original parent,
8064 * which has a filp for sure, which we use as the reference
8065 * count:
8067 if (parent_event->parent)
8068 parent_event = parent_event->parent;
8070 child_event = perf_event_alloc(&parent_event->attr,
8071 parent_event->cpu,
8072 child,
8073 group_leader, parent_event,
8074 NULL, NULL);
8075 if (IS_ERR(child_event))
8076 return child_event;
8078 if (is_orphaned_event(parent_event) ||
8079 !atomic_long_inc_not_zero(&parent_event->refcount)) {
8080 free_event(child_event);
8081 return NULL;
8084 get_ctx(child_ctx);
8087 * Make the child state follow the state of the parent event,
8088 * not its attr.disabled bit. We hold the parent's mutex,
8089 * so we won't race with perf_event_{en, dis}able_family.
8091 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
8092 child_event->state = PERF_EVENT_STATE_INACTIVE;
8093 else
8094 child_event->state = PERF_EVENT_STATE_OFF;
8096 if (parent_event->attr.freq) {
8097 u64 sample_period = parent_event->hw.sample_period;
8098 struct hw_perf_event *hwc = &child_event->hw;
8100 hwc->sample_period = sample_period;
8101 hwc->last_period = sample_period;
8103 local64_set(&hwc->period_left, sample_period);
8106 child_event->ctx = child_ctx;
8107 child_event->overflow_handler = parent_event->overflow_handler;
8108 child_event->overflow_handler_context
8109 = parent_event->overflow_handler_context;
8112 * Precalculate sample_data sizes
8114 perf_event__header_size(child_event);
8115 perf_event__id_header_size(child_event);
8118 * Link it up in the child's context:
8120 raw_spin_lock_irqsave(&child_ctx->lock, flags);
8121 add_event_to_ctx(child_event, child_ctx);
8122 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
8125 * Link this into the parent event's child list
8127 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
8128 mutex_lock(&parent_event->child_mutex);
8129 list_add_tail(&child_event->child_list, &parent_event->child_list);
8130 mutex_unlock(&parent_event->child_mutex);
8132 return child_event;
8135 static int inherit_group(struct perf_event *parent_event,
8136 struct task_struct *parent,
8137 struct perf_event_context *parent_ctx,
8138 struct task_struct *child,
8139 struct perf_event_context *child_ctx)
8141 struct perf_event *leader;
8142 struct perf_event *sub;
8143 struct perf_event *child_ctr;
8145 leader = inherit_event(parent_event, parent, parent_ctx,
8146 child, NULL, child_ctx);
8147 if (IS_ERR(leader))
8148 return PTR_ERR(leader);
8149 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
8150 child_ctr = inherit_event(sub, parent, parent_ctx,
8151 child, leader, child_ctx);
8152 if (IS_ERR(child_ctr))
8153 return PTR_ERR(child_ctr);
8155 return 0;
8158 static int
8159 inherit_task_group(struct perf_event *event, struct task_struct *parent,
8160 struct perf_event_context *parent_ctx,
8161 struct task_struct *child, int ctxn,
8162 int *inherited_all)
8164 int ret;
8165 struct perf_event_context *child_ctx;
8167 if (!event->attr.inherit) {
8168 *inherited_all = 0;
8169 return 0;
8172 child_ctx = child->perf_event_ctxp[ctxn];
8173 if (!child_ctx) {
8175 * This is executed from the parent task context, so
8176 * inherit events that have been marked for cloning.
8177 * First allocate and initialize a context for the
8178 * child.
8181 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
8182 if (!child_ctx)
8183 return -ENOMEM;
8185 child->perf_event_ctxp[ctxn] = child_ctx;
8188 ret = inherit_group(event, parent, parent_ctx,
8189 child, child_ctx);
8191 if (ret)
8192 *inherited_all = 0;
8194 return ret;
8198 * Initialize the perf_event context in task_struct
8200 static int perf_event_init_context(struct task_struct *child, int ctxn)
8202 struct perf_event_context *child_ctx, *parent_ctx;
8203 struct perf_event_context *cloned_ctx;
8204 struct perf_event *event;
8205 struct task_struct *parent = current;
8206 int inherited_all = 1;
8207 unsigned long flags;
8208 int ret = 0;
8210 if (likely(!parent->perf_event_ctxp[ctxn]))
8211 return 0;
8214 * If the parent's context is a clone, pin it so it won't get
8215 * swapped under us.
8217 parent_ctx = perf_pin_task_context(parent, ctxn);
8218 if (!parent_ctx)
8219 return 0;
8222 * No need to check if parent_ctx != NULL here; since we saw
8223 * it non-NULL earlier, the only reason for it to become NULL
8224 * is if we exit, and since we're currently in the middle of
8225 * a fork we can't be exiting at the same time.
8229 * Lock the parent list. No need to lock the child - not PID
8230 * hashed yet and not running, so nobody can access it.
8232 mutex_lock(&parent_ctx->mutex);
8235 * We dont have to disable NMIs - we are only looking at
8236 * the list, not manipulating it:
8238 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
8239 ret = inherit_task_group(event, parent, parent_ctx,
8240 child, ctxn, &inherited_all);
8241 if (ret)
8242 goto out_unlock;
8246 * We can't hold ctx->lock when iterating the ->flexible_group list due
8247 * to allocations, but we need to prevent rotation because
8248 * rotate_ctx() will change the list from interrupt context.
8250 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
8251 parent_ctx->rotate_disable = 1;
8252 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
8254 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
8255 ret = inherit_task_group(event, parent, parent_ctx,
8256 child, ctxn, &inherited_all);
8257 if (ret)
8258 goto out_unlock;
8261 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
8262 parent_ctx->rotate_disable = 0;
8264 child_ctx = child->perf_event_ctxp[ctxn];
8266 if (child_ctx && inherited_all) {
8268 * Mark the child context as a clone of the parent
8269 * context, or of whatever the parent is a clone of.
8271 * Note that if the parent is a clone, the holding of
8272 * parent_ctx->lock avoids it from being uncloned.
8274 cloned_ctx = parent_ctx->parent_ctx;
8275 if (cloned_ctx) {
8276 child_ctx->parent_ctx = cloned_ctx;
8277 child_ctx->parent_gen = parent_ctx->parent_gen;
8278 } else {
8279 child_ctx->parent_ctx = parent_ctx;
8280 child_ctx->parent_gen = parent_ctx->generation;
8282 get_ctx(child_ctx->parent_ctx);
8285 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
8286 out_unlock:
8287 mutex_unlock(&parent_ctx->mutex);
8289 perf_unpin_context(parent_ctx);
8290 put_ctx(parent_ctx);
8292 return ret;
8296 * Initialize the perf_event context in task_struct
8298 int perf_event_init_task(struct task_struct *child)
8300 int ctxn, ret;
8302 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
8303 mutex_init(&child->perf_event_mutex);
8304 INIT_LIST_HEAD(&child->perf_event_list);
8306 for_each_task_context_nr(ctxn) {
8307 ret = perf_event_init_context(child, ctxn);
8308 if (ret) {
8309 perf_event_free_task(child);
8310 return ret;
8314 return 0;
8317 static void __init perf_event_init_all_cpus(void)
8319 struct swevent_htable *swhash;
8320 int cpu;
8322 for_each_possible_cpu(cpu) {
8323 swhash = &per_cpu(swevent_htable, cpu);
8324 mutex_init(&swhash->hlist_mutex);
8325 INIT_LIST_HEAD(&per_cpu(rotation_list, cpu));
8329 static void perf_event_init_cpu(int cpu)
8331 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
8333 mutex_lock(&swhash->hlist_mutex);
8334 if (swhash->hlist_refcount > 0) {
8335 struct swevent_hlist *hlist;
8337 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
8338 WARN_ON(!hlist);
8339 rcu_assign_pointer(swhash->swevent_hlist, hlist);
8341 mutex_unlock(&swhash->hlist_mutex);
8344 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC
8345 static void perf_pmu_rotate_stop(struct pmu *pmu)
8347 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
8349 WARN_ON(!irqs_disabled());
8351 list_del_init(&cpuctx->rotation_list);
8354 static void __perf_event_exit_context(void *__info)
8356 struct remove_event re = { .detach_group = true };
8357 struct perf_event_context *ctx = __info;
8359 perf_pmu_rotate_stop(ctx->pmu);
8361 rcu_read_lock();
8362 list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
8363 __perf_remove_from_context(&re);
8364 rcu_read_unlock();
8367 static void perf_event_exit_cpu_context(int cpu)
8369 struct perf_event_context *ctx;
8370 struct pmu *pmu;
8371 int idx;
8373 idx = srcu_read_lock(&pmus_srcu);
8374 list_for_each_entry_rcu(pmu, &pmus, entry) {
8375 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
8377 mutex_lock(&ctx->mutex);
8378 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
8379 mutex_unlock(&ctx->mutex);
8381 srcu_read_unlock(&pmus_srcu, idx);
8384 static void perf_event_exit_cpu(int cpu)
8386 perf_event_exit_cpu_context(cpu);
8388 #else
8389 static inline void perf_event_exit_cpu(int cpu) { }
8390 #endif
8392 static int
8393 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
8395 int cpu;
8397 for_each_online_cpu(cpu)
8398 perf_event_exit_cpu(cpu);
8400 return NOTIFY_OK;
8404 * Run the perf reboot notifier at the very last possible moment so that
8405 * the generic watchdog code runs as long as possible.
8407 static struct notifier_block perf_reboot_notifier = {
8408 .notifier_call = perf_reboot,
8409 .priority = INT_MIN,
8412 static int
8413 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
8415 unsigned int cpu = (long)hcpu;
8417 switch (action & ~CPU_TASKS_FROZEN) {
8419 case CPU_UP_PREPARE:
8420 case CPU_DOWN_FAILED:
8421 perf_event_init_cpu(cpu);
8422 break;
8424 case CPU_UP_CANCELED:
8425 case CPU_DOWN_PREPARE:
8426 perf_event_exit_cpu(cpu);
8427 break;
8428 default:
8429 break;
8432 return NOTIFY_OK;
8435 void __init perf_event_init(void)
8437 int ret;
8439 idr_init(&pmu_idr);
8441 perf_event_init_all_cpus();
8442 init_srcu_struct(&pmus_srcu);
8443 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
8444 perf_pmu_register(&perf_cpu_clock, NULL, -1);
8445 perf_pmu_register(&perf_task_clock, NULL, -1);
8446 perf_tp_register();
8447 perf_cpu_notifier(perf_cpu_notify);
8448 register_reboot_notifier(&perf_reboot_notifier);
8450 ret = init_hw_breakpoint();
8451 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
8453 /* do not patch jump label more than once per second */
8454 jump_label_rate_limit(&perf_sched_events, HZ);
8457 * Build time assertion that we keep the data_head at the intended
8458 * location. IOW, validation we got the __reserved[] size right.
8460 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
8461 != 1024);
8464 static int __init perf_event_sysfs_init(void)
8466 struct pmu *pmu;
8467 int ret;
8469 mutex_lock(&pmus_lock);
8471 ret = bus_register(&pmu_bus);
8472 if (ret)
8473 goto unlock;
8475 list_for_each_entry(pmu, &pmus, entry) {
8476 if (!pmu->name || pmu->type < 0)
8477 continue;
8479 ret = pmu_dev_alloc(pmu);
8480 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
8482 pmu_bus_running = 1;
8483 ret = 0;
8485 unlock:
8486 mutex_unlock(&pmus_lock);
8488 return ret;
8490 device_initcall(perf_event_sysfs_init);
8492 #ifdef CONFIG_CGROUP_PERF
8493 static struct cgroup_subsys_state *
8494 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
8496 struct perf_cgroup *jc;
8498 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
8499 if (!jc)
8500 return ERR_PTR(-ENOMEM);
8502 jc->info = alloc_percpu(struct perf_cgroup_info);
8503 if (!jc->info) {
8504 kfree(jc);
8505 return ERR_PTR(-ENOMEM);
8508 return &jc->css;
8511 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
8513 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
8515 free_percpu(jc->info);
8516 kfree(jc);
8519 static int __perf_cgroup_move(void *info)
8521 struct task_struct *task = info;
8522 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
8523 return 0;
8526 static void perf_cgroup_attach(struct cgroup_subsys_state *css,
8527 struct cgroup_taskset *tset)
8529 struct task_struct *task;
8531 cgroup_taskset_for_each(task, tset)
8532 task_function_call(task, __perf_cgroup_move, task);
8535 static void perf_cgroup_exit(struct cgroup_subsys_state *css,
8536 struct cgroup_subsys_state *old_css,
8537 struct task_struct *task)
8540 * cgroup_exit() is called in the copy_process() failure path.
8541 * Ignore this case since the task hasn't ran yet, this avoids
8542 * trying to poke a half freed task state from generic code.
8544 if (!(task->flags & PF_EXITING))
8545 return;
8547 task_function_call(task, __perf_cgroup_move, task);
8550 struct cgroup_subsys perf_event_cgrp_subsys = {
8551 .css_alloc = perf_cgroup_css_alloc,
8552 .css_free = perf_cgroup_css_free,
8553 .exit = perf_cgroup_exit,
8554 .attach = perf_cgroup_attach,
8556 #endif /* CONFIG_CGROUP_PERF */