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;
149 static LIST_HEAD(pmus);
150 static DEFINE_MUTEX(pmus_lock);
151 static struct srcu_struct pmus_srcu;
154 * perf event paranoia level:
155 * -1 - not paranoid at all
156 * 0 - disallow raw tracepoint access for unpriv
157 * 1 - disallow cpu events for unpriv
158 * 2 - disallow kernel profiling for unpriv
160 int sysctl_perf_event_paranoid __read_mostly = 1;
162 /* Minimum for 512 kiB + 1 user control page */
163 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
166 * max perf event sample rate
168 #define DEFAULT_MAX_SAMPLE_RATE 100000
169 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
170 static int max_samples_per_tick __read_mostly =
171 DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
173 int perf_proc_update_handler(struct ctl_table *table, int write,
174 void __user *buffer, size_t *lenp,
177 int ret = proc_dointvec(table, write, buffer, lenp, ppos);
182 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
187 static atomic64_t perf_event_id;
189 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
190 enum event_type_t event_type);
192 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
193 enum event_type_t event_type,
194 struct task_struct *task);
196 static void update_context_time(struct perf_event_context *ctx);
197 static u64 perf_event_time(struct perf_event *event);
199 void __weak perf_event_print_debug(void) { }
201 extern __weak const char *perf_pmu_name(void)
206 static inline u64 perf_clock(void)
208 return local_clock();
211 static inline struct perf_cpu_context *
212 __get_cpu_context(struct perf_event_context *ctx)
214 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
217 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
218 struct perf_event_context *ctx)
220 raw_spin_lock(&cpuctx->ctx.lock);
222 raw_spin_lock(&ctx->lock);
225 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
226 struct perf_event_context *ctx)
229 raw_spin_unlock(&ctx->lock);
230 raw_spin_unlock(&cpuctx->ctx.lock);
233 #ifdef CONFIG_CGROUP_PERF
236 * perf_cgroup_info keeps track of time_enabled for a cgroup.
237 * This is a per-cpu dynamically allocated data structure.
239 struct perf_cgroup_info {
245 struct cgroup_subsys_state css;
246 struct perf_cgroup_info __percpu *info;
250 * Must ensure cgroup is pinned (css_get) before calling
251 * this function. In other words, we cannot call this function
252 * if there is no cgroup event for the current CPU context.
254 static inline struct perf_cgroup *
255 perf_cgroup_from_task(struct task_struct *task)
257 return container_of(task_subsys_state(task, perf_subsys_id),
258 struct perf_cgroup, css);
262 perf_cgroup_match(struct perf_event *event)
264 struct perf_event_context *ctx = event->ctx;
265 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
267 /* @event doesn't care about cgroup */
271 /* wants specific cgroup scope but @cpuctx isn't associated with any */
276 * Cgroup scoping is recursive. An event enabled for a cgroup is
277 * also enabled for all its descendant cgroups. If @cpuctx's
278 * cgroup is a descendant of @event's (the test covers identity
279 * case), it's a match.
281 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
282 event->cgrp->css.cgroup);
285 static inline bool perf_tryget_cgroup(struct perf_event *event)
287 return css_tryget(&event->cgrp->css);
290 static inline void perf_put_cgroup(struct perf_event *event)
292 css_put(&event->cgrp->css);
295 static inline void perf_detach_cgroup(struct perf_event *event)
297 perf_put_cgroup(event);
301 static inline int is_cgroup_event(struct perf_event *event)
303 return event->cgrp != NULL;
306 static inline u64 perf_cgroup_event_time(struct perf_event *event)
308 struct perf_cgroup_info *t;
310 t = per_cpu_ptr(event->cgrp->info, event->cpu);
314 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
316 struct perf_cgroup_info *info;
321 info = this_cpu_ptr(cgrp->info);
323 info->time += now - info->timestamp;
324 info->timestamp = now;
327 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
329 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
331 __update_cgrp_time(cgrp_out);
334 static inline void update_cgrp_time_from_event(struct perf_event *event)
336 struct perf_cgroup *cgrp;
339 * ensure we access cgroup data only when needed and
340 * when we know the cgroup is pinned (css_get)
342 if (!is_cgroup_event(event))
345 cgrp = perf_cgroup_from_task(current);
347 * Do not update time when cgroup is not active
349 if (cgrp == event->cgrp)
350 __update_cgrp_time(event->cgrp);
354 perf_cgroup_set_timestamp(struct task_struct *task,
355 struct perf_event_context *ctx)
357 struct perf_cgroup *cgrp;
358 struct perf_cgroup_info *info;
361 * ctx->lock held by caller
362 * ensure we do not access cgroup data
363 * unless we have the cgroup pinned (css_get)
365 if (!task || !ctx->nr_cgroups)
368 cgrp = perf_cgroup_from_task(task);
369 info = this_cpu_ptr(cgrp->info);
370 info->timestamp = ctx->timestamp;
373 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
374 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
377 * reschedule events based on the cgroup constraint of task.
379 * mode SWOUT : schedule out everything
380 * mode SWIN : schedule in based on cgroup for next
382 void perf_cgroup_switch(struct task_struct *task, int mode)
384 struct perf_cpu_context *cpuctx;
389 * disable interrupts to avoid geting nr_cgroup
390 * changes via __perf_event_disable(). Also
393 local_irq_save(flags);
396 * we reschedule only in the presence of cgroup
397 * constrained events.
401 list_for_each_entry_rcu(pmu, &pmus, entry) {
402 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
403 if (cpuctx->unique_pmu != pmu)
404 continue; /* ensure we process each cpuctx once */
407 * perf_cgroup_events says at least one
408 * context on this CPU has cgroup events.
410 * ctx->nr_cgroups reports the number of cgroup
411 * events for a context.
413 if (cpuctx->ctx.nr_cgroups > 0) {
414 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
415 perf_pmu_disable(cpuctx->ctx.pmu);
417 if (mode & PERF_CGROUP_SWOUT) {
418 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
420 * must not be done before ctxswout due
421 * to event_filter_match() in event_sched_out()
426 if (mode & PERF_CGROUP_SWIN) {
427 WARN_ON_ONCE(cpuctx->cgrp);
429 * set cgrp before ctxsw in to allow
430 * event_filter_match() to not have to pass
433 cpuctx->cgrp = perf_cgroup_from_task(task);
434 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
436 perf_pmu_enable(cpuctx->ctx.pmu);
437 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
443 local_irq_restore(flags);
446 static inline void perf_cgroup_sched_out(struct task_struct *task,
447 struct task_struct *next)
449 struct perf_cgroup *cgrp1;
450 struct perf_cgroup *cgrp2 = NULL;
453 * we come here when we know perf_cgroup_events > 0
455 cgrp1 = perf_cgroup_from_task(task);
458 * next is NULL when called from perf_event_enable_on_exec()
459 * that will systematically cause a cgroup_switch()
462 cgrp2 = perf_cgroup_from_task(next);
465 * only schedule out current cgroup events if we know
466 * that we are switching to a different cgroup. Otherwise,
467 * do no touch the cgroup events.
470 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
473 static inline void perf_cgroup_sched_in(struct task_struct *prev,
474 struct task_struct *task)
476 struct perf_cgroup *cgrp1;
477 struct perf_cgroup *cgrp2 = NULL;
480 * we come here when we know perf_cgroup_events > 0
482 cgrp1 = perf_cgroup_from_task(task);
484 /* prev can never be NULL */
485 cgrp2 = perf_cgroup_from_task(prev);
488 * only need to schedule in cgroup events if we are changing
489 * cgroup during ctxsw. Cgroup events were not scheduled
490 * out of ctxsw out if that was not the case.
493 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
496 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
497 struct perf_event_attr *attr,
498 struct perf_event *group_leader)
500 struct perf_cgroup *cgrp;
501 struct cgroup_subsys_state *css;
502 struct fd f = fdget(fd);
508 css = cgroup_css_from_dir(f.file, perf_subsys_id);
514 cgrp = container_of(css, struct perf_cgroup, css);
517 /* must be done before we fput() the file */
518 if (!perf_tryget_cgroup(event)) {
525 * all events in a group must monitor
526 * the same cgroup because a task belongs
527 * to only one perf cgroup at a time
529 if (group_leader && group_leader->cgrp != cgrp) {
530 perf_detach_cgroup(event);
539 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
541 struct perf_cgroup_info *t;
542 t = per_cpu_ptr(event->cgrp->info, event->cpu);
543 event->shadow_ctx_time = now - t->timestamp;
547 perf_cgroup_defer_enabled(struct perf_event *event)
550 * when the current task's perf cgroup does not match
551 * the event's, we need to remember to call the
552 * perf_mark_enable() function the first time a task with
553 * a matching perf cgroup is scheduled in.
555 if (is_cgroup_event(event) && !perf_cgroup_match(event))
556 event->cgrp_defer_enabled = 1;
560 perf_cgroup_mark_enabled(struct perf_event *event,
561 struct perf_event_context *ctx)
563 struct perf_event *sub;
564 u64 tstamp = perf_event_time(event);
566 if (!event->cgrp_defer_enabled)
569 event->cgrp_defer_enabled = 0;
571 event->tstamp_enabled = tstamp - event->total_time_enabled;
572 list_for_each_entry(sub, &event->sibling_list, group_entry) {
573 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
574 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
575 sub->cgrp_defer_enabled = 0;
579 #else /* !CONFIG_CGROUP_PERF */
582 perf_cgroup_match(struct perf_event *event)
587 static inline void perf_detach_cgroup(struct perf_event *event)
590 static inline int is_cgroup_event(struct perf_event *event)
595 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
600 static inline void update_cgrp_time_from_event(struct perf_event *event)
604 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
608 static inline void perf_cgroup_sched_out(struct task_struct *task,
609 struct task_struct *next)
613 static inline void perf_cgroup_sched_in(struct task_struct *prev,
614 struct task_struct *task)
618 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
619 struct perf_event_attr *attr,
620 struct perf_event *group_leader)
626 perf_cgroup_set_timestamp(struct task_struct *task,
627 struct perf_event_context *ctx)
632 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
637 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
641 static inline u64 perf_cgroup_event_time(struct perf_event *event)
647 perf_cgroup_defer_enabled(struct perf_event *event)
652 perf_cgroup_mark_enabled(struct perf_event *event,
653 struct perf_event_context *ctx)
658 void perf_pmu_disable(struct pmu *pmu)
660 int *count = this_cpu_ptr(pmu->pmu_disable_count);
662 pmu->pmu_disable(pmu);
665 void perf_pmu_enable(struct pmu *pmu)
667 int *count = this_cpu_ptr(pmu->pmu_disable_count);
669 pmu->pmu_enable(pmu);
672 static DEFINE_PER_CPU(struct list_head, rotation_list);
675 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
676 * because they're strictly cpu affine and rotate_start is called with IRQs
677 * disabled, while rotate_context is called from IRQ context.
679 static void perf_pmu_rotate_start(struct pmu *pmu)
681 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
682 struct list_head *head = &__get_cpu_var(rotation_list);
684 WARN_ON(!irqs_disabled());
686 if (list_empty(&cpuctx->rotation_list)) {
687 int was_empty = list_empty(head);
688 list_add(&cpuctx->rotation_list, head);
690 tick_nohz_full_kick();
694 static void get_ctx(struct perf_event_context *ctx)
696 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
699 static void put_ctx(struct perf_event_context *ctx)
701 if (atomic_dec_and_test(&ctx->refcount)) {
703 put_ctx(ctx->parent_ctx);
705 put_task_struct(ctx->task);
706 kfree_rcu(ctx, rcu_head);
710 static void unclone_ctx(struct perf_event_context *ctx)
712 if (ctx->parent_ctx) {
713 put_ctx(ctx->parent_ctx);
714 ctx->parent_ctx = NULL;
718 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
721 * only top level events have the pid namespace they were created in
724 event = event->parent;
726 return task_tgid_nr_ns(p, event->ns);
729 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
732 * only top level events have the pid namespace they were created in
735 event = event->parent;
737 return task_pid_nr_ns(p, event->ns);
741 * If we inherit events we want to return the parent event id
744 static u64 primary_event_id(struct perf_event *event)
749 id = event->parent->id;
755 * Get the perf_event_context for a task and lock it.
756 * This has to cope with with the fact that until it is locked,
757 * the context could get moved to another task.
759 static struct perf_event_context *
760 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
762 struct perf_event_context *ctx;
766 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
769 * If this context is a clone of another, it might
770 * get swapped for another underneath us by
771 * perf_event_task_sched_out, though the
772 * rcu_read_lock() protects us from any context
773 * getting freed. Lock the context and check if it
774 * got swapped before we could get the lock, and retry
775 * if so. If we locked the right context, then it
776 * can't get swapped on us any more.
778 raw_spin_lock_irqsave(&ctx->lock, *flags);
779 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
780 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
784 if (!atomic_inc_not_zero(&ctx->refcount)) {
785 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
794 * Get the context for a task and increment its pin_count so it
795 * can't get swapped to another task. This also increments its
796 * reference count so that the context can't get freed.
798 static struct perf_event_context *
799 perf_pin_task_context(struct task_struct *task, int ctxn)
801 struct perf_event_context *ctx;
804 ctx = perf_lock_task_context(task, ctxn, &flags);
807 raw_spin_unlock_irqrestore(&ctx->lock, flags);
812 static void perf_unpin_context(struct perf_event_context *ctx)
816 raw_spin_lock_irqsave(&ctx->lock, flags);
818 raw_spin_unlock_irqrestore(&ctx->lock, flags);
822 * Update the record of the current time in a context.
824 static void update_context_time(struct perf_event_context *ctx)
826 u64 now = perf_clock();
828 ctx->time += now - ctx->timestamp;
829 ctx->timestamp = now;
832 static u64 perf_event_time(struct perf_event *event)
834 struct perf_event_context *ctx = event->ctx;
836 if (is_cgroup_event(event))
837 return perf_cgroup_event_time(event);
839 return ctx ? ctx->time : 0;
843 * Update the total_time_enabled and total_time_running fields for a event.
844 * The caller of this function needs to hold the ctx->lock.
846 static void update_event_times(struct perf_event *event)
848 struct perf_event_context *ctx = event->ctx;
851 if (event->state < PERF_EVENT_STATE_INACTIVE ||
852 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
855 * in cgroup mode, time_enabled represents
856 * the time the event was enabled AND active
857 * tasks were in the monitored cgroup. This is
858 * independent of the activity of the context as
859 * there may be a mix of cgroup and non-cgroup events.
861 * That is why we treat cgroup events differently
864 if (is_cgroup_event(event))
865 run_end = perf_cgroup_event_time(event);
866 else if (ctx->is_active)
869 run_end = event->tstamp_stopped;
871 event->total_time_enabled = run_end - event->tstamp_enabled;
873 if (event->state == PERF_EVENT_STATE_INACTIVE)
874 run_end = event->tstamp_stopped;
876 run_end = perf_event_time(event);
878 event->total_time_running = run_end - event->tstamp_running;
883 * Update total_time_enabled and total_time_running for all events in a group.
885 static void update_group_times(struct perf_event *leader)
887 struct perf_event *event;
889 update_event_times(leader);
890 list_for_each_entry(event, &leader->sibling_list, group_entry)
891 update_event_times(event);
894 static struct list_head *
895 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
897 if (event->attr.pinned)
898 return &ctx->pinned_groups;
900 return &ctx->flexible_groups;
904 * Add a event from the lists for its context.
905 * Must be called with ctx->mutex and ctx->lock held.
908 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
910 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
911 event->attach_state |= PERF_ATTACH_CONTEXT;
914 * If we're a stand alone event or group leader, we go to the context
915 * list, group events are kept attached to the group so that
916 * perf_group_detach can, at all times, locate all siblings.
918 if (event->group_leader == event) {
919 struct list_head *list;
921 if (is_software_event(event))
922 event->group_flags |= PERF_GROUP_SOFTWARE;
924 list = ctx_group_list(event, ctx);
925 list_add_tail(&event->group_entry, list);
928 if (is_cgroup_event(event))
931 if (has_branch_stack(event))
932 ctx->nr_branch_stack++;
934 list_add_rcu(&event->event_entry, &ctx->event_list);
936 perf_pmu_rotate_start(ctx->pmu);
938 if (event->attr.inherit_stat)
943 * Initialize event state based on the perf_event_attr::disabled.
945 static inline void perf_event__state_init(struct perf_event *event)
947 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
948 PERF_EVENT_STATE_INACTIVE;
952 * Called at perf_event creation and when events are attached/detached from a
955 static void perf_event__read_size(struct perf_event *event)
957 int entry = sizeof(u64); /* value */
961 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
964 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
967 if (event->attr.read_format & PERF_FORMAT_ID)
968 entry += sizeof(u64);
970 if (event->attr.read_format & PERF_FORMAT_GROUP) {
971 nr += event->group_leader->nr_siblings;
976 event->read_size = size;
979 static void perf_event__header_size(struct perf_event *event)
981 struct perf_sample_data *data;
982 u64 sample_type = event->attr.sample_type;
985 perf_event__read_size(event);
987 if (sample_type & PERF_SAMPLE_IP)
988 size += sizeof(data->ip);
990 if (sample_type & PERF_SAMPLE_ADDR)
991 size += sizeof(data->addr);
993 if (sample_type & PERF_SAMPLE_PERIOD)
994 size += sizeof(data->period);
996 if (sample_type & PERF_SAMPLE_WEIGHT)
997 size += sizeof(data->weight);
999 if (sample_type & PERF_SAMPLE_READ)
1000 size += event->read_size;
1002 if (sample_type & PERF_SAMPLE_DATA_SRC)
1003 size += sizeof(data->data_src.val);
1005 event->header_size = size;
1008 static void perf_event__id_header_size(struct perf_event *event)
1010 struct perf_sample_data *data;
1011 u64 sample_type = event->attr.sample_type;
1014 if (sample_type & PERF_SAMPLE_TID)
1015 size += sizeof(data->tid_entry);
1017 if (sample_type & PERF_SAMPLE_TIME)
1018 size += sizeof(data->time);
1020 if (sample_type & PERF_SAMPLE_ID)
1021 size += sizeof(data->id);
1023 if (sample_type & PERF_SAMPLE_STREAM_ID)
1024 size += sizeof(data->stream_id);
1026 if (sample_type & PERF_SAMPLE_CPU)
1027 size += sizeof(data->cpu_entry);
1029 event->id_header_size = size;
1032 static void perf_group_attach(struct perf_event *event)
1034 struct perf_event *group_leader = event->group_leader, *pos;
1037 * We can have double attach due to group movement in perf_event_open.
1039 if (event->attach_state & PERF_ATTACH_GROUP)
1042 event->attach_state |= PERF_ATTACH_GROUP;
1044 if (group_leader == event)
1047 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1048 !is_software_event(event))
1049 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1051 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1052 group_leader->nr_siblings++;
1054 perf_event__header_size(group_leader);
1056 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1057 perf_event__header_size(pos);
1061 * Remove a event from the lists for its context.
1062 * Must be called with ctx->mutex and ctx->lock held.
1065 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1067 struct perf_cpu_context *cpuctx;
1069 * We can have double detach due to exit/hot-unplug + close.
1071 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1074 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1076 if (is_cgroup_event(event)) {
1078 cpuctx = __get_cpu_context(ctx);
1080 * if there are no more cgroup events
1081 * then cler cgrp to avoid stale pointer
1082 * in update_cgrp_time_from_cpuctx()
1084 if (!ctx->nr_cgroups)
1085 cpuctx->cgrp = NULL;
1088 if (has_branch_stack(event))
1089 ctx->nr_branch_stack--;
1092 if (event->attr.inherit_stat)
1095 list_del_rcu(&event->event_entry);
1097 if (event->group_leader == event)
1098 list_del_init(&event->group_entry);
1100 update_group_times(event);
1103 * If event was in error state, then keep it
1104 * that way, otherwise bogus counts will be
1105 * returned on read(). The only way to get out
1106 * of error state is by explicit re-enabling
1109 if (event->state > PERF_EVENT_STATE_OFF)
1110 event->state = PERF_EVENT_STATE_OFF;
1113 static void perf_group_detach(struct perf_event *event)
1115 struct perf_event *sibling, *tmp;
1116 struct list_head *list = NULL;
1119 * We can have double detach due to exit/hot-unplug + close.
1121 if (!(event->attach_state & PERF_ATTACH_GROUP))
1124 event->attach_state &= ~PERF_ATTACH_GROUP;
1127 * If this is a sibling, remove it from its group.
1129 if (event->group_leader != event) {
1130 list_del_init(&event->group_entry);
1131 event->group_leader->nr_siblings--;
1135 if (!list_empty(&event->group_entry))
1136 list = &event->group_entry;
1139 * If this was a group event with sibling events then
1140 * upgrade the siblings to singleton events by adding them
1141 * to whatever list we are on.
1143 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1145 list_move_tail(&sibling->group_entry, list);
1146 sibling->group_leader = sibling;
1148 /* Inherit group flags from the previous leader */
1149 sibling->group_flags = event->group_flags;
1153 perf_event__header_size(event->group_leader);
1155 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1156 perf_event__header_size(tmp);
1160 event_filter_match(struct perf_event *event)
1162 return (event->cpu == -1 || event->cpu == smp_processor_id())
1163 && perf_cgroup_match(event);
1167 event_sched_out(struct perf_event *event,
1168 struct perf_cpu_context *cpuctx,
1169 struct perf_event_context *ctx)
1171 u64 tstamp = perf_event_time(event);
1174 * An event which could not be activated because of
1175 * filter mismatch still needs to have its timings
1176 * maintained, otherwise bogus information is return
1177 * via read() for time_enabled, time_running:
1179 if (event->state == PERF_EVENT_STATE_INACTIVE
1180 && !event_filter_match(event)) {
1181 delta = tstamp - event->tstamp_stopped;
1182 event->tstamp_running += delta;
1183 event->tstamp_stopped = tstamp;
1186 if (event->state != PERF_EVENT_STATE_ACTIVE)
1189 event->state = PERF_EVENT_STATE_INACTIVE;
1190 if (event->pending_disable) {
1191 event->pending_disable = 0;
1192 event->state = PERF_EVENT_STATE_OFF;
1194 event->tstamp_stopped = tstamp;
1195 event->pmu->del(event, 0);
1198 if (!is_software_event(event))
1199 cpuctx->active_oncpu--;
1201 if (event->attr.freq && event->attr.sample_freq)
1203 if (event->attr.exclusive || !cpuctx->active_oncpu)
1204 cpuctx->exclusive = 0;
1208 group_sched_out(struct perf_event *group_event,
1209 struct perf_cpu_context *cpuctx,
1210 struct perf_event_context *ctx)
1212 struct perf_event *event;
1213 int state = group_event->state;
1215 event_sched_out(group_event, cpuctx, ctx);
1218 * Schedule out siblings (if any):
1220 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1221 event_sched_out(event, cpuctx, ctx);
1223 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1224 cpuctx->exclusive = 0;
1228 * Cross CPU call to remove a performance event
1230 * We disable the event on the hardware level first. After that we
1231 * remove it from the context list.
1233 static int __perf_remove_from_context(void *info)
1235 struct perf_event *event = info;
1236 struct perf_event_context *ctx = event->ctx;
1237 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1239 raw_spin_lock(&ctx->lock);
1240 event_sched_out(event, cpuctx, ctx);
1241 list_del_event(event, ctx);
1242 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1244 cpuctx->task_ctx = NULL;
1246 raw_spin_unlock(&ctx->lock);
1253 * Remove the event from a task's (or a CPU's) list of events.
1255 * CPU events are removed with a smp call. For task events we only
1256 * call when the task is on a CPU.
1258 * If event->ctx is a cloned context, callers must make sure that
1259 * every task struct that event->ctx->task could possibly point to
1260 * remains valid. This is OK when called from perf_release since
1261 * that only calls us on the top-level context, which can't be a clone.
1262 * When called from perf_event_exit_task, it's OK because the
1263 * context has been detached from its task.
1265 static void perf_remove_from_context(struct perf_event *event)
1267 struct perf_event_context *ctx = event->ctx;
1268 struct task_struct *task = ctx->task;
1270 lockdep_assert_held(&ctx->mutex);
1274 * Per cpu events are removed via an smp call and
1275 * the removal is always successful.
1277 cpu_function_call(event->cpu, __perf_remove_from_context, event);
1282 if (!task_function_call(task, __perf_remove_from_context, event))
1285 raw_spin_lock_irq(&ctx->lock);
1287 * If we failed to find a running task, but find the context active now
1288 * that we've acquired the ctx->lock, retry.
1290 if (ctx->is_active) {
1291 raw_spin_unlock_irq(&ctx->lock);
1296 * Since the task isn't running, its safe to remove the event, us
1297 * holding the ctx->lock ensures the task won't get scheduled in.
1299 list_del_event(event, ctx);
1300 raw_spin_unlock_irq(&ctx->lock);
1304 * Cross CPU call to disable a performance event
1306 int __perf_event_disable(void *info)
1308 struct perf_event *event = info;
1309 struct perf_event_context *ctx = event->ctx;
1310 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1313 * If this is a per-task event, need to check whether this
1314 * event's task is the current task on this cpu.
1316 * Can trigger due to concurrent perf_event_context_sched_out()
1317 * flipping contexts around.
1319 if (ctx->task && cpuctx->task_ctx != ctx)
1322 raw_spin_lock(&ctx->lock);
1325 * If the event is on, turn it off.
1326 * If it is in error state, leave it in error state.
1328 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1329 update_context_time(ctx);
1330 update_cgrp_time_from_event(event);
1331 update_group_times(event);
1332 if (event == event->group_leader)
1333 group_sched_out(event, cpuctx, ctx);
1335 event_sched_out(event, cpuctx, ctx);
1336 event->state = PERF_EVENT_STATE_OFF;
1339 raw_spin_unlock(&ctx->lock);
1347 * If event->ctx is a cloned context, callers must make sure that
1348 * every task struct that event->ctx->task could possibly point to
1349 * remains valid. This condition is satisifed when called through
1350 * perf_event_for_each_child or perf_event_for_each because they
1351 * hold the top-level event's child_mutex, so any descendant that
1352 * goes to exit will block in sync_child_event.
1353 * When called from perf_pending_event it's OK because event->ctx
1354 * is the current context on this CPU and preemption is disabled,
1355 * hence we can't get into perf_event_task_sched_out for this context.
1357 void perf_event_disable(struct perf_event *event)
1359 struct perf_event_context *ctx = event->ctx;
1360 struct task_struct *task = ctx->task;
1364 * Disable the event on the cpu that it's on
1366 cpu_function_call(event->cpu, __perf_event_disable, event);
1371 if (!task_function_call(task, __perf_event_disable, event))
1374 raw_spin_lock_irq(&ctx->lock);
1376 * If the event is still active, we need to retry the cross-call.
1378 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1379 raw_spin_unlock_irq(&ctx->lock);
1381 * Reload the task pointer, it might have been changed by
1382 * a concurrent perf_event_context_sched_out().
1389 * Since we have the lock this context can't be scheduled
1390 * in, so we can change the state safely.
1392 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1393 update_group_times(event);
1394 event->state = PERF_EVENT_STATE_OFF;
1396 raw_spin_unlock_irq(&ctx->lock);
1398 EXPORT_SYMBOL_GPL(perf_event_disable);
1400 static void perf_set_shadow_time(struct perf_event *event,
1401 struct perf_event_context *ctx,
1405 * use the correct time source for the time snapshot
1407 * We could get by without this by leveraging the
1408 * fact that to get to this function, the caller
1409 * has most likely already called update_context_time()
1410 * and update_cgrp_time_xx() and thus both timestamp
1411 * are identical (or very close). Given that tstamp is,
1412 * already adjusted for cgroup, we could say that:
1413 * tstamp - ctx->timestamp
1415 * tstamp - cgrp->timestamp.
1417 * Then, in perf_output_read(), the calculation would
1418 * work with no changes because:
1419 * - event is guaranteed scheduled in
1420 * - no scheduled out in between
1421 * - thus the timestamp would be the same
1423 * But this is a bit hairy.
1425 * So instead, we have an explicit cgroup call to remain
1426 * within the time time source all along. We believe it
1427 * is cleaner and simpler to understand.
1429 if (is_cgroup_event(event))
1430 perf_cgroup_set_shadow_time(event, tstamp);
1432 event->shadow_ctx_time = tstamp - ctx->timestamp;
1435 #define MAX_INTERRUPTS (~0ULL)
1437 static void perf_log_throttle(struct perf_event *event, int enable);
1440 event_sched_in(struct perf_event *event,
1441 struct perf_cpu_context *cpuctx,
1442 struct perf_event_context *ctx)
1444 u64 tstamp = perf_event_time(event);
1446 if (event->state <= PERF_EVENT_STATE_OFF)
1449 event->state = PERF_EVENT_STATE_ACTIVE;
1450 event->oncpu = smp_processor_id();
1453 * Unthrottle events, since we scheduled we might have missed several
1454 * ticks already, also for a heavily scheduling task there is little
1455 * guarantee it'll get a tick in a timely manner.
1457 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1458 perf_log_throttle(event, 1);
1459 event->hw.interrupts = 0;
1463 * The new state must be visible before we turn it on in the hardware:
1467 if (event->pmu->add(event, PERF_EF_START)) {
1468 event->state = PERF_EVENT_STATE_INACTIVE;
1473 event->tstamp_running += tstamp - event->tstamp_stopped;
1475 perf_set_shadow_time(event, ctx, tstamp);
1477 if (!is_software_event(event))
1478 cpuctx->active_oncpu++;
1480 if (event->attr.freq && event->attr.sample_freq)
1483 if (event->attr.exclusive)
1484 cpuctx->exclusive = 1;
1490 group_sched_in(struct perf_event *group_event,
1491 struct perf_cpu_context *cpuctx,
1492 struct perf_event_context *ctx)
1494 struct perf_event *event, *partial_group = NULL;
1495 struct pmu *pmu = group_event->pmu;
1496 u64 now = ctx->time;
1497 bool simulate = false;
1499 if (group_event->state == PERF_EVENT_STATE_OFF)
1502 pmu->start_txn(pmu);
1504 if (event_sched_in(group_event, cpuctx, ctx)) {
1505 pmu->cancel_txn(pmu);
1510 * Schedule in siblings as one group (if any):
1512 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1513 if (event_sched_in(event, cpuctx, ctx)) {
1514 partial_group = event;
1519 if (!pmu->commit_txn(pmu))
1524 * Groups can be scheduled in as one unit only, so undo any
1525 * partial group before returning:
1526 * The events up to the failed event are scheduled out normally,
1527 * tstamp_stopped will be updated.
1529 * The failed events and the remaining siblings need to have
1530 * their timings updated as if they had gone thru event_sched_in()
1531 * and event_sched_out(). This is required to get consistent timings
1532 * across the group. This also takes care of the case where the group
1533 * could never be scheduled by ensuring tstamp_stopped is set to mark
1534 * the time the event was actually stopped, such that time delta
1535 * calculation in update_event_times() is correct.
1537 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1538 if (event == partial_group)
1542 event->tstamp_running += now - event->tstamp_stopped;
1543 event->tstamp_stopped = now;
1545 event_sched_out(event, cpuctx, ctx);
1548 event_sched_out(group_event, cpuctx, ctx);
1550 pmu->cancel_txn(pmu);
1556 * Work out whether we can put this event group on the CPU now.
1558 static int group_can_go_on(struct perf_event *event,
1559 struct perf_cpu_context *cpuctx,
1563 * Groups consisting entirely of software events can always go on.
1565 if (event->group_flags & PERF_GROUP_SOFTWARE)
1568 * If an exclusive group is already on, no other hardware
1571 if (cpuctx->exclusive)
1574 * If this group is exclusive and there are already
1575 * events on the CPU, it can't go on.
1577 if (event->attr.exclusive && cpuctx->active_oncpu)
1580 * Otherwise, try to add it if all previous groups were able
1586 static void add_event_to_ctx(struct perf_event *event,
1587 struct perf_event_context *ctx)
1589 u64 tstamp = perf_event_time(event);
1591 list_add_event(event, ctx);
1592 perf_group_attach(event);
1593 event->tstamp_enabled = tstamp;
1594 event->tstamp_running = tstamp;
1595 event->tstamp_stopped = tstamp;
1598 static void task_ctx_sched_out(struct perf_event_context *ctx);
1600 ctx_sched_in(struct perf_event_context *ctx,
1601 struct perf_cpu_context *cpuctx,
1602 enum event_type_t event_type,
1603 struct task_struct *task);
1605 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
1606 struct perf_event_context *ctx,
1607 struct task_struct *task)
1609 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
1611 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
1612 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
1614 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
1618 * Cross CPU call to install and enable a performance event
1620 * Must be called with ctx->mutex held
1622 static int __perf_install_in_context(void *info)
1624 struct perf_event *event = info;
1625 struct perf_event_context *ctx = event->ctx;
1626 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1627 struct perf_event_context *task_ctx = cpuctx->task_ctx;
1628 struct task_struct *task = current;
1630 perf_ctx_lock(cpuctx, task_ctx);
1631 perf_pmu_disable(cpuctx->ctx.pmu);
1634 * If there was an active task_ctx schedule it out.
1637 task_ctx_sched_out(task_ctx);
1640 * If the context we're installing events in is not the
1641 * active task_ctx, flip them.
1643 if (ctx->task && task_ctx != ctx) {
1645 raw_spin_unlock(&task_ctx->lock);
1646 raw_spin_lock(&ctx->lock);
1651 cpuctx->task_ctx = task_ctx;
1652 task = task_ctx->task;
1655 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
1657 update_context_time(ctx);
1659 * update cgrp time only if current cgrp
1660 * matches event->cgrp. Must be done before
1661 * calling add_event_to_ctx()
1663 update_cgrp_time_from_event(event);
1665 add_event_to_ctx(event, ctx);
1668 * Schedule everything back in
1670 perf_event_sched_in(cpuctx, task_ctx, task);
1672 perf_pmu_enable(cpuctx->ctx.pmu);
1673 perf_ctx_unlock(cpuctx, task_ctx);
1679 * Attach a performance event to a context
1681 * First we add the event to the list with the hardware enable bit
1682 * in event->hw_config cleared.
1684 * If the event is attached to a task which is on a CPU we use a smp
1685 * call to enable it in the task context. The task might have been
1686 * scheduled away, but we check this in the smp call again.
1689 perf_install_in_context(struct perf_event_context *ctx,
1690 struct perf_event *event,
1693 struct task_struct *task = ctx->task;
1695 lockdep_assert_held(&ctx->mutex);
1698 if (event->cpu != -1)
1703 * Per cpu events are installed via an smp call and
1704 * the install is always successful.
1706 cpu_function_call(cpu, __perf_install_in_context, event);
1711 if (!task_function_call(task, __perf_install_in_context, event))
1714 raw_spin_lock_irq(&ctx->lock);
1716 * If we failed to find a running task, but find the context active now
1717 * that we've acquired the ctx->lock, retry.
1719 if (ctx->is_active) {
1720 raw_spin_unlock_irq(&ctx->lock);
1725 * Since the task isn't running, its safe to add the event, us holding
1726 * the ctx->lock ensures the task won't get scheduled in.
1728 add_event_to_ctx(event, ctx);
1729 raw_spin_unlock_irq(&ctx->lock);
1733 * Put a event into inactive state and update time fields.
1734 * Enabling the leader of a group effectively enables all
1735 * the group members that aren't explicitly disabled, so we
1736 * have to update their ->tstamp_enabled also.
1737 * Note: this works for group members as well as group leaders
1738 * since the non-leader members' sibling_lists will be empty.
1740 static void __perf_event_mark_enabled(struct perf_event *event)
1742 struct perf_event *sub;
1743 u64 tstamp = perf_event_time(event);
1745 event->state = PERF_EVENT_STATE_INACTIVE;
1746 event->tstamp_enabled = tstamp - event->total_time_enabled;
1747 list_for_each_entry(sub, &event->sibling_list, group_entry) {
1748 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
1749 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
1754 * Cross CPU call to enable a performance event
1756 static int __perf_event_enable(void *info)
1758 struct perf_event *event = info;
1759 struct perf_event_context *ctx = event->ctx;
1760 struct perf_event *leader = event->group_leader;
1761 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1764 if (WARN_ON_ONCE(!ctx->is_active))
1767 raw_spin_lock(&ctx->lock);
1768 update_context_time(ctx);
1770 if (event->state >= PERF_EVENT_STATE_INACTIVE)
1774 * set current task's cgroup time reference point
1776 perf_cgroup_set_timestamp(current, ctx);
1778 __perf_event_mark_enabled(event);
1780 if (!event_filter_match(event)) {
1781 if (is_cgroup_event(event))
1782 perf_cgroup_defer_enabled(event);
1787 * If the event is in a group and isn't the group leader,
1788 * then don't put it on unless the group is on.
1790 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
1793 if (!group_can_go_on(event, cpuctx, 1)) {
1796 if (event == leader)
1797 err = group_sched_in(event, cpuctx, ctx);
1799 err = event_sched_in(event, cpuctx, ctx);
1804 * If this event can't go on and it's part of a
1805 * group, then the whole group has to come off.
1807 if (leader != event)
1808 group_sched_out(leader, cpuctx, ctx);
1809 if (leader->attr.pinned) {
1810 update_group_times(leader);
1811 leader->state = PERF_EVENT_STATE_ERROR;
1816 raw_spin_unlock(&ctx->lock);
1824 * If event->ctx is a cloned context, callers must make sure that
1825 * every task struct that event->ctx->task could possibly point to
1826 * remains valid. This condition is satisfied when called through
1827 * perf_event_for_each_child or perf_event_for_each as described
1828 * for perf_event_disable.
1830 void perf_event_enable(struct perf_event *event)
1832 struct perf_event_context *ctx = event->ctx;
1833 struct task_struct *task = ctx->task;
1837 * Enable the event on the cpu that it's on
1839 cpu_function_call(event->cpu, __perf_event_enable, event);
1843 raw_spin_lock_irq(&ctx->lock);
1844 if (event->state >= PERF_EVENT_STATE_INACTIVE)
1848 * If the event is in error state, clear that first.
1849 * That way, if we see the event in error state below, we
1850 * know that it has gone back into error state, as distinct
1851 * from the task having been scheduled away before the
1852 * cross-call arrived.
1854 if (event->state == PERF_EVENT_STATE_ERROR)
1855 event->state = PERF_EVENT_STATE_OFF;
1858 if (!ctx->is_active) {
1859 __perf_event_mark_enabled(event);
1863 raw_spin_unlock_irq(&ctx->lock);
1865 if (!task_function_call(task, __perf_event_enable, event))
1868 raw_spin_lock_irq(&ctx->lock);
1871 * If the context is active and the event is still off,
1872 * we need to retry the cross-call.
1874 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
1876 * task could have been flipped by a concurrent
1877 * perf_event_context_sched_out()
1884 raw_spin_unlock_irq(&ctx->lock);
1886 EXPORT_SYMBOL_GPL(perf_event_enable);
1888 int perf_event_refresh(struct perf_event *event, int refresh)
1891 * not supported on inherited events
1893 if (event->attr.inherit || !is_sampling_event(event))
1896 atomic_add(refresh, &event->event_limit);
1897 perf_event_enable(event);
1901 EXPORT_SYMBOL_GPL(perf_event_refresh);
1903 static void ctx_sched_out(struct perf_event_context *ctx,
1904 struct perf_cpu_context *cpuctx,
1905 enum event_type_t event_type)
1907 struct perf_event *event;
1908 int is_active = ctx->is_active;
1910 ctx->is_active &= ~event_type;
1911 if (likely(!ctx->nr_events))
1914 update_context_time(ctx);
1915 update_cgrp_time_from_cpuctx(cpuctx);
1916 if (!ctx->nr_active)
1919 perf_pmu_disable(ctx->pmu);
1920 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
1921 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
1922 group_sched_out(event, cpuctx, ctx);
1925 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
1926 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
1927 group_sched_out(event, cpuctx, ctx);
1929 perf_pmu_enable(ctx->pmu);
1933 * Test whether two contexts are equivalent, i.e. whether they
1934 * have both been cloned from the same version of the same context
1935 * and they both have the same number of enabled events.
1936 * If the number of enabled events is the same, then the set
1937 * of enabled events should be the same, because these are both
1938 * inherited contexts, therefore we can't access individual events
1939 * in them directly with an fd; we can only enable/disable all
1940 * events via prctl, or enable/disable all events in a family
1941 * via ioctl, which will have the same effect on both contexts.
1943 static int context_equiv(struct perf_event_context *ctx1,
1944 struct perf_event_context *ctx2)
1946 return ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx
1947 && ctx1->parent_gen == ctx2->parent_gen
1948 && !ctx1->pin_count && !ctx2->pin_count;
1951 static void __perf_event_sync_stat(struct perf_event *event,
1952 struct perf_event *next_event)
1956 if (!event->attr.inherit_stat)
1960 * Update the event value, we cannot use perf_event_read()
1961 * because we're in the middle of a context switch and have IRQs
1962 * disabled, which upsets smp_call_function_single(), however
1963 * we know the event must be on the current CPU, therefore we
1964 * don't need to use it.
1966 switch (event->state) {
1967 case PERF_EVENT_STATE_ACTIVE:
1968 event->pmu->read(event);
1971 case PERF_EVENT_STATE_INACTIVE:
1972 update_event_times(event);
1980 * In order to keep per-task stats reliable we need to flip the event
1981 * values when we flip the contexts.
1983 value = local64_read(&next_event->count);
1984 value = local64_xchg(&event->count, value);
1985 local64_set(&next_event->count, value);
1987 swap(event->total_time_enabled, next_event->total_time_enabled);
1988 swap(event->total_time_running, next_event->total_time_running);
1991 * Since we swizzled the values, update the user visible data too.
1993 perf_event_update_userpage(event);
1994 perf_event_update_userpage(next_event);
1997 #define list_next_entry(pos, member) \
1998 list_entry(pos->member.next, typeof(*pos), member)
2000 static void perf_event_sync_stat(struct perf_event_context *ctx,
2001 struct perf_event_context *next_ctx)
2003 struct perf_event *event, *next_event;
2008 update_context_time(ctx);
2010 event = list_first_entry(&ctx->event_list,
2011 struct perf_event, event_entry);
2013 next_event = list_first_entry(&next_ctx->event_list,
2014 struct perf_event, event_entry);
2016 while (&event->event_entry != &ctx->event_list &&
2017 &next_event->event_entry != &next_ctx->event_list) {
2019 __perf_event_sync_stat(event, next_event);
2021 event = list_next_entry(event, event_entry);
2022 next_event = list_next_entry(next_event, event_entry);
2026 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2027 struct task_struct *next)
2029 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2030 struct perf_event_context *next_ctx;
2031 struct perf_event_context *parent;
2032 struct perf_cpu_context *cpuctx;
2038 cpuctx = __get_cpu_context(ctx);
2039 if (!cpuctx->task_ctx)
2043 parent = rcu_dereference(ctx->parent_ctx);
2044 next_ctx = next->perf_event_ctxp[ctxn];
2045 if (parent && next_ctx &&
2046 rcu_dereference(next_ctx->parent_ctx) == parent) {
2048 * Looks like the two contexts are clones, so we might be
2049 * able to optimize the context switch. We lock both
2050 * contexts and check that they are clones under the
2051 * lock (including re-checking that neither has been
2052 * uncloned in the meantime). It doesn't matter which
2053 * order we take the locks because no other cpu could
2054 * be trying to lock both of these tasks.
2056 raw_spin_lock(&ctx->lock);
2057 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2058 if (context_equiv(ctx, next_ctx)) {
2060 * XXX do we need a memory barrier of sorts
2061 * wrt to rcu_dereference() of perf_event_ctxp
2063 task->perf_event_ctxp[ctxn] = next_ctx;
2064 next->perf_event_ctxp[ctxn] = ctx;
2066 next_ctx->task = task;
2069 perf_event_sync_stat(ctx, next_ctx);
2071 raw_spin_unlock(&next_ctx->lock);
2072 raw_spin_unlock(&ctx->lock);
2077 raw_spin_lock(&ctx->lock);
2078 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2079 cpuctx->task_ctx = NULL;
2080 raw_spin_unlock(&ctx->lock);
2084 #define for_each_task_context_nr(ctxn) \
2085 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2088 * Called from scheduler to remove the events of the current task,
2089 * with interrupts disabled.
2091 * We stop each event and update the event value in event->count.
2093 * This does not protect us against NMI, but disable()
2094 * sets the disabled bit in the control field of event _before_
2095 * accessing the event control register. If a NMI hits, then it will
2096 * not restart the event.
2098 void __perf_event_task_sched_out(struct task_struct *task,
2099 struct task_struct *next)
2103 for_each_task_context_nr(ctxn)
2104 perf_event_context_sched_out(task, ctxn, next);
2107 * if cgroup events exist on this CPU, then we need
2108 * to check if we have to switch out PMU state.
2109 * cgroup event are system-wide mode only
2111 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2112 perf_cgroup_sched_out(task, next);
2115 static void task_ctx_sched_out(struct perf_event_context *ctx)
2117 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2119 if (!cpuctx->task_ctx)
2122 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2125 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2126 cpuctx->task_ctx = NULL;
2130 * Called with IRQs disabled
2132 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2133 enum event_type_t event_type)
2135 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2139 ctx_pinned_sched_in(struct perf_event_context *ctx,
2140 struct perf_cpu_context *cpuctx)
2142 struct perf_event *event;
2144 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2145 if (event->state <= PERF_EVENT_STATE_OFF)
2147 if (!event_filter_match(event))
2150 /* may need to reset tstamp_enabled */
2151 if (is_cgroup_event(event))
2152 perf_cgroup_mark_enabled(event, ctx);
2154 if (group_can_go_on(event, cpuctx, 1))
2155 group_sched_in(event, cpuctx, ctx);
2158 * If this pinned group hasn't been scheduled,
2159 * put it in error state.
2161 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2162 update_group_times(event);
2163 event->state = PERF_EVENT_STATE_ERROR;
2169 ctx_flexible_sched_in(struct perf_event_context *ctx,
2170 struct perf_cpu_context *cpuctx)
2172 struct perf_event *event;
2175 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2176 /* Ignore events in OFF or ERROR state */
2177 if (event->state <= PERF_EVENT_STATE_OFF)
2180 * Listen to the 'cpu' scheduling filter constraint
2183 if (!event_filter_match(event))
2186 /* may need to reset tstamp_enabled */
2187 if (is_cgroup_event(event))
2188 perf_cgroup_mark_enabled(event, ctx);
2190 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2191 if (group_sched_in(event, cpuctx, ctx))
2198 ctx_sched_in(struct perf_event_context *ctx,
2199 struct perf_cpu_context *cpuctx,
2200 enum event_type_t event_type,
2201 struct task_struct *task)
2204 int is_active = ctx->is_active;
2206 ctx->is_active |= event_type;
2207 if (likely(!ctx->nr_events))
2211 ctx->timestamp = now;
2212 perf_cgroup_set_timestamp(task, ctx);
2214 * First go through the list and put on any pinned groups
2215 * in order to give them the best chance of going on.
2217 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2218 ctx_pinned_sched_in(ctx, cpuctx);
2220 /* Then walk through the lower prio flexible groups */
2221 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2222 ctx_flexible_sched_in(ctx, cpuctx);
2225 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2226 enum event_type_t event_type,
2227 struct task_struct *task)
2229 struct perf_event_context *ctx = &cpuctx->ctx;
2231 ctx_sched_in(ctx, cpuctx, event_type, task);
2234 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2235 struct task_struct *task)
2237 struct perf_cpu_context *cpuctx;
2239 cpuctx = __get_cpu_context(ctx);
2240 if (cpuctx->task_ctx == ctx)
2243 perf_ctx_lock(cpuctx, ctx);
2244 perf_pmu_disable(ctx->pmu);
2246 * We want to keep the following priority order:
2247 * cpu pinned (that don't need to move), task pinned,
2248 * cpu flexible, task flexible.
2250 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2253 cpuctx->task_ctx = ctx;
2255 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2257 perf_pmu_enable(ctx->pmu);
2258 perf_ctx_unlock(cpuctx, ctx);
2261 * Since these rotations are per-cpu, we need to ensure the
2262 * cpu-context we got scheduled on is actually rotating.
2264 perf_pmu_rotate_start(ctx->pmu);
2268 * When sampling the branck stack in system-wide, it may be necessary
2269 * to flush the stack on context switch. This happens when the branch
2270 * stack does not tag its entries with the pid of the current task.
2271 * Otherwise it becomes impossible to associate a branch entry with a
2272 * task. This ambiguity is more likely to appear when the branch stack
2273 * supports priv level filtering and the user sets it to monitor only
2274 * at the user level (which could be a useful measurement in system-wide
2275 * mode). In that case, the risk is high of having a branch stack with
2276 * branch from multiple tasks. Flushing may mean dropping the existing
2277 * entries or stashing them somewhere in the PMU specific code layer.
2279 * This function provides the context switch callback to the lower code
2280 * layer. It is invoked ONLY when there is at least one system-wide context
2281 * with at least one active event using taken branch sampling.
2283 static void perf_branch_stack_sched_in(struct task_struct *prev,
2284 struct task_struct *task)
2286 struct perf_cpu_context *cpuctx;
2288 unsigned long flags;
2290 /* no need to flush branch stack if not changing task */
2294 local_irq_save(flags);
2298 list_for_each_entry_rcu(pmu, &pmus, entry) {
2299 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2302 * check if the context has at least one
2303 * event using PERF_SAMPLE_BRANCH_STACK
2305 if (cpuctx->ctx.nr_branch_stack > 0
2306 && pmu->flush_branch_stack) {
2308 pmu = cpuctx->ctx.pmu;
2310 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2312 perf_pmu_disable(pmu);
2314 pmu->flush_branch_stack();
2316 perf_pmu_enable(pmu);
2318 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2324 local_irq_restore(flags);
2328 * Called from scheduler to add the events of the current task
2329 * with interrupts disabled.
2331 * We restore the event value and then enable it.
2333 * This does not protect us against NMI, but enable()
2334 * sets the enabled bit in the control field of event _before_
2335 * accessing the event control register. If a NMI hits, then it will
2336 * keep the event running.
2338 void __perf_event_task_sched_in(struct task_struct *prev,
2339 struct task_struct *task)
2341 struct perf_event_context *ctx;
2344 for_each_task_context_nr(ctxn) {
2345 ctx = task->perf_event_ctxp[ctxn];
2349 perf_event_context_sched_in(ctx, task);
2352 * if cgroup events exist on this CPU, then we need
2353 * to check if we have to switch in PMU state.
2354 * cgroup event are system-wide mode only
2356 if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2357 perf_cgroup_sched_in(prev, task);
2359 /* check for system-wide branch_stack events */
2360 if (atomic_read(&__get_cpu_var(perf_branch_stack_events)))
2361 perf_branch_stack_sched_in(prev, task);
2364 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2366 u64 frequency = event->attr.sample_freq;
2367 u64 sec = NSEC_PER_SEC;
2368 u64 divisor, dividend;
2370 int count_fls, nsec_fls, frequency_fls, sec_fls;
2372 count_fls = fls64(count);
2373 nsec_fls = fls64(nsec);
2374 frequency_fls = fls64(frequency);
2378 * We got @count in @nsec, with a target of sample_freq HZ
2379 * the target period becomes:
2382 * period = -------------------
2383 * @nsec * sample_freq
2388 * Reduce accuracy by one bit such that @a and @b converge
2389 * to a similar magnitude.
2391 #define REDUCE_FLS(a, b) \
2393 if (a##_fls > b##_fls) { \
2403 * Reduce accuracy until either term fits in a u64, then proceed with
2404 * the other, so that finally we can do a u64/u64 division.
2406 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2407 REDUCE_FLS(nsec, frequency);
2408 REDUCE_FLS(sec, count);
2411 if (count_fls + sec_fls > 64) {
2412 divisor = nsec * frequency;
2414 while (count_fls + sec_fls > 64) {
2415 REDUCE_FLS(count, sec);
2419 dividend = count * sec;
2421 dividend = count * sec;
2423 while (nsec_fls + frequency_fls > 64) {
2424 REDUCE_FLS(nsec, frequency);
2428 divisor = nsec * frequency;
2434 return div64_u64(dividend, divisor);
2437 static DEFINE_PER_CPU(int, perf_throttled_count);
2438 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2440 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2442 struct hw_perf_event *hwc = &event->hw;
2443 s64 period, sample_period;
2446 period = perf_calculate_period(event, nsec, count);
2448 delta = (s64)(period - hwc->sample_period);
2449 delta = (delta + 7) / 8; /* low pass filter */
2451 sample_period = hwc->sample_period + delta;
2456 hwc->sample_period = sample_period;
2458 if (local64_read(&hwc->period_left) > 8*sample_period) {
2460 event->pmu->stop(event, PERF_EF_UPDATE);
2462 local64_set(&hwc->period_left, 0);
2465 event->pmu->start(event, PERF_EF_RELOAD);
2470 * combine freq adjustment with unthrottling to avoid two passes over the
2471 * events. At the same time, make sure, having freq events does not change
2472 * the rate of unthrottling as that would introduce bias.
2474 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
2477 struct perf_event *event;
2478 struct hw_perf_event *hwc;
2479 u64 now, period = TICK_NSEC;
2483 * only need to iterate over all events iff:
2484 * - context have events in frequency mode (needs freq adjust)
2485 * - there are events to unthrottle on this cpu
2487 if (!(ctx->nr_freq || needs_unthr))
2490 raw_spin_lock(&ctx->lock);
2491 perf_pmu_disable(ctx->pmu);
2493 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
2494 if (event->state != PERF_EVENT_STATE_ACTIVE)
2497 if (!event_filter_match(event))
2502 if (needs_unthr && hwc->interrupts == MAX_INTERRUPTS) {
2503 hwc->interrupts = 0;
2504 perf_log_throttle(event, 1);
2505 event->pmu->start(event, 0);
2508 if (!event->attr.freq || !event->attr.sample_freq)
2512 * stop the event and update event->count
2514 event->pmu->stop(event, PERF_EF_UPDATE);
2516 now = local64_read(&event->count);
2517 delta = now - hwc->freq_count_stamp;
2518 hwc->freq_count_stamp = now;
2522 * reload only if value has changed
2523 * we have stopped the event so tell that
2524 * to perf_adjust_period() to avoid stopping it
2528 perf_adjust_period(event, period, delta, false);
2530 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
2533 perf_pmu_enable(ctx->pmu);
2534 raw_spin_unlock(&ctx->lock);
2538 * Round-robin a context's events:
2540 static void rotate_ctx(struct perf_event_context *ctx)
2543 * Rotate the first entry last of non-pinned groups. Rotation might be
2544 * disabled by the inheritance code.
2546 if (!ctx->rotate_disable)
2547 list_rotate_left(&ctx->flexible_groups);
2551 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
2552 * because they're strictly cpu affine and rotate_start is called with IRQs
2553 * disabled, while rotate_context is called from IRQ context.
2555 static void perf_rotate_context(struct perf_cpu_context *cpuctx)
2557 struct perf_event_context *ctx = NULL;
2558 int rotate = 0, remove = 1;
2560 if (cpuctx->ctx.nr_events) {
2562 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
2566 ctx = cpuctx->task_ctx;
2567 if (ctx && ctx->nr_events) {
2569 if (ctx->nr_events != ctx->nr_active)
2576 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2577 perf_pmu_disable(cpuctx->ctx.pmu);
2579 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2581 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
2583 rotate_ctx(&cpuctx->ctx);
2587 perf_event_sched_in(cpuctx, ctx, current);
2589 perf_pmu_enable(cpuctx->ctx.pmu);
2590 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2593 list_del_init(&cpuctx->rotation_list);
2596 #ifdef CONFIG_NO_HZ_FULL
2597 bool perf_event_can_stop_tick(void)
2599 if (list_empty(&__get_cpu_var(rotation_list)))
2606 void perf_event_task_tick(void)
2608 struct list_head *head = &__get_cpu_var(rotation_list);
2609 struct perf_cpu_context *cpuctx, *tmp;
2610 struct perf_event_context *ctx;
2613 WARN_ON(!irqs_disabled());
2615 __this_cpu_inc(perf_throttled_seq);
2616 throttled = __this_cpu_xchg(perf_throttled_count, 0);
2618 list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) {
2620 perf_adjust_freq_unthr_context(ctx, throttled);
2622 ctx = cpuctx->task_ctx;
2624 perf_adjust_freq_unthr_context(ctx, throttled);
2626 if (cpuctx->jiffies_interval == 1 ||
2627 !(jiffies % cpuctx->jiffies_interval))
2628 perf_rotate_context(cpuctx);
2632 static int event_enable_on_exec(struct perf_event *event,
2633 struct perf_event_context *ctx)
2635 if (!event->attr.enable_on_exec)
2638 event->attr.enable_on_exec = 0;
2639 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2642 __perf_event_mark_enabled(event);
2648 * Enable all of a task's events that have been marked enable-on-exec.
2649 * This expects task == current.
2651 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
2653 struct perf_event *event;
2654 unsigned long flags;
2658 local_irq_save(flags);
2659 if (!ctx || !ctx->nr_events)
2663 * We must ctxsw out cgroup events to avoid conflict
2664 * when invoking perf_task_event_sched_in() later on
2665 * in this function. Otherwise we end up trying to
2666 * ctxswin cgroup events which are already scheduled
2669 perf_cgroup_sched_out(current, NULL);
2671 raw_spin_lock(&ctx->lock);
2672 task_ctx_sched_out(ctx);
2674 list_for_each_entry(event, &ctx->event_list, event_entry) {
2675 ret = event_enable_on_exec(event, ctx);
2681 * Unclone this context if we enabled any event.
2686 raw_spin_unlock(&ctx->lock);
2689 * Also calls ctxswin for cgroup events, if any:
2691 perf_event_context_sched_in(ctx, ctx->task);
2693 local_irq_restore(flags);
2697 * Cross CPU call to read the hardware event
2699 static void __perf_event_read(void *info)
2701 struct perf_event *event = info;
2702 struct perf_event_context *ctx = event->ctx;
2703 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2706 * If this is a task context, we need to check whether it is
2707 * the current task context of this cpu. If not it has been
2708 * scheduled out before the smp call arrived. In that case
2709 * event->count would have been updated to a recent sample
2710 * when the event was scheduled out.
2712 if (ctx->task && cpuctx->task_ctx != ctx)
2715 raw_spin_lock(&ctx->lock);
2716 if (ctx->is_active) {
2717 update_context_time(ctx);
2718 update_cgrp_time_from_event(event);
2720 update_event_times(event);
2721 if (event->state == PERF_EVENT_STATE_ACTIVE)
2722 event->pmu->read(event);
2723 raw_spin_unlock(&ctx->lock);
2726 static inline u64 perf_event_count(struct perf_event *event)
2728 return local64_read(&event->count) + atomic64_read(&event->child_count);
2731 static u64 perf_event_read(struct perf_event *event)
2734 * If event is enabled and currently active on a CPU, update the
2735 * value in the event structure:
2737 if (event->state == PERF_EVENT_STATE_ACTIVE) {
2738 smp_call_function_single(event->oncpu,
2739 __perf_event_read, event, 1);
2740 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
2741 struct perf_event_context *ctx = event->ctx;
2742 unsigned long flags;
2744 raw_spin_lock_irqsave(&ctx->lock, flags);
2746 * may read while context is not active
2747 * (e.g., thread is blocked), in that case
2748 * we cannot update context time
2750 if (ctx->is_active) {
2751 update_context_time(ctx);
2752 update_cgrp_time_from_event(event);
2754 update_event_times(event);
2755 raw_spin_unlock_irqrestore(&ctx->lock, flags);
2758 return perf_event_count(event);
2762 * Initialize the perf_event context in a task_struct:
2764 static void __perf_event_init_context(struct perf_event_context *ctx)
2766 raw_spin_lock_init(&ctx->lock);
2767 mutex_init(&ctx->mutex);
2768 INIT_LIST_HEAD(&ctx->pinned_groups);
2769 INIT_LIST_HEAD(&ctx->flexible_groups);
2770 INIT_LIST_HEAD(&ctx->event_list);
2771 atomic_set(&ctx->refcount, 1);
2774 static struct perf_event_context *
2775 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
2777 struct perf_event_context *ctx;
2779 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
2783 __perf_event_init_context(ctx);
2786 get_task_struct(task);
2793 static struct task_struct *
2794 find_lively_task_by_vpid(pid_t vpid)
2796 struct task_struct *task;
2803 task = find_task_by_vpid(vpid);
2805 get_task_struct(task);
2809 return ERR_PTR(-ESRCH);
2811 /* Reuse ptrace permission checks for now. */
2813 if (!ptrace_may_access(task, PTRACE_MODE_READ))
2818 put_task_struct(task);
2819 return ERR_PTR(err);
2824 * Returns a matching context with refcount and pincount.
2826 static struct perf_event_context *
2827 find_get_context(struct pmu *pmu, struct task_struct *task, int cpu)
2829 struct perf_event_context *ctx;
2830 struct perf_cpu_context *cpuctx;
2831 unsigned long flags;
2835 /* Must be root to operate on a CPU event: */
2836 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
2837 return ERR_PTR(-EACCES);
2840 * We could be clever and allow to attach a event to an
2841 * offline CPU and activate it when the CPU comes up, but
2844 if (!cpu_online(cpu))
2845 return ERR_PTR(-ENODEV);
2847 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
2856 ctxn = pmu->task_ctx_nr;
2861 ctx = perf_lock_task_context(task, ctxn, &flags);
2865 raw_spin_unlock_irqrestore(&ctx->lock, flags);
2867 ctx = alloc_perf_context(pmu, task);
2873 mutex_lock(&task->perf_event_mutex);
2875 * If it has already passed perf_event_exit_task().
2876 * we must see PF_EXITING, it takes this mutex too.
2878 if (task->flags & PF_EXITING)
2880 else if (task->perf_event_ctxp[ctxn])
2885 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
2887 mutex_unlock(&task->perf_event_mutex);
2889 if (unlikely(err)) {
2901 return ERR_PTR(err);
2904 static void perf_event_free_filter(struct perf_event *event);
2906 static void free_event_rcu(struct rcu_head *head)
2908 struct perf_event *event;
2910 event = container_of(head, struct perf_event, rcu_head);
2912 put_pid_ns(event->ns);
2913 perf_event_free_filter(event);
2917 static void ring_buffer_put(struct ring_buffer *rb);
2918 static void ring_buffer_detach(struct perf_event *event, struct ring_buffer *rb);
2920 static void free_event(struct perf_event *event)
2922 irq_work_sync(&event->pending);
2924 if (!event->parent) {
2925 if (event->attach_state & PERF_ATTACH_TASK)
2926 static_key_slow_dec_deferred(&perf_sched_events);
2927 if (event->attr.mmap || event->attr.mmap_data)
2928 atomic_dec(&nr_mmap_events);
2929 if (event->attr.comm)
2930 atomic_dec(&nr_comm_events);
2931 if (event->attr.task)
2932 atomic_dec(&nr_task_events);
2933 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
2934 put_callchain_buffers();
2935 if (is_cgroup_event(event)) {
2936 atomic_dec(&per_cpu(perf_cgroup_events, event->cpu));
2937 static_key_slow_dec_deferred(&perf_sched_events);
2940 if (has_branch_stack(event)) {
2941 static_key_slow_dec_deferred(&perf_sched_events);
2942 /* is system-wide event */
2943 if (!(event->attach_state & PERF_ATTACH_TASK)) {
2944 atomic_dec(&per_cpu(perf_branch_stack_events,
2951 struct ring_buffer *rb;
2954 * Can happen when we close an event with re-directed output.
2956 * Since we have a 0 refcount, perf_mmap_close() will skip
2957 * over us; possibly making our ring_buffer_put() the last.
2959 mutex_lock(&event->mmap_mutex);
2962 rcu_assign_pointer(event->rb, NULL);
2963 ring_buffer_detach(event, rb);
2964 ring_buffer_put(rb); /* could be last */
2966 mutex_unlock(&event->mmap_mutex);
2969 if (is_cgroup_event(event))
2970 perf_detach_cgroup(event);
2973 event->destroy(event);
2976 put_ctx(event->ctx);
2978 call_rcu(&event->rcu_head, free_event_rcu);
2981 int perf_event_release_kernel(struct perf_event *event)
2983 struct perf_event_context *ctx = event->ctx;
2985 WARN_ON_ONCE(ctx->parent_ctx);
2987 * There are two ways this annotation is useful:
2989 * 1) there is a lock recursion from perf_event_exit_task
2990 * see the comment there.
2992 * 2) there is a lock-inversion with mmap_sem through
2993 * perf_event_read_group(), which takes faults while
2994 * holding ctx->mutex, however this is called after
2995 * the last filedesc died, so there is no possibility
2996 * to trigger the AB-BA case.
2998 mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
2999 raw_spin_lock_irq(&ctx->lock);
3000 perf_group_detach(event);
3001 raw_spin_unlock_irq(&ctx->lock);
3002 perf_remove_from_context(event);
3003 mutex_unlock(&ctx->mutex);
3009 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3012 * Called when the last reference to the file is gone.
3014 static void put_event(struct perf_event *event)
3016 struct task_struct *owner;
3018 if (!atomic_long_dec_and_test(&event->refcount))
3022 owner = ACCESS_ONCE(event->owner);
3024 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3025 * !owner it means the list deletion is complete and we can indeed
3026 * free this event, otherwise we need to serialize on
3027 * owner->perf_event_mutex.
3029 smp_read_barrier_depends();
3032 * Since delayed_put_task_struct() also drops the last
3033 * task reference we can safely take a new reference
3034 * while holding the rcu_read_lock().
3036 get_task_struct(owner);
3041 mutex_lock(&owner->perf_event_mutex);
3043 * We have to re-check the event->owner field, if it is cleared
3044 * we raced with perf_event_exit_task(), acquiring the mutex
3045 * ensured they're done, and we can proceed with freeing the
3049 list_del_init(&event->owner_entry);
3050 mutex_unlock(&owner->perf_event_mutex);
3051 put_task_struct(owner);
3054 perf_event_release_kernel(event);
3057 static int perf_release(struct inode *inode, struct file *file)
3059 put_event(file->private_data);
3063 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3065 struct perf_event *child;
3071 mutex_lock(&event->child_mutex);
3072 total += perf_event_read(event);
3073 *enabled += event->total_time_enabled +
3074 atomic64_read(&event->child_total_time_enabled);
3075 *running += event->total_time_running +
3076 atomic64_read(&event->child_total_time_running);
3078 list_for_each_entry(child, &event->child_list, child_list) {
3079 total += perf_event_read(child);
3080 *enabled += child->total_time_enabled;
3081 *running += child->total_time_running;
3083 mutex_unlock(&event->child_mutex);
3087 EXPORT_SYMBOL_GPL(perf_event_read_value);
3089 static int perf_event_read_group(struct perf_event *event,
3090 u64 read_format, char __user *buf)
3092 struct perf_event *leader = event->group_leader, *sub;
3093 int n = 0, size = 0, ret = -EFAULT;
3094 struct perf_event_context *ctx = leader->ctx;
3096 u64 count, enabled, running;
3098 mutex_lock(&ctx->mutex);
3099 count = perf_event_read_value(leader, &enabled, &running);
3101 values[n++] = 1 + leader->nr_siblings;
3102 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3103 values[n++] = enabled;
3104 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3105 values[n++] = running;
3106 values[n++] = count;
3107 if (read_format & PERF_FORMAT_ID)
3108 values[n++] = primary_event_id(leader);
3110 size = n * sizeof(u64);
3112 if (copy_to_user(buf, values, size))
3117 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3120 values[n++] = perf_event_read_value(sub, &enabled, &running);
3121 if (read_format & PERF_FORMAT_ID)
3122 values[n++] = primary_event_id(sub);
3124 size = n * sizeof(u64);
3126 if (copy_to_user(buf + ret, values, size)) {
3134 mutex_unlock(&ctx->mutex);
3139 static int perf_event_read_one(struct perf_event *event,
3140 u64 read_format, char __user *buf)
3142 u64 enabled, running;
3146 values[n++] = perf_event_read_value(event, &enabled, &running);
3147 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3148 values[n++] = enabled;
3149 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3150 values[n++] = running;
3151 if (read_format & PERF_FORMAT_ID)
3152 values[n++] = primary_event_id(event);
3154 if (copy_to_user(buf, values, n * sizeof(u64)))
3157 return n * sizeof(u64);
3161 * Read the performance event - simple non blocking version for now
3164 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
3166 u64 read_format = event->attr.read_format;
3170 * Return end-of-file for a read on a event that is in
3171 * error state (i.e. because it was pinned but it couldn't be
3172 * scheduled on to the CPU at some point).
3174 if (event->state == PERF_EVENT_STATE_ERROR)
3177 if (count < event->read_size)
3180 WARN_ON_ONCE(event->ctx->parent_ctx);
3181 if (read_format & PERF_FORMAT_GROUP)
3182 ret = perf_event_read_group(event, read_format, buf);
3184 ret = perf_event_read_one(event, read_format, buf);
3190 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
3192 struct perf_event *event = file->private_data;
3194 return perf_read_hw(event, buf, count);
3197 static unsigned int perf_poll(struct file *file, poll_table *wait)
3199 struct perf_event *event = file->private_data;
3200 struct ring_buffer *rb;
3201 unsigned int events = POLL_HUP;
3204 * Pin the event->rb by taking event->mmap_mutex; otherwise
3205 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
3207 mutex_lock(&event->mmap_mutex);
3210 events = atomic_xchg(&rb->poll, 0);
3211 mutex_unlock(&event->mmap_mutex);
3213 poll_wait(file, &event->waitq, wait);
3218 static void perf_event_reset(struct perf_event *event)
3220 (void)perf_event_read(event);
3221 local64_set(&event->count, 0);
3222 perf_event_update_userpage(event);
3226 * Holding the top-level event's child_mutex means that any
3227 * descendant process that has inherited this event will block
3228 * in sync_child_event if it goes to exit, thus satisfying the
3229 * task existence requirements of perf_event_enable/disable.
3231 static void perf_event_for_each_child(struct perf_event *event,
3232 void (*func)(struct perf_event *))
3234 struct perf_event *child;
3236 WARN_ON_ONCE(event->ctx->parent_ctx);
3237 mutex_lock(&event->child_mutex);
3239 list_for_each_entry(child, &event->child_list, child_list)
3241 mutex_unlock(&event->child_mutex);
3244 static void perf_event_for_each(struct perf_event *event,
3245 void (*func)(struct perf_event *))
3247 struct perf_event_context *ctx = event->ctx;
3248 struct perf_event *sibling;
3250 WARN_ON_ONCE(ctx->parent_ctx);
3251 mutex_lock(&ctx->mutex);
3252 event = event->group_leader;
3254 perf_event_for_each_child(event, func);
3255 list_for_each_entry(sibling, &event->sibling_list, group_entry)
3256 perf_event_for_each_child(sibling, func);
3257 mutex_unlock(&ctx->mutex);
3260 static int perf_event_period(struct perf_event *event, u64 __user *arg)
3262 struct perf_event_context *ctx = event->ctx;
3266 if (!is_sampling_event(event))
3269 if (copy_from_user(&value, arg, sizeof(value)))
3275 raw_spin_lock_irq(&ctx->lock);
3276 if (event->attr.freq) {
3277 if (value > sysctl_perf_event_sample_rate) {
3282 event->attr.sample_freq = value;
3284 event->attr.sample_period = value;
3285 event->hw.sample_period = value;
3288 raw_spin_unlock_irq(&ctx->lock);
3293 static const struct file_operations perf_fops;
3295 static inline int perf_fget_light(int fd, struct fd *p)
3297 struct fd f = fdget(fd);
3301 if (f.file->f_op != &perf_fops) {
3309 static int perf_event_set_output(struct perf_event *event,
3310 struct perf_event *output_event);
3311 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
3313 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
3315 struct perf_event *event = file->private_data;
3316 void (*func)(struct perf_event *);
3320 case PERF_EVENT_IOC_ENABLE:
3321 func = perf_event_enable;
3323 case PERF_EVENT_IOC_DISABLE:
3324 func = perf_event_disable;
3326 case PERF_EVENT_IOC_RESET:
3327 func = perf_event_reset;
3330 case PERF_EVENT_IOC_REFRESH:
3331 return perf_event_refresh(event, arg);
3333 case PERF_EVENT_IOC_PERIOD:
3334 return perf_event_period(event, (u64 __user *)arg);
3336 case PERF_EVENT_IOC_SET_OUTPUT:
3340 struct perf_event *output_event;
3342 ret = perf_fget_light(arg, &output);
3345 output_event = output.file->private_data;
3346 ret = perf_event_set_output(event, output_event);
3349 ret = perf_event_set_output(event, NULL);
3354 case PERF_EVENT_IOC_SET_FILTER:
3355 return perf_event_set_filter(event, (void __user *)arg);
3361 if (flags & PERF_IOC_FLAG_GROUP)
3362 perf_event_for_each(event, func);
3364 perf_event_for_each_child(event, func);
3369 int perf_event_task_enable(void)
3371 struct perf_event *event;
3373 mutex_lock(¤t->perf_event_mutex);
3374 list_for_each_entry(event, ¤t->perf_event_list, owner_entry)
3375 perf_event_for_each_child(event, perf_event_enable);
3376 mutex_unlock(¤t->perf_event_mutex);
3381 int perf_event_task_disable(void)
3383 struct perf_event *event;
3385 mutex_lock(¤t->perf_event_mutex);
3386 list_for_each_entry(event, ¤t->perf_event_list, owner_entry)
3387 perf_event_for_each_child(event, perf_event_disable);
3388 mutex_unlock(¤t->perf_event_mutex);
3393 static int perf_event_index(struct perf_event *event)
3395 if (event->hw.state & PERF_HES_STOPPED)
3398 if (event->state != PERF_EVENT_STATE_ACTIVE)
3401 return event->pmu->event_idx(event);
3404 static void calc_timer_values(struct perf_event *event,
3411 *now = perf_clock();
3412 ctx_time = event->shadow_ctx_time + *now;
3413 *enabled = ctx_time - event->tstamp_enabled;
3414 *running = ctx_time - event->tstamp_running;
3417 void __weak arch_perf_update_userpage(struct perf_event_mmap_page *userpg, u64 now)
3422 * Callers need to ensure there can be no nesting of this function, otherwise
3423 * the seqlock logic goes bad. We can not serialize this because the arch
3424 * code calls this from NMI context.
3426 void perf_event_update_userpage(struct perf_event *event)
3428 struct perf_event_mmap_page *userpg;
3429 struct ring_buffer *rb;
3430 u64 enabled, running, now;
3434 * compute total_time_enabled, total_time_running
3435 * based on snapshot values taken when the event
3436 * was last scheduled in.
3438 * we cannot simply called update_context_time()
3439 * because of locking issue as we can be called in
3442 calc_timer_values(event, &now, &enabled, &running);
3443 rb = rcu_dereference(event->rb);
3447 userpg = rb->user_page;
3450 * Disable preemption so as to not let the corresponding user-space
3451 * spin too long if we get preempted.
3456 userpg->index = perf_event_index(event);
3457 userpg->offset = perf_event_count(event);
3459 userpg->offset -= local64_read(&event->hw.prev_count);
3461 userpg->time_enabled = enabled +
3462 atomic64_read(&event->child_total_time_enabled);
3464 userpg->time_running = running +
3465 atomic64_read(&event->child_total_time_running);
3467 arch_perf_update_userpage(userpg, now);
3476 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
3478 struct perf_event *event = vma->vm_file->private_data;
3479 struct ring_buffer *rb;
3480 int ret = VM_FAULT_SIGBUS;
3482 if (vmf->flags & FAULT_FLAG_MKWRITE) {
3483 if (vmf->pgoff == 0)
3489 rb = rcu_dereference(event->rb);
3493 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
3496 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
3500 get_page(vmf->page);
3501 vmf->page->mapping = vma->vm_file->f_mapping;
3502 vmf->page->index = vmf->pgoff;
3511 static void ring_buffer_attach(struct perf_event *event,
3512 struct ring_buffer *rb)
3514 unsigned long flags;
3516 if (!list_empty(&event->rb_entry))
3519 spin_lock_irqsave(&rb->event_lock, flags);
3520 if (list_empty(&event->rb_entry))
3521 list_add(&event->rb_entry, &rb->event_list);
3522 spin_unlock_irqrestore(&rb->event_lock, flags);
3525 static void ring_buffer_detach(struct perf_event *event, struct ring_buffer *rb)
3527 unsigned long flags;
3529 if (list_empty(&event->rb_entry))
3532 spin_lock_irqsave(&rb->event_lock, flags);
3533 list_del_init(&event->rb_entry);
3534 wake_up_all(&event->waitq);
3535 spin_unlock_irqrestore(&rb->event_lock, flags);
3538 static void ring_buffer_wakeup(struct perf_event *event)
3540 struct ring_buffer *rb;
3543 rb = rcu_dereference(event->rb);
3545 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
3546 wake_up_all(&event->waitq);
3551 static void rb_free_rcu(struct rcu_head *rcu_head)
3553 struct ring_buffer *rb;
3555 rb = container_of(rcu_head, struct ring_buffer, rcu_head);
3559 static struct ring_buffer *ring_buffer_get(struct perf_event *event)
3561 struct ring_buffer *rb;
3564 rb = rcu_dereference(event->rb);
3566 if (!atomic_inc_not_zero(&rb->refcount))
3574 static void ring_buffer_put(struct ring_buffer *rb)
3576 if (!atomic_dec_and_test(&rb->refcount))
3579 WARN_ON_ONCE(!list_empty(&rb->event_list));
3581 call_rcu(&rb->rcu_head, rb_free_rcu);
3584 static void perf_mmap_open(struct vm_area_struct *vma)
3586 struct perf_event *event = vma->vm_file->private_data;
3588 atomic_inc(&event->mmap_count);
3589 atomic_inc(&event->rb->mmap_count);
3593 * A buffer can be mmap()ed multiple times; either directly through the same
3594 * event, or through other events by use of perf_event_set_output().
3596 * In order to undo the VM accounting done by perf_mmap() we need to destroy
3597 * the buffer here, where we still have a VM context. This means we need
3598 * to detach all events redirecting to us.
3600 static void perf_mmap_close(struct vm_area_struct *vma)
3602 struct perf_event *event = vma->vm_file->private_data;
3604 struct ring_buffer *rb = event->rb;
3605 struct user_struct *mmap_user = rb->mmap_user;
3606 int mmap_locked = rb->mmap_locked;
3607 unsigned long size = perf_data_size(rb);
3609 atomic_dec(&rb->mmap_count);
3611 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
3614 /* Detach current event from the buffer. */
3615 rcu_assign_pointer(event->rb, NULL);
3616 ring_buffer_detach(event, rb);
3617 mutex_unlock(&event->mmap_mutex);
3619 /* If there's still other mmap()s of this buffer, we're done. */
3620 if (atomic_read(&rb->mmap_count)) {
3621 ring_buffer_put(rb); /* can't be last */
3626 * No other mmap()s, detach from all other events that might redirect
3627 * into the now unreachable buffer. Somewhat complicated by the
3628 * fact that rb::event_lock otherwise nests inside mmap_mutex.
3632 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
3633 if (!atomic_long_inc_not_zero(&event->refcount)) {
3635 * This event is en-route to free_event() which will
3636 * detach it and remove it from the list.
3642 mutex_lock(&event->mmap_mutex);
3644 * Check we didn't race with perf_event_set_output() which can
3645 * swizzle the rb from under us while we were waiting to
3646 * acquire mmap_mutex.
3648 * If we find a different rb; ignore this event, a next
3649 * iteration will no longer find it on the list. We have to
3650 * still restart the iteration to make sure we're not now
3651 * iterating the wrong list.
3653 if (event->rb == rb) {
3654 rcu_assign_pointer(event->rb, NULL);
3655 ring_buffer_detach(event, rb);
3656 ring_buffer_put(rb); /* can't be last, we still have one */
3658 mutex_unlock(&event->mmap_mutex);
3662 * Restart the iteration; either we're on the wrong list or
3663 * destroyed its integrity by doing a deletion.
3670 * It could be there's still a few 0-ref events on the list; they'll
3671 * get cleaned up by free_event() -- they'll also still have their
3672 * ref on the rb and will free it whenever they are done with it.
3674 * Aside from that, this buffer is 'fully' detached and unmapped,
3675 * undo the VM accounting.
3678 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
3679 vma->vm_mm->pinned_vm -= mmap_locked;
3680 free_uid(mmap_user);
3682 ring_buffer_put(rb); /* could be last */
3685 static const struct vm_operations_struct perf_mmap_vmops = {
3686 .open = perf_mmap_open,
3687 .close = perf_mmap_close,
3688 .fault = perf_mmap_fault,
3689 .page_mkwrite = perf_mmap_fault,
3692 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
3694 struct perf_event *event = file->private_data;
3695 unsigned long user_locked, user_lock_limit;
3696 struct user_struct *user = current_user();
3697 unsigned long locked, lock_limit;
3698 struct ring_buffer *rb;
3699 unsigned long vma_size;
3700 unsigned long nr_pages;
3701 long user_extra, extra;
3702 int ret = 0, flags = 0;
3705 * Don't allow mmap() of inherited per-task counters. This would
3706 * create a performance issue due to all children writing to the
3709 if (event->cpu == -1 && event->attr.inherit)
3712 if (!(vma->vm_flags & VM_SHARED))
3715 vma_size = vma->vm_end - vma->vm_start;
3716 nr_pages = (vma_size / PAGE_SIZE) - 1;
3719 * If we have rb pages ensure they're a power-of-two number, so we
3720 * can do bitmasks instead of modulo.
3722 if (nr_pages != 0 && !is_power_of_2(nr_pages))
3725 if (vma_size != PAGE_SIZE * (1 + nr_pages))
3728 if (vma->vm_pgoff != 0)
3731 WARN_ON_ONCE(event->ctx->parent_ctx);
3733 mutex_lock(&event->mmap_mutex);
3735 if (event->rb->nr_pages != nr_pages) {
3740 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
3742 * Raced against perf_mmap_close() through
3743 * perf_event_set_output(). Try again, hope for better
3746 mutex_unlock(&event->mmap_mutex);
3753 user_extra = nr_pages + 1;
3754 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
3757 * Increase the limit linearly with more CPUs:
3759 user_lock_limit *= num_online_cpus();
3761 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
3764 if (user_locked > user_lock_limit)
3765 extra = user_locked - user_lock_limit;
3767 lock_limit = rlimit(RLIMIT_MEMLOCK);
3768 lock_limit >>= PAGE_SHIFT;
3769 locked = vma->vm_mm->pinned_vm + extra;
3771 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
3772 !capable(CAP_IPC_LOCK)) {
3779 if (vma->vm_flags & VM_WRITE)
3780 flags |= RING_BUFFER_WRITABLE;
3782 rb = rb_alloc(nr_pages,
3783 event->attr.watermark ? event->attr.wakeup_watermark : 0,
3791 atomic_set(&rb->mmap_count, 1);
3792 rb->mmap_locked = extra;
3793 rb->mmap_user = get_current_user();
3795 atomic_long_add(user_extra, &user->locked_vm);
3796 vma->vm_mm->pinned_vm += extra;
3798 ring_buffer_attach(event, rb);
3799 rcu_assign_pointer(event->rb, rb);
3801 perf_event_update_userpage(event);
3805 atomic_inc(&event->mmap_count);
3806 mutex_unlock(&event->mmap_mutex);
3809 * Since pinned accounting is per vm we cannot allow fork() to copy our
3812 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
3813 vma->vm_ops = &perf_mmap_vmops;
3818 static int perf_fasync(int fd, struct file *filp, int on)
3820 struct inode *inode = file_inode(filp);
3821 struct perf_event *event = filp->private_data;
3824 mutex_lock(&inode->i_mutex);
3825 retval = fasync_helper(fd, filp, on, &event->fasync);
3826 mutex_unlock(&inode->i_mutex);
3834 static const struct file_operations perf_fops = {
3835 .llseek = no_llseek,
3836 .release = perf_release,
3839 .unlocked_ioctl = perf_ioctl,
3840 .compat_ioctl = perf_ioctl,
3842 .fasync = perf_fasync,
3848 * If there's data, ensure we set the poll() state and publish everything
3849 * to user-space before waking everybody up.
3852 void perf_event_wakeup(struct perf_event *event)
3854 ring_buffer_wakeup(event);
3856 if (event->pending_kill) {
3857 kill_fasync(&event->fasync, SIGIO, event->pending_kill);
3858 event->pending_kill = 0;
3862 static void perf_pending_event(struct irq_work *entry)
3864 struct perf_event *event = container_of(entry,
3865 struct perf_event, pending);
3867 if (event->pending_disable) {
3868 event->pending_disable = 0;
3869 __perf_event_disable(event);
3872 if (event->pending_wakeup) {
3873 event->pending_wakeup = 0;
3874 perf_event_wakeup(event);
3879 * We assume there is only KVM supporting the callbacks.
3880 * Later on, we might change it to a list if there is
3881 * another virtualization implementation supporting the callbacks.
3883 struct perf_guest_info_callbacks *perf_guest_cbs;
3885 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
3887 perf_guest_cbs = cbs;
3890 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
3892 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
3894 perf_guest_cbs = NULL;
3897 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
3900 perf_output_sample_regs(struct perf_output_handle *handle,
3901 struct pt_regs *regs, u64 mask)
3905 for_each_set_bit(bit, (const unsigned long *) &mask,
3906 sizeof(mask) * BITS_PER_BYTE) {
3909 val = perf_reg_value(regs, bit);
3910 perf_output_put(handle, val);
3914 static void perf_sample_regs_user(struct perf_regs_user *regs_user,
3915 struct pt_regs *regs)
3917 if (!user_mode(regs)) {
3919 regs = task_pt_regs(current);
3925 regs_user->regs = regs;
3926 regs_user->abi = perf_reg_abi(current);
3931 * Get remaining task size from user stack pointer.
3933 * It'd be better to take stack vma map and limit this more
3934 * precisly, but there's no way to get it safely under interrupt,
3935 * so using TASK_SIZE as limit.
3937 static u64 perf_ustack_task_size(struct pt_regs *regs)
3939 unsigned long addr = perf_user_stack_pointer(regs);
3941 if (!addr || addr >= TASK_SIZE)
3944 return TASK_SIZE - addr;
3948 perf_sample_ustack_size(u16 stack_size, u16 header_size,
3949 struct pt_regs *regs)
3953 /* No regs, no stack pointer, no dump. */
3958 * Check if we fit in with the requested stack size into the:
3960 * If we don't, we limit the size to the TASK_SIZE.
3962 * - remaining sample size
3963 * If we don't, we customize the stack size to
3964 * fit in to the remaining sample size.
3967 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
3968 stack_size = min(stack_size, (u16) task_size);
3970 /* Current header size plus static size and dynamic size. */
3971 header_size += 2 * sizeof(u64);
3973 /* Do we fit in with the current stack dump size? */
3974 if ((u16) (header_size + stack_size) < header_size) {
3976 * If we overflow the maximum size for the sample,
3977 * we customize the stack dump size to fit in.
3979 stack_size = USHRT_MAX - header_size - sizeof(u64);
3980 stack_size = round_up(stack_size, sizeof(u64));
3987 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
3988 struct pt_regs *regs)
3990 /* Case of a kernel thread, nothing to dump */
3993 perf_output_put(handle, size);
4002 * - the size requested by user or the best one we can fit
4003 * in to the sample max size
4005 * - user stack dump data
4007 * - the actual dumped size
4011 perf_output_put(handle, dump_size);
4014 sp = perf_user_stack_pointer(regs);
4015 rem = __output_copy_user(handle, (void *) sp, dump_size);
4016 dyn_size = dump_size - rem;
4018 perf_output_skip(handle, rem);
4021 perf_output_put(handle, dyn_size);
4025 static void __perf_event_header__init_id(struct perf_event_header *header,
4026 struct perf_sample_data *data,
4027 struct perf_event *event)
4029 u64 sample_type = event->attr.sample_type;
4031 data->type = sample_type;
4032 header->size += event->id_header_size;
4034 if (sample_type & PERF_SAMPLE_TID) {
4035 /* namespace issues */
4036 data->tid_entry.pid = perf_event_pid(event, current);
4037 data->tid_entry.tid = perf_event_tid(event, current);
4040 if (sample_type & PERF_SAMPLE_TIME)
4041 data->time = perf_clock();
4043 if (sample_type & PERF_SAMPLE_ID)
4044 data->id = primary_event_id(event);
4046 if (sample_type & PERF_SAMPLE_STREAM_ID)
4047 data->stream_id = event->id;
4049 if (sample_type & PERF_SAMPLE_CPU) {
4050 data->cpu_entry.cpu = raw_smp_processor_id();
4051 data->cpu_entry.reserved = 0;
4055 void perf_event_header__init_id(struct perf_event_header *header,
4056 struct perf_sample_data *data,
4057 struct perf_event *event)
4059 if (event->attr.sample_id_all)
4060 __perf_event_header__init_id(header, data, event);
4063 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
4064 struct perf_sample_data *data)
4066 u64 sample_type = data->type;
4068 if (sample_type & PERF_SAMPLE_TID)
4069 perf_output_put(handle, data->tid_entry);
4071 if (sample_type & PERF_SAMPLE_TIME)
4072 perf_output_put(handle, data->time);
4074 if (sample_type & PERF_SAMPLE_ID)
4075 perf_output_put(handle, data->id);
4077 if (sample_type & PERF_SAMPLE_STREAM_ID)
4078 perf_output_put(handle, data->stream_id);
4080 if (sample_type & PERF_SAMPLE_CPU)
4081 perf_output_put(handle, data->cpu_entry);
4084 void perf_event__output_id_sample(struct perf_event *event,
4085 struct perf_output_handle *handle,
4086 struct perf_sample_data *sample)
4088 if (event->attr.sample_id_all)
4089 __perf_event__output_id_sample(handle, sample);
4092 static void perf_output_read_one(struct perf_output_handle *handle,
4093 struct perf_event *event,
4094 u64 enabled, u64 running)
4096 u64 read_format = event->attr.read_format;
4100 values[n++] = perf_event_count(event);
4101 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4102 values[n++] = enabled +
4103 atomic64_read(&event->child_total_time_enabled);
4105 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4106 values[n++] = running +
4107 atomic64_read(&event->child_total_time_running);
4109 if (read_format & PERF_FORMAT_ID)
4110 values[n++] = primary_event_id(event);
4112 __output_copy(handle, values, n * sizeof(u64));
4116 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
4118 static void perf_output_read_group(struct perf_output_handle *handle,
4119 struct perf_event *event,
4120 u64 enabled, u64 running)
4122 struct perf_event *leader = event->group_leader, *sub;
4123 u64 read_format = event->attr.read_format;
4127 values[n++] = 1 + leader->nr_siblings;
4129 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4130 values[n++] = enabled;
4132 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4133 values[n++] = running;
4135 if (leader != event)
4136 leader->pmu->read(leader);
4138 values[n++] = perf_event_count(leader);
4139 if (read_format & PERF_FORMAT_ID)
4140 values[n++] = primary_event_id(leader);
4142 __output_copy(handle, values, n * sizeof(u64));
4144 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4148 sub->pmu->read(sub);
4150 values[n++] = perf_event_count(sub);
4151 if (read_format & PERF_FORMAT_ID)
4152 values[n++] = primary_event_id(sub);
4154 __output_copy(handle, values, n * sizeof(u64));
4158 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
4159 PERF_FORMAT_TOTAL_TIME_RUNNING)
4161 static void perf_output_read(struct perf_output_handle *handle,
4162 struct perf_event *event)
4164 u64 enabled = 0, running = 0, now;
4165 u64 read_format = event->attr.read_format;
4168 * compute total_time_enabled, total_time_running
4169 * based on snapshot values taken when the event
4170 * was last scheduled in.
4172 * we cannot simply called update_context_time()
4173 * because of locking issue as we are called in
4176 if (read_format & PERF_FORMAT_TOTAL_TIMES)
4177 calc_timer_values(event, &now, &enabled, &running);
4179 if (event->attr.read_format & PERF_FORMAT_GROUP)
4180 perf_output_read_group(handle, event, enabled, running);
4182 perf_output_read_one(handle, event, enabled, running);
4185 void perf_output_sample(struct perf_output_handle *handle,
4186 struct perf_event_header *header,
4187 struct perf_sample_data *data,
4188 struct perf_event *event)
4190 u64 sample_type = data->type;
4192 perf_output_put(handle, *header);
4194 if (sample_type & PERF_SAMPLE_IP)
4195 perf_output_put(handle, data->ip);
4197 if (sample_type & PERF_SAMPLE_TID)
4198 perf_output_put(handle, data->tid_entry);
4200 if (sample_type & PERF_SAMPLE_TIME)
4201 perf_output_put(handle, data->time);
4203 if (sample_type & PERF_SAMPLE_ADDR)
4204 perf_output_put(handle, data->addr);
4206 if (sample_type & PERF_SAMPLE_ID)
4207 perf_output_put(handle, data->id);
4209 if (sample_type & PERF_SAMPLE_STREAM_ID)
4210 perf_output_put(handle, data->stream_id);
4212 if (sample_type & PERF_SAMPLE_CPU)
4213 perf_output_put(handle, data->cpu_entry);
4215 if (sample_type & PERF_SAMPLE_PERIOD)
4216 perf_output_put(handle, data->period);
4218 if (sample_type & PERF_SAMPLE_READ)
4219 perf_output_read(handle, event);
4221 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4222 if (data->callchain) {
4225 if (data->callchain)
4226 size += data->callchain->nr;
4228 size *= sizeof(u64);
4230 __output_copy(handle, data->callchain, size);
4233 perf_output_put(handle, nr);
4237 if (sample_type & PERF_SAMPLE_RAW) {
4239 perf_output_put(handle, data->raw->size);
4240 __output_copy(handle, data->raw->data,
4247 .size = sizeof(u32),
4250 perf_output_put(handle, raw);
4254 if (!event->attr.watermark) {
4255 int wakeup_events = event->attr.wakeup_events;
4257 if (wakeup_events) {
4258 struct ring_buffer *rb = handle->rb;
4259 int events = local_inc_return(&rb->events);
4261 if (events >= wakeup_events) {
4262 local_sub(wakeup_events, &rb->events);
4263 local_inc(&rb->wakeup);
4268 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4269 if (data->br_stack) {
4272 size = data->br_stack->nr
4273 * sizeof(struct perf_branch_entry);
4275 perf_output_put(handle, data->br_stack->nr);
4276 perf_output_copy(handle, data->br_stack->entries, size);
4279 * we always store at least the value of nr
4282 perf_output_put(handle, nr);
4286 if (sample_type & PERF_SAMPLE_REGS_USER) {
4287 u64 abi = data->regs_user.abi;
4290 * If there are no regs to dump, notice it through
4291 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
4293 perf_output_put(handle, abi);
4296 u64 mask = event->attr.sample_regs_user;
4297 perf_output_sample_regs(handle,
4298 data->regs_user.regs,
4303 if (sample_type & PERF_SAMPLE_STACK_USER)
4304 perf_output_sample_ustack(handle,
4305 data->stack_user_size,
4306 data->regs_user.regs);
4308 if (sample_type & PERF_SAMPLE_WEIGHT)
4309 perf_output_put(handle, data->weight);
4311 if (sample_type & PERF_SAMPLE_DATA_SRC)
4312 perf_output_put(handle, data->data_src.val);
4315 void perf_prepare_sample(struct perf_event_header *header,
4316 struct perf_sample_data *data,
4317 struct perf_event *event,
4318 struct pt_regs *regs)
4320 u64 sample_type = event->attr.sample_type;
4322 header->type = PERF_RECORD_SAMPLE;
4323 header->size = sizeof(*header) + event->header_size;
4326 header->misc |= perf_misc_flags(regs);
4328 __perf_event_header__init_id(header, data, event);
4330 if (sample_type & PERF_SAMPLE_IP)
4331 data->ip = perf_instruction_pointer(regs);
4333 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4336 data->callchain = perf_callchain(event, regs);
4338 if (data->callchain)
4339 size += data->callchain->nr;
4341 header->size += size * sizeof(u64);
4344 if (sample_type & PERF_SAMPLE_RAW) {
4345 int size = sizeof(u32);
4348 size += data->raw->size;
4350 size += sizeof(u32);
4352 WARN_ON_ONCE(size & (sizeof(u64)-1));
4353 header->size += size;
4356 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4357 int size = sizeof(u64); /* nr */
4358 if (data->br_stack) {
4359 size += data->br_stack->nr
4360 * sizeof(struct perf_branch_entry);
4362 header->size += size;
4365 if (sample_type & PERF_SAMPLE_REGS_USER) {
4366 /* regs dump ABI info */
4367 int size = sizeof(u64);
4369 perf_sample_regs_user(&data->regs_user, regs);
4371 if (data->regs_user.regs) {
4372 u64 mask = event->attr.sample_regs_user;
4373 size += hweight64(mask) * sizeof(u64);
4376 header->size += size;
4379 if (sample_type & PERF_SAMPLE_STACK_USER) {
4381 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
4382 * processed as the last one or have additional check added
4383 * in case new sample type is added, because we could eat
4384 * up the rest of the sample size.
4386 struct perf_regs_user *uregs = &data->regs_user;
4387 u16 stack_size = event->attr.sample_stack_user;
4388 u16 size = sizeof(u64);
4391 perf_sample_regs_user(uregs, regs);
4393 stack_size = perf_sample_ustack_size(stack_size, header->size,
4397 * If there is something to dump, add space for the dump
4398 * itself and for the field that tells the dynamic size,
4399 * which is how many have been actually dumped.
4402 size += sizeof(u64) + stack_size;
4404 data->stack_user_size = stack_size;
4405 header->size += size;
4409 static void perf_event_output(struct perf_event *event,
4410 struct perf_sample_data *data,
4411 struct pt_regs *regs)
4413 struct perf_output_handle handle;
4414 struct perf_event_header header;
4416 /* protect the callchain buffers */
4419 perf_prepare_sample(&header, data, event, regs);
4421 if (perf_output_begin(&handle, event, header.size))
4424 perf_output_sample(&handle, &header, data, event);
4426 perf_output_end(&handle);
4436 struct perf_read_event {
4437 struct perf_event_header header;
4444 perf_event_read_event(struct perf_event *event,
4445 struct task_struct *task)
4447 struct perf_output_handle handle;
4448 struct perf_sample_data sample;
4449 struct perf_read_event read_event = {
4451 .type = PERF_RECORD_READ,
4453 .size = sizeof(read_event) + event->read_size,
4455 .pid = perf_event_pid(event, task),
4456 .tid = perf_event_tid(event, task),
4460 perf_event_header__init_id(&read_event.header, &sample, event);
4461 ret = perf_output_begin(&handle, event, read_event.header.size);
4465 perf_output_put(&handle, read_event);
4466 perf_output_read(&handle, event);
4467 perf_event__output_id_sample(event, &handle, &sample);
4469 perf_output_end(&handle);
4472 typedef int (perf_event_aux_match_cb)(struct perf_event *event, void *data);
4473 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
4476 perf_event_aux_ctx(struct perf_event_context *ctx,
4477 perf_event_aux_match_cb match,
4478 perf_event_aux_output_cb output,
4481 struct perf_event *event;
4483 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4484 if (event->state < PERF_EVENT_STATE_INACTIVE)
4486 if (!event_filter_match(event))
4488 if (match(event, data))
4489 output(event, data);
4494 perf_event_aux(perf_event_aux_match_cb match,
4495 perf_event_aux_output_cb output,
4497 struct perf_event_context *task_ctx)
4499 struct perf_cpu_context *cpuctx;
4500 struct perf_event_context *ctx;
4505 list_for_each_entry_rcu(pmu, &pmus, entry) {
4506 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4507 if (cpuctx->unique_pmu != pmu)
4509 perf_event_aux_ctx(&cpuctx->ctx, match, output, data);
4512 ctxn = pmu->task_ctx_nr;
4515 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4517 perf_event_aux_ctx(ctx, match, output, data);
4519 put_cpu_ptr(pmu->pmu_cpu_context);
4524 perf_event_aux_ctx(task_ctx, match, output, data);
4531 * task tracking -- fork/exit
4533 * enabled by: attr.comm | attr.mmap | attr.mmap_data | attr.task
4536 struct perf_task_event {
4537 struct task_struct *task;
4538 struct perf_event_context *task_ctx;
4541 struct perf_event_header header;
4551 static void perf_event_task_output(struct perf_event *event,
4554 struct perf_task_event *task_event = data;
4555 struct perf_output_handle handle;
4556 struct perf_sample_data sample;
4557 struct task_struct *task = task_event->task;
4558 int ret, size = task_event->event_id.header.size;
4560 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
4562 ret = perf_output_begin(&handle, event,
4563 task_event->event_id.header.size);
4567 task_event->event_id.pid = perf_event_pid(event, task);
4568 task_event->event_id.ppid = perf_event_pid(event, current);
4570 task_event->event_id.tid = perf_event_tid(event, task);
4571 task_event->event_id.ptid = perf_event_tid(event, current);
4573 perf_output_put(&handle, task_event->event_id);
4575 perf_event__output_id_sample(event, &handle, &sample);
4577 perf_output_end(&handle);
4579 task_event->event_id.header.size = size;
4582 static int perf_event_task_match(struct perf_event *event,
4583 void *data __maybe_unused)
4585 return event->attr.comm || event->attr.mmap ||
4586 event->attr.mmap_data || event->attr.task;
4589 static void perf_event_task(struct task_struct *task,
4590 struct perf_event_context *task_ctx,
4593 struct perf_task_event task_event;
4595 if (!atomic_read(&nr_comm_events) &&
4596 !atomic_read(&nr_mmap_events) &&
4597 !atomic_read(&nr_task_events))
4600 task_event = (struct perf_task_event){
4602 .task_ctx = task_ctx,
4605 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
4607 .size = sizeof(task_event.event_id),
4613 .time = perf_clock(),
4617 perf_event_aux(perf_event_task_match,
4618 perf_event_task_output,
4623 void perf_event_fork(struct task_struct *task)
4625 perf_event_task(task, NULL, 1);
4632 struct perf_comm_event {
4633 struct task_struct *task;
4638 struct perf_event_header header;
4645 static void perf_event_comm_output(struct perf_event *event,
4648 struct perf_comm_event *comm_event = data;
4649 struct perf_output_handle handle;
4650 struct perf_sample_data sample;
4651 int size = comm_event->event_id.header.size;
4654 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
4655 ret = perf_output_begin(&handle, event,
4656 comm_event->event_id.header.size);
4661 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
4662 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
4664 perf_output_put(&handle, comm_event->event_id);
4665 __output_copy(&handle, comm_event->comm,
4666 comm_event->comm_size);
4668 perf_event__output_id_sample(event, &handle, &sample);
4670 perf_output_end(&handle);
4672 comm_event->event_id.header.size = size;
4675 static int perf_event_comm_match(struct perf_event *event,
4676 void *data __maybe_unused)
4678 return event->attr.comm;
4681 static void perf_event_comm_event(struct perf_comm_event *comm_event)
4683 char comm[TASK_COMM_LEN];
4686 memset(comm, 0, sizeof(comm));
4687 strlcpy(comm, comm_event->task->comm, sizeof(comm));
4688 size = ALIGN(strlen(comm)+1, sizeof(u64));
4690 comm_event->comm = comm;
4691 comm_event->comm_size = size;
4693 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
4695 perf_event_aux(perf_event_comm_match,
4696 perf_event_comm_output,
4701 void perf_event_comm(struct task_struct *task)
4703 struct perf_comm_event comm_event;
4704 struct perf_event_context *ctx;
4708 for_each_task_context_nr(ctxn) {
4709 ctx = task->perf_event_ctxp[ctxn];
4713 perf_event_enable_on_exec(ctx);
4717 if (!atomic_read(&nr_comm_events))
4720 comm_event = (struct perf_comm_event){
4726 .type = PERF_RECORD_COMM,
4735 perf_event_comm_event(&comm_event);
4742 struct perf_mmap_event {
4743 struct vm_area_struct *vma;
4745 const char *file_name;
4749 struct perf_event_header header;
4759 static void perf_event_mmap_output(struct perf_event *event,
4762 struct perf_mmap_event *mmap_event = data;
4763 struct perf_output_handle handle;
4764 struct perf_sample_data sample;
4765 int size = mmap_event->event_id.header.size;
4768 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
4769 ret = perf_output_begin(&handle, event,
4770 mmap_event->event_id.header.size);
4774 mmap_event->event_id.pid = perf_event_pid(event, current);
4775 mmap_event->event_id.tid = perf_event_tid(event, current);
4777 perf_output_put(&handle, mmap_event->event_id);
4778 __output_copy(&handle, mmap_event->file_name,
4779 mmap_event->file_size);
4781 perf_event__output_id_sample(event, &handle, &sample);
4783 perf_output_end(&handle);
4785 mmap_event->event_id.header.size = size;
4788 static int perf_event_mmap_match(struct perf_event *event,
4791 struct perf_mmap_event *mmap_event = data;
4792 struct vm_area_struct *vma = mmap_event->vma;
4793 int executable = vma->vm_flags & VM_EXEC;
4795 return (!executable && event->attr.mmap_data) ||
4796 (executable && event->attr.mmap);
4799 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
4801 struct vm_area_struct *vma = mmap_event->vma;
4802 struct file *file = vma->vm_file;
4808 memset(tmp, 0, sizeof(tmp));
4812 * d_path works from the end of the rb backwards, so we
4813 * need to add enough zero bytes after the string to handle
4814 * the 64bit alignment we do later.
4816 buf = kzalloc(PATH_MAX + sizeof(u64), GFP_KERNEL);
4818 name = strncpy(tmp, "//enomem", sizeof(tmp));
4821 name = d_path(&file->f_path, buf, PATH_MAX);
4823 name = strncpy(tmp, "//toolong", sizeof(tmp));
4827 if (arch_vma_name(mmap_event->vma)) {
4828 name = strncpy(tmp, arch_vma_name(mmap_event->vma),
4830 tmp[sizeof(tmp) - 1] = '\0';
4835 name = strncpy(tmp, "[vdso]", sizeof(tmp));
4837 } else if (vma->vm_start <= vma->vm_mm->start_brk &&
4838 vma->vm_end >= vma->vm_mm->brk) {
4839 name = strncpy(tmp, "[heap]", sizeof(tmp));
4841 } else if (vma->vm_start <= vma->vm_mm->start_stack &&
4842 vma->vm_end >= vma->vm_mm->start_stack) {
4843 name = strncpy(tmp, "[stack]", sizeof(tmp));
4847 name = strncpy(tmp, "//anon", sizeof(tmp));
4852 size = ALIGN(strlen(name)+1, sizeof(u64));
4854 mmap_event->file_name = name;
4855 mmap_event->file_size = size;
4857 if (!(vma->vm_flags & VM_EXEC))
4858 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
4860 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
4862 perf_event_aux(perf_event_mmap_match,
4863 perf_event_mmap_output,
4870 void perf_event_mmap(struct vm_area_struct *vma)
4872 struct perf_mmap_event mmap_event;
4874 if (!atomic_read(&nr_mmap_events))
4877 mmap_event = (struct perf_mmap_event){
4883 .type = PERF_RECORD_MMAP,
4884 .misc = PERF_RECORD_MISC_USER,
4889 .start = vma->vm_start,
4890 .len = vma->vm_end - vma->vm_start,
4891 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
4895 perf_event_mmap_event(&mmap_event);
4899 * IRQ throttle logging
4902 static void perf_log_throttle(struct perf_event *event, int enable)
4904 struct perf_output_handle handle;
4905 struct perf_sample_data sample;
4909 struct perf_event_header header;
4913 } throttle_event = {
4915 .type = PERF_RECORD_THROTTLE,
4917 .size = sizeof(throttle_event),
4919 .time = perf_clock(),
4920 .id = primary_event_id(event),
4921 .stream_id = event->id,
4925 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
4927 perf_event_header__init_id(&throttle_event.header, &sample, event);
4929 ret = perf_output_begin(&handle, event,
4930 throttle_event.header.size);
4934 perf_output_put(&handle, throttle_event);
4935 perf_event__output_id_sample(event, &handle, &sample);
4936 perf_output_end(&handle);
4940 * Generic event overflow handling, sampling.
4943 static int __perf_event_overflow(struct perf_event *event,
4944 int throttle, struct perf_sample_data *data,
4945 struct pt_regs *regs)
4947 int events = atomic_read(&event->event_limit);
4948 struct hw_perf_event *hwc = &event->hw;
4953 * Non-sampling counters might still use the PMI to fold short
4954 * hardware counters, ignore those.
4956 if (unlikely(!is_sampling_event(event)))
4959 seq = __this_cpu_read(perf_throttled_seq);
4960 if (seq != hwc->interrupts_seq) {
4961 hwc->interrupts_seq = seq;
4962 hwc->interrupts = 1;
4965 if (unlikely(throttle
4966 && hwc->interrupts >= max_samples_per_tick)) {
4967 __this_cpu_inc(perf_throttled_count);
4968 hwc->interrupts = MAX_INTERRUPTS;
4969 perf_log_throttle(event, 0);
4974 if (event->attr.freq) {
4975 u64 now = perf_clock();
4976 s64 delta = now - hwc->freq_time_stamp;
4978 hwc->freq_time_stamp = now;
4980 if (delta > 0 && delta < 2*TICK_NSEC)
4981 perf_adjust_period(event, delta, hwc->last_period, true);
4985 * XXX event_limit might not quite work as expected on inherited
4989 event->pending_kill = POLL_IN;
4990 if (events && atomic_dec_and_test(&event->event_limit)) {
4992 event->pending_kill = POLL_HUP;
4993 event->pending_disable = 1;
4994 irq_work_queue(&event->pending);
4997 if (event->overflow_handler)
4998 event->overflow_handler(event, data, regs);
5000 perf_event_output(event, data, regs);
5002 if (event->fasync && event->pending_kill) {
5003 event->pending_wakeup = 1;
5004 irq_work_queue(&event->pending);
5010 int perf_event_overflow(struct perf_event *event,
5011 struct perf_sample_data *data,
5012 struct pt_regs *regs)
5014 return __perf_event_overflow(event, 1, data, regs);
5018 * Generic software event infrastructure
5021 struct swevent_htable {
5022 struct swevent_hlist *swevent_hlist;
5023 struct mutex hlist_mutex;
5026 /* Recursion avoidance in each contexts */
5027 int recursion[PERF_NR_CONTEXTS];
5030 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
5033 * We directly increment event->count and keep a second value in
5034 * event->hw.period_left to count intervals. This period event
5035 * is kept in the range [-sample_period, 0] so that we can use the
5039 static u64 perf_swevent_set_period(struct perf_event *event)
5041 struct hw_perf_event *hwc = &event->hw;
5042 u64 period = hwc->last_period;
5046 hwc->last_period = hwc->sample_period;
5049 old = val = local64_read(&hwc->period_left);
5053 nr = div64_u64(period + val, period);
5054 offset = nr * period;
5056 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
5062 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
5063 struct perf_sample_data *data,
5064 struct pt_regs *regs)
5066 struct hw_perf_event *hwc = &event->hw;
5070 overflow = perf_swevent_set_period(event);
5072 if (hwc->interrupts == MAX_INTERRUPTS)
5075 for (; overflow; overflow--) {
5076 if (__perf_event_overflow(event, throttle,
5079 * We inhibit the overflow from happening when
5080 * hwc->interrupts == MAX_INTERRUPTS.
5088 static void perf_swevent_event(struct perf_event *event, u64 nr,
5089 struct perf_sample_data *data,
5090 struct pt_regs *regs)
5092 struct hw_perf_event *hwc = &event->hw;
5094 local64_add(nr, &event->count);
5099 if (!is_sampling_event(event))
5102 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
5104 return perf_swevent_overflow(event, 1, data, regs);
5106 data->period = event->hw.last_period;
5108 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
5109 return perf_swevent_overflow(event, 1, data, regs);
5111 if (local64_add_negative(nr, &hwc->period_left))
5114 perf_swevent_overflow(event, 0, data, regs);
5117 static int perf_exclude_event(struct perf_event *event,
5118 struct pt_regs *regs)
5120 if (event->hw.state & PERF_HES_STOPPED)
5124 if (event->attr.exclude_user && user_mode(regs))
5127 if (event->attr.exclude_kernel && !user_mode(regs))
5134 static int perf_swevent_match(struct perf_event *event,
5135 enum perf_type_id type,
5137 struct perf_sample_data *data,
5138 struct pt_regs *regs)
5140 if (event->attr.type != type)
5143 if (event->attr.config != event_id)
5146 if (perf_exclude_event(event, regs))
5152 static inline u64 swevent_hash(u64 type, u32 event_id)
5154 u64 val = event_id | (type << 32);
5156 return hash_64(val, SWEVENT_HLIST_BITS);
5159 static inline struct hlist_head *
5160 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
5162 u64 hash = swevent_hash(type, event_id);
5164 return &hlist->heads[hash];
5167 /* For the read side: events when they trigger */
5168 static inline struct hlist_head *
5169 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
5171 struct swevent_hlist *hlist;
5173 hlist = rcu_dereference(swhash->swevent_hlist);
5177 return __find_swevent_head(hlist, type, event_id);
5180 /* For the event head insertion and removal in the hlist */
5181 static inline struct hlist_head *
5182 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
5184 struct swevent_hlist *hlist;
5185 u32 event_id = event->attr.config;
5186 u64 type = event->attr.type;
5189 * Event scheduling is always serialized against hlist allocation
5190 * and release. Which makes the protected version suitable here.
5191 * The context lock guarantees that.
5193 hlist = rcu_dereference_protected(swhash->swevent_hlist,
5194 lockdep_is_held(&event->ctx->lock));
5198 return __find_swevent_head(hlist, type, event_id);
5201 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
5203 struct perf_sample_data *data,
5204 struct pt_regs *regs)
5206 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5207 struct perf_event *event;
5208 struct hlist_head *head;
5211 head = find_swevent_head_rcu(swhash, type, event_id);
5215 hlist_for_each_entry_rcu(event, head, hlist_entry) {
5216 if (perf_swevent_match(event, type, event_id, data, regs))
5217 perf_swevent_event(event, nr, data, regs);
5223 int perf_swevent_get_recursion_context(void)
5225 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5227 return get_recursion_context(swhash->recursion);
5229 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
5231 inline void perf_swevent_put_recursion_context(int rctx)
5233 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5235 put_recursion_context(swhash->recursion, rctx);
5238 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
5240 struct perf_sample_data data;
5243 preempt_disable_notrace();
5244 rctx = perf_swevent_get_recursion_context();
5248 perf_sample_data_init(&data, addr, 0);
5250 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
5252 perf_swevent_put_recursion_context(rctx);
5253 preempt_enable_notrace();
5256 static void perf_swevent_read(struct perf_event *event)
5260 static int perf_swevent_add(struct perf_event *event, int flags)
5262 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5263 struct hw_perf_event *hwc = &event->hw;
5264 struct hlist_head *head;
5266 if (is_sampling_event(event)) {
5267 hwc->last_period = hwc->sample_period;
5268 perf_swevent_set_period(event);
5271 hwc->state = !(flags & PERF_EF_START);
5273 head = find_swevent_head(swhash, event);
5274 if (WARN_ON_ONCE(!head))
5277 hlist_add_head_rcu(&event->hlist_entry, head);
5282 static void perf_swevent_del(struct perf_event *event, int flags)
5284 hlist_del_rcu(&event->hlist_entry);
5287 static void perf_swevent_start(struct perf_event *event, int flags)
5289 event->hw.state = 0;
5292 static void perf_swevent_stop(struct perf_event *event, int flags)
5294 event->hw.state = PERF_HES_STOPPED;
5297 /* Deref the hlist from the update side */
5298 static inline struct swevent_hlist *
5299 swevent_hlist_deref(struct swevent_htable *swhash)
5301 return rcu_dereference_protected(swhash->swevent_hlist,
5302 lockdep_is_held(&swhash->hlist_mutex));
5305 static void swevent_hlist_release(struct swevent_htable *swhash)
5307 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
5312 rcu_assign_pointer(swhash->swevent_hlist, NULL);
5313 kfree_rcu(hlist, rcu_head);
5316 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
5318 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5320 mutex_lock(&swhash->hlist_mutex);
5322 if (!--swhash->hlist_refcount)
5323 swevent_hlist_release(swhash);
5325 mutex_unlock(&swhash->hlist_mutex);
5328 static void swevent_hlist_put(struct perf_event *event)
5332 if (event->cpu != -1) {
5333 swevent_hlist_put_cpu(event, event->cpu);
5337 for_each_possible_cpu(cpu)
5338 swevent_hlist_put_cpu(event, cpu);
5341 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
5343 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5346 mutex_lock(&swhash->hlist_mutex);
5348 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
5349 struct swevent_hlist *hlist;
5351 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
5356 rcu_assign_pointer(swhash->swevent_hlist, hlist);
5358 swhash->hlist_refcount++;
5360 mutex_unlock(&swhash->hlist_mutex);
5365 static int swevent_hlist_get(struct perf_event *event)
5368 int cpu, failed_cpu;
5370 if (event->cpu != -1)
5371 return swevent_hlist_get_cpu(event, event->cpu);
5374 for_each_possible_cpu(cpu) {
5375 err = swevent_hlist_get_cpu(event, cpu);
5385 for_each_possible_cpu(cpu) {
5386 if (cpu == failed_cpu)
5388 swevent_hlist_put_cpu(event, cpu);
5395 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
5397 static void sw_perf_event_destroy(struct perf_event *event)
5399 u64 event_id = event->attr.config;
5401 WARN_ON(event->parent);
5403 static_key_slow_dec(&perf_swevent_enabled[event_id]);
5404 swevent_hlist_put(event);
5407 static int perf_swevent_init(struct perf_event *event)
5409 u64 event_id = event->attr.config;
5411 if (event->attr.type != PERF_TYPE_SOFTWARE)
5415 * no branch sampling for software events
5417 if (has_branch_stack(event))
5421 case PERF_COUNT_SW_CPU_CLOCK:
5422 case PERF_COUNT_SW_TASK_CLOCK:
5429 if (event_id >= PERF_COUNT_SW_MAX)
5432 if (!event->parent) {
5435 err = swevent_hlist_get(event);
5439 static_key_slow_inc(&perf_swevent_enabled[event_id]);
5440 event->destroy = sw_perf_event_destroy;
5446 static int perf_swevent_event_idx(struct perf_event *event)
5451 static struct pmu perf_swevent = {
5452 .task_ctx_nr = perf_sw_context,
5454 .event_init = perf_swevent_init,
5455 .add = perf_swevent_add,
5456 .del = perf_swevent_del,
5457 .start = perf_swevent_start,
5458 .stop = perf_swevent_stop,
5459 .read = perf_swevent_read,
5461 .event_idx = perf_swevent_event_idx,
5464 #ifdef CONFIG_EVENT_TRACING
5466 static int perf_tp_filter_match(struct perf_event *event,
5467 struct perf_sample_data *data)
5469 void *record = data->raw->data;
5471 if (likely(!event->filter) || filter_match_preds(event->filter, record))
5476 static int perf_tp_event_match(struct perf_event *event,
5477 struct perf_sample_data *data,
5478 struct pt_regs *regs)
5480 if (event->hw.state & PERF_HES_STOPPED)
5483 * All tracepoints are from kernel-space.
5485 if (event->attr.exclude_kernel)
5488 if (!perf_tp_filter_match(event, data))
5494 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
5495 struct pt_regs *regs, struct hlist_head *head, int rctx,
5496 struct task_struct *task)
5498 struct perf_sample_data data;
5499 struct perf_event *event;
5501 struct perf_raw_record raw = {
5506 perf_sample_data_init(&data, addr, 0);
5509 hlist_for_each_entry_rcu(event, head, hlist_entry) {
5510 if (perf_tp_event_match(event, &data, regs))
5511 perf_swevent_event(event, count, &data, regs);
5515 * If we got specified a target task, also iterate its context and
5516 * deliver this event there too.
5518 if (task && task != current) {
5519 struct perf_event_context *ctx;
5520 struct trace_entry *entry = record;
5523 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
5527 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5528 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5530 if (event->attr.config != entry->type)
5532 if (perf_tp_event_match(event, &data, regs))
5533 perf_swevent_event(event, count, &data, regs);
5539 perf_swevent_put_recursion_context(rctx);
5541 EXPORT_SYMBOL_GPL(perf_tp_event);
5543 static void tp_perf_event_destroy(struct perf_event *event)
5545 perf_trace_destroy(event);
5548 static int perf_tp_event_init(struct perf_event *event)
5552 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5556 * no branch sampling for tracepoint events
5558 if (has_branch_stack(event))
5561 err = perf_trace_init(event);
5565 event->destroy = tp_perf_event_destroy;
5570 static struct pmu perf_tracepoint = {
5571 .task_ctx_nr = perf_sw_context,
5573 .event_init = perf_tp_event_init,
5574 .add = perf_trace_add,
5575 .del = perf_trace_del,
5576 .start = perf_swevent_start,
5577 .stop = perf_swevent_stop,
5578 .read = perf_swevent_read,
5580 .event_idx = perf_swevent_event_idx,
5583 static inline void perf_tp_register(void)
5585 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
5588 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
5593 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5596 filter_str = strndup_user(arg, PAGE_SIZE);
5597 if (IS_ERR(filter_str))
5598 return PTR_ERR(filter_str);
5600 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
5606 static void perf_event_free_filter(struct perf_event *event)
5608 ftrace_profile_free_filter(event);
5613 static inline void perf_tp_register(void)
5617 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
5622 static void perf_event_free_filter(struct perf_event *event)
5626 #endif /* CONFIG_EVENT_TRACING */
5628 #ifdef CONFIG_HAVE_HW_BREAKPOINT
5629 void perf_bp_event(struct perf_event *bp, void *data)
5631 struct perf_sample_data sample;
5632 struct pt_regs *regs = data;
5634 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
5636 if (!bp->hw.state && !perf_exclude_event(bp, regs))
5637 perf_swevent_event(bp, 1, &sample, regs);
5642 * hrtimer based swevent callback
5645 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
5647 enum hrtimer_restart ret = HRTIMER_RESTART;
5648 struct perf_sample_data data;
5649 struct pt_regs *regs;
5650 struct perf_event *event;
5653 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
5655 if (event->state != PERF_EVENT_STATE_ACTIVE)
5656 return HRTIMER_NORESTART;
5658 event->pmu->read(event);
5660 perf_sample_data_init(&data, 0, event->hw.last_period);
5661 regs = get_irq_regs();
5663 if (regs && !perf_exclude_event(event, regs)) {
5664 if (!(event->attr.exclude_idle && is_idle_task(current)))
5665 if (__perf_event_overflow(event, 1, &data, regs))
5666 ret = HRTIMER_NORESTART;
5669 period = max_t(u64, 10000, event->hw.sample_period);
5670 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
5675 static void perf_swevent_start_hrtimer(struct perf_event *event)
5677 struct hw_perf_event *hwc = &event->hw;
5680 if (!is_sampling_event(event))
5683 period = local64_read(&hwc->period_left);
5688 local64_set(&hwc->period_left, 0);
5690 period = max_t(u64, 10000, hwc->sample_period);
5692 __hrtimer_start_range_ns(&hwc->hrtimer,
5693 ns_to_ktime(period), 0,
5694 HRTIMER_MODE_REL_PINNED, 0);
5697 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
5699 struct hw_perf_event *hwc = &event->hw;
5701 if (is_sampling_event(event)) {
5702 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
5703 local64_set(&hwc->period_left, ktime_to_ns(remaining));
5705 hrtimer_cancel(&hwc->hrtimer);
5709 static void perf_swevent_init_hrtimer(struct perf_event *event)
5711 struct hw_perf_event *hwc = &event->hw;
5713 if (!is_sampling_event(event))
5716 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
5717 hwc->hrtimer.function = perf_swevent_hrtimer;
5720 * Since hrtimers have a fixed rate, we can do a static freq->period
5721 * mapping and avoid the whole period adjust feedback stuff.
5723 if (event->attr.freq) {
5724 long freq = event->attr.sample_freq;
5726 event->attr.sample_period = NSEC_PER_SEC / freq;
5727 hwc->sample_period = event->attr.sample_period;
5728 local64_set(&hwc->period_left, hwc->sample_period);
5729 hwc->last_period = hwc->sample_period;
5730 event->attr.freq = 0;
5735 * Software event: cpu wall time clock
5738 static void cpu_clock_event_update(struct perf_event *event)
5743 now = local_clock();
5744 prev = local64_xchg(&event->hw.prev_count, now);
5745 local64_add(now - prev, &event->count);
5748 static void cpu_clock_event_start(struct perf_event *event, int flags)
5750 local64_set(&event->hw.prev_count, local_clock());
5751 perf_swevent_start_hrtimer(event);
5754 static void cpu_clock_event_stop(struct perf_event *event, int flags)
5756 perf_swevent_cancel_hrtimer(event);
5757 cpu_clock_event_update(event);
5760 static int cpu_clock_event_add(struct perf_event *event, int flags)
5762 if (flags & PERF_EF_START)
5763 cpu_clock_event_start(event, flags);
5768 static void cpu_clock_event_del(struct perf_event *event, int flags)
5770 cpu_clock_event_stop(event, flags);
5773 static void cpu_clock_event_read(struct perf_event *event)
5775 cpu_clock_event_update(event);
5778 static int cpu_clock_event_init(struct perf_event *event)
5780 if (event->attr.type != PERF_TYPE_SOFTWARE)
5783 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
5787 * no branch sampling for software events
5789 if (has_branch_stack(event))
5792 perf_swevent_init_hrtimer(event);
5797 static struct pmu perf_cpu_clock = {
5798 .task_ctx_nr = perf_sw_context,
5800 .event_init = cpu_clock_event_init,
5801 .add = cpu_clock_event_add,
5802 .del = cpu_clock_event_del,
5803 .start = cpu_clock_event_start,
5804 .stop = cpu_clock_event_stop,
5805 .read = cpu_clock_event_read,
5807 .event_idx = perf_swevent_event_idx,
5811 * Software event: task time clock
5814 static void task_clock_event_update(struct perf_event *event, u64 now)
5819 prev = local64_xchg(&event->hw.prev_count, now);
5821 local64_add(delta, &event->count);
5824 static void task_clock_event_start(struct perf_event *event, int flags)
5826 local64_set(&event->hw.prev_count, event->ctx->time);
5827 perf_swevent_start_hrtimer(event);
5830 static void task_clock_event_stop(struct perf_event *event, int flags)
5832 perf_swevent_cancel_hrtimer(event);
5833 task_clock_event_update(event, event->ctx->time);
5836 static int task_clock_event_add(struct perf_event *event, int flags)
5838 if (flags & PERF_EF_START)
5839 task_clock_event_start(event, flags);
5844 static void task_clock_event_del(struct perf_event *event, int flags)
5846 task_clock_event_stop(event, PERF_EF_UPDATE);
5849 static void task_clock_event_read(struct perf_event *event)
5851 u64 now = perf_clock();
5852 u64 delta = now - event->ctx->timestamp;
5853 u64 time = event->ctx->time + delta;
5855 task_clock_event_update(event, time);
5858 static int task_clock_event_init(struct perf_event *event)
5860 if (event->attr.type != PERF_TYPE_SOFTWARE)
5863 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
5867 * no branch sampling for software events
5869 if (has_branch_stack(event))
5872 perf_swevent_init_hrtimer(event);
5877 static struct pmu perf_task_clock = {
5878 .task_ctx_nr = perf_sw_context,
5880 .event_init = task_clock_event_init,
5881 .add = task_clock_event_add,
5882 .del = task_clock_event_del,
5883 .start = task_clock_event_start,
5884 .stop = task_clock_event_stop,
5885 .read = task_clock_event_read,
5887 .event_idx = perf_swevent_event_idx,
5890 static void perf_pmu_nop_void(struct pmu *pmu)
5894 static int perf_pmu_nop_int(struct pmu *pmu)
5899 static void perf_pmu_start_txn(struct pmu *pmu)
5901 perf_pmu_disable(pmu);
5904 static int perf_pmu_commit_txn(struct pmu *pmu)
5906 perf_pmu_enable(pmu);
5910 static void perf_pmu_cancel_txn(struct pmu *pmu)
5912 perf_pmu_enable(pmu);
5915 static int perf_event_idx_default(struct perf_event *event)
5917 return event->hw.idx + 1;
5921 * Ensures all contexts with the same task_ctx_nr have the same
5922 * pmu_cpu_context too.
5924 static void *find_pmu_context(int ctxn)
5931 list_for_each_entry(pmu, &pmus, entry) {
5932 if (pmu->task_ctx_nr == ctxn)
5933 return pmu->pmu_cpu_context;
5939 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
5943 for_each_possible_cpu(cpu) {
5944 struct perf_cpu_context *cpuctx;
5946 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
5948 if (cpuctx->unique_pmu == old_pmu)
5949 cpuctx->unique_pmu = pmu;
5953 static void free_pmu_context(struct pmu *pmu)
5957 mutex_lock(&pmus_lock);
5959 * Like a real lame refcount.
5961 list_for_each_entry(i, &pmus, entry) {
5962 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
5963 update_pmu_context(i, pmu);
5968 free_percpu(pmu->pmu_cpu_context);
5970 mutex_unlock(&pmus_lock);
5972 static struct idr pmu_idr;
5975 type_show(struct device *dev, struct device_attribute *attr, char *page)
5977 struct pmu *pmu = dev_get_drvdata(dev);
5979 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
5982 static struct device_attribute pmu_dev_attrs[] = {
5987 static int pmu_bus_running;
5988 static struct bus_type pmu_bus = {
5989 .name = "event_source",
5990 .dev_attrs = pmu_dev_attrs,
5993 static void pmu_dev_release(struct device *dev)
5998 static int pmu_dev_alloc(struct pmu *pmu)
6002 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
6006 pmu->dev->groups = pmu->attr_groups;
6007 device_initialize(pmu->dev);
6008 ret = dev_set_name(pmu->dev, "%s", pmu->name);
6012 dev_set_drvdata(pmu->dev, pmu);
6013 pmu->dev->bus = &pmu_bus;
6014 pmu->dev->release = pmu_dev_release;
6015 ret = device_add(pmu->dev);
6023 put_device(pmu->dev);
6027 static struct lock_class_key cpuctx_mutex;
6028 static struct lock_class_key cpuctx_lock;
6030 int perf_pmu_register(struct pmu *pmu, char *name, int type)
6034 mutex_lock(&pmus_lock);
6036 pmu->pmu_disable_count = alloc_percpu(int);
6037 if (!pmu->pmu_disable_count)
6046 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
6054 if (pmu_bus_running) {
6055 ret = pmu_dev_alloc(pmu);
6061 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
6062 if (pmu->pmu_cpu_context)
6063 goto got_cpu_context;
6066 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
6067 if (!pmu->pmu_cpu_context)
6070 for_each_possible_cpu(cpu) {
6071 struct perf_cpu_context *cpuctx;
6073 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6074 __perf_event_init_context(&cpuctx->ctx);
6075 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
6076 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
6077 cpuctx->ctx.type = cpu_context;
6078 cpuctx->ctx.pmu = pmu;
6079 cpuctx->jiffies_interval = 1;
6080 INIT_LIST_HEAD(&cpuctx->rotation_list);
6081 cpuctx->unique_pmu = pmu;
6085 if (!pmu->start_txn) {
6086 if (pmu->pmu_enable) {
6088 * If we have pmu_enable/pmu_disable calls, install
6089 * transaction stubs that use that to try and batch
6090 * hardware accesses.
6092 pmu->start_txn = perf_pmu_start_txn;
6093 pmu->commit_txn = perf_pmu_commit_txn;
6094 pmu->cancel_txn = perf_pmu_cancel_txn;
6096 pmu->start_txn = perf_pmu_nop_void;
6097 pmu->commit_txn = perf_pmu_nop_int;
6098 pmu->cancel_txn = perf_pmu_nop_void;
6102 if (!pmu->pmu_enable) {
6103 pmu->pmu_enable = perf_pmu_nop_void;
6104 pmu->pmu_disable = perf_pmu_nop_void;
6107 if (!pmu->event_idx)
6108 pmu->event_idx = perf_event_idx_default;
6110 list_add_rcu(&pmu->entry, &pmus);
6113 mutex_unlock(&pmus_lock);
6118 device_del(pmu->dev);
6119 put_device(pmu->dev);
6122 if (pmu->type >= PERF_TYPE_MAX)
6123 idr_remove(&pmu_idr, pmu->type);
6126 free_percpu(pmu->pmu_disable_count);
6130 void perf_pmu_unregister(struct pmu *pmu)
6132 mutex_lock(&pmus_lock);
6133 list_del_rcu(&pmu->entry);
6134 mutex_unlock(&pmus_lock);
6137 * We dereference the pmu list under both SRCU and regular RCU, so
6138 * synchronize against both of those.
6140 synchronize_srcu(&pmus_srcu);
6143 free_percpu(pmu->pmu_disable_count);
6144 if (pmu->type >= PERF_TYPE_MAX)
6145 idr_remove(&pmu_idr, pmu->type);
6146 device_del(pmu->dev);
6147 put_device(pmu->dev);
6148 free_pmu_context(pmu);
6151 struct pmu *perf_init_event(struct perf_event *event)
6153 struct pmu *pmu = NULL;
6157 idx = srcu_read_lock(&pmus_srcu);
6160 pmu = idr_find(&pmu_idr, event->attr.type);
6164 ret = pmu->event_init(event);
6170 list_for_each_entry_rcu(pmu, &pmus, entry) {
6172 ret = pmu->event_init(event);
6176 if (ret != -ENOENT) {
6181 pmu = ERR_PTR(-ENOENT);
6183 srcu_read_unlock(&pmus_srcu, idx);
6189 * Allocate and initialize a event structure
6191 static struct perf_event *
6192 perf_event_alloc(struct perf_event_attr *attr, int cpu,
6193 struct task_struct *task,
6194 struct perf_event *group_leader,
6195 struct perf_event *parent_event,
6196 perf_overflow_handler_t overflow_handler,
6200 struct perf_event *event;
6201 struct hw_perf_event *hwc;
6204 if ((unsigned)cpu >= nr_cpu_ids) {
6205 if (!task || cpu != -1)
6206 return ERR_PTR(-EINVAL);
6209 event = kzalloc(sizeof(*event), GFP_KERNEL);
6211 return ERR_PTR(-ENOMEM);
6214 * Single events are their own group leaders, with an
6215 * empty sibling list:
6218 group_leader = event;
6220 mutex_init(&event->child_mutex);
6221 INIT_LIST_HEAD(&event->child_list);
6223 INIT_LIST_HEAD(&event->group_entry);
6224 INIT_LIST_HEAD(&event->event_entry);
6225 INIT_LIST_HEAD(&event->sibling_list);
6226 INIT_LIST_HEAD(&event->rb_entry);
6228 init_waitqueue_head(&event->waitq);
6229 init_irq_work(&event->pending, perf_pending_event);
6231 mutex_init(&event->mmap_mutex);
6233 atomic_long_set(&event->refcount, 1);
6235 event->attr = *attr;
6236 event->group_leader = group_leader;
6240 event->parent = parent_event;
6242 event->ns = get_pid_ns(task_active_pid_ns(current));
6243 event->id = atomic64_inc_return(&perf_event_id);
6245 event->state = PERF_EVENT_STATE_INACTIVE;
6248 event->attach_state = PERF_ATTACH_TASK;
6250 if (attr->type == PERF_TYPE_TRACEPOINT)
6251 event->hw.tp_target = task;
6252 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6254 * hw_breakpoint is a bit difficult here..
6256 else if (attr->type == PERF_TYPE_BREAKPOINT)
6257 event->hw.bp_target = task;
6261 if (!overflow_handler && parent_event) {
6262 overflow_handler = parent_event->overflow_handler;
6263 context = parent_event->overflow_handler_context;
6266 event->overflow_handler = overflow_handler;
6267 event->overflow_handler_context = context;
6269 perf_event__state_init(event);
6274 hwc->sample_period = attr->sample_period;
6275 if (attr->freq && attr->sample_freq)
6276 hwc->sample_period = 1;
6277 hwc->last_period = hwc->sample_period;
6279 local64_set(&hwc->period_left, hwc->sample_period);
6282 * we currently do not support PERF_FORMAT_GROUP on inherited events
6284 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
6287 pmu = perf_init_event(event);
6293 else if (IS_ERR(pmu))
6298 put_pid_ns(event->ns);
6300 return ERR_PTR(err);
6303 if (!event->parent) {
6304 if (event->attach_state & PERF_ATTACH_TASK)
6305 static_key_slow_inc(&perf_sched_events.key);
6306 if (event->attr.mmap || event->attr.mmap_data)
6307 atomic_inc(&nr_mmap_events);
6308 if (event->attr.comm)
6309 atomic_inc(&nr_comm_events);
6310 if (event->attr.task)
6311 atomic_inc(&nr_task_events);
6312 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
6313 err = get_callchain_buffers();
6316 return ERR_PTR(err);
6319 if (has_branch_stack(event)) {
6320 static_key_slow_inc(&perf_sched_events.key);
6321 if (!(event->attach_state & PERF_ATTACH_TASK))
6322 atomic_inc(&per_cpu(perf_branch_stack_events,
6330 static int perf_copy_attr(struct perf_event_attr __user *uattr,
6331 struct perf_event_attr *attr)
6336 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
6340 * zero the full structure, so that a short copy will be nice.
6342 memset(attr, 0, sizeof(*attr));
6344 ret = get_user(size, &uattr->size);
6348 if (size > PAGE_SIZE) /* silly large */
6351 if (!size) /* abi compat */
6352 size = PERF_ATTR_SIZE_VER0;
6354 if (size < PERF_ATTR_SIZE_VER0)
6358 * If we're handed a bigger struct than we know of,
6359 * ensure all the unknown bits are 0 - i.e. new
6360 * user-space does not rely on any kernel feature
6361 * extensions we dont know about yet.
6363 if (size > sizeof(*attr)) {
6364 unsigned char __user *addr;
6365 unsigned char __user *end;
6368 addr = (void __user *)uattr + sizeof(*attr);
6369 end = (void __user *)uattr + size;
6371 for (; addr < end; addr++) {
6372 ret = get_user(val, addr);
6378 size = sizeof(*attr);
6381 ret = copy_from_user(attr, uattr, size);
6385 if (attr->__reserved_1)
6388 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
6391 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
6394 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
6395 u64 mask = attr->branch_sample_type;
6397 /* only using defined bits */
6398 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
6401 /* at least one branch bit must be set */
6402 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
6405 /* kernel level capture: check permissions */
6406 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
6407 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
6410 /* propagate priv level, when not set for branch */
6411 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
6413 /* exclude_kernel checked on syscall entry */
6414 if (!attr->exclude_kernel)
6415 mask |= PERF_SAMPLE_BRANCH_KERNEL;
6417 if (!attr->exclude_user)
6418 mask |= PERF_SAMPLE_BRANCH_USER;
6420 if (!attr->exclude_hv)
6421 mask |= PERF_SAMPLE_BRANCH_HV;
6423 * adjust user setting (for HW filter setup)
6425 attr->branch_sample_type = mask;
6429 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
6430 ret = perf_reg_validate(attr->sample_regs_user);
6435 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
6436 if (!arch_perf_have_user_stack_dump())
6440 * We have __u32 type for the size, but so far
6441 * we can only use __u16 as maximum due to the
6442 * __u16 sample size limit.
6444 if (attr->sample_stack_user >= USHRT_MAX)
6446 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
6454 put_user(sizeof(*attr), &uattr->size);
6460 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
6462 struct ring_buffer *rb = NULL, *old_rb = NULL;
6468 /* don't allow circular references */
6469 if (event == output_event)
6473 * Don't allow cross-cpu buffers
6475 if (output_event->cpu != event->cpu)
6479 * If its not a per-cpu rb, it must be the same task.
6481 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
6485 mutex_lock(&event->mmap_mutex);
6486 /* Can't redirect output if we've got an active mmap() */
6487 if (atomic_read(&event->mmap_count))
6493 /* get the rb we want to redirect to */
6494 rb = ring_buffer_get(output_event);
6500 ring_buffer_detach(event, old_rb);
6503 ring_buffer_attach(event, rb);
6505 rcu_assign_pointer(event->rb, rb);
6508 ring_buffer_put(old_rb);
6510 * Since we detached before setting the new rb, so that we
6511 * could attach the new rb, we could have missed a wakeup.
6514 wake_up_all(&event->waitq);
6519 mutex_unlock(&event->mmap_mutex);
6526 * sys_perf_event_open - open a performance event, associate it to a task/cpu
6528 * @attr_uptr: event_id type attributes for monitoring/sampling
6531 * @group_fd: group leader event fd
6533 SYSCALL_DEFINE5(perf_event_open,
6534 struct perf_event_attr __user *, attr_uptr,
6535 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
6537 struct perf_event *group_leader = NULL, *output_event = NULL;
6538 struct perf_event *event, *sibling;
6539 struct perf_event_attr attr;
6540 struct perf_event_context *ctx;
6541 struct file *event_file = NULL;
6542 struct fd group = {NULL, 0};
6543 struct task_struct *task = NULL;
6549 /* for future expandability... */
6550 if (flags & ~PERF_FLAG_ALL)
6553 err = perf_copy_attr(attr_uptr, &attr);
6557 if (!attr.exclude_kernel) {
6558 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
6563 if (attr.sample_freq > sysctl_perf_event_sample_rate)
6568 * In cgroup mode, the pid argument is used to pass the fd
6569 * opened to the cgroup directory in cgroupfs. The cpu argument
6570 * designates the cpu on which to monitor threads from that
6573 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
6576 event_fd = get_unused_fd();
6580 if (group_fd != -1) {
6581 err = perf_fget_light(group_fd, &group);
6584 group_leader = group.file->private_data;
6585 if (flags & PERF_FLAG_FD_OUTPUT)
6586 output_event = group_leader;
6587 if (flags & PERF_FLAG_FD_NO_GROUP)
6588 group_leader = NULL;
6591 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
6592 task = find_lively_task_by_vpid(pid);
6594 err = PTR_ERR(task);
6601 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
6603 if (IS_ERR(event)) {
6604 err = PTR_ERR(event);
6608 if (flags & PERF_FLAG_PID_CGROUP) {
6609 err = perf_cgroup_connect(pid, event, &attr, group_leader);
6614 * - that has cgroup constraint on event->cpu
6615 * - that may need work on context switch
6617 atomic_inc(&per_cpu(perf_cgroup_events, event->cpu));
6618 static_key_slow_inc(&perf_sched_events.key);
6622 * Special case software events and allow them to be part of
6623 * any hardware group.
6628 (is_software_event(event) != is_software_event(group_leader))) {
6629 if (is_software_event(event)) {
6631 * If event and group_leader are not both a software
6632 * event, and event is, then group leader is not.
6634 * Allow the addition of software events to !software
6635 * groups, this is safe because software events never
6638 pmu = group_leader->pmu;
6639 } else if (is_software_event(group_leader) &&
6640 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
6642 * In case the group is a pure software group, and we
6643 * try to add a hardware event, move the whole group to
6644 * the hardware context.
6651 * Get the target context (task or percpu):
6653 ctx = find_get_context(pmu, task, event->cpu);
6660 put_task_struct(task);
6665 * Look up the group leader (we will attach this event to it):
6671 * Do not allow a recursive hierarchy (this new sibling
6672 * becoming part of another group-sibling):
6674 if (group_leader->group_leader != group_leader)
6677 * Do not allow to attach to a group in a different
6678 * task or CPU context:
6681 if (group_leader->ctx->type != ctx->type)
6684 if (group_leader->ctx != ctx)
6689 * Only a group leader can be exclusive or pinned
6691 if (attr.exclusive || attr.pinned)
6696 err = perf_event_set_output(event, output_event);
6701 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, O_RDWR);
6702 if (IS_ERR(event_file)) {
6703 err = PTR_ERR(event_file);
6708 struct perf_event_context *gctx = group_leader->ctx;
6710 mutex_lock(&gctx->mutex);
6711 perf_remove_from_context(group_leader);
6714 * Removing from the context ends up with disabled
6715 * event. What we want here is event in the initial
6716 * startup state, ready to be add into new context.
6718 perf_event__state_init(group_leader);
6719 list_for_each_entry(sibling, &group_leader->sibling_list,
6721 perf_remove_from_context(sibling);
6722 perf_event__state_init(sibling);
6725 mutex_unlock(&gctx->mutex);
6729 WARN_ON_ONCE(ctx->parent_ctx);
6730 mutex_lock(&ctx->mutex);
6734 perf_install_in_context(ctx, group_leader, event->cpu);
6736 list_for_each_entry(sibling, &group_leader->sibling_list,
6738 perf_install_in_context(ctx, sibling, event->cpu);
6743 perf_install_in_context(ctx, event, event->cpu);
6745 perf_unpin_context(ctx);
6746 mutex_unlock(&ctx->mutex);
6750 event->owner = current;
6752 mutex_lock(¤t->perf_event_mutex);
6753 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
6754 mutex_unlock(¤t->perf_event_mutex);
6757 * Precalculate sample_data sizes
6759 perf_event__header_size(event);
6760 perf_event__id_header_size(event);
6763 * Drop the reference on the group_event after placing the
6764 * new event on the sibling_list. This ensures destruction
6765 * of the group leader will find the pointer to itself in
6766 * perf_group_detach().
6769 fd_install(event_fd, event_file);
6773 perf_unpin_context(ctx);
6780 put_task_struct(task);
6784 put_unused_fd(event_fd);
6789 * perf_event_create_kernel_counter
6791 * @attr: attributes of the counter to create
6792 * @cpu: cpu in which the counter is bound
6793 * @task: task to profile (NULL for percpu)
6796 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
6797 struct task_struct *task,
6798 perf_overflow_handler_t overflow_handler,
6801 struct perf_event_context *ctx;
6802 struct perf_event *event;
6806 * Get the target context (task or percpu):
6809 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
6810 overflow_handler, context);
6811 if (IS_ERR(event)) {
6812 err = PTR_ERR(event);
6816 ctx = find_get_context(event->pmu, task, cpu);
6822 WARN_ON_ONCE(ctx->parent_ctx);
6823 mutex_lock(&ctx->mutex);
6824 perf_install_in_context(ctx, event, cpu);
6826 perf_unpin_context(ctx);
6827 mutex_unlock(&ctx->mutex);
6834 return ERR_PTR(err);
6836 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
6838 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
6840 struct perf_event_context *src_ctx;
6841 struct perf_event_context *dst_ctx;
6842 struct perf_event *event, *tmp;
6845 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
6846 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
6848 mutex_lock(&src_ctx->mutex);
6849 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
6851 perf_remove_from_context(event);
6853 list_add(&event->event_entry, &events);
6855 mutex_unlock(&src_ctx->mutex);
6859 mutex_lock(&dst_ctx->mutex);
6860 list_for_each_entry_safe(event, tmp, &events, event_entry) {
6861 list_del(&event->event_entry);
6862 if (event->state >= PERF_EVENT_STATE_OFF)
6863 event->state = PERF_EVENT_STATE_INACTIVE;
6864 perf_install_in_context(dst_ctx, event, dst_cpu);
6867 mutex_unlock(&dst_ctx->mutex);
6869 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
6871 static void sync_child_event(struct perf_event *child_event,
6872 struct task_struct *child)
6874 struct perf_event *parent_event = child_event->parent;
6877 if (child_event->attr.inherit_stat)
6878 perf_event_read_event(child_event, child);
6880 child_val = perf_event_count(child_event);
6883 * Add back the child's count to the parent's count:
6885 atomic64_add(child_val, &parent_event->child_count);
6886 atomic64_add(child_event->total_time_enabled,
6887 &parent_event->child_total_time_enabled);
6888 atomic64_add(child_event->total_time_running,
6889 &parent_event->child_total_time_running);
6892 * Remove this event from the parent's list
6894 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
6895 mutex_lock(&parent_event->child_mutex);
6896 list_del_init(&child_event->child_list);
6897 mutex_unlock(&parent_event->child_mutex);
6900 * Release the parent event, if this was the last
6903 put_event(parent_event);
6907 __perf_event_exit_task(struct perf_event *child_event,
6908 struct perf_event_context *child_ctx,
6909 struct task_struct *child)
6911 if (child_event->parent) {
6912 raw_spin_lock_irq(&child_ctx->lock);
6913 perf_group_detach(child_event);
6914 raw_spin_unlock_irq(&child_ctx->lock);
6917 perf_remove_from_context(child_event);
6920 * It can happen that the parent exits first, and has events
6921 * that are still around due to the child reference. These
6922 * events need to be zapped.
6924 if (child_event->parent) {
6925 sync_child_event(child_event, child);
6926 free_event(child_event);
6930 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
6932 struct perf_event *child_event, *tmp;
6933 struct perf_event_context *child_ctx;
6934 unsigned long flags;
6936 if (likely(!child->perf_event_ctxp[ctxn])) {
6937 perf_event_task(child, NULL, 0);
6941 local_irq_save(flags);
6943 * We can't reschedule here because interrupts are disabled,
6944 * and either child is current or it is a task that can't be
6945 * scheduled, so we are now safe from rescheduling changing
6948 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
6951 * Take the context lock here so that if find_get_context is
6952 * reading child->perf_event_ctxp, we wait until it has
6953 * incremented the context's refcount before we do put_ctx below.
6955 raw_spin_lock(&child_ctx->lock);
6956 task_ctx_sched_out(child_ctx);
6957 child->perf_event_ctxp[ctxn] = NULL;
6959 * If this context is a clone; unclone it so it can't get
6960 * swapped to another process while we're removing all
6961 * the events from it.
6963 unclone_ctx(child_ctx);
6964 update_context_time(child_ctx);
6965 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
6968 * Report the task dead after unscheduling the events so that we
6969 * won't get any samples after PERF_RECORD_EXIT. We can however still
6970 * get a few PERF_RECORD_READ events.
6972 perf_event_task(child, child_ctx, 0);
6975 * We can recurse on the same lock type through:
6977 * __perf_event_exit_task()
6978 * sync_child_event()
6980 * mutex_lock(&ctx->mutex)
6982 * But since its the parent context it won't be the same instance.
6984 mutex_lock(&child_ctx->mutex);
6987 list_for_each_entry_safe(child_event, tmp, &child_ctx->pinned_groups,
6989 __perf_event_exit_task(child_event, child_ctx, child);
6991 list_for_each_entry_safe(child_event, tmp, &child_ctx->flexible_groups,
6993 __perf_event_exit_task(child_event, child_ctx, child);
6996 * If the last event was a group event, it will have appended all
6997 * its siblings to the list, but we obtained 'tmp' before that which
6998 * will still point to the list head terminating the iteration.
7000 if (!list_empty(&child_ctx->pinned_groups) ||
7001 !list_empty(&child_ctx->flexible_groups))
7004 mutex_unlock(&child_ctx->mutex);
7010 * When a child task exits, feed back event values to parent events.
7012 void perf_event_exit_task(struct task_struct *child)
7014 struct perf_event *event, *tmp;
7017 mutex_lock(&child->perf_event_mutex);
7018 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
7020 list_del_init(&event->owner_entry);
7023 * Ensure the list deletion is visible before we clear
7024 * the owner, closes a race against perf_release() where
7025 * we need to serialize on the owner->perf_event_mutex.
7028 event->owner = NULL;
7030 mutex_unlock(&child->perf_event_mutex);
7032 for_each_task_context_nr(ctxn)
7033 perf_event_exit_task_context(child, ctxn);
7036 static void perf_free_event(struct perf_event *event,
7037 struct perf_event_context *ctx)
7039 struct perf_event *parent = event->parent;
7041 if (WARN_ON_ONCE(!parent))
7044 mutex_lock(&parent->child_mutex);
7045 list_del_init(&event->child_list);
7046 mutex_unlock(&parent->child_mutex);
7050 perf_group_detach(event);
7051 list_del_event(event, ctx);
7056 * free an unexposed, unused context as created by inheritance by
7057 * perf_event_init_task below, used by fork() in case of fail.
7059 void perf_event_free_task(struct task_struct *task)
7061 struct perf_event_context *ctx;
7062 struct perf_event *event, *tmp;
7065 for_each_task_context_nr(ctxn) {
7066 ctx = task->perf_event_ctxp[ctxn];
7070 mutex_lock(&ctx->mutex);
7072 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
7074 perf_free_event(event, ctx);
7076 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
7078 perf_free_event(event, ctx);
7080 if (!list_empty(&ctx->pinned_groups) ||
7081 !list_empty(&ctx->flexible_groups))
7084 mutex_unlock(&ctx->mutex);
7090 void perf_event_delayed_put(struct task_struct *task)
7094 for_each_task_context_nr(ctxn)
7095 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
7099 * inherit a event from parent task to child task:
7101 static struct perf_event *
7102 inherit_event(struct perf_event *parent_event,
7103 struct task_struct *parent,
7104 struct perf_event_context *parent_ctx,
7105 struct task_struct *child,
7106 struct perf_event *group_leader,
7107 struct perf_event_context *child_ctx)
7109 struct perf_event *child_event;
7110 unsigned long flags;
7113 * Instead of creating recursive hierarchies of events,
7114 * we link inherited events back to the original parent,
7115 * which has a filp for sure, which we use as the reference
7118 if (parent_event->parent)
7119 parent_event = parent_event->parent;
7121 child_event = perf_event_alloc(&parent_event->attr,
7124 group_leader, parent_event,
7126 if (IS_ERR(child_event))
7129 if (!atomic_long_inc_not_zero(&parent_event->refcount)) {
7130 free_event(child_event);
7137 * Make the child state follow the state of the parent event,
7138 * not its attr.disabled bit. We hold the parent's mutex,
7139 * so we won't race with perf_event_{en, dis}able_family.
7141 if (parent_event->state >= PERF_EVENT_STATE_INACTIVE)
7142 child_event->state = PERF_EVENT_STATE_INACTIVE;
7144 child_event->state = PERF_EVENT_STATE_OFF;
7146 if (parent_event->attr.freq) {
7147 u64 sample_period = parent_event->hw.sample_period;
7148 struct hw_perf_event *hwc = &child_event->hw;
7150 hwc->sample_period = sample_period;
7151 hwc->last_period = sample_period;
7153 local64_set(&hwc->period_left, sample_period);
7156 child_event->ctx = child_ctx;
7157 child_event->overflow_handler = parent_event->overflow_handler;
7158 child_event->overflow_handler_context
7159 = parent_event->overflow_handler_context;
7162 * Precalculate sample_data sizes
7164 perf_event__header_size(child_event);
7165 perf_event__id_header_size(child_event);
7168 * Link it up in the child's context:
7170 raw_spin_lock_irqsave(&child_ctx->lock, flags);
7171 add_event_to_ctx(child_event, child_ctx);
7172 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7175 * Link this into the parent event's child list
7177 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7178 mutex_lock(&parent_event->child_mutex);
7179 list_add_tail(&child_event->child_list, &parent_event->child_list);
7180 mutex_unlock(&parent_event->child_mutex);
7185 static int inherit_group(struct perf_event *parent_event,
7186 struct task_struct *parent,
7187 struct perf_event_context *parent_ctx,
7188 struct task_struct *child,
7189 struct perf_event_context *child_ctx)
7191 struct perf_event *leader;
7192 struct perf_event *sub;
7193 struct perf_event *child_ctr;
7195 leader = inherit_event(parent_event, parent, parent_ctx,
7196 child, NULL, child_ctx);
7198 return PTR_ERR(leader);
7199 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
7200 child_ctr = inherit_event(sub, parent, parent_ctx,
7201 child, leader, child_ctx);
7202 if (IS_ERR(child_ctr))
7203 return PTR_ERR(child_ctr);
7209 inherit_task_group(struct perf_event *event, struct task_struct *parent,
7210 struct perf_event_context *parent_ctx,
7211 struct task_struct *child, int ctxn,
7215 struct perf_event_context *child_ctx;
7217 if (!event->attr.inherit) {
7222 child_ctx = child->perf_event_ctxp[ctxn];
7225 * This is executed from the parent task context, so
7226 * inherit events that have been marked for cloning.
7227 * First allocate and initialize a context for the
7231 child_ctx = alloc_perf_context(event->pmu, child);
7235 child->perf_event_ctxp[ctxn] = child_ctx;
7238 ret = inherit_group(event, parent, parent_ctx,
7248 * Initialize the perf_event context in task_struct
7250 int perf_event_init_context(struct task_struct *child, int ctxn)
7252 struct perf_event_context *child_ctx, *parent_ctx;
7253 struct perf_event_context *cloned_ctx;
7254 struct perf_event *event;
7255 struct task_struct *parent = current;
7256 int inherited_all = 1;
7257 unsigned long flags;
7260 if (likely(!parent->perf_event_ctxp[ctxn]))
7264 * If the parent's context is a clone, pin it so it won't get
7267 parent_ctx = perf_pin_task_context(parent, ctxn);
7270 * No need to check if parent_ctx != NULL here; since we saw
7271 * it non-NULL earlier, the only reason for it to become NULL
7272 * is if we exit, and since we're currently in the middle of
7273 * a fork we can't be exiting at the same time.
7277 * Lock the parent list. No need to lock the child - not PID
7278 * hashed yet and not running, so nobody can access it.
7280 mutex_lock(&parent_ctx->mutex);
7283 * We dont have to disable NMIs - we are only looking at
7284 * the list, not manipulating it:
7286 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
7287 ret = inherit_task_group(event, parent, parent_ctx,
7288 child, ctxn, &inherited_all);
7294 * We can't hold ctx->lock when iterating the ->flexible_group list due
7295 * to allocations, but we need to prevent rotation because
7296 * rotate_ctx() will change the list from interrupt context.
7298 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7299 parent_ctx->rotate_disable = 1;
7300 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7302 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
7303 ret = inherit_task_group(event, parent, parent_ctx,
7304 child, ctxn, &inherited_all);
7309 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7310 parent_ctx->rotate_disable = 0;
7312 child_ctx = child->perf_event_ctxp[ctxn];
7314 if (child_ctx && inherited_all) {
7316 * Mark the child context as a clone of the parent
7317 * context, or of whatever the parent is a clone of.
7319 * Note that if the parent is a clone, the holding of
7320 * parent_ctx->lock avoids it from being uncloned.
7322 cloned_ctx = parent_ctx->parent_ctx;
7324 child_ctx->parent_ctx = cloned_ctx;
7325 child_ctx->parent_gen = parent_ctx->parent_gen;
7327 child_ctx->parent_ctx = parent_ctx;
7328 child_ctx->parent_gen = parent_ctx->generation;
7330 get_ctx(child_ctx->parent_ctx);
7333 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7334 mutex_unlock(&parent_ctx->mutex);
7336 perf_unpin_context(parent_ctx);
7337 put_ctx(parent_ctx);
7343 * Initialize the perf_event context in task_struct
7345 int perf_event_init_task(struct task_struct *child)
7349 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
7350 mutex_init(&child->perf_event_mutex);
7351 INIT_LIST_HEAD(&child->perf_event_list);
7353 for_each_task_context_nr(ctxn) {
7354 ret = perf_event_init_context(child, ctxn);
7362 static void __init perf_event_init_all_cpus(void)
7364 struct swevent_htable *swhash;
7367 for_each_possible_cpu(cpu) {
7368 swhash = &per_cpu(swevent_htable, cpu);
7369 mutex_init(&swhash->hlist_mutex);
7370 INIT_LIST_HEAD(&per_cpu(rotation_list, cpu));
7374 static void __cpuinit perf_event_init_cpu(int cpu)
7376 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7378 mutex_lock(&swhash->hlist_mutex);
7379 if (swhash->hlist_refcount > 0) {
7380 struct swevent_hlist *hlist;
7382 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
7384 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7386 mutex_unlock(&swhash->hlist_mutex);
7389 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC
7390 static void perf_pmu_rotate_stop(struct pmu *pmu)
7392 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7394 WARN_ON(!irqs_disabled());
7396 list_del_init(&cpuctx->rotation_list);
7399 static void __perf_event_exit_context(void *__info)
7401 struct perf_event_context *ctx = __info;
7402 struct perf_event *event, *tmp;
7404 perf_pmu_rotate_stop(ctx->pmu);
7406 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups, group_entry)
7407 __perf_remove_from_context(event);
7408 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups, group_entry)
7409 __perf_remove_from_context(event);
7412 static void perf_event_exit_cpu_context(int cpu)
7414 struct perf_event_context *ctx;
7418 idx = srcu_read_lock(&pmus_srcu);
7419 list_for_each_entry_rcu(pmu, &pmus, entry) {
7420 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
7422 mutex_lock(&ctx->mutex);
7423 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
7424 mutex_unlock(&ctx->mutex);
7426 srcu_read_unlock(&pmus_srcu, idx);
7429 static void perf_event_exit_cpu(int cpu)
7431 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7433 mutex_lock(&swhash->hlist_mutex);
7434 swevent_hlist_release(swhash);
7435 mutex_unlock(&swhash->hlist_mutex);
7437 perf_event_exit_cpu_context(cpu);
7440 static inline void perf_event_exit_cpu(int cpu) { }
7444 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
7448 for_each_online_cpu(cpu)
7449 perf_event_exit_cpu(cpu);
7455 * Run the perf reboot notifier at the very last possible moment so that
7456 * the generic watchdog code runs as long as possible.
7458 static struct notifier_block perf_reboot_notifier = {
7459 .notifier_call = perf_reboot,
7460 .priority = INT_MIN,
7463 static int __cpuinit
7464 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
7466 unsigned int cpu = (long)hcpu;
7468 switch (action & ~CPU_TASKS_FROZEN) {
7470 case CPU_UP_PREPARE:
7471 case CPU_DOWN_FAILED:
7472 perf_event_init_cpu(cpu);
7475 case CPU_UP_CANCELED:
7476 case CPU_DOWN_PREPARE:
7477 perf_event_exit_cpu(cpu);
7487 void __init perf_event_init(void)
7493 perf_event_init_all_cpus();
7494 init_srcu_struct(&pmus_srcu);
7495 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
7496 perf_pmu_register(&perf_cpu_clock, NULL, -1);
7497 perf_pmu_register(&perf_task_clock, NULL, -1);
7499 perf_cpu_notifier(perf_cpu_notify);
7500 register_reboot_notifier(&perf_reboot_notifier);
7502 ret = init_hw_breakpoint();
7503 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
7505 /* do not patch jump label more than once per second */
7506 jump_label_rate_limit(&perf_sched_events, HZ);
7509 * Build time assertion that we keep the data_head at the intended
7510 * location. IOW, validation we got the __reserved[] size right.
7512 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
7516 static int __init perf_event_sysfs_init(void)
7521 mutex_lock(&pmus_lock);
7523 ret = bus_register(&pmu_bus);
7527 list_for_each_entry(pmu, &pmus, entry) {
7528 if (!pmu->name || pmu->type < 0)
7531 ret = pmu_dev_alloc(pmu);
7532 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
7534 pmu_bus_running = 1;
7538 mutex_unlock(&pmus_lock);
7542 device_initcall(perf_event_sysfs_init);
7544 #ifdef CONFIG_CGROUP_PERF
7545 static struct cgroup_subsys_state *perf_cgroup_css_alloc(struct cgroup *cont)
7547 struct perf_cgroup *jc;
7549 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
7551 return ERR_PTR(-ENOMEM);
7553 jc->info = alloc_percpu(struct perf_cgroup_info);
7556 return ERR_PTR(-ENOMEM);
7562 static void perf_cgroup_css_free(struct cgroup *cont)
7564 struct perf_cgroup *jc;
7565 jc = container_of(cgroup_subsys_state(cont, perf_subsys_id),
7566 struct perf_cgroup, css);
7567 free_percpu(jc->info);
7571 static int __perf_cgroup_move(void *info)
7573 struct task_struct *task = info;
7574 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
7578 static void perf_cgroup_attach(struct cgroup *cgrp, struct cgroup_taskset *tset)
7580 struct task_struct *task;
7582 cgroup_taskset_for_each(task, cgrp, tset)
7583 task_function_call(task, __perf_cgroup_move, task);
7586 static void perf_cgroup_exit(struct cgroup *cgrp, struct cgroup *old_cgrp,
7587 struct task_struct *task)
7590 * cgroup_exit() is called in the copy_process() failure path.
7591 * Ignore this case since the task hasn't ran yet, this avoids
7592 * trying to poke a half freed task state from generic code.
7594 if (!(task->flags & PF_EXITING))
7597 task_function_call(task, __perf_cgroup_move, task);
7600 struct cgroup_subsys perf_subsys = {
7601 .name = "perf_event",
7602 .subsys_id = perf_subsys_id,
7603 .css_alloc = perf_cgroup_css_alloc,
7604 .css_free = perf_cgroup_css_free,
7605 .exit = perf_cgroup_exit,
7606 .attach = perf_cgroup_attach,
7608 #endif /* CONFIG_CGROUP_PERF */