2 * Performance events core code:
4 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
5 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
6 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
7 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
9 * For licensing details see kernel-base/COPYING
14 #include <linux/cpu.h>
15 #include <linux/smp.h>
16 #include <linux/idr.h>
17 #include <linux/file.h>
18 #include <linux/poll.h>
19 #include <linux/slab.h>
20 #include <linux/hash.h>
21 #include <linux/tick.h>
22 #include <linux/sysfs.h>
23 #include <linux/dcache.h>
24 #include <linux/percpu.h>
25 #include <linux/ptrace.h>
26 #include <linux/reboot.h>
27 #include <linux/vmstat.h>
28 #include <linux/device.h>
29 #include <linux/export.h>
30 #include <linux/vmalloc.h>
31 #include <linux/hardirq.h>
32 #include <linux/rculist.h>
33 #include <linux/uaccess.h>
34 #include <linux/syscalls.h>
35 #include <linux/anon_inodes.h>
36 #include <linux/kernel_stat.h>
37 #include <linux/perf_event.h>
38 #include <linux/ftrace_event.h>
39 #include <linux/hw_breakpoint.h>
40 #include <linux/mm_types.h>
41 #include <linux/cgroup.h>
45 #include <asm/irq_regs.h>
47 struct remote_function_call {
48 struct task_struct *p;
49 int (*func)(void *info);
54 static void remote_function(void *data)
56 struct remote_function_call *tfc = data;
57 struct task_struct *p = tfc->p;
61 if (task_cpu(p) != smp_processor_id() || !task_curr(p))
65 tfc->ret = tfc->func(tfc->info);
69 * task_function_call - call a function on the cpu on which a task runs
70 * @p: the task to evaluate
71 * @func: the function to be called
72 * @info: the function call argument
74 * Calls the function @func when the task is currently running. This might
75 * be on the current CPU, which just calls the function directly
77 * returns: @func return value, or
78 * -ESRCH - when the process isn't running
79 * -EAGAIN - when the process moved away
82 task_function_call(struct task_struct *p, int (*func) (void *info), void *info)
84 struct remote_function_call data = {
88 .ret = -ESRCH, /* No such (running) process */
92 smp_call_function_single(task_cpu(p), remote_function, &data, 1);
98 * cpu_function_call - call a function on the cpu
99 * @func: the function to be called
100 * @info: the function call argument
102 * Calls the function @func on the remote cpu.
104 * returns: @func return value or -ENXIO when the cpu is offline
106 static int cpu_function_call(int cpu, int (*func) (void *info), void *info)
108 struct remote_function_call data = {
112 .ret = -ENXIO, /* No such CPU */
115 smp_call_function_single(cpu, remote_function, &data, 1);
120 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
121 PERF_FLAG_FD_OUTPUT |\
122 PERF_FLAG_PID_CGROUP)
125 * branch priv levels that need permission checks
127 #define PERF_SAMPLE_BRANCH_PERM_PLM \
128 (PERF_SAMPLE_BRANCH_KERNEL |\
129 PERF_SAMPLE_BRANCH_HV)
132 EVENT_FLEXIBLE = 0x1,
134 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
138 * perf_sched_events : >0 events exist
139 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
141 struct static_key_deferred perf_sched_events __read_mostly;
142 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
143 static DEFINE_PER_CPU(atomic_t, perf_branch_stack_events);
145 static atomic_t nr_mmap_events __read_mostly;
146 static atomic_t nr_comm_events __read_mostly;
147 static atomic_t nr_task_events __read_mostly;
148 static atomic_t nr_freq_events __read_mostly;
150 static LIST_HEAD(pmus);
151 static DEFINE_MUTEX(pmus_lock);
152 static struct srcu_struct pmus_srcu;
155 * perf event paranoia level:
156 * -1 - not paranoid at all
157 * 0 - disallow raw tracepoint access for unpriv
158 * 1 - disallow cpu events for unpriv
159 * 2 - disallow kernel profiling for unpriv
161 int sysctl_perf_event_paranoid __read_mostly = 1;
163 /* Minimum for 512 kiB + 1 user control page */
164 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
167 * max perf event sample rate
169 #define DEFAULT_MAX_SAMPLE_RATE 100000
170 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
171 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
173 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
175 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
176 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
178 static int perf_sample_allowed_ns __read_mostly =
179 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
181 void update_perf_cpu_limits(void)
183 u64 tmp = perf_sample_period_ns;
185 tmp *= sysctl_perf_cpu_time_max_percent;
187 ACCESS_ONCE(perf_sample_allowed_ns) = tmp;
190 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
192 int perf_proc_update_handler(struct ctl_table *table, int write,
193 void __user *buffer, size_t *lenp,
196 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
201 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
202 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
203 update_perf_cpu_limits();
208 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
210 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
211 void __user *buffer, size_t *lenp,
214 int ret = proc_dointvec(table, write, buffer, lenp, ppos);
219 update_perf_cpu_limits();
225 * perf samples are done in some very critical code paths (NMIs).
226 * If they take too much CPU time, the system can lock up and not
227 * get any real work done. This will drop the sample rate when
228 * we detect that events are taking too long.
230 #define NR_ACCUMULATED_SAMPLES 128
231 static DEFINE_PER_CPU(u64, running_sample_length);
233 void perf_sample_event_took(u64 sample_len_ns)
235 u64 avg_local_sample_len;
236 u64 local_samples_len;
237 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
242 /* decay the counter by 1 average sample */
243 local_samples_len = __get_cpu_var(running_sample_length);
244 local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES;
245 local_samples_len += sample_len_ns;
246 __get_cpu_var(running_sample_length) = local_samples_len;
249 * note: this will be biased artifically low until we have
250 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
251 * from having to maintain a count.
253 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
255 if (avg_local_sample_len <= allowed_ns)
258 if (max_samples_per_tick <= 1)
261 max_samples_per_tick = DIV_ROUND_UP(max_samples_per_tick, 2);
262 sysctl_perf_event_sample_rate = max_samples_per_tick * HZ;
263 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
265 printk_ratelimited(KERN_WARNING
266 "perf samples too long (%lld > %lld), lowering "
267 "kernel.perf_event_max_sample_rate to %d\n",
268 avg_local_sample_len, allowed_ns,
269 sysctl_perf_event_sample_rate);
271 update_perf_cpu_limits();
274 static atomic64_t perf_event_id;
276 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
277 enum event_type_t event_type);
279 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
280 enum event_type_t event_type,
281 struct task_struct *task);
283 static void update_context_time(struct perf_event_context *ctx);
284 static u64 perf_event_time(struct perf_event *event);
286 void __weak perf_event_print_debug(void) { }
288 extern __weak const char *perf_pmu_name(void)
293 static inline u64 perf_clock(void)
295 return local_clock();
298 static inline struct perf_cpu_context *
299 __get_cpu_context(struct perf_event_context *ctx)
301 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
304 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
305 struct perf_event_context *ctx)
307 raw_spin_lock(&cpuctx->ctx.lock);
309 raw_spin_lock(&ctx->lock);
312 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
313 struct perf_event_context *ctx)
316 raw_spin_unlock(&ctx->lock);
317 raw_spin_unlock(&cpuctx->ctx.lock);
320 #ifdef CONFIG_CGROUP_PERF
323 * perf_cgroup_info keeps track of time_enabled for a cgroup.
324 * This is a per-cpu dynamically allocated data structure.
326 struct perf_cgroup_info {
332 struct cgroup_subsys_state css;
333 struct perf_cgroup_info __percpu *info;
337 * Must ensure cgroup is pinned (css_get) before calling
338 * this function. In other words, we cannot call this function
339 * if there is no cgroup event for the current CPU context.
341 static inline struct perf_cgroup *
342 perf_cgroup_from_task(struct task_struct *task)
344 return container_of(task_css(task, perf_subsys_id),
345 struct perf_cgroup, css);
349 perf_cgroup_match(struct perf_event *event)
351 struct perf_event_context *ctx = event->ctx;
352 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
354 /* @event doesn't care about cgroup */
358 /* wants specific cgroup scope but @cpuctx isn't associated with any */
363 * Cgroup scoping is recursive. An event enabled for a cgroup is
364 * also enabled for all its descendant cgroups. If @cpuctx's
365 * cgroup is a descendant of @event's (the test covers identity
366 * case), it's a match.
368 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
369 event->cgrp->css.cgroup);
372 static inline bool perf_tryget_cgroup(struct perf_event *event)
374 return css_tryget(&event->cgrp->css);
377 static inline void perf_put_cgroup(struct perf_event *event)
379 css_put(&event->cgrp->css);
382 static inline void perf_detach_cgroup(struct perf_event *event)
384 perf_put_cgroup(event);
388 static inline int is_cgroup_event(struct perf_event *event)
390 return event->cgrp != NULL;
393 static inline u64 perf_cgroup_event_time(struct perf_event *event)
395 struct perf_cgroup_info *t;
397 t = per_cpu_ptr(event->cgrp->info, event->cpu);
401 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
403 struct perf_cgroup_info *info;
408 info = this_cpu_ptr(cgrp->info);
410 info->time += now - info->timestamp;
411 info->timestamp = now;
414 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
416 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
418 __update_cgrp_time(cgrp_out);
421 static inline void update_cgrp_time_from_event(struct perf_event *event)
423 struct perf_cgroup *cgrp;
426 * ensure we access cgroup data only when needed and
427 * when we know the cgroup is pinned (css_get)
429 if (!is_cgroup_event(event))
432 cgrp = perf_cgroup_from_task(current);
434 * Do not update time when cgroup is not active
436 if (cgrp == event->cgrp)
437 __update_cgrp_time(event->cgrp);
441 perf_cgroup_set_timestamp(struct task_struct *task,
442 struct perf_event_context *ctx)
444 struct perf_cgroup *cgrp;
445 struct perf_cgroup_info *info;
448 * ctx->lock held by caller
449 * ensure we do not access cgroup data
450 * unless we have the cgroup pinned (css_get)
452 if (!task || !ctx->nr_cgroups)
455 cgrp = perf_cgroup_from_task(task);
456 info = this_cpu_ptr(cgrp->info);
457 info->timestamp = ctx->timestamp;
460 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
461 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
464 * reschedule events based on the cgroup constraint of task.
466 * mode SWOUT : schedule out everything
467 * mode SWIN : schedule in based on cgroup for next
469 void perf_cgroup_switch(struct task_struct *task, int mode)
471 struct perf_cpu_context *cpuctx;
476 * disable interrupts to avoid geting nr_cgroup
477 * changes via __perf_event_disable(). Also
480 local_irq_save(flags);
483 * we reschedule only in the presence of cgroup
484 * constrained events.
488 list_for_each_entry_rcu(pmu, &pmus, entry) {
489 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
490 if (cpuctx->unique_pmu != pmu)
491 continue; /* ensure we process each cpuctx once */
494 * perf_cgroup_events says at least one
495 * context on this CPU has cgroup events.
497 * ctx->nr_cgroups reports the number of cgroup
498 * events for a context.
500 if (cpuctx->ctx.nr_cgroups > 0) {
501 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
502 perf_pmu_disable(cpuctx->ctx.pmu);
504 if (mode & PERF_CGROUP_SWOUT) {
505 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
507 * must not be done before ctxswout due
508 * to event_filter_match() in event_sched_out()
513 if (mode & PERF_CGROUP_SWIN) {
514 WARN_ON_ONCE(cpuctx->cgrp);
516 * set cgrp before ctxsw in to allow
517 * event_filter_match() to not have to pass
520 cpuctx->cgrp = perf_cgroup_from_task(task);
521 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
523 perf_pmu_enable(cpuctx->ctx.pmu);
524 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
530 local_irq_restore(flags);
533 static inline void perf_cgroup_sched_out(struct task_struct *task,
534 struct task_struct *next)
536 struct perf_cgroup *cgrp1;
537 struct perf_cgroup *cgrp2 = NULL;
540 * we come here when we know perf_cgroup_events > 0
542 cgrp1 = perf_cgroup_from_task(task);
545 * next is NULL when called from perf_event_enable_on_exec()
546 * that will systematically cause a cgroup_switch()
549 cgrp2 = perf_cgroup_from_task(next);
552 * only schedule out current cgroup events if we know
553 * that we are switching to a different cgroup. Otherwise,
554 * do no touch the cgroup events.
557 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
560 static inline void perf_cgroup_sched_in(struct task_struct *prev,
561 struct task_struct *task)
563 struct perf_cgroup *cgrp1;
564 struct perf_cgroup *cgrp2 = NULL;
567 * we come here when we know perf_cgroup_events > 0
569 cgrp1 = perf_cgroup_from_task(task);
571 /* prev can never be NULL */
572 cgrp2 = perf_cgroup_from_task(prev);
575 * only need to schedule in cgroup events if we are changing
576 * cgroup during ctxsw. Cgroup events were not scheduled
577 * out of ctxsw out if that was not the case.
580 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
583 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
584 struct perf_event_attr *attr,
585 struct perf_event *group_leader)
587 struct perf_cgroup *cgrp;
588 struct cgroup_subsys_state *css;
589 struct fd f = fdget(fd);
597 css = css_from_dir(f.file->f_dentry, &perf_subsys);
603 cgrp = container_of(css, struct perf_cgroup, css);
606 /* must be done before we fput() the file */
607 if (!perf_tryget_cgroup(event)) {
614 * all events in a group must monitor
615 * the same cgroup because a task belongs
616 * to only one perf cgroup at a time
618 if (group_leader && group_leader->cgrp != cgrp) {
619 perf_detach_cgroup(event);
629 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
631 struct perf_cgroup_info *t;
632 t = per_cpu_ptr(event->cgrp->info, event->cpu);
633 event->shadow_ctx_time = now - t->timestamp;
637 perf_cgroup_defer_enabled(struct perf_event *event)
640 * when the current task's perf cgroup does not match
641 * the event's, we need to remember to call the
642 * perf_mark_enable() function the first time a task with
643 * a matching perf cgroup is scheduled in.
645 if (is_cgroup_event(event) && !perf_cgroup_match(event))
646 event->cgrp_defer_enabled = 1;
650 perf_cgroup_mark_enabled(struct perf_event *event,
651 struct perf_event_context *ctx)
653 struct perf_event *sub;
654 u64 tstamp = perf_event_time(event);
656 if (!event->cgrp_defer_enabled)
659 event->cgrp_defer_enabled = 0;
661 event->tstamp_enabled = tstamp - event->total_time_enabled;
662 list_for_each_entry(sub, &event->sibling_list, group_entry) {
663 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
664 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
665 sub->cgrp_defer_enabled = 0;
669 #else /* !CONFIG_CGROUP_PERF */
672 perf_cgroup_match(struct perf_event *event)
677 static inline void perf_detach_cgroup(struct perf_event *event)
680 static inline int is_cgroup_event(struct perf_event *event)
685 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
690 static inline void update_cgrp_time_from_event(struct perf_event *event)
694 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
698 static inline void perf_cgroup_sched_out(struct task_struct *task,
699 struct task_struct *next)
703 static inline void perf_cgroup_sched_in(struct task_struct *prev,
704 struct task_struct *task)
708 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
709 struct perf_event_attr *attr,
710 struct perf_event *group_leader)
716 perf_cgroup_set_timestamp(struct task_struct *task,
717 struct perf_event_context *ctx)
722 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
727 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
731 static inline u64 perf_cgroup_event_time(struct perf_event *event)
737 perf_cgroup_defer_enabled(struct perf_event *event)
742 perf_cgroup_mark_enabled(struct perf_event *event,
743 struct perf_event_context *ctx)
749 * set default to be dependent on timer tick just
752 #define PERF_CPU_HRTIMER (1000 / HZ)
754 * function must be called with interrupts disbled
756 static enum hrtimer_restart perf_cpu_hrtimer_handler(struct hrtimer *hr)
758 struct perf_cpu_context *cpuctx;
759 enum hrtimer_restart ret = HRTIMER_NORESTART;
762 WARN_ON(!irqs_disabled());
764 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
766 rotations = perf_rotate_context(cpuctx);
769 * arm timer if needed
772 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
773 ret = HRTIMER_RESTART;
779 /* CPU is going down */
780 void perf_cpu_hrtimer_cancel(int cpu)
782 struct perf_cpu_context *cpuctx;
786 if (WARN_ON(cpu != smp_processor_id()))
789 local_irq_save(flags);
793 list_for_each_entry_rcu(pmu, &pmus, entry) {
794 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
796 if (pmu->task_ctx_nr == perf_sw_context)
799 hrtimer_cancel(&cpuctx->hrtimer);
804 local_irq_restore(flags);
807 static void __perf_cpu_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
809 struct hrtimer *hr = &cpuctx->hrtimer;
810 struct pmu *pmu = cpuctx->ctx.pmu;
813 /* no multiplexing needed for SW PMU */
814 if (pmu->task_ctx_nr == perf_sw_context)
818 * check default is sane, if not set then force to
819 * default interval (1/tick)
821 timer = pmu->hrtimer_interval_ms;
823 timer = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
825 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
827 hrtimer_init(hr, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
828 hr->function = perf_cpu_hrtimer_handler;
831 static void perf_cpu_hrtimer_restart(struct perf_cpu_context *cpuctx)
833 struct hrtimer *hr = &cpuctx->hrtimer;
834 struct pmu *pmu = cpuctx->ctx.pmu;
837 if (pmu->task_ctx_nr == perf_sw_context)
840 if (hrtimer_active(hr))
843 if (!hrtimer_callback_running(hr))
844 __hrtimer_start_range_ns(hr, cpuctx->hrtimer_interval,
845 0, HRTIMER_MODE_REL_PINNED, 0);
848 void perf_pmu_disable(struct pmu *pmu)
850 int *count = this_cpu_ptr(pmu->pmu_disable_count);
852 pmu->pmu_disable(pmu);
855 void perf_pmu_enable(struct pmu *pmu)
857 int *count = this_cpu_ptr(pmu->pmu_disable_count);
859 pmu->pmu_enable(pmu);
862 static DEFINE_PER_CPU(struct list_head, rotation_list);
865 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
866 * because they're strictly cpu affine and rotate_start is called with IRQs
867 * disabled, while rotate_context is called from IRQ context.
869 static void perf_pmu_rotate_start(struct pmu *pmu)
871 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
872 struct list_head *head = &__get_cpu_var(rotation_list);
874 WARN_ON(!irqs_disabled());
876 if (list_empty(&cpuctx->rotation_list))
877 list_add(&cpuctx->rotation_list, head);
880 static void get_ctx(struct perf_event_context *ctx)
882 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
885 static void put_ctx(struct perf_event_context *ctx)
887 if (atomic_dec_and_test(&ctx->refcount)) {
889 put_ctx(ctx->parent_ctx);
891 put_task_struct(ctx->task);
892 kfree_rcu(ctx, rcu_head);
896 static void unclone_ctx(struct perf_event_context *ctx)
898 if (ctx->parent_ctx) {
899 put_ctx(ctx->parent_ctx);
900 ctx->parent_ctx = NULL;
904 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
907 * only top level events have the pid namespace they were created in
910 event = event->parent;
912 return task_tgid_nr_ns(p, event->ns);
915 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
918 * only top level events have the pid namespace they were created in
921 event = event->parent;
923 return task_pid_nr_ns(p, event->ns);
927 * If we inherit events we want to return the parent event id
930 static u64 primary_event_id(struct perf_event *event)
935 id = event->parent->id;
941 * Get the perf_event_context for a task and lock it.
942 * This has to cope with with the fact that until it is locked,
943 * the context could get moved to another task.
945 static struct perf_event_context *
946 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
948 struct perf_event_context *ctx;
952 * One of the few rules of preemptible RCU is that one cannot do
953 * rcu_read_unlock() while holding a scheduler (or nested) lock when
954 * part of the read side critical section was preemptible -- see
955 * rcu_read_unlock_special().
957 * Since ctx->lock nests under rq->lock we must ensure the entire read
958 * side critical section is non-preemptible.
962 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
965 * If this context is a clone of another, it might
966 * get swapped for another underneath us by
967 * perf_event_task_sched_out, though the
968 * rcu_read_lock() protects us from any context
969 * getting freed. Lock the context and check if it
970 * got swapped before we could get the lock, and retry
971 * if so. If we locked the right context, then it
972 * can't get swapped on us any more.
974 raw_spin_lock_irqsave(&ctx->lock, *flags);
975 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
976 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
982 if (!atomic_inc_not_zero(&ctx->refcount)) {
983 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
993 * Get the context for a task and increment its pin_count so it
994 * can't get swapped to another task. This also increments its
995 * reference count so that the context can't get freed.
997 static struct perf_event_context *
998 perf_pin_task_context(struct task_struct *task, int ctxn)
1000 struct perf_event_context *ctx;
1001 unsigned long flags;
1003 ctx = perf_lock_task_context(task, ctxn, &flags);
1006 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1011 static void perf_unpin_context(struct perf_event_context *ctx)
1013 unsigned long flags;
1015 raw_spin_lock_irqsave(&ctx->lock, flags);
1017 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1021 * Update the record of the current time in a context.
1023 static void update_context_time(struct perf_event_context *ctx)
1025 u64 now = perf_clock();
1027 ctx->time += now - ctx->timestamp;
1028 ctx->timestamp = now;
1031 static u64 perf_event_time(struct perf_event *event)
1033 struct perf_event_context *ctx = event->ctx;
1035 if (is_cgroup_event(event))
1036 return perf_cgroup_event_time(event);
1038 return ctx ? ctx->time : 0;
1042 * Update the total_time_enabled and total_time_running fields for a event.
1043 * The caller of this function needs to hold the ctx->lock.
1045 static void update_event_times(struct perf_event *event)
1047 struct perf_event_context *ctx = event->ctx;
1050 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1051 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1054 * in cgroup mode, time_enabled represents
1055 * the time the event was enabled AND active
1056 * tasks were in the monitored cgroup. This is
1057 * independent of the activity of the context as
1058 * there may be a mix of cgroup and non-cgroup events.
1060 * That is why we treat cgroup events differently
1063 if (is_cgroup_event(event))
1064 run_end = perf_cgroup_event_time(event);
1065 else if (ctx->is_active)
1066 run_end = ctx->time;
1068 run_end = event->tstamp_stopped;
1070 event->total_time_enabled = run_end - event->tstamp_enabled;
1072 if (event->state == PERF_EVENT_STATE_INACTIVE)
1073 run_end = event->tstamp_stopped;
1075 run_end = perf_event_time(event);
1077 event->total_time_running = run_end - event->tstamp_running;
1082 * Update total_time_enabled and total_time_running for all events in a group.
1084 static void update_group_times(struct perf_event *leader)
1086 struct perf_event *event;
1088 update_event_times(leader);
1089 list_for_each_entry(event, &leader->sibling_list, group_entry)
1090 update_event_times(event);
1093 static struct list_head *
1094 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1096 if (event->attr.pinned)
1097 return &ctx->pinned_groups;
1099 return &ctx->flexible_groups;
1103 * Add a event from the lists for its context.
1104 * Must be called with ctx->mutex and ctx->lock held.
1107 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1109 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1110 event->attach_state |= PERF_ATTACH_CONTEXT;
1113 * If we're a stand alone event or group leader, we go to the context
1114 * list, group events are kept attached to the group so that
1115 * perf_group_detach can, at all times, locate all siblings.
1117 if (event->group_leader == event) {
1118 struct list_head *list;
1120 if (is_software_event(event))
1121 event->group_flags |= PERF_GROUP_SOFTWARE;
1123 list = ctx_group_list(event, ctx);
1124 list_add_tail(&event->group_entry, list);
1127 if (is_cgroup_event(event))
1130 if (has_branch_stack(event))
1131 ctx->nr_branch_stack++;
1133 list_add_rcu(&event->event_entry, &ctx->event_list);
1134 if (!ctx->nr_events)
1135 perf_pmu_rotate_start(ctx->pmu);
1137 if (event->attr.inherit_stat)
1142 * Initialize event state based on the perf_event_attr::disabled.
1144 static inline void perf_event__state_init(struct perf_event *event)
1146 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1147 PERF_EVENT_STATE_INACTIVE;
1151 * Called at perf_event creation and when events are attached/detached from a
1154 static void perf_event__read_size(struct perf_event *event)
1156 int entry = sizeof(u64); /* value */
1160 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1161 size += sizeof(u64);
1163 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1164 size += sizeof(u64);
1166 if (event->attr.read_format & PERF_FORMAT_ID)
1167 entry += sizeof(u64);
1169 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1170 nr += event->group_leader->nr_siblings;
1171 size += sizeof(u64);
1175 event->read_size = size;
1178 static void perf_event__header_size(struct perf_event *event)
1180 struct perf_sample_data *data;
1181 u64 sample_type = event->attr.sample_type;
1184 perf_event__read_size(event);
1186 if (sample_type & PERF_SAMPLE_IP)
1187 size += sizeof(data->ip);
1189 if (sample_type & PERF_SAMPLE_ADDR)
1190 size += sizeof(data->addr);
1192 if (sample_type & PERF_SAMPLE_PERIOD)
1193 size += sizeof(data->period);
1195 if (sample_type & PERF_SAMPLE_WEIGHT)
1196 size += sizeof(data->weight);
1198 if (sample_type & PERF_SAMPLE_READ)
1199 size += event->read_size;
1201 if (sample_type & PERF_SAMPLE_DATA_SRC)
1202 size += sizeof(data->data_src.val);
1204 if (sample_type & PERF_SAMPLE_TRANSACTION)
1205 size += sizeof(data->txn);
1207 event->header_size = size;
1210 static void perf_event__id_header_size(struct perf_event *event)
1212 struct perf_sample_data *data;
1213 u64 sample_type = event->attr.sample_type;
1216 if (sample_type & PERF_SAMPLE_TID)
1217 size += sizeof(data->tid_entry);
1219 if (sample_type & PERF_SAMPLE_TIME)
1220 size += sizeof(data->time);
1222 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1223 size += sizeof(data->id);
1225 if (sample_type & PERF_SAMPLE_ID)
1226 size += sizeof(data->id);
1228 if (sample_type & PERF_SAMPLE_STREAM_ID)
1229 size += sizeof(data->stream_id);
1231 if (sample_type & PERF_SAMPLE_CPU)
1232 size += sizeof(data->cpu_entry);
1234 event->id_header_size = size;
1237 static void perf_group_attach(struct perf_event *event)
1239 struct perf_event *group_leader = event->group_leader, *pos;
1242 * We can have double attach due to group movement in perf_event_open.
1244 if (event->attach_state & PERF_ATTACH_GROUP)
1247 event->attach_state |= PERF_ATTACH_GROUP;
1249 if (group_leader == event)
1252 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1253 !is_software_event(event))
1254 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1256 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1257 group_leader->nr_siblings++;
1259 perf_event__header_size(group_leader);
1261 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1262 perf_event__header_size(pos);
1266 * Remove a event from the lists for its context.
1267 * Must be called with ctx->mutex and ctx->lock held.
1270 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1272 struct perf_cpu_context *cpuctx;
1274 * We can have double detach due to exit/hot-unplug + close.
1276 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1279 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1281 if (is_cgroup_event(event)) {
1283 cpuctx = __get_cpu_context(ctx);
1285 * if there are no more cgroup events
1286 * then cler cgrp to avoid stale pointer
1287 * in update_cgrp_time_from_cpuctx()
1289 if (!ctx->nr_cgroups)
1290 cpuctx->cgrp = NULL;
1293 if (has_branch_stack(event))
1294 ctx->nr_branch_stack--;
1297 if (event->attr.inherit_stat)
1300 list_del_rcu(&event->event_entry);
1302 if (event->group_leader == event)
1303 list_del_init(&event->group_entry);
1305 update_group_times(event);
1308 * If event was in error state, then keep it
1309 * that way, otherwise bogus counts will be
1310 * returned on read(). The only way to get out
1311 * of error state is by explicit re-enabling
1314 if (event->state > PERF_EVENT_STATE_OFF)
1315 event->state = PERF_EVENT_STATE_OFF;
1318 static void perf_group_detach(struct perf_event *event)
1320 struct perf_event *sibling, *tmp;
1321 struct list_head *list = NULL;
1324 * We can have double detach due to exit/hot-unplug + close.
1326 if (!(event->attach_state & PERF_ATTACH_GROUP))
1329 event->attach_state &= ~PERF_ATTACH_GROUP;
1332 * If this is a sibling, remove it from its group.
1334 if (event->group_leader != event) {
1335 list_del_init(&event->group_entry);
1336 event->group_leader->nr_siblings--;
1340 if (!list_empty(&event->group_entry))
1341 list = &event->group_entry;
1344 * If this was a group event with sibling events then
1345 * upgrade the siblings to singleton events by adding them
1346 * to whatever list we are on.
1348 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1350 list_move_tail(&sibling->group_entry, list);
1351 sibling->group_leader = sibling;
1353 /* Inherit group flags from the previous leader */
1354 sibling->group_flags = event->group_flags;
1358 perf_event__header_size(event->group_leader);
1360 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1361 perf_event__header_size(tmp);
1365 event_filter_match(struct perf_event *event)
1367 return (event->cpu == -1 || event->cpu == smp_processor_id())
1368 && perf_cgroup_match(event);
1372 event_sched_out(struct perf_event *event,
1373 struct perf_cpu_context *cpuctx,
1374 struct perf_event_context *ctx)
1376 u64 tstamp = perf_event_time(event);
1379 * An event which could not be activated because of
1380 * filter mismatch still needs to have its timings
1381 * maintained, otherwise bogus information is return
1382 * via read() for time_enabled, time_running:
1384 if (event->state == PERF_EVENT_STATE_INACTIVE
1385 && !event_filter_match(event)) {
1386 delta = tstamp - event->tstamp_stopped;
1387 event->tstamp_running += delta;
1388 event->tstamp_stopped = tstamp;
1391 if (event->state != PERF_EVENT_STATE_ACTIVE)
1394 event->state = PERF_EVENT_STATE_INACTIVE;
1395 if (event->pending_disable) {
1396 event->pending_disable = 0;
1397 event->state = PERF_EVENT_STATE_OFF;
1399 event->tstamp_stopped = tstamp;
1400 event->pmu->del(event, 0);
1403 if (!is_software_event(event))
1404 cpuctx->active_oncpu--;
1406 if (event->attr.freq && event->attr.sample_freq)
1408 if (event->attr.exclusive || !cpuctx->active_oncpu)
1409 cpuctx->exclusive = 0;
1413 group_sched_out(struct perf_event *group_event,
1414 struct perf_cpu_context *cpuctx,
1415 struct perf_event_context *ctx)
1417 struct perf_event *event;
1418 int state = group_event->state;
1420 event_sched_out(group_event, cpuctx, ctx);
1423 * Schedule out siblings (if any):
1425 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1426 event_sched_out(event, cpuctx, ctx);
1428 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1429 cpuctx->exclusive = 0;
1433 * Cross CPU call to remove a performance event
1435 * We disable the event on the hardware level first. After that we
1436 * remove it from the context list.
1438 static int __perf_remove_from_context(void *info)
1440 struct perf_event *event = info;
1441 struct perf_event_context *ctx = event->ctx;
1442 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1444 raw_spin_lock(&ctx->lock);
1445 event_sched_out(event, cpuctx, ctx);
1446 list_del_event(event, ctx);
1447 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1449 cpuctx->task_ctx = NULL;
1451 raw_spin_unlock(&ctx->lock);
1458 * Remove the event from a task's (or a CPU's) list of events.
1460 * CPU events are removed with a smp call. For task events we only
1461 * call when the task is on a CPU.
1463 * If event->ctx is a cloned context, callers must make sure that
1464 * every task struct that event->ctx->task could possibly point to
1465 * remains valid. This is OK when called from perf_release since
1466 * that only calls us on the top-level context, which can't be a clone.
1467 * When called from perf_event_exit_task, it's OK because the
1468 * context has been detached from its task.
1470 static void perf_remove_from_context(struct perf_event *event)
1472 struct perf_event_context *ctx = event->ctx;
1473 struct task_struct *task = ctx->task;
1475 lockdep_assert_held(&ctx->mutex);
1479 * Per cpu events are removed via an smp call and
1480 * the removal is always successful.
1482 cpu_function_call(event->cpu, __perf_remove_from_context, event);
1487 if (!task_function_call(task, __perf_remove_from_context, event))
1490 raw_spin_lock_irq(&ctx->lock);
1492 * If we failed to find a running task, but find the context active now
1493 * that we've acquired the ctx->lock, retry.
1495 if (ctx->is_active) {
1496 raw_spin_unlock_irq(&ctx->lock);
1501 * Since the task isn't running, its safe to remove the event, us
1502 * holding the ctx->lock ensures the task won't get scheduled in.
1504 list_del_event(event, ctx);
1505 raw_spin_unlock_irq(&ctx->lock);
1509 * Cross CPU call to disable a performance event
1511 int __perf_event_disable(void *info)
1513 struct perf_event *event = info;
1514 struct perf_event_context *ctx = event->ctx;
1515 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1518 * If this is a per-task event, need to check whether this
1519 * event's task is the current task on this cpu.
1521 * Can trigger due to concurrent perf_event_context_sched_out()
1522 * flipping contexts around.
1524 if (ctx->task && cpuctx->task_ctx != ctx)
1527 raw_spin_lock(&ctx->lock);
1530 * If the event is on, turn it off.
1531 * If it is in error state, leave it in error state.
1533 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1534 update_context_time(ctx);
1535 update_cgrp_time_from_event(event);
1536 update_group_times(event);
1537 if (event == event->group_leader)
1538 group_sched_out(event, cpuctx, ctx);
1540 event_sched_out(event, cpuctx, ctx);
1541 event->state = PERF_EVENT_STATE_OFF;
1544 raw_spin_unlock(&ctx->lock);
1552 * If event->ctx is a cloned context, callers must make sure that
1553 * every task struct that event->ctx->task could possibly point to
1554 * remains valid. This condition is satisifed when called through
1555 * perf_event_for_each_child or perf_event_for_each because they
1556 * hold the top-level event's child_mutex, so any descendant that
1557 * goes to exit will block in sync_child_event.
1558 * When called from perf_pending_event it's OK because event->ctx
1559 * is the current context on this CPU and preemption is disabled,
1560 * hence we can't get into perf_event_task_sched_out for this context.
1562 void perf_event_disable(struct perf_event *event)
1564 struct perf_event_context *ctx = event->ctx;
1565 struct task_struct *task = ctx->task;
1569 * Disable the event on the cpu that it's on
1571 cpu_function_call(event->cpu, __perf_event_disable, event);
1576 if (!task_function_call(task, __perf_event_disable, event))
1579 raw_spin_lock_irq(&ctx->lock);
1581 * If the event is still active, we need to retry the cross-call.
1583 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1584 raw_spin_unlock_irq(&ctx->lock);
1586 * Reload the task pointer, it might have been changed by
1587 * a concurrent perf_event_context_sched_out().
1594 * Since we have the lock this context can't be scheduled
1595 * in, so we can change the state safely.
1597 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1598 update_group_times(event);
1599 event->state = PERF_EVENT_STATE_OFF;
1601 raw_spin_unlock_irq(&ctx->lock);
1603 EXPORT_SYMBOL_GPL(perf_event_disable);
1605 static void perf_set_shadow_time(struct perf_event *event,
1606 struct perf_event_context *ctx,
1610 * use the correct time source for the time snapshot
1612 * We could get by without this by leveraging the
1613 * fact that to get to this function, the caller
1614 * has most likely already called update_context_time()
1615 * and update_cgrp_time_xx() and thus both timestamp
1616 * are identical (or very close). Given that tstamp is,
1617 * already adjusted for cgroup, we could say that:
1618 * tstamp - ctx->timestamp
1620 * tstamp - cgrp->timestamp.
1622 * Then, in perf_output_read(), the calculation would
1623 * work with no changes because:
1624 * - event is guaranteed scheduled in
1625 * - no scheduled out in between
1626 * - thus the timestamp would be the same
1628 * But this is a bit hairy.
1630 * So instead, we have an explicit cgroup call to remain
1631 * within the time time source all along. We believe it
1632 * is cleaner and simpler to understand.
1634 if (is_cgroup_event(event))
1635 perf_cgroup_set_shadow_time(event, tstamp);
1637 event->shadow_ctx_time = tstamp - ctx->timestamp;
1640 #define MAX_INTERRUPTS (~0ULL)
1642 static void perf_log_throttle(struct perf_event *event, int enable);
1645 event_sched_in(struct perf_event *event,
1646 struct perf_cpu_context *cpuctx,
1647 struct perf_event_context *ctx)
1649 u64 tstamp = perf_event_time(event);
1651 if (event->state <= PERF_EVENT_STATE_OFF)
1654 event->state = PERF_EVENT_STATE_ACTIVE;
1655 event->oncpu = smp_processor_id();
1658 * Unthrottle events, since we scheduled we might have missed several
1659 * ticks already, also for a heavily scheduling task there is little
1660 * guarantee it'll get a tick in a timely manner.
1662 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1663 perf_log_throttle(event, 1);
1664 event->hw.interrupts = 0;
1668 * The new state must be visible before we turn it on in the hardware:
1672 if (event->pmu->add(event, PERF_EF_START)) {
1673 event->state = PERF_EVENT_STATE_INACTIVE;
1678 event->tstamp_running += tstamp - event->tstamp_stopped;
1680 perf_set_shadow_time(event, ctx, tstamp);
1682 if (!is_software_event(event))
1683 cpuctx->active_oncpu++;
1685 if (event->attr.freq && event->attr.sample_freq)
1688 if (event->attr.exclusive)
1689 cpuctx->exclusive = 1;
1695 group_sched_in(struct perf_event *group_event,
1696 struct perf_cpu_context *cpuctx,
1697 struct perf_event_context *ctx)
1699 struct perf_event *event, *partial_group = NULL;
1700 struct pmu *pmu = group_event->pmu;
1701 u64 now = ctx->time;
1702 bool simulate = false;
1704 if (group_event->state == PERF_EVENT_STATE_OFF)
1707 pmu->start_txn(pmu);
1709 if (event_sched_in(group_event, cpuctx, ctx)) {
1710 pmu->cancel_txn(pmu);
1711 perf_cpu_hrtimer_restart(cpuctx);
1716 * Schedule in siblings as one group (if any):
1718 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1719 if (event_sched_in(event, cpuctx, ctx)) {
1720 partial_group = event;
1725 if (!pmu->commit_txn(pmu))
1730 * Groups can be scheduled in as one unit only, so undo any
1731 * partial group before returning:
1732 * The events up to the failed event are scheduled out normally,
1733 * tstamp_stopped will be updated.
1735 * The failed events and the remaining siblings need to have
1736 * their timings updated as if they had gone thru event_sched_in()
1737 * and event_sched_out(). This is required to get consistent timings
1738 * across the group. This also takes care of the case where the group
1739 * could never be scheduled by ensuring tstamp_stopped is set to mark
1740 * the time the event was actually stopped, such that time delta
1741 * calculation in update_event_times() is correct.
1743 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1744 if (event == partial_group)
1748 event->tstamp_running += now - event->tstamp_stopped;
1749 event->tstamp_stopped = now;
1751 event_sched_out(event, cpuctx, ctx);
1754 event_sched_out(group_event, cpuctx, ctx);
1756 pmu->cancel_txn(pmu);
1758 perf_cpu_hrtimer_restart(cpuctx);
1764 * Work out whether we can put this event group on the CPU now.
1766 static int group_can_go_on(struct perf_event *event,
1767 struct perf_cpu_context *cpuctx,
1771 * Groups consisting entirely of software events can always go on.
1773 if (event->group_flags & PERF_GROUP_SOFTWARE)
1776 * If an exclusive group is already on, no other hardware
1779 if (cpuctx->exclusive)
1782 * If this group is exclusive and there are already
1783 * events on the CPU, it can't go on.
1785 if (event->attr.exclusive && cpuctx->active_oncpu)
1788 * Otherwise, try to add it if all previous groups were able
1794 static void add_event_to_ctx(struct perf_event *event,
1795 struct perf_event_context *ctx)
1797 u64 tstamp = perf_event_time(event);
1799 list_add_event(event, ctx);
1800 perf_group_attach(event);
1801 event->tstamp_enabled = tstamp;
1802 event->tstamp_running = tstamp;
1803 event->tstamp_stopped = tstamp;
1806 static void task_ctx_sched_out(struct perf_event_context *ctx);
1808 ctx_sched_in(struct perf_event_context *ctx,
1809 struct perf_cpu_context *cpuctx,
1810 enum event_type_t event_type,
1811 struct task_struct *task);
1813 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
1814 struct perf_event_context *ctx,
1815 struct task_struct *task)
1817 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
1819 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
1820 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
1822 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
1826 * Cross CPU call to install and enable a performance event
1828 * Must be called with ctx->mutex held
1830 static int __perf_install_in_context(void *info)
1832 struct perf_event *event = info;
1833 struct perf_event_context *ctx = event->ctx;
1834 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1835 struct perf_event_context *task_ctx = cpuctx->task_ctx;
1836 struct task_struct *task = current;
1838 perf_ctx_lock(cpuctx, task_ctx);
1839 perf_pmu_disable(cpuctx->ctx.pmu);
1842 * If there was an active task_ctx schedule it out.
1845 task_ctx_sched_out(task_ctx);
1848 * If the context we're installing events in is not the
1849 * active task_ctx, flip them.
1851 if (ctx->task && task_ctx != ctx) {
1853 raw_spin_unlock(&task_ctx->lock);
1854 raw_spin_lock(&ctx->lock);
1859 cpuctx->task_ctx = task_ctx;
1860 task = task_ctx->task;
1863 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
1865 update_context_time(ctx);
1867 * update cgrp time only if current cgrp
1868 * matches event->cgrp. Must be done before
1869 * calling add_event_to_ctx()
1871 update_cgrp_time_from_event(event);
1873 add_event_to_ctx(event, ctx);
1876 * Schedule everything back in
1878 perf_event_sched_in(cpuctx, task_ctx, task);
1880 perf_pmu_enable(cpuctx->ctx.pmu);
1881 perf_ctx_unlock(cpuctx, task_ctx);
1887 * Attach a performance event to a context
1889 * First we add the event to the list with the hardware enable bit
1890 * in event->hw_config cleared.
1892 * If the event is attached to a task which is on a CPU we use a smp
1893 * call to enable it in the task context. The task might have been
1894 * scheduled away, but we check this in the smp call again.
1897 perf_install_in_context(struct perf_event_context *ctx,
1898 struct perf_event *event,
1901 struct task_struct *task = ctx->task;
1903 lockdep_assert_held(&ctx->mutex);
1906 if (event->cpu != -1)
1911 * Per cpu events are installed via an smp call and
1912 * the install is always successful.
1914 cpu_function_call(cpu, __perf_install_in_context, event);
1919 if (!task_function_call(task, __perf_install_in_context, event))
1922 raw_spin_lock_irq(&ctx->lock);
1924 * If we failed to find a running task, but find the context active now
1925 * that we've acquired the ctx->lock, retry.
1927 if (ctx->is_active) {
1928 raw_spin_unlock_irq(&ctx->lock);
1933 * Since the task isn't running, its safe to add the event, us holding
1934 * the ctx->lock ensures the task won't get scheduled in.
1936 add_event_to_ctx(event, ctx);
1937 raw_spin_unlock_irq(&ctx->lock);
1941 * Put a event into inactive state and update time fields.
1942 * Enabling the leader of a group effectively enables all
1943 * the group members that aren't explicitly disabled, so we
1944 * have to update their ->tstamp_enabled also.
1945 * Note: this works for group members as well as group leaders
1946 * since the non-leader members' sibling_lists will be empty.
1948 static void __perf_event_mark_enabled(struct perf_event *event)
1950 struct perf_event *sub;
1951 u64 tstamp = perf_event_time(event);
1953 event->state = PERF_EVENT_STATE_INACTIVE;
1954 event->tstamp_enabled = tstamp - event->total_time_enabled;
1955 list_for_each_entry(sub, &event->sibling_list, group_entry) {
1956 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
1957 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
1962 * Cross CPU call to enable a performance event
1964 static int __perf_event_enable(void *info)
1966 struct perf_event *event = info;
1967 struct perf_event_context *ctx = event->ctx;
1968 struct perf_event *leader = event->group_leader;
1969 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1973 * There's a time window between 'ctx->is_active' check
1974 * in perf_event_enable function and this place having:
1976 * - ctx->lock unlocked
1978 * where the task could be killed and 'ctx' deactivated
1979 * by perf_event_exit_task.
1981 if (!ctx->is_active)
1984 raw_spin_lock(&ctx->lock);
1985 update_context_time(ctx);
1987 if (event->state >= PERF_EVENT_STATE_INACTIVE)
1991 * set current task's cgroup time reference point
1993 perf_cgroup_set_timestamp(current, ctx);
1995 __perf_event_mark_enabled(event);
1997 if (!event_filter_match(event)) {
1998 if (is_cgroup_event(event))
1999 perf_cgroup_defer_enabled(event);
2004 * If the event is in a group and isn't the group leader,
2005 * then don't put it on unless the group is on.
2007 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
2010 if (!group_can_go_on(event, cpuctx, 1)) {
2013 if (event == leader)
2014 err = group_sched_in(event, cpuctx, ctx);
2016 err = event_sched_in(event, cpuctx, ctx);
2021 * If this event can't go on and it's part of a
2022 * group, then the whole group has to come off.
2024 if (leader != event) {
2025 group_sched_out(leader, cpuctx, ctx);
2026 perf_cpu_hrtimer_restart(cpuctx);
2028 if (leader->attr.pinned) {
2029 update_group_times(leader);
2030 leader->state = PERF_EVENT_STATE_ERROR;
2035 raw_spin_unlock(&ctx->lock);
2043 * If event->ctx is a cloned context, callers must make sure that
2044 * every task struct that event->ctx->task could possibly point to
2045 * remains valid. This condition is satisfied when called through
2046 * perf_event_for_each_child or perf_event_for_each as described
2047 * for perf_event_disable.
2049 void perf_event_enable(struct perf_event *event)
2051 struct perf_event_context *ctx = event->ctx;
2052 struct task_struct *task = ctx->task;
2056 * Enable the event on the cpu that it's on
2058 cpu_function_call(event->cpu, __perf_event_enable, event);
2062 raw_spin_lock_irq(&ctx->lock);
2063 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2067 * If the event is in error state, clear that first.
2068 * That way, if we see the event in error state below, we
2069 * know that it has gone back into error state, as distinct
2070 * from the task having been scheduled away before the
2071 * cross-call arrived.
2073 if (event->state == PERF_EVENT_STATE_ERROR)
2074 event->state = PERF_EVENT_STATE_OFF;
2077 if (!ctx->is_active) {
2078 __perf_event_mark_enabled(event);
2082 raw_spin_unlock_irq(&ctx->lock);
2084 if (!task_function_call(task, __perf_event_enable, event))
2087 raw_spin_lock_irq(&ctx->lock);
2090 * If the context is active and the event is still off,
2091 * we need to retry the cross-call.
2093 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
2095 * task could have been flipped by a concurrent
2096 * perf_event_context_sched_out()
2103 raw_spin_unlock_irq(&ctx->lock);
2105 EXPORT_SYMBOL_GPL(perf_event_enable);
2107 int perf_event_refresh(struct perf_event *event, int refresh)
2110 * not supported on inherited events
2112 if (event->attr.inherit || !is_sampling_event(event))
2115 atomic_add(refresh, &event->event_limit);
2116 perf_event_enable(event);
2120 EXPORT_SYMBOL_GPL(perf_event_refresh);
2122 static void ctx_sched_out(struct perf_event_context *ctx,
2123 struct perf_cpu_context *cpuctx,
2124 enum event_type_t event_type)
2126 struct perf_event *event;
2127 int is_active = ctx->is_active;
2129 ctx->is_active &= ~event_type;
2130 if (likely(!ctx->nr_events))
2133 update_context_time(ctx);
2134 update_cgrp_time_from_cpuctx(cpuctx);
2135 if (!ctx->nr_active)
2138 perf_pmu_disable(ctx->pmu);
2139 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2140 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2141 group_sched_out(event, cpuctx, ctx);
2144 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2145 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2146 group_sched_out(event, cpuctx, ctx);
2148 perf_pmu_enable(ctx->pmu);
2152 * Test whether two contexts are equivalent, i.e. whether they
2153 * have both been cloned from the same version of the same context
2154 * and they both have the same number of enabled events.
2155 * If the number of enabled events is the same, then the set
2156 * of enabled events should be the same, because these are both
2157 * inherited contexts, therefore we can't access individual events
2158 * in them directly with an fd; we can only enable/disable all
2159 * events via prctl, or enable/disable all events in a family
2160 * via ioctl, which will have the same effect on both contexts.
2162 static int context_equiv(struct perf_event_context *ctx1,
2163 struct perf_event_context *ctx2)
2165 return ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx
2166 && ctx1->parent_gen == ctx2->parent_gen
2167 && !ctx1->pin_count && !ctx2->pin_count;
2170 static void __perf_event_sync_stat(struct perf_event *event,
2171 struct perf_event *next_event)
2175 if (!event->attr.inherit_stat)
2179 * Update the event value, we cannot use perf_event_read()
2180 * because we're in the middle of a context switch and have IRQs
2181 * disabled, which upsets smp_call_function_single(), however
2182 * we know the event must be on the current CPU, therefore we
2183 * don't need to use it.
2185 switch (event->state) {
2186 case PERF_EVENT_STATE_ACTIVE:
2187 event->pmu->read(event);
2190 case PERF_EVENT_STATE_INACTIVE:
2191 update_event_times(event);
2199 * In order to keep per-task stats reliable we need to flip the event
2200 * values when we flip the contexts.
2202 value = local64_read(&next_event->count);
2203 value = local64_xchg(&event->count, value);
2204 local64_set(&next_event->count, value);
2206 swap(event->total_time_enabled, next_event->total_time_enabled);
2207 swap(event->total_time_running, next_event->total_time_running);
2210 * Since we swizzled the values, update the user visible data too.
2212 perf_event_update_userpage(event);
2213 perf_event_update_userpage(next_event);
2216 #define list_next_entry(pos, member) \
2217 list_entry(pos->member.next, typeof(*pos), member)
2219 static void perf_event_sync_stat(struct perf_event_context *ctx,
2220 struct perf_event_context *next_ctx)
2222 struct perf_event *event, *next_event;
2227 update_context_time(ctx);
2229 event = list_first_entry(&ctx->event_list,
2230 struct perf_event, event_entry);
2232 next_event = list_first_entry(&next_ctx->event_list,
2233 struct perf_event, event_entry);
2235 while (&event->event_entry != &ctx->event_list &&
2236 &next_event->event_entry != &next_ctx->event_list) {
2238 __perf_event_sync_stat(event, next_event);
2240 event = list_next_entry(event, event_entry);
2241 next_event = list_next_entry(next_event, event_entry);
2245 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2246 struct task_struct *next)
2248 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2249 struct perf_event_context *next_ctx;
2250 struct perf_event_context *parent;
2251 struct perf_cpu_context *cpuctx;
2257 cpuctx = __get_cpu_context(ctx);
2258 if (!cpuctx->task_ctx)
2262 parent = rcu_dereference(ctx->parent_ctx);
2263 next_ctx = next->perf_event_ctxp[ctxn];
2264 if (parent && next_ctx &&
2265 rcu_dereference(next_ctx->parent_ctx) == parent) {
2267 * Looks like the two contexts are clones, so we might be
2268 * able to optimize the context switch. We lock both
2269 * contexts and check that they are clones under the
2270 * lock (including re-checking that neither has been
2271 * uncloned in the meantime). It doesn't matter which
2272 * order we take the locks because no other cpu could
2273 * be trying to lock both of these tasks.
2275 raw_spin_lock(&ctx->lock);
2276 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2277 if (context_equiv(ctx, next_ctx)) {
2279 * XXX do we need a memory barrier of sorts
2280 * wrt to rcu_dereference() of perf_event_ctxp
2282 task->perf_event_ctxp[ctxn] = next_ctx;
2283 next->perf_event_ctxp[ctxn] = ctx;
2285 next_ctx->task = task;
2288 perf_event_sync_stat(ctx, next_ctx);
2290 raw_spin_unlock(&next_ctx->lock);
2291 raw_spin_unlock(&ctx->lock);
2296 raw_spin_lock(&ctx->lock);
2297 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2298 cpuctx->task_ctx = NULL;
2299 raw_spin_unlock(&ctx->lock);
2303 #define for_each_task_context_nr(ctxn) \
2304 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2307 * Called from scheduler to remove the events of the current task,
2308 * with interrupts disabled.
2310 * We stop each event and update the event value in event->count.
2312 * This does not protect us against NMI, but disable()
2313 * sets the disabled bit in the control field of event _before_
2314 * accessing the event control register. If a NMI hits, then it will
2315 * not restart the event.
2317 void __perf_event_task_sched_out(struct task_struct *task,
2318 struct task_struct *next)
2322 for_each_task_context_nr(ctxn)
2323 perf_event_context_sched_out(task, ctxn, next);
2326 * if cgroup events exist on this CPU, then we need
2327 * to check if we have to switch out PMU state.
2328 * cgroup event are system-wide mode only
2330 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2331 perf_cgroup_sched_out(task, next);
2334 static void task_ctx_sched_out(struct perf_event_context *ctx)
2336 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2338 if (!cpuctx->task_ctx)
2341 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2344 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2345 cpuctx->task_ctx = NULL;
2349 * Called with IRQs disabled
2351 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2352 enum event_type_t event_type)
2354 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2358 ctx_pinned_sched_in(struct perf_event_context *ctx,
2359 struct perf_cpu_context *cpuctx)
2361 struct perf_event *event;
2363 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2364 if (event->state <= PERF_EVENT_STATE_OFF)
2366 if (!event_filter_match(event))
2369 /* may need to reset tstamp_enabled */
2370 if (is_cgroup_event(event))
2371 perf_cgroup_mark_enabled(event, ctx);
2373 if (group_can_go_on(event, cpuctx, 1))
2374 group_sched_in(event, cpuctx, ctx);
2377 * If this pinned group hasn't been scheduled,
2378 * put it in error state.
2380 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2381 update_group_times(event);
2382 event->state = PERF_EVENT_STATE_ERROR;
2388 ctx_flexible_sched_in(struct perf_event_context *ctx,
2389 struct perf_cpu_context *cpuctx)
2391 struct perf_event *event;
2394 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2395 /* Ignore events in OFF or ERROR state */
2396 if (event->state <= PERF_EVENT_STATE_OFF)
2399 * Listen to the 'cpu' scheduling filter constraint
2402 if (!event_filter_match(event))
2405 /* may need to reset tstamp_enabled */
2406 if (is_cgroup_event(event))
2407 perf_cgroup_mark_enabled(event, ctx);
2409 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2410 if (group_sched_in(event, cpuctx, ctx))
2417 ctx_sched_in(struct perf_event_context *ctx,
2418 struct perf_cpu_context *cpuctx,
2419 enum event_type_t event_type,
2420 struct task_struct *task)
2423 int is_active = ctx->is_active;
2425 ctx->is_active |= event_type;
2426 if (likely(!ctx->nr_events))
2430 ctx->timestamp = now;
2431 perf_cgroup_set_timestamp(task, ctx);
2433 * First go through the list and put on any pinned groups
2434 * in order to give them the best chance of going on.
2436 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2437 ctx_pinned_sched_in(ctx, cpuctx);
2439 /* Then walk through the lower prio flexible groups */
2440 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2441 ctx_flexible_sched_in(ctx, cpuctx);
2444 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2445 enum event_type_t event_type,
2446 struct task_struct *task)
2448 struct perf_event_context *ctx = &cpuctx->ctx;
2450 ctx_sched_in(ctx, cpuctx, event_type, task);
2453 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2454 struct task_struct *task)
2456 struct perf_cpu_context *cpuctx;
2458 cpuctx = __get_cpu_context(ctx);
2459 if (cpuctx->task_ctx == ctx)
2462 perf_ctx_lock(cpuctx, ctx);
2463 perf_pmu_disable(ctx->pmu);
2465 * We want to keep the following priority order:
2466 * cpu pinned (that don't need to move), task pinned,
2467 * cpu flexible, task flexible.
2469 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2472 cpuctx->task_ctx = ctx;
2474 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2476 perf_pmu_enable(ctx->pmu);
2477 perf_ctx_unlock(cpuctx, ctx);
2480 * Since these rotations are per-cpu, we need to ensure the
2481 * cpu-context we got scheduled on is actually rotating.
2483 perf_pmu_rotate_start(ctx->pmu);
2487 * When sampling the branck stack in system-wide, it may be necessary
2488 * to flush the stack on context switch. This happens when the branch
2489 * stack does not tag its entries with the pid of the current task.
2490 * Otherwise it becomes impossible to associate a branch entry with a
2491 * task. This ambiguity is more likely to appear when the branch stack
2492 * supports priv level filtering and the user sets it to monitor only
2493 * at the user level (which could be a useful measurement in system-wide
2494 * mode). In that case, the risk is high of having a branch stack with
2495 * branch from multiple tasks. Flushing may mean dropping the existing
2496 * entries or stashing them somewhere in the PMU specific code layer.
2498 * This function provides the context switch callback to the lower code
2499 * layer. It is invoked ONLY when there is at least one system-wide context
2500 * with at least one active event using taken branch sampling.
2502 static void perf_branch_stack_sched_in(struct task_struct *prev,
2503 struct task_struct *task)
2505 struct perf_cpu_context *cpuctx;
2507 unsigned long flags;
2509 /* no need to flush branch stack if not changing task */
2513 local_irq_save(flags);
2517 list_for_each_entry_rcu(pmu, &pmus, entry) {
2518 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2521 * check if the context has at least one
2522 * event using PERF_SAMPLE_BRANCH_STACK
2524 if (cpuctx->ctx.nr_branch_stack > 0
2525 && pmu->flush_branch_stack) {
2527 pmu = cpuctx->ctx.pmu;
2529 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2531 perf_pmu_disable(pmu);
2533 pmu->flush_branch_stack();
2535 perf_pmu_enable(pmu);
2537 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2543 local_irq_restore(flags);
2547 * Called from scheduler to add the events of the current task
2548 * with interrupts disabled.
2550 * We restore the event value and then enable it.
2552 * This does not protect us against NMI, but enable()
2553 * sets the enabled bit in the control field of event _before_
2554 * accessing the event control register. If a NMI hits, then it will
2555 * keep the event running.
2557 void __perf_event_task_sched_in(struct task_struct *prev,
2558 struct task_struct *task)
2560 struct perf_event_context *ctx;
2563 for_each_task_context_nr(ctxn) {
2564 ctx = task->perf_event_ctxp[ctxn];
2568 perf_event_context_sched_in(ctx, task);
2571 * if cgroup events exist on this CPU, then we need
2572 * to check if we have to switch in PMU state.
2573 * cgroup event are system-wide mode only
2575 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2576 perf_cgroup_sched_in(prev, task);
2578 /* check for system-wide branch_stack events */
2579 if (atomic_read(&__get_cpu_var(perf_branch_stack_events)))
2580 perf_branch_stack_sched_in(prev, task);
2583 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2585 u64 frequency = event->attr.sample_freq;
2586 u64 sec = NSEC_PER_SEC;
2587 u64 divisor, dividend;
2589 int count_fls, nsec_fls, frequency_fls, sec_fls;
2591 count_fls = fls64(count);
2592 nsec_fls = fls64(nsec);
2593 frequency_fls = fls64(frequency);
2597 * We got @count in @nsec, with a target of sample_freq HZ
2598 * the target period becomes:
2601 * period = -------------------
2602 * @nsec * sample_freq
2607 * Reduce accuracy by one bit such that @a and @b converge
2608 * to a similar magnitude.
2610 #define REDUCE_FLS(a, b) \
2612 if (a##_fls > b##_fls) { \
2622 * Reduce accuracy until either term fits in a u64, then proceed with
2623 * the other, so that finally we can do a u64/u64 division.
2625 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2626 REDUCE_FLS(nsec, frequency);
2627 REDUCE_FLS(sec, count);
2630 if (count_fls + sec_fls > 64) {
2631 divisor = nsec * frequency;
2633 while (count_fls + sec_fls > 64) {
2634 REDUCE_FLS(count, sec);
2638 dividend = count * sec;
2640 dividend = count * sec;
2642 while (nsec_fls + frequency_fls > 64) {
2643 REDUCE_FLS(nsec, frequency);
2647 divisor = nsec * frequency;
2653 return div64_u64(dividend, divisor);
2656 static DEFINE_PER_CPU(int, perf_throttled_count);
2657 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2659 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2661 struct hw_perf_event *hwc = &event->hw;
2662 s64 period, sample_period;
2665 period = perf_calculate_period(event, nsec, count);
2667 delta = (s64)(period - hwc->sample_period);
2668 delta = (delta + 7) / 8; /* low pass filter */
2670 sample_period = hwc->sample_period + delta;
2675 hwc->sample_period = sample_period;
2677 if (local64_read(&hwc->period_left) > 8*sample_period) {
2679 event->pmu->stop(event, PERF_EF_UPDATE);
2681 local64_set(&hwc->period_left, 0);
2684 event->pmu->start(event, PERF_EF_RELOAD);
2689 * combine freq adjustment with unthrottling to avoid two passes over the
2690 * events. At the same time, make sure, having freq events does not change
2691 * the rate of unthrottling as that would introduce bias.
2693 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
2696 struct perf_event *event;
2697 struct hw_perf_event *hwc;
2698 u64 now, period = TICK_NSEC;
2702 * only need to iterate over all events iff:
2703 * - context have events in frequency mode (needs freq adjust)
2704 * - there are events to unthrottle on this cpu
2706 if (!(ctx->nr_freq || needs_unthr))
2709 raw_spin_lock(&ctx->lock);
2710 perf_pmu_disable(ctx->pmu);
2712 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
2713 if (event->state != PERF_EVENT_STATE_ACTIVE)
2716 if (!event_filter_match(event))
2721 if (hwc->interrupts == MAX_INTERRUPTS) {
2722 hwc->interrupts = 0;
2723 perf_log_throttle(event, 1);
2724 event->pmu->start(event, 0);
2727 if (!event->attr.freq || !event->attr.sample_freq)
2731 * stop the event and update event->count
2733 event->pmu->stop(event, PERF_EF_UPDATE);
2735 now = local64_read(&event->count);
2736 delta = now - hwc->freq_count_stamp;
2737 hwc->freq_count_stamp = now;
2741 * reload only if value has changed
2742 * we have stopped the event so tell that
2743 * to perf_adjust_period() to avoid stopping it
2747 perf_adjust_period(event, period, delta, false);
2749 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
2752 perf_pmu_enable(ctx->pmu);
2753 raw_spin_unlock(&ctx->lock);
2757 * Round-robin a context's events:
2759 static void rotate_ctx(struct perf_event_context *ctx)
2762 * Rotate the first entry last of non-pinned groups. Rotation might be
2763 * disabled by the inheritance code.
2765 if (!ctx->rotate_disable)
2766 list_rotate_left(&ctx->flexible_groups);
2770 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
2771 * because they're strictly cpu affine and rotate_start is called with IRQs
2772 * disabled, while rotate_context is called from IRQ context.
2774 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
2776 struct perf_event_context *ctx = NULL;
2777 int rotate = 0, remove = 1;
2779 if (cpuctx->ctx.nr_events) {
2781 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
2785 ctx = cpuctx->task_ctx;
2786 if (ctx && ctx->nr_events) {
2788 if (ctx->nr_events != ctx->nr_active)
2795 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2796 perf_pmu_disable(cpuctx->ctx.pmu);
2798 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2800 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
2802 rotate_ctx(&cpuctx->ctx);
2806 perf_event_sched_in(cpuctx, ctx, current);
2808 perf_pmu_enable(cpuctx->ctx.pmu);
2809 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2812 list_del_init(&cpuctx->rotation_list);
2817 #ifdef CONFIG_NO_HZ_FULL
2818 bool perf_event_can_stop_tick(void)
2820 if (atomic_read(&nr_freq_events) ||
2821 __this_cpu_read(perf_throttled_count))
2828 void perf_event_task_tick(void)
2830 struct list_head *head = &__get_cpu_var(rotation_list);
2831 struct perf_cpu_context *cpuctx, *tmp;
2832 struct perf_event_context *ctx;
2835 WARN_ON(!irqs_disabled());
2837 __this_cpu_inc(perf_throttled_seq);
2838 throttled = __this_cpu_xchg(perf_throttled_count, 0);
2840 list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) {
2842 perf_adjust_freq_unthr_context(ctx, throttled);
2844 ctx = cpuctx->task_ctx;
2846 perf_adjust_freq_unthr_context(ctx, throttled);
2850 static int event_enable_on_exec(struct perf_event *event,
2851 struct perf_event_context *ctx)
2853 if (!event->attr.enable_on_exec)
2856 event->attr.enable_on_exec = 0;
2857 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2860 __perf_event_mark_enabled(event);
2866 * Enable all of a task's events that have been marked enable-on-exec.
2867 * This expects task == current.
2869 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
2871 struct perf_event *event;
2872 unsigned long flags;
2876 local_irq_save(flags);
2877 if (!ctx || !ctx->nr_events)
2881 * We must ctxsw out cgroup events to avoid conflict
2882 * when invoking perf_task_event_sched_in() later on
2883 * in this function. Otherwise we end up trying to
2884 * ctxswin cgroup events which are already scheduled
2887 perf_cgroup_sched_out(current, NULL);
2889 raw_spin_lock(&ctx->lock);
2890 task_ctx_sched_out(ctx);
2892 list_for_each_entry(event, &ctx->event_list, event_entry) {
2893 ret = event_enable_on_exec(event, ctx);
2899 * Unclone this context if we enabled any event.
2904 raw_spin_unlock(&ctx->lock);
2907 * Also calls ctxswin for cgroup events, if any:
2909 perf_event_context_sched_in(ctx, ctx->task);
2911 local_irq_restore(flags);
2915 * Cross CPU call to read the hardware event
2917 static void __perf_event_read(void *info)
2919 struct perf_event *event = info;
2920 struct perf_event_context *ctx = event->ctx;
2921 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2924 * If this is a task context, we need to check whether it is
2925 * the current task context of this cpu. If not it has been
2926 * scheduled out before the smp call arrived. In that case
2927 * event->count would have been updated to a recent sample
2928 * when the event was scheduled out.
2930 if (ctx->task && cpuctx->task_ctx != ctx)
2933 raw_spin_lock(&ctx->lock);
2934 if (ctx->is_active) {
2935 update_context_time(ctx);
2936 update_cgrp_time_from_event(event);
2938 update_event_times(event);
2939 if (event->state == PERF_EVENT_STATE_ACTIVE)
2940 event->pmu->read(event);
2941 raw_spin_unlock(&ctx->lock);
2944 static inline u64 perf_event_count(struct perf_event *event)
2946 return local64_read(&event->count) + atomic64_read(&event->child_count);
2949 static u64 perf_event_read(struct perf_event *event)
2952 * If event is enabled and currently active on a CPU, update the
2953 * value in the event structure:
2955 if (event->state == PERF_EVENT_STATE_ACTIVE) {
2956 smp_call_function_single(event->oncpu,
2957 __perf_event_read, event, 1);
2958 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
2959 struct perf_event_context *ctx = event->ctx;
2960 unsigned long flags;
2962 raw_spin_lock_irqsave(&ctx->lock, flags);
2964 * may read while context is not active
2965 * (e.g., thread is blocked), in that case
2966 * we cannot update context time
2968 if (ctx->is_active) {
2969 update_context_time(ctx);
2970 update_cgrp_time_from_event(event);
2972 update_event_times(event);
2973 raw_spin_unlock_irqrestore(&ctx->lock, flags);
2976 return perf_event_count(event);
2980 * Initialize the perf_event context in a task_struct:
2982 static void __perf_event_init_context(struct perf_event_context *ctx)
2984 raw_spin_lock_init(&ctx->lock);
2985 mutex_init(&ctx->mutex);
2986 INIT_LIST_HEAD(&ctx->pinned_groups);
2987 INIT_LIST_HEAD(&ctx->flexible_groups);
2988 INIT_LIST_HEAD(&ctx->event_list);
2989 atomic_set(&ctx->refcount, 1);
2992 static struct perf_event_context *
2993 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
2995 struct perf_event_context *ctx;
2997 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3001 __perf_event_init_context(ctx);
3004 get_task_struct(task);
3011 static struct task_struct *
3012 find_lively_task_by_vpid(pid_t vpid)
3014 struct task_struct *task;
3021 task = find_task_by_vpid(vpid);
3023 get_task_struct(task);
3027 return ERR_PTR(-ESRCH);
3029 /* Reuse ptrace permission checks for now. */
3031 if (!ptrace_may_access(task, PTRACE_MODE_READ))
3036 put_task_struct(task);
3037 return ERR_PTR(err);
3042 * Returns a matching context with refcount and pincount.
3044 static struct perf_event_context *
3045 find_get_context(struct pmu *pmu, struct task_struct *task, int cpu)
3047 struct perf_event_context *ctx;
3048 struct perf_cpu_context *cpuctx;
3049 unsigned long flags;
3053 /* Must be root to operate on a CPU event: */
3054 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3055 return ERR_PTR(-EACCES);
3058 * We could be clever and allow to attach a event to an
3059 * offline CPU and activate it when the CPU comes up, but
3062 if (!cpu_online(cpu))
3063 return ERR_PTR(-ENODEV);
3065 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3074 ctxn = pmu->task_ctx_nr;
3079 ctx = perf_lock_task_context(task, ctxn, &flags);
3083 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3085 ctx = alloc_perf_context(pmu, task);
3091 mutex_lock(&task->perf_event_mutex);
3093 * If it has already passed perf_event_exit_task().
3094 * we must see PF_EXITING, it takes this mutex too.
3096 if (task->flags & PF_EXITING)
3098 else if (task->perf_event_ctxp[ctxn])
3103 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3105 mutex_unlock(&task->perf_event_mutex);
3107 if (unlikely(err)) {
3119 return ERR_PTR(err);
3122 static void perf_event_free_filter(struct perf_event *event);
3124 static void free_event_rcu(struct rcu_head *head)
3126 struct perf_event *event;
3128 event = container_of(head, struct perf_event, rcu_head);
3130 put_pid_ns(event->ns);
3131 perf_event_free_filter(event);
3135 static void ring_buffer_put(struct ring_buffer *rb);
3136 static void ring_buffer_detach(struct perf_event *event, struct ring_buffer *rb);
3138 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3143 if (has_branch_stack(event)) {
3144 if (!(event->attach_state & PERF_ATTACH_TASK))
3145 atomic_dec(&per_cpu(perf_branch_stack_events, cpu));
3147 if (is_cgroup_event(event))
3148 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3151 static void unaccount_event(struct perf_event *event)
3156 if (event->attach_state & PERF_ATTACH_TASK)
3157 static_key_slow_dec_deferred(&perf_sched_events);
3158 if (event->attr.mmap || event->attr.mmap_data)
3159 atomic_dec(&nr_mmap_events);
3160 if (event->attr.comm)
3161 atomic_dec(&nr_comm_events);
3162 if (event->attr.task)
3163 atomic_dec(&nr_task_events);
3164 if (event->attr.freq)
3165 atomic_dec(&nr_freq_events);
3166 if (is_cgroup_event(event))
3167 static_key_slow_dec_deferred(&perf_sched_events);
3168 if (has_branch_stack(event))
3169 static_key_slow_dec_deferred(&perf_sched_events);
3171 unaccount_event_cpu(event, event->cpu);
3174 static void __free_event(struct perf_event *event)
3176 if (!event->parent) {
3177 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3178 put_callchain_buffers();
3182 event->destroy(event);
3185 put_ctx(event->ctx);
3187 call_rcu(&event->rcu_head, free_event_rcu);
3189 static void free_event(struct perf_event *event)
3191 irq_work_sync(&event->pending);
3193 unaccount_event(event);
3196 struct ring_buffer *rb;
3199 * Can happen when we close an event with re-directed output.
3201 * Since we have a 0 refcount, perf_mmap_close() will skip
3202 * over us; possibly making our ring_buffer_put() the last.
3204 mutex_lock(&event->mmap_mutex);
3207 rcu_assign_pointer(event->rb, NULL);
3208 ring_buffer_detach(event, rb);
3209 ring_buffer_put(rb); /* could be last */
3211 mutex_unlock(&event->mmap_mutex);
3214 if (is_cgroup_event(event))
3215 perf_detach_cgroup(event);
3218 __free_event(event);
3221 int perf_event_release_kernel(struct perf_event *event)
3223 struct perf_event_context *ctx = event->ctx;
3225 WARN_ON_ONCE(ctx->parent_ctx);
3227 * There are two ways this annotation is useful:
3229 * 1) there is a lock recursion from perf_event_exit_task
3230 * see the comment there.
3232 * 2) there is a lock-inversion with mmap_sem through
3233 * perf_event_read_group(), which takes faults while
3234 * holding ctx->mutex, however this is called after
3235 * the last filedesc died, so there is no possibility
3236 * to trigger the AB-BA case.
3238 mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
3239 raw_spin_lock_irq(&ctx->lock);
3240 perf_group_detach(event);
3241 raw_spin_unlock_irq(&ctx->lock);
3242 perf_remove_from_context(event);
3243 mutex_unlock(&ctx->mutex);
3249 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3252 * Called when the last reference to the file is gone.
3254 static void put_event(struct perf_event *event)
3256 struct task_struct *owner;
3258 if (!atomic_long_dec_and_test(&event->refcount))
3262 owner = ACCESS_ONCE(event->owner);
3264 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3265 * !owner it means the list deletion is complete and we can indeed
3266 * free this event, otherwise we need to serialize on
3267 * owner->perf_event_mutex.
3269 smp_read_barrier_depends();
3272 * Since delayed_put_task_struct() also drops the last
3273 * task reference we can safely take a new reference
3274 * while holding the rcu_read_lock().
3276 get_task_struct(owner);
3281 mutex_lock(&owner->perf_event_mutex);
3283 * We have to re-check the event->owner field, if it is cleared
3284 * we raced with perf_event_exit_task(), acquiring the mutex
3285 * ensured they're done, and we can proceed with freeing the
3289 list_del_init(&event->owner_entry);
3290 mutex_unlock(&owner->perf_event_mutex);
3291 put_task_struct(owner);
3294 perf_event_release_kernel(event);
3297 static int perf_release(struct inode *inode, struct file *file)
3299 put_event(file->private_data);
3303 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3305 struct perf_event *child;
3311 mutex_lock(&event->child_mutex);
3312 total += perf_event_read(event);
3313 *enabled += event->total_time_enabled +
3314 atomic64_read(&event->child_total_time_enabled);
3315 *running += event->total_time_running +
3316 atomic64_read(&event->child_total_time_running);
3318 list_for_each_entry(child, &event->child_list, child_list) {
3319 total += perf_event_read(child);
3320 *enabled += child->total_time_enabled;
3321 *running += child->total_time_running;
3323 mutex_unlock(&event->child_mutex);
3327 EXPORT_SYMBOL_GPL(perf_event_read_value);
3329 static int perf_event_read_group(struct perf_event *event,
3330 u64 read_format, char __user *buf)
3332 struct perf_event *leader = event->group_leader, *sub;
3333 int n = 0, size = 0, ret = -EFAULT;
3334 struct perf_event_context *ctx = leader->ctx;
3336 u64 count, enabled, running;
3338 mutex_lock(&ctx->mutex);
3339 count = perf_event_read_value(leader, &enabled, &running);
3341 values[n++] = 1 + leader->nr_siblings;
3342 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3343 values[n++] = enabled;
3344 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3345 values[n++] = running;
3346 values[n++] = count;
3347 if (read_format & PERF_FORMAT_ID)
3348 values[n++] = primary_event_id(leader);
3350 size = n * sizeof(u64);
3352 if (copy_to_user(buf, values, size))
3357 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3360 values[n++] = perf_event_read_value(sub, &enabled, &running);
3361 if (read_format & PERF_FORMAT_ID)
3362 values[n++] = primary_event_id(sub);
3364 size = n * sizeof(u64);
3366 if (copy_to_user(buf + ret, values, size)) {
3374 mutex_unlock(&ctx->mutex);
3379 static int perf_event_read_one(struct perf_event *event,
3380 u64 read_format, char __user *buf)
3382 u64 enabled, running;
3386 values[n++] = perf_event_read_value(event, &enabled, &running);
3387 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3388 values[n++] = enabled;
3389 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3390 values[n++] = running;
3391 if (read_format & PERF_FORMAT_ID)
3392 values[n++] = primary_event_id(event);
3394 if (copy_to_user(buf, values, n * sizeof(u64)))
3397 return n * sizeof(u64);
3401 * Read the performance event - simple non blocking version for now
3404 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
3406 u64 read_format = event->attr.read_format;
3410 * Return end-of-file for a read on a event that is in
3411 * error state (i.e. because it was pinned but it couldn't be
3412 * scheduled on to the CPU at some point).
3414 if (event->state == PERF_EVENT_STATE_ERROR)
3417 if (count < event->read_size)
3420 WARN_ON_ONCE(event->ctx->parent_ctx);
3421 if (read_format & PERF_FORMAT_GROUP)
3422 ret = perf_event_read_group(event, read_format, buf);
3424 ret = perf_event_read_one(event, read_format, buf);
3430 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
3432 struct perf_event *event = file->private_data;
3434 return perf_read_hw(event, buf, count);
3437 static unsigned int perf_poll(struct file *file, poll_table *wait)
3439 struct perf_event *event = file->private_data;
3440 struct ring_buffer *rb;
3441 unsigned int events = POLL_HUP;
3444 * Pin the event->rb by taking event->mmap_mutex; otherwise
3445 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
3447 mutex_lock(&event->mmap_mutex);
3450 events = atomic_xchg(&rb->poll, 0);
3451 mutex_unlock(&event->mmap_mutex);
3453 poll_wait(file, &event->waitq, wait);
3458 static void perf_event_reset(struct perf_event *event)
3460 (void)perf_event_read(event);
3461 local64_set(&event->count, 0);
3462 perf_event_update_userpage(event);
3466 * Holding the top-level event's child_mutex means that any
3467 * descendant process that has inherited this event will block
3468 * in sync_child_event if it goes to exit, thus satisfying the
3469 * task existence requirements of perf_event_enable/disable.
3471 static void perf_event_for_each_child(struct perf_event *event,
3472 void (*func)(struct perf_event *))
3474 struct perf_event *child;
3476 WARN_ON_ONCE(event->ctx->parent_ctx);
3477 mutex_lock(&event->child_mutex);
3479 list_for_each_entry(child, &event->child_list, child_list)
3481 mutex_unlock(&event->child_mutex);
3484 static void perf_event_for_each(struct perf_event *event,
3485 void (*func)(struct perf_event *))
3487 struct perf_event_context *ctx = event->ctx;
3488 struct perf_event *sibling;
3490 WARN_ON_ONCE(ctx->parent_ctx);
3491 mutex_lock(&ctx->mutex);
3492 event = event->group_leader;
3494 perf_event_for_each_child(event, func);
3495 list_for_each_entry(sibling, &event->sibling_list, group_entry)
3496 perf_event_for_each_child(sibling, func);
3497 mutex_unlock(&ctx->mutex);
3500 static int perf_event_period(struct perf_event *event, u64 __user *arg)
3502 struct perf_event_context *ctx = event->ctx;
3506 if (!is_sampling_event(event))
3509 if (copy_from_user(&value, arg, sizeof(value)))
3515 raw_spin_lock_irq(&ctx->lock);
3516 if (event->attr.freq) {
3517 if (value > sysctl_perf_event_sample_rate) {
3522 event->attr.sample_freq = value;
3524 event->attr.sample_period = value;
3525 event->hw.sample_period = value;
3528 raw_spin_unlock_irq(&ctx->lock);
3533 static const struct file_operations perf_fops;
3535 static inline int perf_fget_light(int fd, struct fd *p)
3537 struct fd f = fdget(fd);
3541 if (f.file->f_op != &perf_fops) {
3549 static int perf_event_set_output(struct perf_event *event,
3550 struct perf_event *output_event);
3551 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
3553 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
3555 struct perf_event *event = file->private_data;
3556 void (*func)(struct perf_event *);
3560 case PERF_EVENT_IOC_ENABLE:
3561 func = perf_event_enable;
3563 case PERF_EVENT_IOC_DISABLE:
3564 func = perf_event_disable;
3566 case PERF_EVENT_IOC_RESET:
3567 func = perf_event_reset;
3570 case PERF_EVENT_IOC_REFRESH:
3571 return perf_event_refresh(event, arg);
3573 case PERF_EVENT_IOC_PERIOD:
3574 return perf_event_period(event, (u64 __user *)arg);
3576 case PERF_EVENT_IOC_ID:
3578 u64 id = primary_event_id(event);
3580 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
3585 case PERF_EVENT_IOC_SET_OUTPUT:
3589 struct perf_event *output_event;
3591 ret = perf_fget_light(arg, &output);
3594 output_event = output.file->private_data;
3595 ret = perf_event_set_output(event, output_event);
3598 ret = perf_event_set_output(event, NULL);
3603 case PERF_EVENT_IOC_SET_FILTER:
3604 return perf_event_set_filter(event, (void __user *)arg);
3610 if (flags & PERF_IOC_FLAG_GROUP)
3611 perf_event_for_each(event, func);
3613 perf_event_for_each_child(event, func);
3618 int perf_event_task_enable(void)
3620 struct perf_event *event;
3622 mutex_lock(¤t->perf_event_mutex);
3623 list_for_each_entry(event, ¤t->perf_event_list, owner_entry)
3624 perf_event_for_each_child(event, perf_event_enable);
3625 mutex_unlock(¤t->perf_event_mutex);
3630 int perf_event_task_disable(void)
3632 struct perf_event *event;
3634 mutex_lock(¤t->perf_event_mutex);
3635 list_for_each_entry(event, ¤t->perf_event_list, owner_entry)
3636 perf_event_for_each_child(event, perf_event_disable);
3637 mutex_unlock(¤t->perf_event_mutex);
3642 static int perf_event_index(struct perf_event *event)
3644 if (event->hw.state & PERF_HES_STOPPED)
3647 if (event->state != PERF_EVENT_STATE_ACTIVE)
3650 return event->pmu->event_idx(event);
3653 static void calc_timer_values(struct perf_event *event,
3660 *now = perf_clock();
3661 ctx_time = event->shadow_ctx_time + *now;
3662 *enabled = ctx_time - event->tstamp_enabled;
3663 *running = ctx_time - event->tstamp_running;
3666 static void perf_event_init_userpage(struct perf_event *event)
3668 struct perf_event_mmap_page *userpg;
3669 struct ring_buffer *rb;
3672 rb = rcu_dereference(event->rb);
3676 userpg = rb->user_page;
3678 /* Allow new userspace to detect that bit 0 is deprecated */
3679 userpg->cap_bit0_is_deprecated = 1;
3680 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
3686 void __weak arch_perf_update_userpage(struct perf_event_mmap_page *userpg, u64 now)
3691 * Callers need to ensure there can be no nesting of this function, otherwise
3692 * the seqlock logic goes bad. We can not serialize this because the arch
3693 * code calls this from NMI context.
3695 void perf_event_update_userpage(struct perf_event *event)
3697 struct perf_event_mmap_page *userpg;
3698 struct ring_buffer *rb;
3699 u64 enabled, running, now;
3702 rb = rcu_dereference(event->rb);
3707 * compute total_time_enabled, total_time_running
3708 * based on snapshot values taken when the event
3709 * was last scheduled in.
3711 * we cannot simply called update_context_time()
3712 * because of locking issue as we can be called in
3715 calc_timer_values(event, &now, &enabled, &running);
3717 userpg = rb->user_page;
3719 * Disable preemption so as to not let the corresponding user-space
3720 * spin too long if we get preempted.
3725 userpg->index = perf_event_index(event);
3726 userpg->offset = perf_event_count(event);
3728 userpg->offset -= local64_read(&event->hw.prev_count);
3730 userpg->time_enabled = enabled +
3731 atomic64_read(&event->child_total_time_enabled);
3733 userpg->time_running = running +
3734 atomic64_read(&event->child_total_time_running);
3736 arch_perf_update_userpage(userpg, now);
3745 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
3747 struct perf_event *event = vma->vm_file->private_data;
3748 struct ring_buffer *rb;
3749 int ret = VM_FAULT_SIGBUS;
3751 if (vmf->flags & FAULT_FLAG_MKWRITE) {
3752 if (vmf->pgoff == 0)
3758 rb = rcu_dereference(event->rb);
3762 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
3765 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
3769 get_page(vmf->page);
3770 vmf->page->mapping = vma->vm_file->f_mapping;
3771 vmf->page->index = vmf->pgoff;
3780 static void ring_buffer_attach(struct perf_event *event,
3781 struct ring_buffer *rb)
3783 unsigned long flags;
3785 if (!list_empty(&event->rb_entry))
3788 spin_lock_irqsave(&rb->event_lock, flags);
3789 if (list_empty(&event->rb_entry))
3790 list_add(&event->rb_entry, &rb->event_list);
3791 spin_unlock_irqrestore(&rb->event_lock, flags);
3794 static void ring_buffer_detach(struct perf_event *event, struct ring_buffer *rb)
3796 unsigned long flags;
3798 if (list_empty(&event->rb_entry))
3801 spin_lock_irqsave(&rb->event_lock, flags);
3802 list_del_init(&event->rb_entry);
3803 wake_up_all(&event->waitq);
3804 spin_unlock_irqrestore(&rb->event_lock, flags);
3807 static void ring_buffer_wakeup(struct perf_event *event)
3809 struct ring_buffer *rb;
3812 rb = rcu_dereference(event->rb);
3814 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
3815 wake_up_all(&event->waitq);
3820 static void rb_free_rcu(struct rcu_head *rcu_head)
3822 struct ring_buffer *rb;
3824 rb = container_of(rcu_head, struct ring_buffer, rcu_head);
3828 static struct ring_buffer *ring_buffer_get(struct perf_event *event)
3830 struct ring_buffer *rb;
3833 rb = rcu_dereference(event->rb);
3835 if (!atomic_inc_not_zero(&rb->refcount))
3843 static void ring_buffer_put(struct ring_buffer *rb)
3845 if (!atomic_dec_and_test(&rb->refcount))
3848 WARN_ON_ONCE(!list_empty(&rb->event_list));
3850 call_rcu(&rb->rcu_head, rb_free_rcu);
3853 static void perf_mmap_open(struct vm_area_struct *vma)
3855 struct perf_event *event = vma->vm_file->private_data;
3857 atomic_inc(&event->mmap_count);
3858 atomic_inc(&event->rb->mmap_count);
3862 * A buffer can be mmap()ed multiple times; either directly through the same
3863 * event, or through other events by use of perf_event_set_output().
3865 * In order to undo the VM accounting done by perf_mmap() we need to destroy
3866 * the buffer here, where we still have a VM context. This means we need
3867 * to detach all events redirecting to us.
3869 static void perf_mmap_close(struct vm_area_struct *vma)
3871 struct perf_event *event = vma->vm_file->private_data;
3873 struct ring_buffer *rb = event->rb;
3874 struct user_struct *mmap_user = rb->mmap_user;
3875 int mmap_locked = rb->mmap_locked;
3876 unsigned long size = perf_data_size(rb);
3878 atomic_dec(&rb->mmap_count);
3880 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
3883 /* Detach current event from the buffer. */
3884 rcu_assign_pointer(event->rb, NULL);
3885 ring_buffer_detach(event, rb);
3886 mutex_unlock(&event->mmap_mutex);
3888 /* If there's still other mmap()s of this buffer, we're done. */
3889 if (atomic_read(&rb->mmap_count)) {
3890 ring_buffer_put(rb); /* can't be last */
3895 * No other mmap()s, detach from all other events that might redirect
3896 * into the now unreachable buffer. Somewhat complicated by the
3897 * fact that rb::event_lock otherwise nests inside mmap_mutex.
3901 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
3902 if (!atomic_long_inc_not_zero(&event->refcount)) {
3904 * This event is en-route to free_event() which will
3905 * detach it and remove it from the list.
3911 mutex_lock(&event->mmap_mutex);
3913 * Check we didn't race with perf_event_set_output() which can
3914 * swizzle the rb from under us while we were waiting to
3915 * acquire mmap_mutex.
3917 * If we find a different rb; ignore this event, a next
3918 * iteration will no longer find it on the list. We have to
3919 * still restart the iteration to make sure we're not now
3920 * iterating the wrong list.
3922 if (event->rb == rb) {
3923 rcu_assign_pointer(event->rb, NULL);
3924 ring_buffer_detach(event, rb);
3925 ring_buffer_put(rb); /* can't be last, we still have one */
3927 mutex_unlock(&event->mmap_mutex);
3931 * Restart the iteration; either we're on the wrong list or
3932 * destroyed its integrity by doing a deletion.
3939 * It could be there's still a few 0-ref events on the list; they'll
3940 * get cleaned up by free_event() -- they'll also still have their
3941 * ref on the rb and will free it whenever they are done with it.
3943 * Aside from that, this buffer is 'fully' detached and unmapped,
3944 * undo the VM accounting.
3947 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
3948 vma->vm_mm->pinned_vm -= mmap_locked;
3949 free_uid(mmap_user);
3951 ring_buffer_put(rb); /* could be last */
3954 static const struct vm_operations_struct perf_mmap_vmops = {
3955 .open = perf_mmap_open,
3956 .close = perf_mmap_close,
3957 .fault = perf_mmap_fault,
3958 .page_mkwrite = perf_mmap_fault,
3961 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
3963 struct perf_event *event = file->private_data;
3964 unsigned long user_locked, user_lock_limit;
3965 struct user_struct *user = current_user();
3966 unsigned long locked, lock_limit;
3967 struct ring_buffer *rb;
3968 unsigned long vma_size;
3969 unsigned long nr_pages;
3970 long user_extra, extra;
3971 int ret = 0, flags = 0;
3974 * Don't allow mmap() of inherited per-task counters. This would
3975 * create a performance issue due to all children writing to the
3978 if (event->cpu == -1 && event->attr.inherit)
3981 if (!(vma->vm_flags & VM_SHARED))
3984 vma_size = vma->vm_end - vma->vm_start;
3985 nr_pages = (vma_size / PAGE_SIZE) - 1;
3988 * If we have rb pages ensure they're a power-of-two number, so we
3989 * can do bitmasks instead of modulo.
3991 if (nr_pages != 0 && !is_power_of_2(nr_pages))
3994 if (vma_size != PAGE_SIZE * (1 + nr_pages))
3997 if (vma->vm_pgoff != 0)
4000 WARN_ON_ONCE(event->ctx->parent_ctx);
4002 mutex_lock(&event->mmap_mutex);
4004 if (event->rb->nr_pages != nr_pages) {
4009 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4011 * Raced against perf_mmap_close() through
4012 * perf_event_set_output(). Try again, hope for better
4015 mutex_unlock(&event->mmap_mutex);
4022 user_extra = nr_pages + 1;
4023 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
4026 * Increase the limit linearly with more CPUs:
4028 user_lock_limit *= num_online_cpus();
4030 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
4033 if (user_locked > user_lock_limit)
4034 extra = user_locked - user_lock_limit;
4036 lock_limit = rlimit(RLIMIT_MEMLOCK);
4037 lock_limit >>= PAGE_SHIFT;
4038 locked = vma->vm_mm->pinned_vm + extra;
4040 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
4041 !capable(CAP_IPC_LOCK)) {
4048 if (vma->vm_flags & VM_WRITE)
4049 flags |= RING_BUFFER_WRITABLE;
4051 rb = rb_alloc(nr_pages,
4052 event->attr.watermark ? event->attr.wakeup_watermark : 0,
4060 atomic_set(&rb->mmap_count, 1);
4061 rb->mmap_locked = extra;
4062 rb->mmap_user = get_current_user();
4064 atomic_long_add(user_extra, &user->locked_vm);
4065 vma->vm_mm->pinned_vm += extra;
4067 ring_buffer_attach(event, rb);
4068 rcu_assign_pointer(event->rb, rb);
4070 perf_event_init_userpage(event);
4071 perf_event_update_userpage(event);
4075 atomic_inc(&event->mmap_count);
4076 mutex_unlock(&event->mmap_mutex);
4079 * Since pinned accounting is per vm we cannot allow fork() to copy our
4082 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
4083 vma->vm_ops = &perf_mmap_vmops;
4088 static int perf_fasync(int fd, struct file *filp, int on)
4090 struct inode *inode = file_inode(filp);
4091 struct perf_event *event = filp->private_data;
4094 mutex_lock(&inode->i_mutex);
4095 retval = fasync_helper(fd, filp, on, &event->fasync);
4096 mutex_unlock(&inode->i_mutex);
4104 static const struct file_operations perf_fops = {
4105 .llseek = no_llseek,
4106 .release = perf_release,
4109 .unlocked_ioctl = perf_ioctl,
4110 .compat_ioctl = perf_ioctl,
4112 .fasync = perf_fasync,
4118 * If there's data, ensure we set the poll() state and publish everything
4119 * to user-space before waking everybody up.
4122 void perf_event_wakeup(struct perf_event *event)
4124 ring_buffer_wakeup(event);
4126 if (event->pending_kill) {
4127 kill_fasync(&event->fasync, SIGIO, event->pending_kill);
4128 event->pending_kill = 0;
4132 static void perf_pending_event(struct irq_work *entry)
4134 struct perf_event *event = container_of(entry,
4135 struct perf_event, pending);
4137 if (event->pending_disable) {
4138 event->pending_disable = 0;
4139 __perf_event_disable(event);
4142 if (event->pending_wakeup) {
4143 event->pending_wakeup = 0;
4144 perf_event_wakeup(event);
4149 * We assume there is only KVM supporting the callbacks.
4150 * Later on, we might change it to a list if there is
4151 * another virtualization implementation supporting the callbacks.
4153 struct perf_guest_info_callbacks *perf_guest_cbs;
4155 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4157 perf_guest_cbs = cbs;
4160 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
4162 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4164 perf_guest_cbs = NULL;
4167 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
4170 perf_output_sample_regs(struct perf_output_handle *handle,
4171 struct pt_regs *regs, u64 mask)
4175 for_each_set_bit(bit, (const unsigned long *) &mask,
4176 sizeof(mask) * BITS_PER_BYTE) {
4179 val = perf_reg_value(regs, bit);
4180 perf_output_put(handle, val);
4184 static void perf_sample_regs_user(struct perf_regs_user *regs_user,
4185 struct pt_regs *regs)
4187 if (!user_mode(regs)) {
4189 regs = task_pt_regs(current);
4195 regs_user->regs = regs;
4196 regs_user->abi = perf_reg_abi(current);
4201 * Get remaining task size from user stack pointer.
4203 * It'd be better to take stack vma map and limit this more
4204 * precisly, but there's no way to get it safely under interrupt,
4205 * so using TASK_SIZE as limit.
4207 static u64 perf_ustack_task_size(struct pt_regs *regs)
4209 unsigned long addr = perf_user_stack_pointer(regs);
4211 if (!addr || addr >= TASK_SIZE)
4214 return TASK_SIZE - addr;
4218 perf_sample_ustack_size(u16 stack_size, u16 header_size,
4219 struct pt_regs *regs)
4223 /* No regs, no stack pointer, no dump. */
4228 * Check if we fit in with the requested stack size into the:
4230 * If we don't, we limit the size to the TASK_SIZE.
4232 * - remaining sample size
4233 * If we don't, we customize the stack size to
4234 * fit in to the remaining sample size.
4237 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
4238 stack_size = min(stack_size, (u16) task_size);
4240 /* Current header size plus static size and dynamic size. */
4241 header_size += 2 * sizeof(u64);
4243 /* Do we fit in with the current stack dump size? */
4244 if ((u16) (header_size + stack_size) < header_size) {
4246 * If we overflow the maximum size for the sample,
4247 * we customize the stack dump size to fit in.
4249 stack_size = USHRT_MAX - header_size - sizeof(u64);
4250 stack_size = round_up(stack_size, sizeof(u64));
4257 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
4258 struct pt_regs *regs)
4260 /* Case of a kernel thread, nothing to dump */
4263 perf_output_put(handle, size);
4272 * - the size requested by user or the best one we can fit
4273 * in to the sample max size
4275 * - user stack dump data
4277 * - the actual dumped size
4281 perf_output_put(handle, dump_size);
4284 sp = perf_user_stack_pointer(regs);
4285 rem = __output_copy_user(handle, (void *) sp, dump_size);
4286 dyn_size = dump_size - rem;
4288 perf_output_skip(handle, rem);
4291 perf_output_put(handle, dyn_size);
4295 static void __perf_event_header__init_id(struct perf_event_header *header,
4296 struct perf_sample_data *data,
4297 struct perf_event *event)
4299 u64 sample_type = event->attr.sample_type;
4301 data->type = sample_type;
4302 header->size += event->id_header_size;
4304 if (sample_type & PERF_SAMPLE_TID) {
4305 /* namespace issues */
4306 data->tid_entry.pid = perf_event_pid(event, current);
4307 data->tid_entry.tid = perf_event_tid(event, current);
4310 if (sample_type & PERF_SAMPLE_TIME)
4311 data->time = perf_clock();
4313 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
4314 data->id = primary_event_id(event);
4316 if (sample_type & PERF_SAMPLE_STREAM_ID)
4317 data->stream_id = event->id;
4319 if (sample_type & PERF_SAMPLE_CPU) {
4320 data->cpu_entry.cpu = raw_smp_processor_id();
4321 data->cpu_entry.reserved = 0;
4325 void perf_event_header__init_id(struct perf_event_header *header,
4326 struct perf_sample_data *data,
4327 struct perf_event *event)
4329 if (event->attr.sample_id_all)
4330 __perf_event_header__init_id(header, data, event);
4333 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
4334 struct perf_sample_data *data)
4336 u64 sample_type = data->type;
4338 if (sample_type & PERF_SAMPLE_TID)
4339 perf_output_put(handle, data->tid_entry);
4341 if (sample_type & PERF_SAMPLE_TIME)
4342 perf_output_put(handle, data->time);
4344 if (sample_type & PERF_SAMPLE_ID)
4345 perf_output_put(handle, data->id);
4347 if (sample_type & PERF_SAMPLE_STREAM_ID)
4348 perf_output_put(handle, data->stream_id);
4350 if (sample_type & PERF_SAMPLE_CPU)
4351 perf_output_put(handle, data->cpu_entry);
4353 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4354 perf_output_put(handle, data->id);
4357 void perf_event__output_id_sample(struct perf_event *event,
4358 struct perf_output_handle *handle,
4359 struct perf_sample_data *sample)
4361 if (event->attr.sample_id_all)
4362 __perf_event__output_id_sample(handle, sample);
4365 static void perf_output_read_one(struct perf_output_handle *handle,
4366 struct perf_event *event,
4367 u64 enabled, u64 running)
4369 u64 read_format = event->attr.read_format;
4373 values[n++] = perf_event_count(event);
4374 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4375 values[n++] = enabled +
4376 atomic64_read(&event->child_total_time_enabled);
4378 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4379 values[n++] = running +
4380 atomic64_read(&event->child_total_time_running);
4382 if (read_format & PERF_FORMAT_ID)
4383 values[n++] = primary_event_id(event);
4385 __output_copy(handle, values, n * sizeof(u64));
4389 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
4391 static void perf_output_read_group(struct perf_output_handle *handle,
4392 struct perf_event *event,
4393 u64 enabled, u64 running)
4395 struct perf_event *leader = event->group_leader, *sub;
4396 u64 read_format = event->attr.read_format;
4400 values[n++] = 1 + leader->nr_siblings;
4402 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4403 values[n++] = enabled;
4405 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4406 values[n++] = running;
4408 if (leader != event)
4409 leader->pmu->read(leader);
4411 values[n++] = perf_event_count(leader);
4412 if (read_format & PERF_FORMAT_ID)
4413 values[n++] = primary_event_id(leader);
4415 __output_copy(handle, values, n * sizeof(u64));
4417 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4420 if ((sub != event) &&
4421 (sub->state == PERF_EVENT_STATE_ACTIVE))
4422 sub->pmu->read(sub);
4424 values[n++] = perf_event_count(sub);
4425 if (read_format & PERF_FORMAT_ID)
4426 values[n++] = primary_event_id(sub);
4428 __output_copy(handle, values, n * sizeof(u64));
4432 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
4433 PERF_FORMAT_TOTAL_TIME_RUNNING)
4435 static void perf_output_read(struct perf_output_handle *handle,
4436 struct perf_event *event)
4438 u64 enabled = 0, running = 0, now;
4439 u64 read_format = event->attr.read_format;
4442 * compute total_time_enabled, total_time_running
4443 * based on snapshot values taken when the event
4444 * was last scheduled in.
4446 * we cannot simply called update_context_time()
4447 * because of locking issue as we are called in
4450 if (read_format & PERF_FORMAT_TOTAL_TIMES)
4451 calc_timer_values(event, &now, &enabled, &running);
4453 if (event->attr.read_format & PERF_FORMAT_GROUP)
4454 perf_output_read_group(handle, event, enabled, running);
4456 perf_output_read_one(handle, event, enabled, running);
4459 void perf_output_sample(struct perf_output_handle *handle,
4460 struct perf_event_header *header,
4461 struct perf_sample_data *data,
4462 struct perf_event *event)
4464 u64 sample_type = data->type;
4466 perf_output_put(handle, *header);
4468 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4469 perf_output_put(handle, data->id);
4471 if (sample_type & PERF_SAMPLE_IP)
4472 perf_output_put(handle, data->ip);
4474 if (sample_type & PERF_SAMPLE_TID)
4475 perf_output_put(handle, data->tid_entry);
4477 if (sample_type & PERF_SAMPLE_TIME)
4478 perf_output_put(handle, data->time);
4480 if (sample_type & PERF_SAMPLE_ADDR)
4481 perf_output_put(handle, data->addr);
4483 if (sample_type & PERF_SAMPLE_ID)
4484 perf_output_put(handle, data->id);
4486 if (sample_type & PERF_SAMPLE_STREAM_ID)
4487 perf_output_put(handle, data->stream_id);
4489 if (sample_type & PERF_SAMPLE_CPU)
4490 perf_output_put(handle, data->cpu_entry);
4492 if (sample_type & PERF_SAMPLE_PERIOD)
4493 perf_output_put(handle, data->period);
4495 if (sample_type & PERF_SAMPLE_READ)
4496 perf_output_read(handle, event);
4498 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4499 if (data->callchain) {
4502 if (data->callchain)
4503 size += data->callchain->nr;
4505 size *= sizeof(u64);
4507 __output_copy(handle, data->callchain, size);
4510 perf_output_put(handle, nr);
4514 if (sample_type & PERF_SAMPLE_RAW) {
4516 perf_output_put(handle, data->raw->size);
4517 __output_copy(handle, data->raw->data,
4524 .size = sizeof(u32),
4527 perf_output_put(handle, raw);
4531 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4532 if (data->br_stack) {
4535 size = data->br_stack->nr
4536 * sizeof(struct perf_branch_entry);
4538 perf_output_put(handle, data->br_stack->nr);
4539 perf_output_copy(handle, data->br_stack->entries, size);
4542 * we always store at least the value of nr
4545 perf_output_put(handle, nr);
4549 if (sample_type & PERF_SAMPLE_REGS_USER) {
4550 u64 abi = data->regs_user.abi;
4553 * If there are no regs to dump, notice it through
4554 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
4556 perf_output_put(handle, abi);
4559 u64 mask = event->attr.sample_regs_user;
4560 perf_output_sample_regs(handle,
4561 data->regs_user.regs,
4566 if (sample_type & PERF_SAMPLE_STACK_USER) {
4567 perf_output_sample_ustack(handle,
4568 data->stack_user_size,
4569 data->regs_user.regs);
4572 if (sample_type & PERF_SAMPLE_WEIGHT)
4573 perf_output_put(handle, data->weight);
4575 if (sample_type & PERF_SAMPLE_DATA_SRC)
4576 perf_output_put(handle, data->data_src.val);
4578 if (sample_type & PERF_SAMPLE_TRANSACTION)
4579 perf_output_put(handle, data->txn);
4581 if (!event->attr.watermark) {
4582 int wakeup_events = event->attr.wakeup_events;
4584 if (wakeup_events) {
4585 struct ring_buffer *rb = handle->rb;
4586 int events = local_inc_return(&rb->events);
4588 if (events >= wakeup_events) {
4589 local_sub(wakeup_events, &rb->events);
4590 local_inc(&rb->wakeup);
4596 void perf_prepare_sample(struct perf_event_header *header,
4597 struct perf_sample_data *data,
4598 struct perf_event *event,
4599 struct pt_regs *regs)
4601 u64 sample_type = event->attr.sample_type;
4603 header->type = PERF_RECORD_SAMPLE;
4604 header->size = sizeof(*header) + event->header_size;
4607 header->misc |= perf_misc_flags(regs);
4609 __perf_event_header__init_id(header, data, event);
4611 if (sample_type & PERF_SAMPLE_IP)
4612 data->ip = perf_instruction_pointer(regs);
4614 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4617 data->callchain = perf_callchain(event, regs);
4619 if (data->callchain)
4620 size += data->callchain->nr;
4622 header->size += size * sizeof(u64);
4625 if (sample_type & PERF_SAMPLE_RAW) {
4626 int size = sizeof(u32);
4629 size += data->raw->size;
4631 size += sizeof(u32);
4633 WARN_ON_ONCE(size & (sizeof(u64)-1));
4634 header->size += size;
4637 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4638 int size = sizeof(u64); /* nr */
4639 if (data->br_stack) {
4640 size += data->br_stack->nr
4641 * sizeof(struct perf_branch_entry);
4643 header->size += size;
4646 if (sample_type & PERF_SAMPLE_REGS_USER) {
4647 /* regs dump ABI info */
4648 int size = sizeof(u64);
4650 perf_sample_regs_user(&data->regs_user, regs);
4652 if (data->regs_user.regs) {
4653 u64 mask = event->attr.sample_regs_user;
4654 size += hweight64(mask) * sizeof(u64);
4657 header->size += size;
4660 if (sample_type & PERF_SAMPLE_STACK_USER) {
4662 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
4663 * processed as the last one or have additional check added
4664 * in case new sample type is added, because we could eat
4665 * up the rest of the sample size.
4667 struct perf_regs_user *uregs = &data->regs_user;
4668 u16 stack_size = event->attr.sample_stack_user;
4669 u16 size = sizeof(u64);
4672 perf_sample_regs_user(uregs, regs);
4674 stack_size = perf_sample_ustack_size(stack_size, header->size,
4678 * If there is something to dump, add space for the dump
4679 * itself and for the field that tells the dynamic size,
4680 * which is how many have been actually dumped.
4683 size += sizeof(u64) + stack_size;
4685 data->stack_user_size = stack_size;
4686 header->size += size;
4690 static void perf_event_output(struct perf_event *event,
4691 struct perf_sample_data *data,
4692 struct pt_regs *regs)
4694 struct perf_output_handle handle;
4695 struct perf_event_header header;
4697 /* protect the callchain buffers */
4700 perf_prepare_sample(&header, data, event, regs);
4702 if (perf_output_begin(&handle, event, header.size))
4705 perf_output_sample(&handle, &header, data, event);
4707 perf_output_end(&handle);
4717 struct perf_read_event {
4718 struct perf_event_header header;
4725 perf_event_read_event(struct perf_event *event,
4726 struct task_struct *task)
4728 struct perf_output_handle handle;
4729 struct perf_sample_data sample;
4730 struct perf_read_event read_event = {
4732 .type = PERF_RECORD_READ,
4734 .size = sizeof(read_event) + event->read_size,
4736 .pid = perf_event_pid(event, task),
4737 .tid = perf_event_tid(event, task),
4741 perf_event_header__init_id(&read_event.header, &sample, event);
4742 ret = perf_output_begin(&handle, event, read_event.header.size);
4746 perf_output_put(&handle, read_event);
4747 perf_output_read(&handle, event);
4748 perf_event__output_id_sample(event, &handle, &sample);
4750 perf_output_end(&handle);
4753 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
4756 perf_event_aux_ctx(struct perf_event_context *ctx,
4757 perf_event_aux_output_cb output,
4760 struct perf_event *event;
4762 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4763 if (event->state < PERF_EVENT_STATE_INACTIVE)
4765 if (!event_filter_match(event))
4767 output(event, data);
4772 perf_event_aux(perf_event_aux_output_cb output, void *data,
4773 struct perf_event_context *task_ctx)
4775 struct perf_cpu_context *cpuctx;
4776 struct perf_event_context *ctx;
4781 list_for_each_entry_rcu(pmu, &pmus, entry) {
4782 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4783 if (cpuctx->unique_pmu != pmu)
4785 perf_event_aux_ctx(&cpuctx->ctx, output, data);
4788 ctxn = pmu->task_ctx_nr;
4791 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4793 perf_event_aux_ctx(ctx, output, data);
4795 put_cpu_ptr(pmu->pmu_cpu_context);
4800 perf_event_aux_ctx(task_ctx, output, data);
4807 * task tracking -- fork/exit
4809 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
4812 struct perf_task_event {
4813 struct task_struct *task;
4814 struct perf_event_context *task_ctx;
4817 struct perf_event_header header;
4827 static int perf_event_task_match(struct perf_event *event)
4829 return event->attr.comm || event->attr.mmap ||
4830 event->attr.mmap2 || event->attr.mmap_data ||
4834 static void perf_event_task_output(struct perf_event *event,
4837 struct perf_task_event *task_event = data;
4838 struct perf_output_handle handle;
4839 struct perf_sample_data sample;
4840 struct task_struct *task = task_event->task;
4841 int ret, size = task_event->event_id.header.size;
4843 if (!perf_event_task_match(event))
4846 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
4848 ret = perf_output_begin(&handle, event,
4849 task_event->event_id.header.size);
4853 task_event->event_id.pid = perf_event_pid(event, task);
4854 task_event->event_id.ppid = perf_event_pid(event, current);
4856 task_event->event_id.tid = perf_event_tid(event, task);
4857 task_event->event_id.ptid = perf_event_tid(event, current);
4859 perf_output_put(&handle, task_event->event_id);
4861 perf_event__output_id_sample(event, &handle, &sample);
4863 perf_output_end(&handle);
4865 task_event->event_id.header.size = size;
4868 static void perf_event_task(struct task_struct *task,
4869 struct perf_event_context *task_ctx,
4872 struct perf_task_event task_event;
4874 if (!atomic_read(&nr_comm_events) &&
4875 !atomic_read(&nr_mmap_events) &&
4876 !atomic_read(&nr_task_events))
4879 task_event = (struct perf_task_event){
4881 .task_ctx = task_ctx,
4884 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
4886 .size = sizeof(task_event.event_id),
4892 .time = perf_clock(),
4896 perf_event_aux(perf_event_task_output,
4901 void perf_event_fork(struct task_struct *task)
4903 perf_event_task(task, NULL, 1);
4910 struct perf_comm_event {
4911 struct task_struct *task;
4916 struct perf_event_header header;
4923 static int perf_event_comm_match(struct perf_event *event)
4925 return event->attr.comm;
4928 static void perf_event_comm_output(struct perf_event *event,
4931 struct perf_comm_event *comm_event = data;
4932 struct perf_output_handle handle;
4933 struct perf_sample_data sample;
4934 int size = comm_event->event_id.header.size;
4937 if (!perf_event_comm_match(event))
4940 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
4941 ret = perf_output_begin(&handle, event,
4942 comm_event->event_id.header.size);
4947 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
4948 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
4950 perf_output_put(&handle, comm_event->event_id);
4951 __output_copy(&handle, comm_event->comm,
4952 comm_event->comm_size);
4954 perf_event__output_id_sample(event, &handle, &sample);
4956 perf_output_end(&handle);
4958 comm_event->event_id.header.size = size;
4961 static void perf_event_comm_event(struct perf_comm_event *comm_event)
4963 char comm[TASK_COMM_LEN];
4966 memset(comm, 0, sizeof(comm));
4967 strlcpy(comm, comm_event->task->comm, sizeof(comm));
4968 size = ALIGN(strlen(comm)+1, sizeof(u64));
4970 comm_event->comm = comm;
4971 comm_event->comm_size = size;
4973 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
4975 perf_event_aux(perf_event_comm_output,
4980 void perf_event_comm(struct task_struct *task)
4982 struct perf_comm_event comm_event;
4983 struct perf_event_context *ctx;
4987 for_each_task_context_nr(ctxn) {
4988 ctx = task->perf_event_ctxp[ctxn];
4992 perf_event_enable_on_exec(ctx);
4996 if (!atomic_read(&nr_comm_events))
4999 comm_event = (struct perf_comm_event){
5005 .type = PERF_RECORD_COMM,
5014 perf_event_comm_event(&comm_event);
5021 struct perf_mmap_event {
5022 struct vm_area_struct *vma;
5024 const char *file_name;
5031 struct perf_event_header header;
5041 static int perf_event_mmap_match(struct perf_event *event,
5044 struct perf_mmap_event *mmap_event = data;
5045 struct vm_area_struct *vma = mmap_event->vma;
5046 int executable = vma->vm_flags & VM_EXEC;
5048 return (!executable && event->attr.mmap_data) ||
5049 (executable && (event->attr.mmap || event->attr.mmap2));
5052 static void perf_event_mmap_output(struct perf_event *event,
5055 struct perf_mmap_event *mmap_event = data;
5056 struct perf_output_handle handle;
5057 struct perf_sample_data sample;
5058 int size = mmap_event->event_id.header.size;
5061 if (!perf_event_mmap_match(event, data))
5064 if (event->attr.mmap2) {
5065 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
5066 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
5067 mmap_event->event_id.header.size += sizeof(mmap_event->min);
5068 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
5069 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
5072 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
5073 ret = perf_output_begin(&handle, event,
5074 mmap_event->event_id.header.size);
5078 mmap_event->event_id.pid = perf_event_pid(event, current);
5079 mmap_event->event_id.tid = perf_event_tid(event, current);
5081 perf_output_put(&handle, mmap_event->event_id);
5083 if (event->attr.mmap2) {
5084 perf_output_put(&handle, mmap_event->maj);
5085 perf_output_put(&handle, mmap_event->min);
5086 perf_output_put(&handle, mmap_event->ino);
5087 perf_output_put(&handle, mmap_event->ino_generation);
5090 __output_copy(&handle, mmap_event->file_name,
5091 mmap_event->file_size);
5093 perf_event__output_id_sample(event, &handle, &sample);
5095 perf_output_end(&handle);
5097 mmap_event->event_id.header.size = size;
5100 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
5102 struct vm_area_struct *vma = mmap_event->vma;
5103 struct file *file = vma->vm_file;
5104 int maj = 0, min = 0;
5105 u64 ino = 0, gen = 0;
5112 struct inode *inode;
5115 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5117 name = strncpy(tmp, "//enomem", sizeof(tmp));
5121 * d_path() works from the end of the rb backwards, so we
5122 * need to add enough zero bytes after the string to handle
5123 * the 64bit alignment we do later.
5125 name = d_path(&file->f_path, buf, PATH_MAX - sizeof(u64));
5127 name = strncpy(tmp, "//toolong", sizeof(tmp));
5130 inode = file_inode(vma->vm_file);
5131 dev = inode->i_sb->s_dev;
5133 gen = inode->i_generation;
5138 name = (char *)arch_vma_name(vma);
5140 name = strncpy(tmp, name, sizeof(tmp) - 1);
5141 tmp[sizeof(tmp) - 1] = '\0';
5145 if (vma->vm_start <= vma->vm_mm->start_brk &&
5146 vma->vm_end >= vma->vm_mm->brk) {
5147 name = strncpy(tmp, "[heap]", sizeof(tmp));
5150 if (vma->vm_start <= vma->vm_mm->start_stack &&
5151 vma->vm_end >= vma->vm_mm->start_stack) {
5152 name = strncpy(tmp, "[stack]", sizeof(tmp));
5156 name = strncpy(tmp, "//anon", sizeof(tmp));
5162 * Since our buffer works in 8 byte units we need to align our string
5163 * size to a multiple of 8. However, we must guarantee the tail end is
5164 * zero'd out to avoid leaking random bits to userspace.
5166 size = strlen(name)+1;
5167 while (!IS_ALIGNED(size, sizeof(u64)))
5168 name[size++] = '\0';
5170 mmap_event->file_name = name;
5171 mmap_event->file_size = size;
5172 mmap_event->maj = maj;
5173 mmap_event->min = min;
5174 mmap_event->ino = ino;
5175 mmap_event->ino_generation = gen;
5177 if (!(vma->vm_flags & VM_EXEC))
5178 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
5180 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
5182 perf_event_aux(perf_event_mmap_output,
5189 void perf_event_mmap(struct vm_area_struct *vma)
5191 struct perf_mmap_event mmap_event;
5193 if (!atomic_read(&nr_mmap_events))
5196 mmap_event = (struct perf_mmap_event){
5202 .type = PERF_RECORD_MMAP,
5203 .misc = PERF_RECORD_MISC_USER,
5208 .start = vma->vm_start,
5209 .len = vma->vm_end - vma->vm_start,
5210 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
5212 /* .maj (attr_mmap2 only) */
5213 /* .min (attr_mmap2 only) */
5214 /* .ino (attr_mmap2 only) */
5215 /* .ino_generation (attr_mmap2 only) */
5218 perf_event_mmap_event(&mmap_event);
5222 * IRQ throttle logging
5225 static void perf_log_throttle(struct perf_event *event, int enable)
5227 struct perf_output_handle handle;
5228 struct perf_sample_data sample;
5232 struct perf_event_header header;
5236 } throttle_event = {
5238 .type = PERF_RECORD_THROTTLE,
5240 .size = sizeof(throttle_event),
5242 .time = perf_clock(),
5243 .id = primary_event_id(event),
5244 .stream_id = event->id,
5248 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
5250 perf_event_header__init_id(&throttle_event.header, &sample, event);
5252 ret = perf_output_begin(&handle, event,
5253 throttle_event.header.size);
5257 perf_output_put(&handle, throttle_event);
5258 perf_event__output_id_sample(event, &handle, &sample);
5259 perf_output_end(&handle);
5263 * Generic event overflow handling, sampling.
5266 static int __perf_event_overflow(struct perf_event *event,
5267 int throttle, struct perf_sample_data *data,
5268 struct pt_regs *regs)
5270 int events = atomic_read(&event->event_limit);
5271 struct hw_perf_event *hwc = &event->hw;
5276 * Non-sampling counters might still use the PMI to fold short
5277 * hardware counters, ignore those.
5279 if (unlikely(!is_sampling_event(event)))
5282 seq = __this_cpu_read(perf_throttled_seq);
5283 if (seq != hwc->interrupts_seq) {
5284 hwc->interrupts_seq = seq;
5285 hwc->interrupts = 1;
5288 if (unlikely(throttle
5289 && hwc->interrupts >= max_samples_per_tick)) {
5290 __this_cpu_inc(perf_throttled_count);
5291 hwc->interrupts = MAX_INTERRUPTS;
5292 perf_log_throttle(event, 0);
5293 tick_nohz_full_kick();
5298 if (event->attr.freq) {
5299 u64 now = perf_clock();
5300 s64 delta = now - hwc->freq_time_stamp;
5302 hwc->freq_time_stamp = now;
5304 if (delta > 0 && delta < 2*TICK_NSEC)
5305 perf_adjust_period(event, delta, hwc->last_period, true);
5309 * XXX event_limit might not quite work as expected on inherited
5313 event->pending_kill = POLL_IN;
5314 if (events && atomic_dec_and_test(&event->event_limit)) {
5316 event->pending_kill = POLL_HUP;
5317 event->pending_disable = 1;
5318 irq_work_queue(&event->pending);
5321 if (event->overflow_handler)
5322 event->overflow_handler(event, data, regs);
5324 perf_event_output(event, data, regs);
5326 if (event->fasync && event->pending_kill) {
5327 event->pending_wakeup = 1;
5328 irq_work_queue(&event->pending);
5334 int perf_event_overflow(struct perf_event *event,
5335 struct perf_sample_data *data,
5336 struct pt_regs *regs)
5338 return __perf_event_overflow(event, 1, data, regs);
5342 * Generic software event infrastructure
5345 struct swevent_htable {
5346 struct swevent_hlist *swevent_hlist;
5347 struct mutex hlist_mutex;
5350 /* Recursion avoidance in each contexts */
5351 int recursion[PERF_NR_CONTEXTS];
5354 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
5357 * We directly increment event->count and keep a second value in
5358 * event->hw.period_left to count intervals. This period event
5359 * is kept in the range [-sample_period, 0] so that we can use the
5363 u64 perf_swevent_set_period(struct perf_event *event)
5365 struct hw_perf_event *hwc = &event->hw;
5366 u64 period = hwc->last_period;
5370 hwc->last_period = hwc->sample_period;
5373 old = val = local64_read(&hwc->period_left);
5377 nr = div64_u64(period + val, period);
5378 offset = nr * period;
5380 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
5386 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
5387 struct perf_sample_data *data,
5388 struct pt_regs *regs)
5390 struct hw_perf_event *hwc = &event->hw;
5394 overflow = perf_swevent_set_period(event);
5396 if (hwc->interrupts == MAX_INTERRUPTS)
5399 for (; overflow; overflow--) {
5400 if (__perf_event_overflow(event, throttle,
5403 * We inhibit the overflow from happening when
5404 * hwc->interrupts == MAX_INTERRUPTS.
5412 static void perf_swevent_event(struct perf_event *event, u64 nr,
5413 struct perf_sample_data *data,
5414 struct pt_regs *regs)
5416 struct hw_perf_event *hwc = &event->hw;
5418 local64_add(nr, &event->count);
5423 if (!is_sampling_event(event))
5426 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
5428 return perf_swevent_overflow(event, 1, data, regs);
5430 data->period = event->hw.last_period;
5432 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
5433 return perf_swevent_overflow(event, 1, data, regs);
5435 if (local64_add_negative(nr, &hwc->period_left))
5438 perf_swevent_overflow(event, 0, data, regs);
5441 static int perf_exclude_event(struct perf_event *event,
5442 struct pt_regs *regs)
5444 if (event->hw.state & PERF_HES_STOPPED)
5448 if (event->attr.exclude_user && user_mode(regs))
5451 if (event->attr.exclude_kernel && !user_mode(regs))
5458 static int perf_swevent_match(struct perf_event *event,
5459 enum perf_type_id type,
5461 struct perf_sample_data *data,
5462 struct pt_regs *regs)
5464 if (event->attr.type != type)
5467 if (event->attr.config != event_id)
5470 if (perf_exclude_event(event, regs))
5476 static inline u64 swevent_hash(u64 type, u32 event_id)
5478 u64 val = event_id | (type << 32);
5480 return hash_64(val, SWEVENT_HLIST_BITS);
5483 static inline struct hlist_head *
5484 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
5486 u64 hash = swevent_hash(type, event_id);
5488 return &hlist->heads[hash];
5491 /* For the read side: events when they trigger */
5492 static inline struct hlist_head *
5493 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
5495 struct swevent_hlist *hlist;
5497 hlist = rcu_dereference(swhash->swevent_hlist);
5501 return __find_swevent_head(hlist, type, event_id);
5504 /* For the event head insertion and removal in the hlist */
5505 static inline struct hlist_head *
5506 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
5508 struct swevent_hlist *hlist;
5509 u32 event_id = event->attr.config;
5510 u64 type = event->attr.type;
5513 * Event scheduling is always serialized against hlist allocation
5514 * and release. Which makes the protected version suitable here.
5515 * The context lock guarantees that.
5517 hlist = rcu_dereference_protected(swhash->swevent_hlist,
5518 lockdep_is_held(&event->ctx->lock));
5522 return __find_swevent_head(hlist, type, event_id);
5525 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
5527 struct perf_sample_data *data,
5528 struct pt_regs *regs)
5530 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5531 struct perf_event *event;
5532 struct hlist_head *head;
5535 head = find_swevent_head_rcu(swhash, type, event_id);
5539 hlist_for_each_entry_rcu(event, head, hlist_entry) {
5540 if (perf_swevent_match(event, type, event_id, data, regs))
5541 perf_swevent_event(event, nr, data, regs);
5547 int perf_swevent_get_recursion_context(void)
5549 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5551 return get_recursion_context(swhash->recursion);
5553 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
5555 inline void perf_swevent_put_recursion_context(int rctx)
5557 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5559 put_recursion_context(swhash->recursion, rctx);
5562 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
5564 struct perf_sample_data data;
5567 preempt_disable_notrace();
5568 rctx = perf_swevent_get_recursion_context();
5572 perf_sample_data_init(&data, addr, 0);
5574 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
5576 perf_swevent_put_recursion_context(rctx);
5577 preempt_enable_notrace();
5580 static void perf_swevent_read(struct perf_event *event)
5584 static int perf_swevent_add(struct perf_event *event, int flags)
5586 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5587 struct hw_perf_event *hwc = &event->hw;
5588 struct hlist_head *head;
5590 if (is_sampling_event(event)) {
5591 hwc->last_period = hwc->sample_period;
5592 perf_swevent_set_period(event);
5595 hwc->state = !(flags & PERF_EF_START);
5597 head = find_swevent_head(swhash, event);
5598 if (WARN_ON_ONCE(!head))
5601 hlist_add_head_rcu(&event->hlist_entry, head);
5606 static void perf_swevent_del(struct perf_event *event, int flags)
5608 hlist_del_rcu(&event->hlist_entry);
5611 static void perf_swevent_start(struct perf_event *event, int flags)
5613 event->hw.state = 0;
5616 static void perf_swevent_stop(struct perf_event *event, int flags)
5618 event->hw.state = PERF_HES_STOPPED;
5621 /* Deref the hlist from the update side */
5622 static inline struct swevent_hlist *
5623 swevent_hlist_deref(struct swevent_htable *swhash)
5625 return rcu_dereference_protected(swhash->swevent_hlist,
5626 lockdep_is_held(&swhash->hlist_mutex));
5629 static void swevent_hlist_release(struct swevent_htable *swhash)
5631 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
5636 rcu_assign_pointer(swhash->swevent_hlist, NULL);
5637 kfree_rcu(hlist, rcu_head);
5640 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
5642 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5644 mutex_lock(&swhash->hlist_mutex);
5646 if (!--swhash->hlist_refcount)
5647 swevent_hlist_release(swhash);
5649 mutex_unlock(&swhash->hlist_mutex);
5652 static void swevent_hlist_put(struct perf_event *event)
5656 if (event->cpu != -1) {
5657 swevent_hlist_put_cpu(event, event->cpu);
5661 for_each_possible_cpu(cpu)
5662 swevent_hlist_put_cpu(event, cpu);
5665 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
5667 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5670 mutex_lock(&swhash->hlist_mutex);
5672 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
5673 struct swevent_hlist *hlist;
5675 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
5680 rcu_assign_pointer(swhash->swevent_hlist, hlist);
5682 swhash->hlist_refcount++;
5684 mutex_unlock(&swhash->hlist_mutex);
5689 static int swevent_hlist_get(struct perf_event *event)
5692 int cpu, failed_cpu;
5694 if (event->cpu != -1)
5695 return swevent_hlist_get_cpu(event, event->cpu);
5698 for_each_possible_cpu(cpu) {
5699 err = swevent_hlist_get_cpu(event, cpu);
5709 for_each_possible_cpu(cpu) {
5710 if (cpu == failed_cpu)
5712 swevent_hlist_put_cpu(event, cpu);
5719 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
5721 static void sw_perf_event_destroy(struct perf_event *event)
5723 u64 event_id = event->attr.config;
5725 WARN_ON(event->parent);
5727 static_key_slow_dec(&perf_swevent_enabled[event_id]);
5728 swevent_hlist_put(event);
5731 static int perf_swevent_init(struct perf_event *event)
5733 u64 event_id = event->attr.config;
5735 if (event->attr.type != PERF_TYPE_SOFTWARE)
5739 * no branch sampling for software events
5741 if (has_branch_stack(event))
5745 case PERF_COUNT_SW_CPU_CLOCK:
5746 case PERF_COUNT_SW_TASK_CLOCK:
5753 if (event_id >= PERF_COUNT_SW_MAX)
5756 if (!event->parent) {
5759 err = swevent_hlist_get(event);
5763 static_key_slow_inc(&perf_swevent_enabled[event_id]);
5764 event->destroy = sw_perf_event_destroy;
5770 static int perf_swevent_event_idx(struct perf_event *event)
5775 static struct pmu perf_swevent = {
5776 .task_ctx_nr = perf_sw_context,
5778 .event_init = perf_swevent_init,
5779 .add = perf_swevent_add,
5780 .del = perf_swevent_del,
5781 .start = perf_swevent_start,
5782 .stop = perf_swevent_stop,
5783 .read = perf_swevent_read,
5785 .event_idx = perf_swevent_event_idx,
5788 #ifdef CONFIG_EVENT_TRACING
5790 static int perf_tp_filter_match(struct perf_event *event,
5791 struct perf_sample_data *data)
5793 void *record = data->raw->data;
5795 if (likely(!event->filter) || filter_match_preds(event->filter, record))
5800 static int perf_tp_event_match(struct perf_event *event,
5801 struct perf_sample_data *data,
5802 struct pt_regs *regs)
5804 if (event->hw.state & PERF_HES_STOPPED)
5807 * All tracepoints are from kernel-space.
5809 if (event->attr.exclude_kernel)
5812 if (!perf_tp_filter_match(event, data))
5818 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
5819 struct pt_regs *regs, struct hlist_head *head, int rctx,
5820 struct task_struct *task)
5822 struct perf_sample_data data;
5823 struct perf_event *event;
5825 struct perf_raw_record raw = {
5830 perf_sample_data_init(&data, addr, 0);
5833 hlist_for_each_entry_rcu(event, head, hlist_entry) {
5834 if (perf_tp_event_match(event, &data, regs))
5835 perf_swevent_event(event, count, &data, regs);
5839 * If we got specified a target task, also iterate its context and
5840 * deliver this event there too.
5842 if (task && task != current) {
5843 struct perf_event_context *ctx;
5844 struct trace_entry *entry = record;
5847 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
5851 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5852 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5854 if (event->attr.config != entry->type)
5856 if (perf_tp_event_match(event, &data, regs))
5857 perf_swevent_event(event, count, &data, regs);
5863 perf_swevent_put_recursion_context(rctx);
5865 EXPORT_SYMBOL_GPL(perf_tp_event);
5867 static void tp_perf_event_destroy(struct perf_event *event)
5869 perf_trace_destroy(event);
5872 static int perf_tp_event_init(struct perf_event *event)
5876 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5880 * no branch sampling for tracepoint events
5882 if (has_branch_stack(event))
5885 err = perf_trace_init(event);
5889 event->destroy = tp_perf_event_destroy;
5894 static struct pmu perf_tracepoint = {
5895 .task_ctx_nr = perf_sw_context,
5897 .event_init = perf_tp_event_init,
5898 .add = perf_trace_add,
5899 .del = perf_trace_del,
5900 .start = perf_swevent_start,
5901 .stop = perf_swevent_stop,
5902 .read = perf_swevent_read,
5904 .event_idx = perf_swevent_event_idx,
5907 static inline void perf_tp_register(void)
5909 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
5912 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
5917 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5920 filter_str = strndup_user(arg, PAGE_SIZE);
5921 if (IS_ERR(filter_str))
5922 return PTR_ERR(filter_str);
5924 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
5930 static void perf_event_free_filter(struct perf_event *event)
5932 ftrace_profile_free_filter(event);
5937 static inline void perf_tp_register(void)
5941 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
5946 static void perf_event_free_filter(struct perf_event *event)
5950 #endif /* CONFIG_EVENT_TRACING */
5952 #ifdef CONFIG_HAVE_HW_BREAKPOINT
5953 void perf_bp_event(struct perf_event *bp, void *data)
5955 struct perf_sample_data sample;
5956 struct pt_regs *regs = data;
5958 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
5960 if (!bp->hw.state && !perf_exclude_event(bp, regs))
5961 perf_swevent_event(bp, 1, &sample, regs);
5966 * hrtimer based swevent callback
5969 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
5971 enum hrtimer_restart ret = HRTIMER_RESTART;
5972 struct perf_sample_data data;
5973 struct pt_regs *regs;
5974 struct perf_event *event;
5977 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
5979 if (event->state != PERF_EVENT_STATE_ACTIVE)
5980 return HRTIMER_NORESTART;
5982 event->pmu->read(event);
5984 perf_sample_data_init(&data, 0, event->hw.last_period);
5985 regs = get_irq_regs();
5987 if (regs && !perf_exclude_event(event, regs)) {
5988 if (!(event->attr.exclude_idle && is_idle_task(current)))
5989 if (__perf_event_overflow(event, 1, &data, regs))
5990 ret = HRTIMER_NORESTART;
5993 period = max_t(u64, 10000, event->hw.sample_period);
5994 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
5999 static void perf_swevent_start_hrtimer(struct perf_event *event)
6001 struct hw_perf_event *hwc = &event->hw;
6004 if (!is_sampling_event(event))
6007 period = local64_read(&hwc->period_left);
6012 local64_set(&hwc->period_left, 0);
6014 period = max_t(u64, 10000, hwc->sample_period);
6016 __hrtimer_start_range_ns(&hwc->hrtimer,
6017 ns_to_ktime(period), 0,
6018 HRTIMER_MODE_REL_PINNED, 0);
6021 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
6023 struct hw_perf_event *hwc = &event->hw;
6025 if (is_sampling_event(event)) {
6026 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
6027 local64_set(&hwc->period_left, ktime_to_ns(remaining));
6029 hrtimer_cancel(&hwc->hrtimer);
6033 static void perf_swevent_init_hrtimer(struct perf_event *event)
6035 struct hw_perf_event *hwc = &event->hw;
6037 if (!is_sampling_event(event))
6040 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6041 hwc->hrtimer.function = perf_swevent_hrtimer;
6044 * Since hrtimers have a fixed rate, we can do a static freq->period
6045 * mapping and avoid the whole period adjust feedback stuff.
6047 if (event->attr.freq) {
6048 long freq = event->attr.sample_freq;
6050 event->attr.sample_period = NSEC_PER_SEC / freq;
6051 hwc->sample_period = event->attr.sample_period;
6052 local64_set(&hwc->period_left, hwc->sample_period);
6053 hwc->last_period = hwc->sample_period;
6054 event->attr.freq = 0;
6059 * Software event: cpu wall time clock
6062 static void cpu_clock_event_update(struct perf_event *event)
6067 now = local_clock();
6068 prev = local64_xchg(&event->hw.prev_count, now);
6069 local64_add(now - prev, &event->count);
6072 static void cpu_clock_event_start(struct perf_event *event, int flags)
6074 local64_set(&event->hw.prev_count, local_clock());
6075 perf_swevent_start_hrtimer(event);
6078 static void cpu_clock_event_stop(struct perf_event *event, int flags)
6080 perf_swevent_cancel_hrtimer(event);
6081 cpu_clock_event_update(event);
6084 static int cpu_clock_event_add(struct perf_event *event, int flags)
6086 if (flags & PERF_EF_START)
6087 cpu_clock_event_start(event, flags);
6092 static void cpu_clock_event_del(struct perf_event *event, int flags)
6094 cpu_clock_event_stop(event, flags);
6097 static void cpu_clock_event_read(struct perf_event *event)
6099 cpu_clock_event_update(event);
6102 static int cpu_clock_event_init(struct perf_event *event)
6104 if (event->attr.type != PERF_TYPE_SOFTWARE)
6107 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
6111 * no branch sampling for software events
6113 if (has_branch_stack(event))
6116 perf_swevent_init_hrtimer(event);
6121 static struct pmu perf_cpu_clock = {
6122 .task_ctx_nr = perf_sw_context,
6124 .event_init = cpu_clock_event_init,
6125 .add = cpu_clock_event_add,
6126 .del = cpu_clock_event_del,
6127 .start = cpu_clock_event_start,
6128 .stop = cpu_clock_event_stop,
6129 .read = cpu_clock_event_read,
6131 .event_idx = perf_swevent_event_idx,
6135 * Software event: task time clock
6138 static void task_clock_event_update(struct perf_event *event, u64 now)
6143 prev = local64_xchg(&event->hw.prev_count, now);
6145 local64_add(delta, &event->count);
6148 static void task_clock_event_start(struct perf_event *event, int flags)
6150 local64_set(&event->hw.prev_count, event->ctx->time);
6151 perf_swevent_start_hrtimer(event);
6154 static void task_clock_event_stop(struct perf_event *event, int flags)
6156 perf_swevent_cancel_hrtimer(event);
6157 task_clock_event_update(event, event->ctx->time);
6160 static int task_clock_event_add(struct perf_event *event, int flags)
6162 if (flags & PERF_EF_START)
6163 task_clock_event_start(event, flags);
6168 static void task_clock_event_del(struct perf_event *event, int flags)
6170 task_clock_event_stop(event, PERF_EF_UPDATE);
6173 static void task_clock_event_read(struct perf_event *event)
6175 u64 now = perf_clock();
6176 u64 delta = now - event->ctx->timestamp;
6177 u64 time = event->ctx->time + delta;
6179 task_clock_event_update(event, time);
6182 static int task_clock_event_init(struct perf_event *event)
6184 if (event->attr.type != PERF_TYPE_SOFTWARE)
6187 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
6191 * no branch sampling for software events
6193 if (has_branch_stack(event))
6196 perf_swevent_init_hrtimer(event);
6201 static struct pmu perf_task_clock = {
6202 .task_ctx_nr = perf_sw_context,
6204 .event_init = task_clock_event_init,
6205 .add = task_clock_event_add,
6206 .del = task_clock_event_del,
6207 .start = task_clock_event_start,
6208 .stop = task_clock_event_stop,
6209 .read = task_clock_event_read,
6211 .event_idx = perf_swevent_event_idx,
6214 static void perf_pmu_nop_void(struct pmu *pmu)
6218 static int perf_pmu_nop_int(struct pmu *pmu)
6223 static void perf_pmu_start_txn(struct pmu *pmu)
6225 perf_pmu_disable(pmu);
6228 static int perf_pmu_commit_txn(struct pmu *pmu)
6230 perf_pmu_enable(pmu);
6234 static void perf_pmu_cancel_txn(struct pmu *pmu)
6236 perf_pmu_enable(pmu);
6239 static int perf_event_idx_default(struct perf_event *event)
6241 return event->hw.idx + 1;
6245 * Ensures all contexts with the same task_ctx_nr have the same
6246 * pmu_cpu_context too.
6248 static void *find_pmu_context(int ctxn)
6255 list_for_each_entry(pmu, &pmus, entry) {
6256 if (pmu->task_ctx_nr == ctxn)
6257 return pmu->pmu_cpu_context;
6263 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
6267 for_each_possible_cpu(cpu) {
6268 struct perf_cpu_context *cpuctx;
6270 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6272 if (cpuctx->unique_pmu == old_pmu)
6273 cpuctx->unique_pmu = pmu;
6277 static void free_pmu_context(struct pmu *pmu)
6281 mutex_lock(&pmus_lock);
6283 * Like a real lame refcount.
6285 list_for_each_entry(i, &pmus, entry) {
6286 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
6287 update_pmu_context(i, pmu);
6292 free_percpu(pmu->pmu_cpu_context);
6294 mutex_unlock(&pmus_lock);
6296 static struct idr pmu_idr;
6299 type_show(struct device *dev, struct device_attribute *attr, char *page)
6301 struct pmu *pmu = dev_get_drvdata(dev);
6303 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
6307 perf_event_mux_interval_ms_show(struct device *dev,
6308 struct device_attribute *attr,
6311 struct pmu *pmu = dev_get_drvdata(dev);
6313 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
6317 perf_event_mux_interval_ms_store(struct device *dev,
6318 struct device_attribute *attr,
6319 const char *buf, size_t count)
6321 struct pmu *pmu = dev_get_drvdata(dev);
6322 int timer, cpu, ret;
6324 ret = kstrtoint(buf, 0, &timer);
6331 /* same value, noting to do */
6332 if (timer == pmu->hrtimer_interval_ms)
6335 pmu->hrtimer_interval_ms = timer;
6337 /* update all cpuctx for this PMU */
6338 for_each_possible_cpu(cpu) {
6339 struct perf_cpu_context *cpuctx;
6340 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6341 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
6343 if (hrtimer_active(&cpuctx->hrtimer))
6344 hrtimer_forward_now(&cpuctx->hrtimer, cpuctx->hrtimer_interval);
6350 static struct device_attribute pmu_dev_attrs[] = {
6352 __ATTR_RW(perf_event_mux_interval_ms),
6356 static int pmu_bus_running;
6357 static struct bus_type pmu_bus = {
6358 .name = "event_source",
6359 .dev_attrs = pmu_dev_attrs,
6362 static void pmu_dev_release(struct device *dev)
6367 static int pmu_dev_alloc(struct pmu *pmu)
6371 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
6375 pmu->dev->groups = pmu->attr_groups;
6376 device_initialize(pmu->dev);
6377 ret = dev_set_name(pmu->dev, "%s", pmu->name);
6381 dev_set_drvdata(pmu->dev, pmu);
6382 pmu->dev->bus = &pmu_bus;
6383 pmu->dev->release = pmu_dev_release;
6384 ret = device_add(pmu->dev);
6392 put_device(pmu->dev);
6396 static struct lock_class_key cpuctx_mutex;
6397 static struct lock_class_key cpuctx_lock;
6399 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
6403 mutex_lock(&pmus_lock);
6405 pmu->pmu_disable_count = alloc_percpu(int);
6406 if (!pmu->pmu_disable_count)
6415 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
6423 if (pmu_bus_running) {
6424 ret = pmu_dev_alloc(pmu);
6430 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
6431 if (pmu->pmu_cpu_context)
6432 goto got_cpu_context;
6435 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
6436 if (!pmu->pmu_cpu_context)
6439 for_each_possible_cpu(cpu) {
6440 struct perf_cpu_context *cpuctx;
6442 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6443 __perf_event_init_context(&cpuctx->ctx);
6444 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
6445 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
6446 cpuctx->ctx.type = cpu_context;
6447 cpuctx->ctx.pmu = pmu;
6449 __perf_cpu_hrtimer_init(cpuctx, cpu);
6451 INIT_LIST_HEAD(&cpuctx->rotation_list);
6452 cpuctx->unique_pmu = pmu;
6456 if (!pmu->start_txn) {
6457 if (pmu->pmu_enable) {
6459 * If we have pmu_enable/pmu_disable calls, install
6460 * transaction stubs that use that to try and batch
6461 * hardware accesses.
6463 pmu->start_txn = perf_pmu_start_txn;
6464 pmu->commit_txn = perf_pmu_commit_txn;
6465 pmu->cancel_txn = perf_pmu_cancel_txn;
6467 pmu->start_txn = perf_pmu_nop_void;
6468 pmu->commit_txn = perf_pmu_nop_int;
6469 pmu->cancel_txn = perf_pmu_nop_void;
6473 if (!pmu->pmu_enable) {
6474 pmu->pmu_enable = perf_pmu_nop_void;
6475 pmu->pmu_disable = perf_pmu_nop_void;
6478 if (!pmu->event_idx)
6479 pmu->event_idx = perf_event_idx_default;
6481 list_add_rcu(&pmu->entry, &pmus);
6484 mutex_unlock(&pmus_lock);
6489 device_del(pmu->dev);
6490 put_device(pmu->dev);
6493 if (pmu->type >= PERF_TYPE_MAX)
6494 idr_remove(&pmu_idr, pmu->type);
6497 free_percpu(pmu->pmu_disable_count);
6501 void perf_pmu_unregister(struct pmu *pmu)
6503 mutex_lock(&pmus_lock);
6504 list_del_rcu(&pmu->entry);
6505 mutex_unlock(&pmus_lock);
6508 * We dereference the pmu list under both SRCU and regular RCU, so
6509 * synchronize against both of those.
6511 synchronize_srcu(&pmus_srcu);
6514 free_percpu(pmu->pmu_disable_count);
6515 if (pmu->type >= PERF_TYPE_MAX)
6516 idr_remove(&pmu_idr, pmu->type);
6517 device_del(pmu->dev);
6518 put_device(pmu->dev);
6519 free_pmu_context(pmu);
6522 struct pmu *perf_init_event(struct perf_event *event)
6524 struct pmu *pmu = NULL;
6528 idx = srcu_read_lock(&pmus_srcu);
6531 pmu = idr_find(&pmu_idr, event->attr.type);
6535 ret = pmu->event_init(event);
6541 list_for_each_entry_rcu(pmu, &pmus, entry) {
6543 ret = pmu->event_init(event);
6547 if (ret != -ENOENT) {
6552 pmu = ERR_PTR(-ENOENT);
6554 srcu_read_unlock(&pmus_srcu, idx);
6559 static void account_event_cpu(struct perf_event *event, int cpu)
6564 if (has_branch_stack(event)) {
6565 if (!(event->attach_state & PERF_ATTACH_TASK))
6566 atomic_inc(&per_cpu(perf_branch_stack_events, cpu));
6568 if (is_cgroup_event(event))
6569 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
6572 static void account_event(struct perf_event *event)
6577 if (event->attach_state & PERF_ATTACH_TASK)
6578 static_key_slow_inc(&perf_sched_events.key);
6579 if (event->attr.mmap || event->attr.mmap_data)
6580 atomic_inc(&nr_mmap_events);
6581 if (event->attr.comm)
6582 atomic_inc(&nr_comm_events);
6583 if (event->attr.task)
6584 atomic_inc(&nr_task_events);
6585 if (event->attr.freq) {
6586 if (atomic_inc_return(&nr_freq_events) == 1)
6587 tick_nohz_full_kick_all();
6589 if (has_branch_stack(event))
6590 static_key_slow_inc(&perf_sched_events.key);
6591 if (is_cgroup_event(event))
6592 static_key_slow_inc(&perf_sched_events.key);
6594 account_event_cpu(event, event->cpu);
6598 * Allocate and initialize a event structure
6600 static struct perf_event *
6601 perf_event_alloc(struct perf_event_attr *attr, int cpu,
6602 struct task_struct *task,
6603 struct perf_event *group_leader,
6604 struct perf_event *parent_event,
6605 perf_overflow_handler_t overflow_handler,
6609 struct perf_event *event;
6610 struct hw_perf_event *hwc;
6613 if ((unsigned)cpu >= nr_cpu_ids) {
6614 if (!task || cpu != -1)
6615 return ERR_PTR(-EINVAL);
6618 event = kzalloc(sizeof(*event), GFP_KERNEL);
6620 return ERR_PTR(-ENOMEM);
6623 * Single events are their own group leaders, with an
6624 * empty sibling list:
6627 group_leader = event;
6629 mutex_init(&event->child_mutex);
6630 INIT_LIST_HEAD(&event->child_list);
6632 INIT_LIST_HEAD(&event->group_entry);
6633 INIT_LIST_HEAD(&event->event_entry);
6634 INIT_LIST_HEAD(&event->sibling_list);
6635 INIT_LIST_HEAD(&event->rb_entry);
6637 init_waitqueue_head(&event->waitq);
6638 init_irq_work(&event->pending, perf_pending_event);
6640 mutex_init(&event->mmap_mutex);
6642 atomic_long_set(&event->refcount, 1);
6644 event->attr = *attr;
6645 event->group_leader = group_leader;
6649 event->parent = parent_event;
6651 event->ns = get_pid_ns(task_active_pid_ns(current));
6652 event->id = atomic64_inc_return(&perf_event_id);
6654 event->state = PERF_EVENT_STATE_INACTIVE;
6657 event->attach_state = PERF_ATTACH_TASK;
6659 if (attr->type == PERF_TYPE_TRACEPOINT)
6660 event->hw.tp_target = task;
6661 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6663 * hw_breakpoint is a bit difficult here..
6665 else if (attr->type == PERF_TYPE_BREAKPOINT)
6666 event->hw.bp_target = task;
6670 if (!overflow_handler && parent_event) {
6671 overflow_handler = parent_event->overflow_handler;
6672 context = parent_event->overflow_handler_context;
6675 event->overflow_handler = overflow_handler;
6676 event->overflow_handler_context = context;
6678 perf_event__state_init(event);
6683 hwc->sample_period = attr->sample_period;
6684 if (attr->freq && attr->sample_freq)
6685 hwc->sample_period = 1;
6686 hwc->last_period = hwc->sample_period;
6688 local64_set(&hwc->period_left, hwc->sample_period);
6691 * we currently do not support PERF_FORMAT_GROUP on inherited events
6693 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
6696 pmu = perf_init_event(event);
6699 else if (IS_ERR(pmu)) {
6704 if (!event->parent) {
6705 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
6706 err = get_callchain_buffers();
6716 event->destroy(event);
6719 put_pid_ns(event->ns);
6722 return ERR_PTR(err);
6725 static int perf_copy_attr(struct perf_event_attr __user *uattr,
6726 struct perf_event_attr *attr)
6731 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
6735 * zero the full structure, so that a short copy will be nice.
6737 memset(attr, 0, sizeof(*attr));
6739 ret = get_user(size, &uattr->size);
6743 if (size > PAGE_SIZE) /* silly large */
6746 if (!size) /* abi compat */
6747 size = PERF_ATTR_SIZE_VER0;
6749 if (size < PERF_ATTR_SIZE_VER0)
6753 * If we're handed a bigger struct than we know of,
6754 * ensure all the unknown bits are 0 - i.e. new
6755 * user-space does not rely on any kernel feature
6756 * extensions we dont know about yet.
6758 if (size > sizeof(*attr)) {
6759 unsigned char __user *addr;
6760 unsigned char __user *end;
6763 addr = (void __user *)uattr + sizeof(*attr);
6764 end = (void __user *)uattr + size;
6766 for (; addr < end; addr++) {
6767 ret = get_user(val, addr);
6773 size = sizeof(*attr);
6776 ret = copy_from_user(attr, uattr, size);
6780 /* disabled for now */
6784 if (attr->__reserved_1)
6787 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
6790 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
6793 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
6794 u64 mask = attr->branch_sample_type;
6796 /* only using defined bits */
6797 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
6800 /* at least one branch bit must be set */
6801 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
6804 /* propagate priv level, when not set for branch */
6805 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
6807 /* exclude_kernel checked on syscall entry */
6808 if (!attr->exclude_kernel)
6809 mask |= PERF_SAMPLE_BRANCH_KERNEL;
6811 if (!attr->exclude_user)
6812 mask |= PERF_SAMPLE_BRANCH_USER;
6814 if (!attr->exclude_hv)
6815 mask |= PERF_SAMPLE_BRANCH_HV;
6817 * adjust user setting (for HW filter setup)
6819 attr->branch_sample_type = mask;
6821 /* privileged levels capture (kernel, hv): check permissions */
6822 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
6823 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
6827 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
6828 ret = perf_reg_validate(attr->sample_regs_user);
6833 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
6834 if (!arch_perf_have_user_stack_dump())
6838 * We have __u32 type for the size, but so far
6839 * we can only use __u16 as maximum due to the
6840 * __u16 sample size limit.
6842 if (attr->sample_stack_user >= USHRT_MAX)
6844 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
6852 put_user(sizeof(*attr), &uattr->size);
6858 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
6860 struct ring_buffer *rb = NULL, *old_rb = NULL;
6866 /* don't allow circular references */
6867 if (event == output_event)
6871 * Don't allow cross-cpu buffers
6873 if (output_event->cpu != event->cpu)
6877 * If its not a per-cpu rb, it must be the same task.
6879 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
6883 mutex_lock(&event->mmap_mutex);
6884 /* Can't redirect output if we've got an active mmap() */
6885 if (atomic_read(&event->mmap_count))
6891 /* get the rb we want to redirect to */
6892 rb = ring_buffer_get(output_event);
6898 ring_buffer_detach(event, old_rb);
6901 ring_buffer_attach(event, rb);
6903 rcu_assign_pointer(event->rb, rb);
6906 ring_buffer_put(old_rb);
6908 * Since we detached before setting the new rb, so that we
6909 * could attach the new rb, we could have missed a wakeup.
6912 wake_up_all(&event->waitq);
6917 mutex_unlock(&event->mmap_mutex);
6924 * sys_perf_event_open - open a performance event, associate it to a task/cpu
6926 * @attr_uptr: event_id type attributes for monitoring/sampling
6929 * @group_fd: group leader event fd
6931 SYSCALL_DEFINE5(perf_event_open,
6932 struct perf_event_attr __user *, attr_uptr,
6933 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
6935 struct perf_event *group_leader = NULL, *output_event = NULL;
6936 struct perf_event *event, *sibling;
6937 struct perf_event_attr attr;
6938 struct perf_event_context *ctx;
6939 struct file *event_file = NULL;
6940 struct fd group = {NULL, 0};
6941 struct task_struct *task = NULL;
6947 /* for future expandability... */
6948 if (flags & ~PERF_FLAG_ALL)
6951 err = perf_copy_attr(attr_uptr, &attr);
6955 if (!attr.exclude_kernel) {
6956 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
6961 if (attr.sample_freq > sysctl_perf_event_sample_rate)
6966 * In cgroup mode, the pid argument is used to pass the fd
6967 * opened to the cgroup directory in cgroupfs. The cpu argument
6968 * designates the cpu on which to monitor threads from that
6971 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
6974 event_fd = get_unused_fd();
6978 if (group_fd != -1) {
6979 err = perf_fget_light(group_fd, &group);
6982 group_leader = group.file->private_data;
6983 if (flags & PERF_FLAG_FD_OUTPUT)
6984 output_event = group_leader;
6985 if (flags & PERF_FLAG_FD_NO_GROUP)
6986 group_leader = NULL;
6989 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
6990 task = find_lively_task_by_vpid(pid);
6992 err = PTR_ERR(task);
6999 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
7001 if (IS_ERR(event)) {
7002 err = PTR_ERR(event);
7006 if (flags & PERF_FLAG_PID_CGROUP) {
7007 err = perf_cgroup_connect(pid, event, &attr, group_leader);
7009 __free_event(event);
7014 account_event(event);
7017 * Special case software events and allow them to be part of
7018 * any hardware group.
7023 (is_software_event(event) != is_software_event(group_leader))) {
7024 if (is_software_event(event)) {
7026 * If event and group_leader are not both a software
7027 * event, and event is, then group leader is not.
7029 * Allow the addition of software events to !software
7030 * groups, this is safe because software events never
7033 pmu = group_leader->pmu;
7034 } else if (is_software_event(group_leader) &&
7035 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
7037 * In case the group is a pure software group, and we
7038 * try to add a hardware event, move the whole group to
7039 * the hardware context.
7046 * Get the target context (task or percpu):
7048 ctx = find_get_context(pmu, task, event->cpu);
7055 put_task_struct(task);
7060 * Look up the group leader (we will attach this event to it):
7066 * Do not allow a recursive hierarchy (this new sibling
7067 * becoming part of another group-sibling):
7069 if (group_leader->group_leader != group_leader)
7072 * Do not allow to attach to a group in a different
7073 * task or CPU context:
7076 if (group_leader->ctx->type != ctx->type)
7079 if (group_leader->ctx != ctx)
7084 * Only a group leader can be exclusive or pinned
7086 if (attr.exclusive || attr.pinned)
7091 err = perf_event_set_output(event, output_event);
7096 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, O_RDWR);
7097 if (IS_ERR(event_file)) {
7098 err = PTR_ERR(event_file);
7103 struct perf_event_context *gctx = group_leader->ctx;
7105 mutex_lock(&gctx->mutex);
7106 perf_remove_from_context(group_leader);
7109 * Removing from the context ends up with disabled
7110 * event. What we want here is event in the initial
7111 * startup state, ready to be add into new context.
7113 perf_event__state_init(group_leader);
7114 list_for_each_entry(sibling, &group_leader->sibling_list,
7116 perf_remove_from_context(sibling);
7117 perf_event__state_init(sibling);
7120 mutex_unlock(&gctx->mutex);
7124 WARN_ON_ONCE(ctx->parent_ctx);
7125 mutex_lock(&ctx->mutex);
7129 perf_install_in_context(ctx, group_leader, event->cpu);
7131 list_for_each_entry(sibling, &group_leader->sibling_list,
7133 perf_install_in_context(ctx, sibling, event->cpu);
7138 perf_install_in_context(ctx, event, event->cpu);
7140 perf_unpin_context(ctx);
7141 mutex_unlock(&ctx->mutex);
7145 event->owner = current;
7147 mutex_lock(¤t->perf_event_mutex);
7148 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
7149 mutex_unlock(¤t->perf_event_mutex);
7152 * Precalculate sample_data sizes
7154 perf_event__header_size(event);
7155 perf_event__id_header_size(event);
7158 * Drop the reference on the group_event after placing the
7159 * new event on the sibling_list. This ensures destruction
7160 * of the group leader will find the pointer to itself in
7161 * perf_group_detach().
7164 fd_install(event_fd, event_file);
7168 perf_unpin_context(ctx);
7175 put_task_struct(task);
7179 put_unused_fd(event_fd);
7184 * perf_event_create_kernel_counter
7186 * @attr: attributes of the counter to create
7187 * @cpu: cpu in which the counter is bound
7188 * @task: task to profile (NULL for percpu)
7191 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
7192 struct task_struct *task,
7193 perf_overflow_handler_t overflow_handler,
7196 struct perf_event_context *ctx;
7197 struct perf_event *event;
7201 * Get the target context (task or percpu):
7204 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
7205 overflow_handler, context);
7206 if (IS_ERR(event)) {
7207 err = PTR_ERR(event);
7211 account_event(event);
7213 ctx = find_get_context(event->pmu, task, cpu);
7219 WARN_ON_ONCE(ctx->parent_ctx);
7220 mutex_lock(&ctx->mutex);
7221 perf_install_in_context(ctx, event, cpu);
7223 perf_unpin_context(ctx);
7224 mutex_unlock(&ctx->mutex);
7231 return ERR_PTR(err);
7233 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
7235 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
7237 struct perf_event_context *src_ctx;
7238 struct perf_event_context *dst_ctx;
7239 struct perf_event *event, *tmp;
7242 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
7243 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
7245 mutex_lock(&src_ctx->mutex);
7246 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
7248 perf_remove_from_context(event);
7249 unaccount_event_cpu(event, src_cpu);
7251 list_add(&event->migrate_entry, &events);
7253 mutex_unlock(&src_ctx->mutex);
7257 mutex_lock(&dst_ctx->mutex);
7258 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
7259 list_del(&event->migrate_entry);
7260 if (event->state >= PERF_EVENT_STATE_OFF)
7261 event->state = PERF_EVENT_STATE_INACTIVE;
7262 account_event_cpu(event, dst_cpu);
7263 perf_install_in_context(dst_ctx, event, dst_cpu);
7266 mutex_unlock(&dst_ctx->mutex);
7268 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
7270 static void sync_child_event(struct perf_event *child_event,
7271 struct task_struct *child)
7273 struct perf_event *parent_event = child_event->parent;
7276 if (child_event->attr.inherit_stat)
7277 perf_event_read_event(child_event, child);
7279 child_val = perf_event_count(child_event);
7282 * Add back the child's count to the parent's count:
7284 atomic64_add(child_val, &parent_event->child_count);
7285 atomic64_add(child_event->total_time_enabled,
7286 &parent_event->child_total_time_enabled);
7287 atomic64_add(child_event->total_time_running,
7288 &parent_event->child_total_time_running);
7291 * Remove this event from the parent's list
7293 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7294 mutex_lock(&parent_event->child_mutex);
7295 list_del_init(&child_event->child_list);
7296 mutex_unlock(&parent_event->child_mutex);
7299 * Release the parent event, if this was the last
7302 put_event(parent_event);
7306 __perf_event_exit_task(struct perf_event *child_event,
7307 struct perf_event_context *child_ctx,
7308 struct task_struct *child)
7310 if (child_event->parent) {
7311 raw_spin_lock_irq(&child_ctx->lock);
7312 perf_group_detach(child_event);
7313 raw_spin_unlock_irq(&child_ctx->lock);
7316 perf_remove_from_context(child_event);
7319 * It can happen that the parent exits first, and has events
7320 * that are still around due to the child reference. These
7321 * events need to be zapped.
7323 if (child_event->parent) {
7324 sync_child_event(child_event, child);
7325 free_event(child_event);
7329 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
7331 struct perf_event *child_event, *tmp;
7332 struct perf_event_context *child_ctx;
7333 unsigned long flags;
7335 if (likely(!child->perf_event_ctxp[ctxn])) {
7336 perf_event_task(child, NULL, 0);
7340 local_irq_save(flags);
7342 * We can't reschedule here because interrupts are disabled,
7343 * and either child is current or it is a task that can't be
7344 * scheduled, so we are now safe from rescheduling changing
7347 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
7350 * Take the context lock here so that if find_get_context is
7351 * reading child->perf_event_ctxp, we wait until it has
7352 * incremented the context's refcount before we do put_ctx below.
7354 raw_spin_lock(&child_ctx->lock);
7355 task_ctx_sched_out(child_ctx);
7356 child->perf_event_ctxp[ctxn] = NULL;
7358 * If this context is a clone; unclone it so it can't get
7359 * swapped to another process while we're removing all
7360 * the events from it.
7362 unclone_ctx(child_ctx);
7363 update_context_time(child_ctx);
7364 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7367 * Report the task dead after unscheduling the events so that we
7368 * won't get any samples after PERF_RECORD_EXIT. We can however still
7369 * get a few PERF_RECORD_READ events.
7371 perf_event_task(child, child_ctx, 0);
7374 * We can recurse on the same lock type through:
7376 * __perf_event_exit_task()
7377 * sync_child_event()
7379 * mutex_lock(&ctx->mutex)
7381 * But since its the parent context it won't be the same instance.
7383 mutex_lock(&child_ctx->mutex);
7386 list_for_each_entry_safe(child_event, tmp, &child_ctx->pinned_groups,
7388 __perf_event_exit_task(child_event, child_ctx, child);
7390 list_for_each_entry_safe(child_event, tmp, &child_ctx->flexible_groups,
7392 __perf_event_exit_task(child_event, child_ctx, child);
7395 * If the last event was a group event, it will have appended all
7396 * its siblings to the list, but we obtained 'tmp' before that which
7397 * will still point to the list head terminating the iteration.
7399 if (!list_empty(&child_ctx->pinned_groups) ||
7400 !list_empty(&child_ctx->flexible_groups))
7403 mutex_unlock(&child_ctx->mutex);
7409 * When a child task exits, feed back event values to parent events.
7411 void perf_event_exit_task(struct task_struct *child)
7413 struct perf_event *event, *tmp;
7416 mutex_lock(&child->perf_event_mutex);
7417 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
7419 list_del_init(&event->owner_entry);
7422 * Ensure the list deletion is visible before we clear
7423 * the owner, closes a race against perf_release() where
7424 * we need to serialize on the owner->perf_event_mutex.
7427 event->owner = NULL;
7429 mutex_unlock(&child->perf_event_mutex);
7431 for_each_task_context_nr(ctxn)
7432 perf_event_exit_task_context(child, ctxn);
7435 static void perf_free_event(struct perf_event *event,
7436 struct perf_event_context *ctx)
7438 struct perf_event *parent = event->parent;
7440 if (WARN_ON_ONCE(!parent))
7443 mutex_lock(&parent->child_mutex);
7444 list_del_init(&event->child_list);
7445 mutex_unlock(&parent->child_mutex);
7449 perf_group_detach(event);
7450 list_del_event(event, ctx);
7455 * free an unexposed, unused context as created by inheritance by
7456 * perf_event_init_task below, used by fork() in case of fail.
7458 void perf_event_free_task(struct task_struct *task)
7460 struct perf_event_context *ctx;
7461 struct perf_event *event, *tmp;
7464 for_each_task_context_nr(ctxn) {
7465 ctx = task->perf_event_ctxp[ctxn];
7469 mutex_lock(&ctx->mutex);
7471 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
7473 perf_free_event(event, ctx);
7475 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
7477 perf_free_event(event, ctx);
7479 if (!list_empty(&ctx->pinned_groups) ||
7480 !list_empty(&ctx->flexible_groups))
7483 mutex_unlock(&ctx->mutex);
7489 void perf_event_delayed_put(struct task_struct *task)
7493 for_each_task_context_nr(ctxn)
7494 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
7498 * inherit a event from parent task to child task:
7500 static struct perf_event *
7501 inherit_event(struct perf_event *parent_event,
7502 struct task_struct *parent,
7503 struct perf_event_context *parent_ctx,
7504 struct task_struct *child,
7505 struct perf_event *group_leader,
7506 struct perf_event_context *child_ctx)
7508 struct perf_event *child_event;
7509 unsigned long flags;
7512 * Instead of creating recursive hierarchies of events,
7513 * we link inherited events back to the original parent,
7514 * which has a filp for sure, which we use as the reference
7517 if (parent_event->parent)
7518 parent_event = parent_event->parent;
7520 child_event = perf_event_alloc(&parent_event->attr,
7523 group_leader, parent_event,
7525 if (IS_ERR(child_event))
7528 if (!atomic_long_inc_not_zero(&parent_event->refcount)) {
7529 free_event(child_event);
7536 * Make the child state follow the state of the parent event,
7537 * not its attr.disabled bit. We hold the parent's mutex,
7538 * so we won't race with perf_event_{en, dis}able_family.
7540 if (parent_event->state >= PERF_EVENT_STATE_INACTIVE)
7541 child_event->state = PERF_EVENT_STATE_INACTIVE;
7543 child_event->state = PERF_EVENT_STATE_OFF;
7545 if (parent_event->attr.freq) {
7546 u64 sample_period = parent_event->hw.sample_period;
7547 struct hw_perf_event *hwc = &child_event->hw;
7549 hwc->sample_period = sample_period;
7550 hwc->last_period = sample_period;
7552 local64_set(&hwc->period_left, sample_period);
7555 child_event->ctx = child_ctx;
7556 child_event->overflow_handler = parent_event->overflow_handler;
7557 child_event->overflow_handler_context
7558 = parent_event->overflow_handler_context;
7561 * Precalculate sample_data sizes
7563 perf_event__header_size(child_event);
7564 perf_event__id_header_size(child_event);
7567 * Link it up in the child's context:
7569 raw_spin_lock_irqsave(&child_ctx->lock, flags);
7570 add_event_to_ctx(child_event, child_ctx);
7571 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7574 * Link this into the parent event's child list
7576 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7577 mutex_lock(&parent_event->child_mutex);
7578 list_add_tail(&child_event->child_list, &parent_event->child_list);
7579 mutex_unlock(&parent_event->child_mutex);
7584 static int inherit_group(struct perf_event *parent_event,
7585 struct task_struct *parent,
7586 struct perf_event_context *parent_ctx,
7587 struct task_struct *child,
7588 struct perf_event_context *child_ctx)
7590 struct perf_event *leader;
7591 struct perf_event *sub;
7592 struct perf_event *child_ctr;
7594 leader = inherit_event(parent_event, parent, parent_ctx,
7595 child, NULL, child_ctx);
7597 return PTR_ERR(leader);
7598 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
7599 child_ctr = inherit_event(sub, parent, parent_ctx,
7600 child, leader, child_ctx);
7601 if (IS_ERR(child_ctr))
7602 return PTR_ERR(child_ctr);
7608 inherit_task_group(struct perf_event *event, struct task_struct *parent,
7609 struct perf_event_context *parent_ctx,
7610 struct task_struct *child, int ctxn,
7614 struct perf_event_context *child_ctx;
7616 if (!event->attr.inherit) {
7621 child_ctx = child->perf_event_ctxp[ctxn];
7624 * This is executed from the parent task context, so
7625 * inherit events that have been marked for cloning.
7626 * First allocate and initialize a context for the
7630 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
7634 child->perf_event_ctxp[ctxn] = child_ctx;
7637 ret = inherit_group(event, parent, parent_ctx,
7647 * Initialize the perf_event context in task_struct
7649 int perf_event_init_context(struct task_struct *child, int ctxn)
7651 struct perf_event_context *child_ctx, *parent_ctx;
7652 struct perf_event_context *cloned_ctx;
7653 struct perf_event *event;
7654 struct task_struct *parent = current;
7655 int inherited_all = 1;
7656 unsigned long flags;
7659 if (likely(!parent->perf_event_ctxp[ctxn]))
7663 * If the parent's context is a clone, pin it so it won't get
7666 parent_ctx = perf_pin_task_context(parent, ctxn);
7669 * No need to check if parent_ctx != NULL here; since we saw
7670 * it non-NULL earlier, the only reason for it to become NULL
7671 * is if we exit, and since we're currently in the middle of
7672 * a fork we can't be exiting at the same time.
7676 * Lock the parent list. No need to lock the child - not PID
7677 * hashed yet and not running, so nobody can access it.
7679 mutex_lock(&parent_ctx->mutex);
7682 * We dont have to disable NMIs - we are only looking at
7683 * the list, not manipulating it:
7685 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
7686 ret = inherit_task_group(event, parent, parent_ctx,
7687 child, ctxn, &inherited_all);
7693 * We can't hold ctx->lock when iterating the ->flexible_group list due
7694 * to allocations, but we need to prevent rotation because
7695 * rotate_ctx() will change the list from interrupt context.
7697 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7698 parent_ctx->rotate_disable = 1;
7699 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7701 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
7702 ret = inherit_task_group(event, parent, parent_ctx,
7703 child, ctxn, &inherited_all);
7708 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7709 parent_ctx->rotate_disable = 0;
7711 child_ctx = child->perf_event_ctxp[ctxn];
7713 if (child_ctx && inherited_all) {
7715 * Mark the child context as a clone of the parent
7716 * context, or of whatever the parent is a clone of.
7718 * Note that if the parent is a clone, the holding of
7719 * parent_ctx->lock avoids it from being uncloned.
7721 cloned_ctx = parent_ctx->parent_ctx;
7723 child_ctx->parent_ctx = cloned_ctx;
7724 child_ctx->parent_gen = parent_ctx->parent_gen;
7726 child_ctx->parent_ctx = parent_ctx;
7727 child_ctx->parent_gen = parent_ctx->generation;
7729 get_ctx(child_ctx->parent_ctx);
7732 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7733 mutex_unlock(&parent_ctx->mutex);
7735 perf_unpin_context(parent_ctx);
7736 put_ctx(parent_ctx);
7742 * Initialize the perf_event context in task_struct
7744 int perf_event_init_task(struct task_struct *child)
7748 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
7749 mutex_init(&child->perf_event_mutex);
7750 INIT_LIST_HEAD(&child->perf_event_list);
7752 for_each_task_context_nr(ctxn) {
7753 ret = perf_event_init_context(child, ctxn);
7761 static void __init perf_event_init_all_cpus(void)
7763 struct swevent_htable *swhash;
7766 for_each_possible_cpu(cpu) {
7767 swhash = &per_cpu(swevent_htable, cpu);
7768 mutex_init(&swhash->hlist_mutex);
7769 INIT_LIST_HEAD(&per_cpu(rotation_list, cpu));
7773 static void perf_event_init_cpu(int cpu)
7775 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7777 mutex_lock(&swhash->hlist_mutex);
7778 if (swhash->hlist_refcount > 0) {
7779 struct swevent_hlist *hlist;
7781 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
7783 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7785 mutex_unlock(&swhash->hlist_mutex);
7788 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC
7789 static void perf_pmu_rotate_stop(struct pmu *pmu)
7791 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7793 WARN_ON(!irqs_disabled());
7795 list_del_init(&cpuctx->rotation_list);
7798 static void __perf_event_exit_context(void *__info)
7800 struct perf_event_context *ctx = __info;
7801 struct perf_event *event, *tmp;
7803 perf_pmu_rotate_stop(ctx->pmu);
7805 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups, group_entry)
7806 __perf_remove_from_context(event);
7807 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups, group_entry)
7808 __perf_remove_from_context(event);
7811 static void perf_event_exit_cpu_context(int cpu)
7813 struct perf_event_context *ctx;
7817 idx = srcu_read_lock(&pmus_srcu);
7818 list_for_each_entry_rcu(pmu, &pmus, entry) {
7819 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
7821 mutex_lock(&ctx->mutex);
7822 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
7823 mutex_unlock(&ctx->mutex);
7825 srcu_read_unlock(&pmus_srcu, idx);
7828 static void perf_event_exit_cpu(int cpu)
7830 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7832 mutex_lock(&swhash->hlist_mutex);
7833 swevent_hlist_release(swhash);
7834 mutex_unlock(&swhash->hlist_mutex);
7836 perf_event_exit_cpu_context(cpu);
7839 static inline void perf_event_exit_cpu(int cpu) { }
7843 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
7847 for_each_online_cpu(cpu)
7848 perf_event_exit_cpu(cpu);
7854 * Run the perf reboot notifier at the very last possible moment so that
7855 * the generic watchdog code runs as long as possible.
7857 static struct notifier_block perf_reboot_notifier = {
7858 .notifier_call = perf_reboot,
7859 .priority = INT_MIN,
7863 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
7865 unsigned int cpu = (long)hcpu;
7867 switch (action & ~CPU_TASKS_FROZEN) {
7869 case CPU_UP_PREPARE:
7870 case CPU_DOWN_FAILED:
7871 perf_event_init_cpu(cpu);
7874 case CPU_UP_CANCELED:
7875 case CPU_DOWN_PREPARE:
7876 perf_event_exit_cpu(cpu);
7885 void __init perf_event_init(void)
7891 perf_event_init_all_cpus();
7892 init_srcu_struct(&pmus_srcu);
7893 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
7894 perf_pmu_register(&perf_cpu_clock, NULL, -1);
7895 perf_pmu_register(&perf_task_clock, NULL, -1);
7897 perf_cpu_notifier(perf_cpu_notify);
7898 register_reboot_notifier(&perf_reboot_notifier);
7900 ret = init_hw_breakpoint();
7901 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
7903 /* do not patch jump label more than once per second */
7904 jump_label_rate_limit(&perf_sched_events, HZ);
7907 * Build time assertion that we keep the data_head at the intended
7908 * location. IOW, validation we got the __reserved[] size right.
7910 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
7914 static int __init perf_event_sysfs_init(void)
7919 mutex_lock(&pmus_lock);
7921 ret = bus_register(&pmu_bus);
7925 list_for_each_entry(pmu, &pmus, entry) {
7926 if (!pmu->name || pmu->type < 0)
7929 ret = pmu_dev_alloc(pmu);
7930 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
7932 pmu_bus_running = 1;
7936 mutex_unlock(&pmus_lock);
7940 device_initcall(perf_event_sysfs_init);
7942 #ifdef CONFIG_CGROUP_PERF
7943 static struct cgroup_subsys_state *
7944 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
7946 struct perf_cgroup *jc;
7948 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
7950 return ERR_PTR(-ENOMEM);
7952 jc->info = alloc_percpu(struct perf_cgroup_info);
7955 return ERR_PTR(-ENOMEM);
7961 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
7963 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
7965 free_percpu(jc->info);
7969 static int __perf_cgroup_move(void *info)
7971 struct task_struct *task = info;
7972 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
7976 static void perf_cgroup_attach(struct cgroup_subsys_state *css,
7977 struct cgroup_taskset *tset)
7979 struct task_struct *task;
7981 cgroup_taskset_for_each(task, css, tset)
7982 task_function_call(task, __perf_cgroup_move, task);
7985 static void perf_cgroup_exit(struct cgroup_subsys_state *css,
7986 struct cgroup_subsys_state *old_css,
7987 struct task_struct *task)
7990 * cgroup_exit() is called in the copy_process() failure path.
7991 * Ignore this case since the task hasn't ran yet, this avoids
7992 * trying to poke a half freed task state from generic code.
7994 if (!(task->flags & PF_EXITING))
7997 task_function_call(task, __perf_cgroup_move, task);
8000 struct cgroup_subsys perf_subsys = {
8001 .name = "perf_event",
8002 .subsys_id = perf_subsys_id,
8003 .css_alloc = perf_cgroup_css_alloc,
8004 .css_free = perf_cgroup_css_free,
8005 .exit = perf_cgroup_exit,
8006 .attach = perf_cgroup_attach,
8008 #endif /* CONFIG_CGROUP_PERF */