perf: Reduce perf_disable() usage
[linux-2.6.git] / kernel / perf_event.c
blob9a98ce95356106d689c9fba843dbb5a67a67c4c0
1 /*
2 * Performance events core code:
4 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
5 * Copyright (C) 2008-2009 Red Hat, Inc., Ingo Molnar
6 * Copyright (C) 2008-2009 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
7 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
9 * For licensing details see kernel-base/COPYING
12 #include <linux/fs.h>
13 #include <linux/mm.h>
14 #include <linux/cpu.h>
15 #include <linux/smp.h>
16 #include <linux/file.h>
17 #include <linux/poll.h>
18 #include <linux/slab.h>
19 #include <linux/hash.h>
20 #include <linux/sysfs.h>
21 #include <linux/dcache.h>
22 #include <linux/percpu.h>
23 #include <linux/ptrace.h>
24 #include <linux/vmstat.h>
25 #include <linux/vmalloc.h>
26 #include <linux/hardirq.h>
27 #include <linux/rculist.h>
28 #include <linux/uaccess.h>
29 #include <linux/syscalls.h>
30 #include <linux/anon_inodes.h>
31 #include <linux/kernel_stat.h>
32 #include <linux/perf_event.h>
33 #include <linux/ftrace_event.h>
35 #include <asm/irq_regs.h>
38 * Each CPU has a list of per CPU events:
40 static DEFINE_PER_CPU(struct perf_cpu_context, perf_cpu_context);
42 int perf_max_events __read_mostly = 1;
43 static int perf_reserved_percpu __read_mostly;
44 static int perf_overcommit __read_mostly = 1;
46 static atomic_t nr_events __read_mostly;
47 static atomic_t nr_mmap_events __read_mostly;
48 static atomic_t nr_comm_events __read_mostly;
49 static atomic_t nr_task_events __read_mostly;
52 * perf event paranoia level:
53 * -1 - not paranoid at all
54 * 0 - disallow raw tracepoint access for unpriv
55 * 1 - disallow cpu events for unpriv
56 * 2 - disallow kernel profiling for unpriv
58 int sysctl_perf_event_paranoid __read_mostly = 1;
60 int sysctl_perf_event_mlock __read_mostly = 512; /* 'free' kb per user */
63 * max perf event sample rate
65 int sysctl_perf_event_sample_rate __read_mostly = 100000;
67 static atomic64_t perf_event_id;
70 * Lock for (sysadmin-configurable) event reservations:
72 static DEFINE_SPINLOCK(perf_resource_lock);
74 void __weak hw_perf_disable(void) { barrier(); }
75 void __weak hw_perf_enable(void) { barrier(); }
77 void __weak perf_event_print_debug(void) { }
79 static DEFINE_PER_CPU(int, perf_disable_count);
81 void perf_disable(void)
83 if (!__get_cpu_var(perf_disable_count)++)
84 hw_perf_disable();
87 void perf_enable(void)
89 if (!--__get_cpu_var(perf_disable_count))
90 hw_perf_enable();
93 static void get_ctx(struct perf_event_context *ctx)
95 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
98 static void free_ctx(struct rcu_head *head)
100 struct perf_event_context *ctx;
102 ctx = container_of(head, struct perf_event_context, rcu_head);
103 kfree(ctx);
106 static void put_ctx(struct perf_event_context *ctx)
108 if (atomic_dec_and_test(&ctx->refcount)) {
109 if (ctx->parent_ctx)
110 put_ctx(ctx->parent_ctx);
111 if (ctx->task)
112 put_task_struct(ctx->task);
113 call_rcu(&ctx->rcu_head, free_ctx);
117 static void unclone_ctx(struct perf_event_context *ctx)
119 if (ctx->parent_ctx) {
120 put_ctx(ctx->parent_ctx);
121 ctx->parent_ctx = NULL;
126 * If we inherit events we want to return the parent event id
127 * to userspace.
129 static u64 primary_event_id(struct perf_event *event)
131 u64 id = event->id;
133 if (event->parent)
134 id = event->parent->id;
136 return id;
140 * Get the perf_event_context for a task and lock it.
141 * This has to cope with with the fact that until it is locked,
142 * the context could get moved to another task.
144 static struct perf_event_context *
145 perf_lock_task_context(struct task_struct *task, unsigned long *flags)
147 struct perf_event_context *ctx;
149 rcu_read_lock();
150 retry:
151 ctx = rcu_dereference(task->perf_event_ctxp);
152 if (ctx) {
154 * If this context is a clone of another, it might
155 * get swapped for another underneath us by
156 * perf_event_task_sched_out, though the
157 * rcu_read_lock() protects us from any context
158 * getting freed. Lock the context and check if it
159 * got swapped before we could get the lock, and retry
160 * if so. If we locked the right context, then it
161 * can't get swapped on us any more.
163 raw_spin_lock_irqsave(&ctx->lock, *flags);
164 if (ctx != rcu_dereference(task->perf_event_ctxp)) {
165 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
166 goto retry;
169 if (!atomic_inc_not_zero(&ctx->refcount)) {
170 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
171 ctx = NULL;
174 rcu_read_unlock();
175 return ctx;
179 * Get the context for a task and increment its pin_count so it
180 * can't get swapped to another task. This also increments its
181 * reference count so that the context can't get freed.
183 static struct perf_event_context *perf_pin_task_context(struct task_struct *task)
185 struct perf_event_context *ctx;
186 unsigned long flags;
188 ctx = perf_lock_task_context(task, &flags);
189 if (ctx) {
190 ++ctx->pin_count;
191 raw_spin_unlock_irqrestore(&ctx->lock, flags);
193 return ctx;
196 static void perf_unpin_context(struct perf_event_context *ctx)
198 unsigned long flags;
200 raw_spin_lock_irqsave(&ctx->lock, flags);
201 --ctx->pin_count;
202 raw_spin_unlock_irqrestore(&ctx->lock, flags);
203 put_ctx(ctx);
206 static inline u64 perf_clock(void)
208 return local_clock();
212 * Update the record of the current time in a context.
214 static void update_context_time(struct perf_event_context *ctx)
216 u64 now = perf_clock();
218 ctx->time += now - ctx->timestamp;
219 ctx->timestamp = now;
223 * Update the total_time_enabled and total_time_running fields for a event.
225 static void update_event_times(struct perf_event *event)
227 struct perf_event_context *ctx = event->ctx;
228 u64 run_end;
230 if (event->state < PERF_EVENT_STATE_INACTIVE ||
231 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
232 return;
234 if (ctx->is_active)
235 run_end = ctx->time;
236 else
237 run_end = event->tstamp_stopped;
239 event->total_time_enabled = run_end - event->tstamp_enabled;
241 if (event->state == PERF_EVENT_STATE_INACTIVE)
242 run_end = event->tstamp_stopped;
243 else
244 run_end = ctx->time;
246 event->total_time_running = run_end - event->tstamp_running;
250 * Update total_time_enabled and total_time_running for all events in a group.
252 static void update_group_times(struct perf_event *leader)
254 struct perf_event *event;
256 update_event_times(leader);
257 list_for_each_entry(event, &leader->sibling_list, group_entry)
258 update_event_times(event);
261 static struct list_head *
262 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
264 if (event->attr.pinned)
265 return &ctx->pinned_groups;
266 else
267 return &ctx->flexible_groups;
271 * Add a event from the lists for its context.
272 * Must be called with ctx->mutex and ctx->lock held.
274 static void
275 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
277 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
278 event->attach_state |= PERF_ATTACH_CONTEXT;
281 * If we're a stand alone event or group leader, we go to the context
282 * list, group events are kept attached to the group so that
283 * perf_group_detach can, at all times, locate all siblings.
285 if (event->group_leader == event) {
286 struct list_head *list;
288 if (is_software_event(event))
289 event->group_flags |= PERF_GROUP_SOFTWARE;
291 list = ctx_group_list(event, ctx);
292 list_add_tail(&event->group_entry, list);
295 list_add_rcu(&event->event_entry, &ctx->event_list);
296 ctx->nr_events++;
297 if (event->attr.inherit_stat)
298 ctx->nr_stat++;
301 static void perf_group_attach(struct perf_event *event)
303 struct perf_event *group_leader = event->group_leader;
305 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_GROUP);
306 event->attach_state |= PERF_ATTACH_GROUP;
308 if (group_leader == event)
309 return;
311 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
312 !is_software_event(event))
313 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
315 list_add_tail(&event->group_entry, &group_leader->sibling_list);
316 group_leader->nr_siblings++;
320 * Remove a event from the lists for its context.
321 * Must be called with ctx->mutex and ctx->lock held.
323 static void
324 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
327 * We can have double detach due to exit/hot-unplug + close.
329 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
330 return;
332 event->attach_state &= ~PERF_ATTACH_CONTEXT;
334 ctx->nr_events--;
335 if (event->attr.inherit_stat)
336 ctx->nr_stat--;
338 list_del_rcu(&event->event_entry);
340 if (event->group_leader == event)
341 list_del_init(&event->group_entry);
343 update_group_times(event);
346 * If event was in error state, then keep it
347 * that way, otherwise bogus counts will be
348 * returned on read(). The only way to get out
349 * of error state is by explicit re-enabling
350 * of the event
352 if (event->state > PERF_EVENT_STATE_OFF)
353 event->state = PERF_EVENT_STATE_OFF;
356 static void perf_group_detach(struct perf_event *event)
358 struct perf_event *sibling, *tmp;
359 struct list_head *list = NULL;
362 * We can have double detach due to exit/hot-unplug + close.
364 if (!(event->attach_state & PERF_ATTACH_GROUP))
365 return;
367 event->attach_state &= ~PERF_ATTACH_GROUP;
370 * If this is a sibling, remove it from its group.
372 if (event->group_leader != event) {
373 list_del_init(&event->group_entry);
374 event->group_leader->nr_siblings--;
375 return;
378 if (!list_empty(&event->group_entry))
379 list = &event->group_entry;
382 * If this was a group event with sibling events then
383 * upgrade the siblings to singleton events by adding them
384 * to whatever list we are on.
386 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
387 if (list)
388 list_move_tail(&sibling->group_entry, list);
389 sibling->group_leader = sibling;
391 /* Inherit group flags from the previous leader */
392 sibling->group_flags = event->group_flags;
396 static inline int
397 event_filter_match(struct perf_event *event)
399 return event->cpu == -1 || event->cpu == smp_processor_id();
402 static void
403 event_sched_out(struct perf_event *event,
404 struct perf_cpu_context *cpuctx,
405 struct perf_event_context *ctx)
407 u64 delta;
409 * An event which could not be activated because of
410 * filter mismatch still needs to have its timings
411 * maintained, otherwise bogus information is return
412 * via read() for time_enabled, time_running:
414 if (event->state == PERF_EVENT_STATE_INACTIVE
415 && !event_filter_match(event)) {
416 delta = ctx->time - event->tstamp_stopped;
417 event->tstamp_running += delta;
418 event->tstamp_stopped = ctx->time;
421 if (event->state != PERF_EVENT_STATE_ACTIVE)
422 return;
424 event->state = PERF_EVENT_STATE_INACTIVE;
425 if (event->pending_disable) {
426 event->pending_disable = 0;
427 event->state = PERF_EVENT_STATE_OFF;
429 event->tstamp_stopped = ctx->time;
430 event->pmu->disable(event);
431 event->oncpu = -1;
433 if (!is_software_event(event))
434 cpuctx->active_oncpu--;
435 ctx->nr_active--;
436 if (event->attr.exclusive || !cpuctx->active_oncpu)
437 cpuctx->exclusive = 0;
440 static void
441 group_sched_out(struct perf_event *group_event,
442 struct perf_cpu_context *cpuctx,
443 struct perf_event_context *ctx)
445 struct perf_event *event;
446 int state = group_event->state;
448 event_sched_out(group_event, cpuctx, ctx);
451 * Schedule out siblings (if any):
453 list_for_each_entry(event, &group_event->sibling_list, group_entry)
454 event_sched_out(event, cpuctx, ctx);
456 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
457 cpuctx->exclusive = 0;
461 * Cross CPU call to remove a performance event
463 * We disable the event on the hardware level first. After that we
464 * remove it from the context list.
466 static void __perf_event_remove_from_context(void *info)
468 struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
469 struct perf_event *event = info;
470 struct perf_event_context *ctx = event->ctx;
473 * If this is a task context, we need to check whether it is
474 * the current task context of this cpu. If not it has been
475 * scheduled out before the smp call arrived.
477 if (ctx->task && cpuctx->task_ctx != ctx)
478 return;
480 raw_spin_lock(&ctx->lock);
482 event_sched_out(event, cpuctx, ctx);
484 list_del_event(event, ctx);
486 if (!ctx->task) {
488 * Allow more per task events with respect to the
489 * reservation:
491 cpuctx->max_pertask =
492 min(perf_max_events - ctx->nr_events,
493 perf_max_events - perf_reserved_percpu);
496 raw_spin_unlock(&ctx->lock);
501 * Remove the event from a task's (or a CPU's) list of events.
503 * Must be called with ctx->mutex held.
505 * CPU events are removed with a smp call. For task events we only
506 * call when the task is on a CPU.
508 * If event->ctx is a cloned context, callers must make sure that
509 * every task struct that event->ctx->task could possibly point to
510 * remains valid. This is OK when called from perf_release since
511 * that only calls us on the top-level context, which can't be a clone.
512 * When called from perf_event_exit_task, it's OK because the
513 * context has been detached from its task.
515 static void perf_event_remove_from_context(struct perf_event *event)
517 struct perf_event_context *ctx = event->ctx;
518 struct task_struct *task = ctx->task;
520 if (!task) {
522 * Per cpu events are removed via an smp call and
523 * the removal is always successful.
525 smp_call_function_single(event->cpu,
526 __perf_event_remove_from_context,
527 event, 1);
528 return;
531 retry:
532 task_oncpu_function_call(task, __perf_event_remove_from_context,
533 event);
535 raw_spin_lock_irq(&ctx->lock);
537 * If the context is active we need to retry the smp call.
539 if (ctx->nr_active && !list_empty(&event->group_entry)) {
540 raw_spin_unlock_irq(&ctx->lock);
541 goto retry;
545 * The lock prevents that this context is scheduled in so we
546 * can remove the event safely, if the call above did not
547 * succeed.
549 if (!list_empty(&event->group_entry))
550 list_del_event(event, ctx);
551 raw_spin_unlock_irq(&ctx->lock);
555 * Cross CPU call to disable a performance event
557 static void __perf_event_disable(void *info)
559 struct perf_event *event = info;
560 struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
561 struct perf_event_context *ctx = event->ctx;
564 * If this is a per-task event, need to check whether this
565 * event's task is the current task on this cpu.
567 if (ctx->task && cpuctx->task_ctx != ctx)
568 return;
570 raw_spin_lock(&ctx->lock);
573 * If the event is on, turn it off.
574 * If it is in error state, leave it in error state.
576 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
577 update_context_time(ctx);
578 update_group_times(event);
579 if (event == event->group_leader)
580 group_sched_out(event, cpuctx, ctx);
581 else
582 event_sched_out(event, cpuctx, ctx);
583 event->state = PERF_EVENT_STATE_OFF;
586 raw_spin_unlock(&ctx->lock);
590 * Disable a event.
592 * If event->ctx is a cloned context, callers must make sure that
593 * every task struct that event->ctx->task could possibly point to
594 * remains valid. This condition is satisifed when called through
595 * perf_event_for_each_child or perf_event_for_each because they
596 * hold the top-level event's child_mutex, so any descendant that
597 * goes to exit will block in sync_child_event.
598 * When called from perf_pending_event it's OK because event->ctx
599 * is the current context on this CPU and preemption is disabled,
600 * hence we can't get into perf_event_task_sched_out for this context.
602 void perf_event_disable(struct perf_event *event)
604 struct perf_event_context *ctx = event->ctx;
605 struct task_struct *task = ctx->task;
607 if (!task) {
609 * Disable the event on the cpu that it's on
611 smp_call_function_single(event->cpu, __perf_event_disable,
612 event, 1);
613 return;
616 retry:
617 task_oncpu_function_call(task, __perf_event_disable, event);
619 raw_spin_lock_irq(&ctx->lock);
621 * If the event is still active, we need to retry the cross-call.
623 if (event->state == PERF_EVENT_STATE_ACTIVE) {
624 raw_spin_unlock_irq(&ctx->lock);
625 goto retry;
629 * Since we have the lock this context can't be scheduled
630 * in, so we can change the state safely.
632 if (event->state == PERF_EVENT_STATE_INACTIVE) {
633 update_group_times(event);
634 event->state = PERF_EVENT_STATE_OFF;
637 raw_spin_unlock_irq(&ctx->lock);
640 static int
641 event_sched_in(struct perf_event *event,
642 struct perf_cpu_context *cpuctx,
643 struct perf_event_context *ctx)
645 if (event->state <= PERF_EVENT_STATE_OFF)
646 return 0;
648 event->state = PERF_EVENT_STATE_ACTIVE;
649 event->oncpu = smp_processor_id();
651 * The new state must be visible before we turn it on in the hardware:
653 smp_wmb();
655 if (event->pmu->enable(event)) {
656 event->state = PERF_EVENT_STATE_INACTIVE;
657 event->oncpu = -1;
658 return -EAGAIN;
661 event->tstamp_running += ctx->time - event->tstamp_stopped;
663 if (!is_software_event(event))
664 cpuctx->active_oncpu++;
665 ctx->nr_active++;
667 if (event->attr.exclusive)
668 cpuctx->exclusive = 1;
670 return 0;
673 static int
674 group_sched_in(struct perf_event *group_event,
675 struct perf_cpu_context *cpuctx,
676 struct perf_event_context *ctx)
678 struct perf_event *event, *partial_group = NULL;
679 struct pmu *pmu = group_event->pmu;
680 bool txn = false;
682 if (group_event->state == PERF_EVENT_STATE_OFF)
683 return 0;
685 /* Check if group transaction availabe */
686 if (pmu->start_txn)
687 txn = true;
689 if (txn)
690 pmu->start_txn(pmu);
692 if (event_sched_in(group_event, cpuctx, ctx)) {
693 if (txn)
694 pmu->cancel_txn(pmu);
695 return -EAGAIN;
699 * Schedule in siblings as one group (if any):
701 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
702 if (event_sched_in(event, cpuctx, ctx)) {
703 partial_group = event;
704 goto group_error;
708 if (!txn || !pmu->commit_txn(pmu))
709 return 0;
711 group_error:
713 * Groups can be scheduled in as one unit only, so undo any
714 * partial group before returning:
716 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
717 if (event == partial_group)
718 break;
719 event_sched_out(event, cpuctx, ctx);
721 event_sched_out(group_event, cpuctx, ctx);
723 if (txn)
724 pmu->cancel_txn(pmu);
726 return -EAGAIN;
730 * Work out whether we can put this event group on the CPU now.
732 static int group_can_go_on(struct perf_event *event,
733 struct perf_cpu_context *cpuctx,
734 int can_add_hw)
737 * Groups consisting entirely of software events can always go on.
739 if (event->group_flags & PERF_GROUP_SOFTWARE)
740 return 1;
742 * If an exclusive group is already on, no other hardware
743 * events can go on.
745 if (cpuctx->exclusive)
746 return 0;
748 * If this group is exclusive and there are already
749 * events on the CPU, it can't go on.
751 if (event->attr.exclusive && cpuctx->active_oncpu)
752 return 0;
754 * Otherwise, try to add it if all previous groups were able
755 * to go on.
757 return can_add_hw;
760 static void add_event_to_ctx(struct perf_event *event,
761 struct perf_event_context *ctx)
763 list_add_event(event, ctx);
764 perf_group_attach(event);
765 event->tstamp_enabled = ctx->time;
766 event->tstamp_running = ctx->time;
767 event->tstamp_stopped = ctx->time;
771 * Cross CPU call to install and enable a performance event
773 * Must be called with ctx->mutex held
775 static void __perf_install_in_context(void *info)
777 struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
778 struct perf_event *event = info;
779 struct perf_event_context *ctx = event->ctx;
780 struct perf_event *leader = event->group_leader;
781 int err;
784 * If this is a task context, we need to check whether it is
785 * the current task context of this cpu. If not it has been
786 * scheduled out before the smp call arrived.
787 * Or possibly this is the right context but it isn't
788 * on this cpu because it had no events.
790 if (ctx->task && cpuctx->task_ctx != ctx) {
791 if (cpuctx->task_ctx || ctx->task != current)
792 return;
793 cpuctx->task_ctx = ctx;
796 raw_spin_lock(&ctx->lock);
797 ctx->is_active = 1;
798 update_context_time(ctx);
800 add_event_to_ctx(event, ctx);
802 if (event->cpu != -1 && event->cpu != smp_processor_id())
803 goto unlock;
806 * Don't put the event on if it is disabled or if
807 * it is in a group and the group isn't on.
809 if (event->state != PERF_EVENT_STATE_INACTIVE ||
810 (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE))
811 goto unlock;
814 * An exclusive event can't go on if there are already active
815 * hardware events, and no hardware event can go on if there
816 * is already an exclusive event on.
818 if (!group_can_go_on(event, cpuctx, 1))
819 err = -EEXIST;
820 else
821 err = event_sched_in(event, cpuctx, ctx);
823 if (err) {
825 * This event couldn't go on. If it is in a group
826 * then we have to pull the whole group off.
827 * If the event group is pinned then put it in error state.
829 if (leader != event)
830 group_sched_out(leader, cpuctx, ctx);
831 if (leader->attr.pinned) {
832 update_group_times(leader);
833 leader->state = PERF_EVENT_STATE_ERROR;
837 if (!err && !ctx->task && cpuctx->max_pertask)
838 cpuctx->max_pertask--;
840 unlock:
841 raw_spin_unlock(&ctx->lock);
845 * Attach a performance event to a context
847 * First we add the event to the list with the hardware enable bit
848 * in event->hw_config cleared.
850 * If the event is attached to a task which is on a CPU we use a smp
851 * call to enable it in the task context. The task might have been
852 * scheduled away, but we check this in the smp call again.
854 * Must be called with ctx->mutex held.
856 static void
857 perf_install_in_context(struct perf_event_context *ctx,
858 struct perf_event *event,
859 int cpu)
861 struct task_struct *task = ctx->task;
863 if (!task) {
865 * Per cpu events are installed via an smp call and
866 * the install is always successful.
868 smp_call_function_single(cpu, __perf_install_in_context,
869 event, 1);
870 return;
873 retry:
874 task_oncpu_function_call(task, __perf_install_in_context,
875 event);
877 raw_spin_lock_irq(&ctx->lock);
879 * we need to retry the smp call.
881 if (ctx->is_active && list_empty(&event->group_entry)) {
882 raw_spin_unlock_irq(&ctx->lock);
883 goto retry;
887 * The lock prevents that this context is scheduled in so we
888 * can add the event safely, if it the call above did not
889 * succeed.
891 if (list_empty(&event->group_entry))
892 add_event_to_ctx(event, ctx);
893 raw_spin_unlock_irq(&ctx->lock);
897 * Put a event into inactive state and update time fields.
898 * Enabling the leader of a group effectively enables all
899 * the group members that aren't explicitly disabled, so we
900 * have to update their ->tstamp_enabled also.
901 * Note: this works for group members as well as group leaders
902 * since the non-leader members' sibling_lists will be empty.
904 static void __perf_event_mark_enabled(struct perf_event *event,
905 struct perf_event_context *ctx)
907 struct perf_event *sub;
909 event->state = PERF_EVENT_STATE_INACTIVE;
910 event->tstamp_enabled = ctx->time - event->total_time_enabled;
911 list_for_each_entry(sub, &event->sibling_list, group_entry) {
912 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
913 sub->tstamp_enabled =
914 ctx->time - sub->total_time_enabled;
920 * Cross CPU call to enable a performance event
922 static void __perf_event_enable(void *info)
924 struct perf_event *event = info;
925 struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
926 struct perf_event_context *ctx = event->ctx;
927 struct perf_event *leader = event->group_leader;
928 int err;
931 * If this is a per-task event, need to check whether this
932 * event's task is the current task on this cpu.
934 if (ctx->task && cpuctx->task_ctx != ctx) {
935 if (cpuctx->task_ctx || ctx->task != current)
936 return;
937 cpuctx->task_ctx = ctx;
940 raw_spin_lock(&ctx->lock);
941 ctx->is_active = 1;
942 update_context_time(ctx);
944 if (event->state >= PERF_EVENT_STATE_INACTIVE)
945 goto unlock;
946 __perf_event_mark_enabled(event, ctx);
948 if (event->cpu != -1 && event->cpu != smp_processor_id())
949 goto unlock;
952 * If the event is in a group and isn't the group leader,
953 * then don't put it on unless the group is on.
955 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
956 goto unlock;
958 if (!group_can_go_on(event, cpuctx, 1)) {
959 err = -EEXIST;
960 } else {
961 if (event == leader)
962 err = group_sched_in(event, cpuctx, ctx);
963 else
964 err = event_sched_in(event, cpuctx, ctx);
967 if (err) {
969 * If this event can't go on and it's part of a
970 * group, then the whole group has to come off.
972 if (leader != event)
973 group_sched_out(leader, cpuctx, ctx);
974 if (leader->attr.pinned) {
975 update_group_times(leader);
976 leader->state = PERF_EVENT_STATE_ERROR;
980 unlock:
981 raw_spin_unlock(&ctx->lock);
985 * Enable a event.
987 * If event->ctx is a cloned context, callers must make sure that
988 * every task struct that event->ctx->task could possibly point to
989 * remains valid. This condition is satisfied when called through
990 * perf_event_for_each_child or perf_event_for_each as described
991 * for perf_event_disable.
993 void perf_event_enable(struct perf_event *event)
995 struct perf_event_context *ctx = event->ctx;
996 struct task_struct *task = ctx->task;
998 if (!task) {
1000 * Enable the event on the cpu that it's on
1002 smp_call_function_single(event->cpu, __perf_event_enable,
1003 event, 1);
1004 return;
1007 raw_spin_lock_irq(&ctx->lock);
1008 if (event->state >= PERF_EVENT_STATE_INACTIVE)
1009 goto out;
1012 * If the event is in error state, clear that first.
1013 * That way, if we see the event in error state below, we
1014 * know that it has gone back into error state, as distinct
1015 * from the task having been scheduled away before the
1016 * cross-call arrived.
1018 if (event->state == PERF_EVENT_STATE_ERROR)
1019 event->state = PERF_EVENT_STATE_OFF;
1021 retry:
1022 raw_spin_unlock_irq(&ctx->lock);
1023 task_oncpu_function_call(task, __perf_event_enable, event);
1025 raw_spin_lock_irq(&ctx->lock);
1028 * If the context is active and the event is still off,
1029 * we need to retry the cross-call.
1031 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF)
1032 goto retry;
1035 * Since we have the lock this context can't be scheduled
1036 * in, so we can change the state safely.
1038 if (event->state == PERF_EVENT_STATE_OFF)
1039 __perf_event_mark_enabled(event, ctx);
1041 out:
1042 raw_spin_unlock_irq(&ctx->lock);
1045 static int perf_event_refresh(struct perf_event *event, int refresh)
1048 * not supported on inherited events
1050 if (event->attr.inherit)
1051 return -EINVAL;
1053 atomic_add(refresh, &event->event_limit);
1054 perf_event_enable(event);
1056 return 0;
1059 enum event_type_t {
1060 EVENT_FLEXIBLE = 0x1,
1061 EVENT_PINNED = 0x2,
1062 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
1065 static void ctx_sched_out(struct perf_event_context *ctx,
1066 struct perf_cpu_context *cpuctx,
1067 enum event_type_t event_type)
1069 struct perf_event *event;
1071 raw_spin_lock(&ctx->lock);
1072 ctx->is_active = 0;
1073 if (likely(!ctx->nr_events))
1074 goto out;
1075 update_context_time(ctx);
1077 if (!ctx->nr_active)
1078 goto out;
1080 if (event_type & EVENT_PINNED) {
1081 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
1082 group_sched_out(event, cpuctx, ctx);
1085 if (event_type & EVENT_FLEXIBLE) {
1086 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
1087 group_sched_out(event, cpuctx, ctx);
1089 out:
1090 raw_spin_unlock(&ctx->lock);
1094 * Test whether two contexts are equivalent, i.e. whether they
1095 * have both been cloned from the same version of the same context
1096 * and they both have the same number of enabled events.
1097 * If the number of enabled events is the same, then the set
1098 * of enabled events should be the same, because these are both
1099 * inherited contexts, therefore we can't access individual events
1100 * in them directly with an fd; we can only enable/disable all
1101 * events via prctl, or enable/disable all events in a family
1102 * via ioctl, which will have the same effect on both contexts.
1104 static int context_equiv(struct perf_event_context *ctx1,
1105 struct perf_event_context *ctx2)
1107 return ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx
1108 && ctx1->parent_gen == ctx2->parent_gen
1109 && !ctx1->pin_count && !ctx2->pin_count;
1112 static void __perf_event_sync_stat(struct perf_event *event,
1113 struct perf_event *next_event)
1115 u64 value;
1117 if (!event->attr.inherit_stat)
1118 return;
1121 * Update the event value, we cannot use perf_event_read()
1122 * because we're in the middle of a context switch and have IRQs
1123 * disabled, which upsets smp_call_function_single(), however
1124 * we know the event must be on the current CPU, therefore we
1125 * don't need to use it.
1127 switch (event->state) {
1128 case PERF_EVENT_STATE_ACTIVE:
1129 event->pmu->read(event);
1130 /* fall-through */
1132 case PERF_EVENT_STATE_INACTIVE:
1133 update_event_times(event);
1134 break;
1136 default:
1137 break;
1141 * In order to keep per-task stats reliable we need to flip the event
1142 * values when we flip the contexts.
1144 value = local64_read(&next_event->count);
1145 value = local64_xchg(&event->count, value);
1146 local64_set(&next_event->count, value);
1148 swap(event->total_time_enabled, next_event->total_time_enabled);
1149 swap(event->total_time_running, next_event->total_time_running);
1152 * Since we swizzled the values, update the user visible data too.
1154 perf_event_update_userpage(event);
1155 perf_event_update_userpage(next_event);
1158 #define list_next_entry(pos, member) \
1159 list_entry(pos->member.next, typeof(*pos), member)
1161 static void perf_event_sync_stat(struct perf_event_context *ctx,
1162 struct perf_event_context *next_ctx)
1164 struct perf_event *event, *next_event;
1166 if (!ctx->nr_stat)
1167 return;
1169 update_context_time(ctx);
1171 event = list_first_entry(&ctx->event_list,
1172 struct perf_event, event_entry);
1174 next_event = list_first_entry(&next_ctx->event_list,
1175 struct perf_event, event_entry);
1177 while (&event->event_entry != &ctx->event_list &&
1178 &next_event->event_entry != &next_ctx->event_list) {
1180 __perf_event_sync_stat(event, next_event);
1182 event = list_next_entry(event, event_entry);
1183 next_event = list_next_entry(next_event, event_entry);
1188 * Called from scheduler to remove the events of the current task,
1189 * with interrupts disabled.
1191 * We stop each event and update the event value in event->count.
1193 * This does not protect us against NMI, but disable()
1194 * sets the disabled bit in the control field of event _before_
1195 * accessing the event control register. If a NMI hits, then it will
1196 * not restart the event.
1198 void perf_event_task_sched_out(struct task_struct *task,
1199 struct task_struct *next)
1201 struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
1202 struct perf_event_context *ctx = task->perf_event_ctxp;
1203 struct perf_event_context *next_ctx;
1204 struct perf_event_context *parent;
1205 int do_switch = 1;
1207 perf_sw_event(PERF_COUNT_SW_CONTEXT_SWITCHES, 1, 1, NULL, 0);
1209 if (likely(!ctx || !cpuctx->task_ctx))
1210 return;
1212 rcu_read_lock();
1213 parent = rcu_dereference(ctx->parent_ctx);
1214 next_ctx = next->perf_event_ctxp;
1215 if (parent && next_ctx &&
1216 rcu_dereference(next_ctx->parent_ctx) == parent) {
1218 * Looks like the two contexts are clones, so we might be
1219 * able to optimize the context switch. We lock both
1220 * contexts and check that they are clones under the
1221 * lock (including re-checking that neither has been
1222 * uncloned in the meantime). It doesn't matter which
1223 * order we take the locks because no other cpu could
1224 * be trying to lock both of these tasks.
1226 raw_spin_lock(&ctx->lock);
1227 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
1228 if (context_equiv(ctx, next_ctx)) {
1230 * XXX do we need a memory barrier of sorts
1231 * wrt to rcu_dereference() of perf_event_ctxp
1233 task->perf_event_ctxp = next_ctx;
1234 next->perf_event_ctxp = ctx;
1235 ctx->task = next;
1236 next_ctx->task = task;
1237 do_switch = 0;
1239 perf_event_sync_stat(ctx, next_ctx);
1241 raw_spin_unlock(&next_ctx->lock);
1242 raw_spin_unlock(&ctx->lock);
1244 rcu_read_unlock();
1246 if (do_switch) {
1247 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
1248 cpuctx->task_ctx = NULL;
1252 static void task_ctx_sched_out(struct perf_event_context *ctx,
1253 enum event_type_t event_type)
1255 struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
1257 if (!cpuctx->task_ctx)
1258 return;
1260 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
1261 return;
1263 ctx_sched_out(ctx, cpuctx, event_type);
1264 cpuctx->task_ctx = NULL;
1268 * Called with IRQs disabled
1270 static void __perf_event_task_sched_out(struct perf_event_context *ctx)
1272 task_ctx_sched_out(ctx, EVENT_ALL);
1276 * Called with IRQs disabled
1278 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
1279 enum event_type_t event_type)
1281 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
1284 static void
1285 ctx_pinned_sched_in(struct perf_event_context *ctx,
1286 struct perf_cpu_context *cpuctx)
1288 struct perf_event *event;
1290 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
1291 if (event->state <= PERF_EVENT_STATE_OFF)
1292 continue;
1293 if (event->cpu != -1 && event->cpu != smp_processor_id())
1294 continue;
1296 if (group_can_go_on(event, cpuctx, 1))
1297 group_sched_in(event, cpuctx, ctx);
1300 * If this pinned group hasn't been scheduled,
1301 * put it in error state.
1303 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1304 update_group_times(event);
1305 event->state = PERF_EVENT_STATE_ERROR;
1310 static void
1311 ctx_flexible_sched_in(struct perf_event_context *ctx,
1312 struct perf_cpu_context *cpuctx)
1314 struct perf_event *event;
1315 int can_add_hw = 1;
1317 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
1318 /* Ignore events in OFF or ERROR state */
1319 if (event->state <= PERF_EVENT_STATE_OFF)
1320 continue;
1322 * Listen to the 'cpu' scheduling filter constraint
1323 * of events:
1325 if (event->cpu != -1 && event->cpu != smp_processor_id())
1326 continue;
1328 if (group_can_go_on(event, cpuctx, can_add_hw)) {
1329 if (group_sched_in(event, cpuctx, ctx))
1330 can_add_hw = 0;
1335 static void
1336 ctx_sched_in(struct perf_event_context *ctx,
1337 struct perf_cpu_context *cpuctx,
1338 enum event_type_t event_type)
1340 raw_spin_lock(&ctx->lock);
1341 ctx->is_active = 1;
1342 if (likely(!ctx->nr_events))
1343 goto out;
1345 ctx->timestamp = perf_clock();
1348 * First go through the list and put on any pinned groups
1349 * in order to give them the best chance of going on.
1351 if (event_type & EVENT_PINNED)
1352 ctx_pinned_sched_in(ctx, cpuctx);
1354 /* Then walk through the lower prio flexible groups */
1355 if (event_type & EVENT_FLEXIBLE)
1356 ctx_flexible_sched_in(ctx, cpuctx);
1358 out:
1359 raw_spin_unlock(&ctx->lock);
1362 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
1363 enum event_type_t event_type)
1365 struct perf_event_context *ctx = &cpuctx->ctx;
1367 ctx_sched_in(ctx, cpuctx, event_type);
1370 static void task_ctx_sched_in(struct task_struct *task,
1371 enum event_type_t event_type)
1373 struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
1374 struct perf_event_context *ctx = task->perf_event_ctxp;
1376 if (likely(!ctx))
1377 return;
1378 if (cpuctx->task_ctx == ctx)
1379 return;
1380 ctx_sched_in(ctx, cpuctx, event_type);
1381 cpuctx->task_ctx = ctx;
1384 * Called from scheduler to add the events of the current task
1385 * with interrupts disabled.
1387 * We restore the event value and then enable it.
1389 * This does not protect us against NMI, but enable()
1390 * sets the enabled bit in the control field of event _before_
1391 * accessing the event control register. If a NMI hits, then it will
1392 * keep the event running.
1394 void perf_event_task_sched_in(struct task_struct *task)
1396 struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
1397 struct perf_event_context *ctx = task->perf_event_ctxp;
1399 if (likely(!ctx))
1400 return;
1402 if (cpuctx->task_ctx == ctx)
1403 return;
1406 * We want to keep the following priority order:
1407 * cpu pinned (that don't need to move), task pinned,
1408 * cpu flexible, task flexible.
1410 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
1412 ctx_sched_in(ctx, cpuctx, EVENT_PINNED);
1413 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE);
1414 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE);
1416 cpuctx->task_ctx = ctx;
1419 #define MAX_INTERRUPTS (~0ULL)
1421 static void perf_log_throttle(struct perf_event *event, int enable);
1423 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
1425 u64 frequency = event->attr.sample_freq;
1426 u64 sec = NSEC_PER_SEC;
1427 u64 divisor, dividend;
1429 int count_fls, nsec_fls, frequency_fls, sec_fls;
1431 count_fls = fls64(count);
1432 nsec_fls = fls64(nsec);
1433 frequency_fls = fls64(frequency);
1434 sec_fls = 30;
1437 * We got @count in @nsec, with a target of sample_freq HZ
1438 * the target period becomes:
1440 * @count * 10^9
1441 * period = -------------------
1442 * @nsec * sample_freq
1447 * Reduce accuracy by one bit such that @a and @b converge
1448 * to a similar magnitude.
1450 #define REDUCE_FLS(a, b) \
1451 do { \
1452 if (a##_fls > b##_fls) { \
1453 a >>= 1; \
1454 a##_fls--; \
1455 } else { \
1456 b >>= 1; \
1457 b##_fls--; \
1459 } while (0)
1462 * Reduce accuracy until either term fits in a u64, then proceed with
1463 * the other, so that finally we can do a u64/u64 division.
1465 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
1466 REDUCE_FLS(nsec, frequency);
1467 REDUCE_FLS(sec, count);
1470 if (count_fls + sec_fls > 64) {
1471 divisor = nsec * frequency;
1473 while (count_fls + sec_fls > 64) {
1474 REDUCE_FLS(count, sec);
1475 divisor >>= 1;
1478 dividend = count * sec;
1479 } else {
1480 dividend = count * sec;
1482 while (nsec_fls + frequency_fls > 64) {
1483 REDUCE_FLS(nsec, frequency);
1484 dividend >>= 1;
1487 divisor = nsec * frequency;
1490 if (!divisor)
1491 return dividend;
1493 return div64_u64(dividend, divisor);
1496 static void perf_event_stop(struct perf_event *event)
1498 if (!event->pmu->stop)
1499 return event->pmu->disable(event);
1501 return event->pmu->stop(event);
1504 static int perf_event_start(struct perf_event *event)
1506 if (!event->pmu->start)
1507 return event->pmu->enable(event);
1509 return event->pmu->start(event);
1512 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count)
1514 struct hw_perf_event *hwc = &event->hw;
1515 s64 period, sample_period;
1516 s64 delta;
1518 period = perf_calculate_period(event, nsec, count);
1520 delta = (s64)(period - hwc->sample_period);
1521 delta = (delta + 7) / 8; /* low pass filter */
1523 sample_period = hwc->sample_period + delta;
1525 if (!sample_period)
1526 sample_period = 1;
1528 hwc->sample_period = sample_period;
1530 if (local64_read(&hwc->period_left) > 8*sample_period) {
1531 perf_event_stop(event);
1532 local64_set(&hwc->period_left, 0);
1533 perf_event_start(event);
1537 static void perf_ctx_adjust_freq(struct perf_event_context *ctx)
1539 struct perf_event *event;
1540 struct hw_perf_event *hwc;
1541 u64 interrupts, now;
1542 s64 delta;
1544 raw_spin_lock(&ctx->lock);
1545 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
1546 if (event->state != PERF_EVENT_STATE_ACTIVE)
1547 continue;
1549 if (event->cpu != -1 && event->cpu != smp_processor_id())
1550 continue;
1552 hwc = &event->hw;
1554 interrupts = hwc->interrupts;
1555 hwc->interrupts = 0;
1558 * unthrottle events on the tick
1560 if (interrupts == MAX_INTERRUPTS) {
1561 perf_log_throttle(event, 1);
1562 event->pmu->unthrottle(event);
1565 if (!event->attr.freq || !event->attr.sample_freq)
1566 continue;
1568 event->pmu->read(event);
1569 now = local64_read(&event->count);
1570 delta = now - hwc->freq_count_stamp;
1571 hwc->freq_count_stamp = now;
1573 if (delta > 0)
1574 perf_adjust_period(event, TICK_NSEC, delta);
1576 raw_spin_unlock(&ctx->lock);
1580 * Round-robin a context's events:
1582 static void rotate_ctx(struct perf_event_context *ctx)
1584 raw_spin_lock(&ctx->lock);
1586 /* Rotate the first entry last of non-pinned groups */
1587 list_rotate_left(&ctx->flexible_groups);
1589 raw_spin_unlock(&ctx->lock);
1592 void perf_event_task_tick(struct task_struct *curr)
1594 struct perf_cpu_context *cpuctx;
1595 struct perf_event_context *ctx;
1596 int rotate = 0;
1598 if (!atomic_read(&nr_events))
1599 return;
1601 cpuctx = &__get_cpu_var(perf_cpu_context);
1602 if (cpuctx->ctx.nr_events &&
1603 cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
1604 rotate = 1;
1606 ctx = curr->perf_event_ctxp;
1607 if (ctx && ctx->nr_events && ctx->nr_events != ctx->nr_active)
1608 rotate = 1;
1610 perf_ctx_adjust_freq(&cpuctx->ctx);
1611 if (ctx)
1612 perf_ctx_adjust_freq(ctx);
1614 if (!rotate)
1615 return;
1617 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
1618 if (ctx)
1619 task_ctx_sched_out(ctx, EVENT_FLEXIBLE);
1621 rotate_ctx(&cpuctx->ctx);
1622 if (ctx)
1623 rotate_ctx(ctx);
1625 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE);
1626 if (ctx)
1627 task_ctx_sched_in(curr, EVENT_FLEXIBLE);
1630 static int event_enable_on_exec(struct perf_event *event,
1631 struct perf_event_context *ctx)
1633 if (!event->attr.enable_on_exec)
1634 return 0;
1636 event->attr.enable_on_exec = 0;
1637 if (event->state >= PERF_EVENT_STATE_INACTIVE)
1638 return 0;
1640 __perf_event_mark_enabled(event, ctx);
1642 return 1;
1646 * Enable all of a task's events that have been marked enable-on-exec.
1647 * This expects task == current.
1649 static void perf_event_enable_on_exec(struct task_struct *task)
1651 struct perf_event_context *ctx;
1652 struct perf_event *event;
1653 unsigned long flags;
1654 int enabled = 0;
1655 int ret;
1657 local_irq_save(flags);
1658 ctx = task->perf_event_ctxp;
1659 if (!ctx || !ctx->nr_events)
1660 goto out;
1662 __perf_event_task_sched_out(ctx);
1664 raw_spin_lock(&ctx->lock);
1666 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
1667 ret = event_enable_on_exec(event, ctx);
1668 if (ret)
1669 enabled = 1;
1672 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
1673 ret = event_enable_on_exec(event, ctx);
1674 if (ret)
1675 enabled = 1;
1679 * Unclone this context if we enabled any event.
1681 if (enabled)
1682 unclone_ctx(ctx);
1684 raw_spin_unlock(&ctx->lock);
1686 perf_event_task_sched_in(task);
1687 out:
1688 local_irq_restore(flags);
1692 * Cross CPU call to read the hardware event
1694 static void __perf_event_read(void *info)
1696 struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
1697 struct perf_event *event = info;
1698 struct perf_event_context *ctx = event->ctx;
1701 * If this is a task context, we need to check whether it is
1702 * the current task context of this cpu. If not it has been
1703 * scheduled out before the smp call arrived. In that case
1704 * event->count would have been updated to a recent sample
1705 * when the event was scheduled out.
1707 if (ctx->task && cpuctx->task_ctx != ctx)
1708 return;
1710 raw_spin_lock(&ctx->lock);
1711 update_context_time(ctx);
1712 update_event_times(event);
1713 raw_spin_unlock(&ctx->lock);
1715 event->pmu->read(event);
1718 static inline u64 perf_event_count(struct perf_event *event)
1720 return local64_read(&event->count) + atomic64_read(&event->child_count);
1723 static u64 perf_event_read(struct perf_event *event)
1726 * If event is enabled and currently active on a CPU, update the
1727 * value in the event structure:
1729 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1730 smp_call_function_single(event->oncpu,
1731 __perf_event_read, event, 1);
1732 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
1733 struct perf_event_context *ctx = event->ctx;
1734 unsigned long flags;
1736 raw_spin_lock_irqsave(&ctx->lock, flags);
1737 update_context_time(ctx);
1738 update_event_times(event);
1739 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1742 return perf_event_count(event);
1746 * Callchain support
1749 struct callchain_cpus_entries {
1750 struct rcu_head rcu_head;
1751 struct perf_callchain_entry *cpu_entries[0];
1754 static DEFINE_PER_CPU(int, callchain_recursion[PERF_NR_CONTEXTS]);
1755 static atomic_t nr_callchain_events;
1756 static DEFINE_MUTEX(callchain_mutex);
1757 struct callchain_cpus_entries *callchain_cpus_entries;
1760 __weak void perf_callchain_kernel(struct perf_callchain_entry *entry,
1761 struct pt_regs *regs)
1765 __weak void perf_callchain_user(struct perf_callchain_entry *entry,
1766 struct pt_regs *regs)
1770 static void release_callchain_buffers_rcu(struct rcu_head *head)
1772 struct callchain_cpus_entries *entries;
1773 int cpu;
1775 entries = container_of(head, struct callchain_cpus_entries, rcu_head);
1777 for_each_possible_cpu(cpu)
1778 kfree(entries->cpu_entries[cpu]);
1780 kfree(entries);
1783 static void release_callchain_buffers(void)
1785 struct callchain_cpus_entries *entries;
1787 entries = callchain_cpus_entries;
1788 rcu_assign_pointer(callchain_cpus_entries, NULL);
1789 call_rcu(&entries->rcu_head, release_callchain_buffers_rcu);
1792 static int alloc_callchain_buffers(void)
1794 int cpu;
1795 int size;
1796 struct callchain_cpus_entries *entries;
1799 * We can't use the percpu allocation API for data that can be
1800 * accessed from NMI. Use a temporary manual per cpu allocation
1801 * until that gets sorted out.
1803 size = sizeof(*entries) + sizeof(struct perf_callchain_entry *) *
1804 num_possible_cpus();
1806 entries = kzalloc(size, GFP_KERNEL);
1807 if (!entries)
1808 return -ENOMEM;
1810 size = sizeof(struct perf_callchain_entry) * PERF_NR_CONTEXTS;
1812 for_each_possible_cpu(cpu) {
1813 entries->cpu_entries[cpu] = kmalloc_node(size, GFP_KERNEL,
1814 cpu_to_node(cpu));
1815 if (!entries->cpu_entries[cpu])
1816 goto fail;
1819 rcu_assign_pointer(callchain_cpus_entries, entries);
1821 return 0;
1823 fail:
1824 for_each_possible_cpu(cpu)
1825 kfree(entries->cpu_entries[cpu]);
1826 kfree(entries);
1828 return -ENOMEM;
1831 static int get_callchain_buffers(void)
1833 int err = 0;
1834 int count;
1836 mutex_lock(&callchain_mutex);
1838 count = atomic_inc_return(&nr_callchain_events);
1839 if (WARN_ON_ONCE(count < 1)) {
1840 err = -EINVAL;
1841 goto exit;
1844 if (count > 1) {
1845 /* If the allocation failed, give up */
1846 if (!callchain_cpus_entries)
1847 err = -ENOMEM;
1848 goto exit;
1851 err = alloc_callchain_buffers();
1852 if (err)
1853 release_callchain_buffers();
1854 exit:
1855 mutex_unlock(&callchain_mutex);
1857 return err;
1860 static void put_callchain_buffers(void)
1862 if (atomic_dec_and_mutex_lock(&nr_callchain_events, &callchain_mutex)) {
1863 release_callchain_buffers();
1864 mutex_unlock(&callchain_mutex);
1868 static int get_recursion_context(int *recursion)
1870 int rctx;
1872 if (in_nmi())
1873 rctx = 3;
1874 else if (in_irq())
1875 rctx = 2;
1876 else if (in_softirq())
1877 rctx = 1;
1878 else
1879 rctx = 0;
1881 if (recursion[rctx])
1882 return -1;
1884 recursion[rctx]++;
1885 barrier();
1887 return rctx;
1890 static inline void put_recursion_context(int *recursion, int rctx)
1892 barrier();
1893 recursion[rctx]--;
1896 static struct perf_callchain_entry *get_callchain_entry(int *rctx)
1898 int cpu;
1899 struct callchain_cpus_entries *entries;
1901 *rctx = get_recursion_context(__get_cpu_var(callchain_recursion));
1902 if (*rctx == -1)
1903 return NULL;
1905 entries = rcu_dereference(callchain_cpus_entries);
1906 if (!entries)
1907 return NULL;
1909 cpu = smp_processor_id();
1911 return &entries->cpu_entries[cpu][*rctx];
1914 static void
1915 put_callchain_entry(int rctx)
1917 put_recursion_context(__get_cpu_var(callchain_recursion), rctx);
1920 static struct perf_callchain_entry *perf_callchain(struct pt_regs *regs)
1922 int rctx;
1923 struct perf_callchain_entry *entry;
1926 entry = get_callchain_entry(&rctx);
1927 if (rctx == -1)
1928 return NULL;
1930 if (!entry)
1931 goto exit_put;
1933 entry->nr = 0;
1935 if (!user_mode(regs)) {
1936 perf_callchain_store(entry, PERF_CONTEXT_KERNEL);
1937 perf_callchain_kernel(entry, regs);
1938 if (current->mm)
1939 regs = task_pt_regs(current);
1940 else
1941 regs = NULL;
1944 if (regs) {
1945 perf_callchain_store(entry, PERF_CONTEXT_USER);
1946 perf_callchain_user(entry, regs);
1949 exit_put:
1950 put_callchain_entry(rctx);
1952 return entry;
1956 * Initialize the perf_event context in a task_struct:
1958 static void
1959 __perf_event_init_context(struct perf_event_context *ctx,
1960 struct task_struct *task)
1962 raw_spin_lock_init(&ctx->lock);
1963 mutex_init(&ctx->mutex);
1964 INIT_LIST_HEAD(&ctx->pinned_groups);
1965 INIT_LIST_HEAD(&ctx->flexible_groups);
1966 INIT_LIST_HEAD(&ctx->event_list);
1967 atomic_set(&ctx->refcount, 1);
1968 ctx->task = task;
1971 static struct perf_event_context *find_get_context(pid_t pid, int cpu)
1973 struct perf_event_context *ctx;
1974 struct perf_cpu_context *cpuctx;
1975 struct task_struct *task;
1976 unsigned long flags;
1977 int err;
1979 if (pid == -1 && cpu != -1) {
1980 /* Must be root to operate on a CPU event: */
1981 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
1982 return ERR_PTR(-EACCES);
1984 if (cpu < 0 || cpu >= nr_cpumask_bits)
1985 return ERR_PTR(-EINVAL);
1988 * We could be clever and allow to attach a event to an
1989 * offline CPU and activate it when the CPU comes up, but
1990 * that's for later.
1992 if (!cpu_online(cpu))
1993 return ERR_PTR(-ENODEV);
1995 cpuctx = &per_cpu(perf_cpu_context, cpu);
1996 ctx = &cpuctx->ctx;
1997 get_ctx(ctx);
1999 return ctx;
2002 rcu_read_lock();
2003 if (!pid)
2004 task = current;
2005 else
2006 task = find_task_by_vpid(pid);
2007 if (task)
2008 get_task_struct(task);
2009 rcu_read_unlock();
2011 if (!task)
2012 return ERR_PTR(-ESRCH);
2015 * Can't attach events to a dying task.
2017 err = -ESRCH;
2018 if (task->flags & PF_EXITING)
2019 goto errout;
2021 /* Reuse ptrace permission checks for now. */
2022 err = -EACCES;
2023 if (!ptrace_may_access(task, PTRACE_MODE_READ))
2024 goto errout;
2026 retry:
2027 ctx = perf_lock_task_context(task, &flags);
2028 if (ctx) {
2029 unclone_ctx(ctx);
2030 raw_spin_unlock_irqrestore(&ctx->lock, flags);
2033 if (!ctx) {
2034 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
2035 err = -ENOMEM;
2036 if (!ctx)
2037 goto errout;
2038 __perf_event_init_context(ctx, task);
2039 get_ctx(ctx);
2040 if (cmpxchg(&task->perf_event_ctxp, NULL, ctx)) {
2042 * We raced with some other task; use
2043 * the context they set.
2045 kfree(ctx);
2046 goto retry;
2048 get_task_struct(task);
2051 put_task_struct(task);
2052 return ctx;
2054 errout:
2055 put_task_struct(task);
2056 return ERR_PTR(err);
2059 static void perf_event_free_filter(struct perf_event *event);
2061 static void free_event_rcu(struct rcu_head *head)
2063 struct perf_event *event;
2065 event = container_of(head, struct perf_event, rcu_head);
2066 if (event->ns)
2067 put_pid_ns(event->ns);
2068 perf_event_free_filter(event);
2069 kfree(event);
2072 static void perf_pending_sync(struct perf_event *event);
2073 static void perf_buffer_put(struct perf_buffer *buffer);
2075 static void free_event(struct perf_event *event)
2077 perf_pending_sync(event);
2079 if (!event->parent) {
2080 atomic_dec(&nr_events);
2081 if (event->attr.mmap || event->attr.mmap_data)
2082 atomic_dec(&nr_mmap_events);
2083 if (event->attr.comm)
2084 atomic_dec(&nr_comm_events);
2085 if (event->attr.task)
2086 atomic_dec(&nr_task_events);
2087 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
2088 put_callchain_buffers();
2091 if (event->buffer) {
2092 perf_buffer_put(event->buffer);
2093 event->buffer = NULL;
2096 if (event->destroy)
2097 event->destroy(event);
2099 put_ctx(event->ctx);
2100 call_rcu(&event->rcu_head, free_event_rcu);
2103 int perf_event_release_kernel(struct perf_event *event)
2105 struct perf_event_context *ctx = event->ctx;
2108 * Remove from the PMU, can't get re-enabled since we got
2109 * here because the last ref went.
2111 perf_event_disable(event);
2113 WARN_ON_ONCE(ctx->parent_ctx);
2115 * There are two ways this annotation is useful:
2117 * 1) there is a lock recursion from perf_event_exit_task
2118 * see the comment there.
2120 * 2) there is a lock-inversion with mmap_sem through
2121 * perf_event_read_group(), which takes faults while
2122 * holding ctx->mutex, however this is called after
2123 * the last filedesc died, so there is no possibility
2124 * to trigger the AB-BA case.
2126 mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
2127 raw_spin_lock_irq(&ctx->lock);
2128 perf_group_detach(event);
2129 list_del_event(event, ctx);
2130 raw_spin_unlock_irq(&ctx->lock);
2131 mutex_unlock(&ctx->mutex);
2133 mutex_lock(&event->owner->perf_event_mutex);
2134 list_del_init(&event->owner_entry);
2135 mutex_unlock(&event->owner->perf_event_mutex);
2136 put_task_struct(event->owner);
2138 free_event(event);
2140 return 0;
2142 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
2145 * Called when the last reference to the file is gone.
2147 static int perf_release(struct inode *inode, struct file *file)
2149 struct perf_event *event = file->private_data;
2151 file->private_data = NULL;
2153 return perf_event_release_kernel(event);
2156 static int perf_event_read_size(struct perf_event *event)
2158 int entry = sizeof(u64); /* value */
2159 int size = 0;
2160 int nr = 1;
2162 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
2163 size += sizeof(u64);
2165 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
2166 size += sizeof(u64);
2168 if (event->attr.read_format & PERF_FORMAT_ID)
2169 entry += sizeof(u64);
2171 if (event->attr.read_format & PERF_FORMAT_GROUP) {
2172 nr += event->group_leader->nr_siblings;
2173 size += sizeof(u64);
2176 size += entry * nr;
2178 return size;
2181 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
2183 struct perf_event *child;
2184 u64 total = 0;
2186 *enabled = 0;
2187 *running = 0;
2189 mutex_lock(&event->child_mutex);
2190 total += perf_event_read(event);
2191 *enabled += event->total_time_enabled +
2192 atomic64_read(&event->child_total_time_enabled);
2193 *running += event->total_time_running +
2194 atomic64_read(&event->child_total_time_running);
2196 list_for_each_entry(child, &event->child_list, child_list) {
2197 total += perf_event_read(child);
2198 *enabled += child->total_time_enabled;
2199 *running += child->total_time_running;
2201 mutex_unlock(&event->child_mutex);
2203 return total;
2205 EXPORT_SYMBOL_GPL(perf_event_read_value);
2207 static int perf_event_read_group(struct perf_event *event,
2208 u64 read_format, char __user *buf)
2210 struct perf_event *leader = event->group_leader, *sub;
2211 int n = 0, size = 0, ret = -EFAULT;
2212 struct perf_event_context *ctx = leader->ctx;
2213 u64 values[5];
2214 u64 count, enabled, running;
2216 mutex_lock(&ctx->mutex);
2217 count = perf_event_read_value(leader, &enabled, &running);
2219 values[n++] = 1 + leader->nr_siblings;
2220 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
2221 values[n++] = enabled;
2222 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
2223 values[n++] = running;
2224 values[n++] = count;
2225 if (read_format & PERF_FORMAT_ID)
2226 values[n++] = primary_event_id(leader);
2228 size = n * sizeof(u64);
2230 if (copy_to_user(buf, values, size))
2231 goto unlock;
2233 ret = size;
2235 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
2236 n = 0;
2238 values[n++] = perf_event_read_value(sub, &enabled, &running);
2239 if (read_format & PERF_FORMAT_ID)
2240 values[n++] = primary_event_id(sub);
2242 size = n * sizeof(u64);
2244 if (copy_to_user(buf + ret, values, size)) {
2245 ret = -EFAULT;
2246 goto unlock;
2249 ret += size;
2251 unlock:
2252 mutex_unlock(&ctx->mutex);
2254 return ret;
2257 static int perf_event_read_one(struct perf_event *event,
2258 u64 read_format, char __user *buf)
2260 u64 enabled, running;
2261 u64 values[4];
2262 int n = 0;
2264 values[n++] = perf_event_read_value(event, &enabled, &running);
2265 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
2266 values[n++] = enabled;
2267 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
2268 values[n++] = running;
2269 if (read_format & PERF_FORMAT_ID)
2270 values[n++] = primary_event_id(event);
2272 if (copy_to_user(buf, values, n * sizeof(u64)))
2273 return -EFAULT;
2275 return n * sizeof(u64);
2279 * Read the performance event - simple non blocking version for now
2281 static ssize_t
2282 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
2284 u64 read_format = event->attr.read_format;
2285 int ret;
2288 * Return end-of-file for a read on a event that is in
2289 * error state (i.e. because it was pinned but it couldn't be
2290 * scheduled on to the CPU at some point).
2292 if (event->state == PERF_EVENT_STATE_ERROR)
2293 return 0;
2295 if (count < perf_event_read_size(event))
2296 return -ENOSPC;
2298 WARN_ON_ONCE(event->ctx->parent_ctx);
2299 if (read_format & PERF_FORMAT_GROUP)
2300 ret = perf_event_read_group(event, read_format, buf);
2301 else
2302 ret = perf_event_read_one(event, read_format, buf);
2304 return ret;
2307 static ssize_t
2308 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
2310 struct perf_event *event = file->private_data;
2312 return perf_read_hw(event, buf, count);
2315 static unsigned int perf_poll(struct file *file, poll_table *wait)
2317 struct perf_event *event = file->private_data;
2318 struct perf_buffer *buffer;
2319 unsigned int events = POLL_HUP;
2321 rcu_read_lock();
2322 buffer = rcu_dereference(event->buffer);
2323 if (buffer)
2324 events = atomic_xchg(&buffer->poll, 0);
2325 rcu_read_unlock();
2327 poll_wait(file, &event->waitq, wait);
2329 return events;
2332 static void perf_event_reset(struct perf_event *event)
2334 (void)perf_event_read(event);
2335 local64_set(&event->count, 0);
2336 perf_event_update_userpage(event);
2340 * Holding the top-level event's child_mutex means that any
2341 * descendant process that has inherited this event will block
2342 * in sync_child_event if it goes to exit, thus satisfying the
2343 * task existence requirements of perf_event_enable/disable.
2345 static void perf_event_for_each_child(struct perf_event *event,
2346 void (*func)(struct perf_event *))
2348 struct perf_event *child;
2350 WARN_ON_ONCE(event->ctx->parent_ctx);
2351 mutex_lock(&event->child_mutex);
2352 func(event);
2353 list_for_each_entry(child, &event->child_list, child_list)
2354 func(child);
2355 mutex_unlock(&event->child_mutex);
2358 static void perf_event_for_each(struct perf_event *event,
2359 void (*func)(struct perf_event *))
2361 struct perf_event_context *ctx = event->ctx;
2362 struct perf_event *sibling;
2364 WARN_ON_ONCE(ctx->parent_ctx);
2365 mutex_lock(&ctx->mutex);
2366 event = event->group_leader;
2368 perf_event_for_each_child(event, func);
2369 func(event);
2370 list_for_each_entry(sibling, &event->sibling_list, group_entry)
2371 perf_event_for_each_child(event, func);
2372 mutex_unlock(&ctx->mutex);
2375 static int perf_event_period(struct perf_event *event, u64 __user *arg)
2377 struct perf_event_context *ctx = event->ctx;
2378 unsigned long size;
2379 int ret = 0;
2380 u64 value;
2382 if (!event->attr.sample_period)
2383 return -EINVAL;
2385 size = copy_from_user(&value, arg, sizeof(value));
2386 if (size != sizeof(value))
2387 return -EFAULT;
2389 if (!value)
2390 return -EINVAL;
2392 raw_spin_lock_irq(&ctx->lock);
2393 if (event->attr.freq) {
2394 if (value > sysctl_perf_event_sample_rate) {
2395 ret = -EINVAL;
2396 goto unlock;
2399 event->attr.sample_freq = value;
2400 } else {
2401 event->attr.sample_period = value;
2402 event->hw.sample_period = value;
2404 unlock:
2405 raw_spin_unlock_irq(&ctx->lock);
2407 return ret;
2410 static const struct file_operations perf_fops;
2412 static struct perf_event *perf_fget_light(int fd, int *fput_needed)
2414 struct file *file;
2416 file = fget_light(fd, fput_needed);
2417 if (!file)
2418 return ERR_PTR(-EBADF);
2420 if (file->f_op != &perf_fops) {
2421 fput_light(file, *fput_needed);
2422 *fput_needed = 0;
2423 return ERR_PTR(-EBADF);
2426 return file->private_data;
2429 static int perf_event_set_output(struct perf_event *event,
2430 struct perf_event *output_event);
2431 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
2433 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2435 struct perf_event *event = file->private_data;
2436 void (*func)(struct perf_event *);
2437 u32 flags = arg;
2439 switch (cmd) {
2440 case PERF_EVENT_IOC_ENABLE:
2441 func = perf_event_enable;
2442 break;
2443 case PERF_EVENT_IOC_DISABLE:
2444 func = perf_event_disable;
2445 break;
2446 case PERF_EVENT_IOC_RESET:
2447 func = perf_event_reset;
2448 break;
2450 case PERF_EVENT_IOC_REFRESH:
2451 return perf_event_refresh(event, arg);
2453 case PERF_EVENT_IOC_PERIOD:
2454 return perf_event_period(event, (u64 __user *)arg);
2456 case PERF_EVENT_IOC_SET_OUTPUT:
2458 struct perf_event *output_event = NULL;
2459 int fput_needed = 0;
2460 int ret;
2462 if (arg != -1) {
2463 output_event = perf_fget_light(arg, &fput_needed);
2464 if (IS_ERR(output_event))
2465 return PTR_ERR(output_event);
2468 ret = perf_event_set_output(event, output_event);
2469 if (output_event)
2470 fput_light(output_event->filp, fput_needed);
2472 return ret;
2475 case PERF_EVENT_IOC_SET_FILTER:
2476 return perf_event_set_filter(event, (void __user *)arg);
2478 default:
2479 return -ENOTTY;
2482 if (flags & PERF_IOC_FLAG_GROUP)
2483 perf_event_for_each(event, func);
2484 else
2485 perf_event_for_each_child(event, func);
2487 return 0;
2490 int perf_event_task_enable(void)
2492 struct perf_event *event;
2494 mutex_lock(&current->perf_event_mutex);
2495 list_for_each_entry(event, &current->perf_event_list, owner_entry)
2496 perf_event_for_each_child(event, perf_event_enable);
2497 mutex_unlock(&current->perf_event_mutex);
2499 return 0;
2502 int perf_event_task_disable(void)
2504 struct perf_event *event;
2506 mutex_lock(&current->perf_event_mutex);
2507 list_for_each_entry(event, &current->perf_event_list, owner_entry)
2508 perf_event_for_each_child(event, perf_event_disable);
2509 mutex_unlock(&current->perf_event_mutex);
2511 return 0;
2514 #ifndef PERF_EVENT_INDEX_OFFSET
2515 # define PERF_EVENT_INDEX_OFFSET 0
2516 #endif
2518 static int perf_event_index(struct perf_event *event)
2520 if (event->state != PERF_EVENT_STATE_ACTIVE)
2521 return 0;
2523 return event->hw.idx + 1 - PERF_EVENT_INDEX_OFFSET;
2527 * Callers need to ensure there can be no nesting of this function, otherwise
2528 * the seqlock logic goes bad. We can not serialize this because the arch
2529 * code calls this from NMI context.
2531 void perf_event_update_userpage(struct perf_event *event)
2533 struct perf_event_mmap_page *userpg;
2534 struct perf_buffer *buffer;
2536 rcu_read_lock();
2537 buffer = rcu_dereference(event->buffer);
2538 if (!buffer)
2539 goto unlock;
2541 userpg = buffer->user_page;
2544 * Disable preemption so as to not let the corresponding user-space
2545 * spin too long if we get preempted.
2547 preempt_disable();
2548 ++userpg->lock;
2549 barrier();
2550 userpg->index = perf_event_index(event);
2551 userpg->offset = perf_event_count(event);
2552 if (event->state == PERF_EVENT_STATE_ACTIVE)
2553 userpg->offset -= local64_read(&event->hw.prev_count);
2555 userpg->time_enabled = event->total_time_enabled +
2556 atomic64_read(&event->child_total_time_enabled);
2558 userpg->time_running = event->total_time_running +
2559 atomic64_read(&event->child_total_time_running);
2561 barrier();
2562 ++userpg->lock;
2563 preempt_enable();
2564 unlock:
2565 rcu_read_unlock();
2568 static unsigned long perf_data_size(struct perf_buffer *buffer);
2570 static void
2571 perf_buffer_init(struct perf_buffer *buffer, long watermark, int flags)
2573 long max_size = perf_data_size(buffer);
2575 if (watermark)
2576 buffer->watermark = min(max_size, watermark);
2578 if (!buffer->watermark)
2579 buffer->watermark = max_size / 2;
2581 if (flags & PERF_BUFFER_WRITABLE)
2582 buffer->writable = 1;
2584 atomic_set(&buffer->refcount, 1);
2587 #ifndef CONFIG_PERF_USE_VMALLOC
2590 * Back perf_mmap() with regular GFP_KERNEL-0 pages.
2593 static struct page *
2594 perf_mmap_to_page(struct perf_buffer *buffer, unsigned long pgoff)
2596 if (pgoff > buffer->nr_pages)
2597 return NULL;
2599 if (pgoff == 0)
2600 return virt_to_page(buffer->user_page);
2602 return virt_to_page(buffer->data_pages[pgoff - 1]);
2605 static void *perf_mmap_alloc_page(int cpu)
2607 struct page *page;
2608 int node;
2610 node = (cpu == -1) ? cpu : cpu_to_node(cpu);
2611 page = alloc_pages_node(node, GFP_KERNEL | __GFP_ZERO, 0);
2612 if (!page)
2613 return NULL;
2615 return page_address(page);
2618 static struct perf_buffer *
2619 perf_buffer_alloc(int nr_pages, long watermark, int cpu, int flags)
2621 struct perf_buffer *buffer;
2622 unsigned long size;
2623 int i;
2625 size = sizeof(struct perf_buffer);
2626 size += nr_pages * sizeof(void *);
2628 buffer = kzalloc(size, GFP_KERNEL);
2629 if (!buffer)
2630 goto fail;
2632 buffer->user_page = perf_mmap_alloc_page(cpu);
2633 if (!buffer->user_page)
2634 goto fail_user_page;
2636 for (i = 0; i < nr_pages; i++) {
2637 buffer->data_pages[i] = perf_mmap_alloc_page(cpu);
2638 if (!buffer->data_pages[i])
2639 goto fail_data_pages;
2642 buffer->nr_pages = nr_pages;
2644 perf_buffer_init(buffer, watermark, flags);
2646 return buffer;
2648 fail_data_pages:
2649 for (i--; i >= 0; i--)
2650 free_page((unsigned long)buffer->data_pages[i]);
2652 free_page((unsigned long)buffer->user_page);
2654 fail_user_page:
2655 kfree(buffer);
2657 fail:
2658 return NULL;
2661 static void perf_mmap_free_page(unsigned long addr)
2663 struct page *page = virt_to_page((void *)addr);
2665 page->mapping = NULL;
2666 __free_page(page);
2669 static void perf_buffer_free(struct perf_buffer *buffer)
2671 int i;
2673 perf_mmap_free_page((unsigned long)buffer->user_page);
2674 for (i = 0; i < buffer->nr_pages; i++)
2675 perf_mmap_free_page((unsigned long)buffer->data_pages[i]);
2676 kfree(buffer);
2679 static inline int page_order(struct perf_buffer *buffer)
2681 return 0;
2684 #else
2687 * Back perf_mmap() with vmalloc memory.
2689 * Required for architectures that have d-cache aliasing issues.
2692 static inline int page_order(struct perf_buffer *buffer)
2694 return buffer->page_order;
2697 static struct page *
2698 perf_mmap_to_page(struct perf_buffer *buffer, unsigned long pgoff)
2700 if (pgoff > (1UL << page_order(buffer)))
2701 return NULL;
2703 return vmalloc_to_page((void *)buffer->user_page + pgoff * PAGE_SIZE);
2706 static void perf_mmap_unmark_page(void *addr)
2708 struct page *page = vmalloc_to_page(addr);
2710 page->mapping = NULL;
2713 static void perf_buffer_free_work(struct work_struct *work)
2715 struct perf_buffer *buffer;
2716 void *base;
2717 int i, nr;
2719 buffer = container_of(work, struct perf_buffer, work);
2720 nr = 1 << page_order(buffer);
2722 base = buffer->user_page;
2723 for (i = 0; i < nr + 1; i++)
2724 perf_mmap_unmark_page(base + (i * PAGE_SIZE));
2726 vfree(base);
2727 kfree(buffer);
2730 static void perf_buffer_free(struct perf_buffer *buffer)
2732 schedule_work(&buffer->work);
2735 static struct perf_buffer *
2736 perf_buffer_alloc(int nr_pages, long watermark, int cpu, int flags)
2738 struct perf_buffer *buffer;
2739 unsigned long size;
2740 void *all_buf;
2742 size = sizeof(struct perf_buffer);
2743 size += sizeof(void *);
2745 buffer = kzalloc(size, GFP_KERNEL);
2746 if (!buffer)
2747 goto fail;
2749 INIT_WORK(&buffer->work, perf_buffer_free_work);
2751 all_buf = vmalloc_user((nr_pages + 1) * PAGE_SIZE);
2752 if (!all_buf)
2753 goto fail_all_buf;
2755 buffer->user_page = all_buf;
2756 buffer->data_pages[0] = all_buf + PAGE_SIZE;
2757 buffer->page_order = ilog2(nr_pages);
2758 buffer->nr_pages = 1;
2760 perf_buffer_init(buffer, watermark, flags);
2762 return buffer;
2764 fail_all_buf:
2765 kfree(buffer);
2767 fail:
2768 return NULL;
2771 #endif
2773 static unsigned long perf_data_size(struct perf_buffer *buffer)
2775 return buffer->nr_pages << (PAGE_SHIFT + page_order(buffer));
2778 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
2780 struct perf_event *event = vma->vm_file->private_data;
2781 struct perf_buffer *buffer;
2782 int ret = VM_FAULT_SIGBUS;
2784 if (vmf->flags & FAULT_FLAG_MKWRITE) {
2785 if (vmf->pgoff == 0)
2786 ret = 0;
2787 return ret;
2790 rcu_read_lock();
2791 buffer = rcu_dereference(event->buffer);
2792 if (!buffer)
2793 goto unlock;
2795 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
2796 goto unlock;
2798 vmf->page = perf_mmap_to_page(buffer, vmf->pgoff);
2799 if (!vmf->page)
2800 goto unlock;
2802 get_page(vmf->page);
2803 vmf->page->mapping = vma->vm_file->f_mapping;
2804 vmf->page->index = vmf->pgoff;
2806 ret = 0;
2807 unlock:
2808 rcu_read_unlock();
2810 return ret;
2813 static void perf_buffer_free_rcu(struct rcu_head *rcu_head)
2815 struct perf_buffer *buffer;
2817 buffer = container_of(rcu_head, struct perf_buffer, rcu_head);
2818 perf_buffer_free(buffer);
2821 static struct perf_buffer *perf_buffer_get(struct perf_event *event)
2823 struct perf_buffer *buffer;
2825 rcu_read_lock();
2826 buffer = rcu_dereference(event->buffer);
2827 if (buffer) {
2828 if (!atomic_inc_not_zero(&buffer->refcount))
2829 buffer = NULL;
2831 rcu_read_unlock();
2833 return buffer;
2836 static void perf_buffer_put(struct perf_buffer *buffer)
2838 if (!atomic_dec_and_test(&buffer->refcount))
2839 return;
2841 call_rcu(&buffer->rcu_head, perf_buffer_free_rcu);
2844 static void perf_mmap_open(struct vm_area_struct *vma)
2846 struct perf_event *event = vma->vm_file->private_data;
2848 atomic_inc(&event->mmap_count);
2851 static void perf_mmap_close(struct vm_area_struct *vma)
2853 struct perf_event *event = vma->vm_file->private_data;
2855 if (atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex)) {
2856 unsigned long size = perf_data_size(event->buffer);
2857 struct user_struct *user = event->mmap_user;
2858 struct perf_buffer *buffer = event->buffer;
2860 atomic_long_sub((size >> PAGE_SHIFT) + 1, &user->locked_vm);
2861 vma->vm_mm->locked_vm -= event->mmap_locked;
2862 rcu_assign_pointer(event->buffer, NULL);
2863 mutex_unlock(&event->mmap_mutex);
2865 perf_buffer_put(buffer);
2866 free_uid(user);
2870 static const struct vm_operations_struct perf_mmap_vmops = {
2871 .open = perf_mmap_open,
2872 .close = perf_mmap_close,
2873 .fault = perf_mmap_fault,
2874 .page_mkwrite = perf_mmap_fault,
2877 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
2879 struct perf_event *event = file->private_data;
2880 unsigned long user_locked, user_lock_limit;
2881 struct user_struct *user = current_user();
2882 unsigned long locked, lock_limit;
2883 struct perf_buffer *buffer;
2884 unsigned long vma_size;
2885 unsigned long nr_pages;
2886 long user_extra, extra;
2887 int ret = 0, flags = 0;
2890 * Don't allow mmap() of inherited per-task counters. This would
2891 * create a performance issue due to all children writing to the
2892 * same buffer.
2894 if (event->cpu == -1 && event->attr.inherit)
2895 return -EINVAL;
2897 if (!(vma->vm_flags & VM_SHARED))
2898 return -EINVAL;
2900 vma_size = vma->vm_end - vma->vm_start;
2901 nr_pages = (vma_size / PAGE_SIZE) - 1;
2904 * If we have buffer pages ensure they're a power-of-two number, so we
2905 * can do bitmasks instead of modulo.
2907 if (nr_pages != 0 && !is_power_of_2(nr_pages))
2908 return -EINVAL;
2910 if (vma_size != PAGE_SIZE * (1 + nr_pages))
2911 return -EINVAL;
2913 if (vma->vm_pgoff != 0)
2914 return -EINVAL;
2916 WARN_ON_ONCE(event->ctx->parent_ctx);
2917 mutex_lock(&event->mmap_mutex);
2918 if (event->buffer) {
2919 if (event->buffer->nr_pages == nr_pages)
2920 atomic_inc(&event->buffer->refcount);
2921 else
2922 ret = -EINVAL;
2923 goto unlock;
2926 user_extra = nr_pages + 1;
2927 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
2930 * Increase the limit linearly with more CPUs:
2932 user_lock_limit *= num_online_cpus();
2934 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
2936 extra = 0;
2937 if (user_locked > user_lock_limit)
2938 extra = user_locked - user_lock_limit;
2940 lock_limit = rlimit(RLIMIT_MEMLOCK);
2941 lock_limit >>= PAGE_SHIFT;
2942 locked = vma->vm_mm->locked_vm + extra;
2944 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
2945 !capable(CAP_IPC_LOCK)) {
2946 ret = -EPERM;
2947 goto unlock;
2950 WARN_ON(event->buffer);
2952 if (vma->vm_flags & VM_WRITE)
2953 flags |= PERF_BUFFER_WRITABLE;
2955 buffer = perf_buffer_alloc(nr_pages, event->attr.wakeup_watermark,
2956 event->cpu, flags);
2957 if (!buffer) {
2958 ret = -ENOMEM;
2959 goto unlock;
2961 rcu_assign_pointer(event->buffer, buffer);
2963 atomic_long_add(user_extra, &user->locked_vm);
2964 event->mmap_locked = extra;
2965 event->mmap_user = get_current_user();
2966 vma->vm_mm->locked_vm += event->mmap_locked;
2968 unlock:
2969 if (!ret)
2970 atomic_inc(&event->mmap_count);
2971 mutex_unlock(&event->mmap_mutex);
2973 vma->vm_flags |= VM_RESERVED;
2974 vma->vm_ops = &perf_mmap_vmops;
2976 return ret;
2979 static int perf_fasync(int fd, struct file *filp, int on)
2981 struct inode *inode = filp->f_path.dentry->d_inode;
2982 struct perf_event *event = filp->private_data;
2983 int retval;
2985 mutex_lock(&inode->i_mutex);
2986 retval = fasync_helper(fd, filp, on, &event->fasync);
2987 mutex_unlock(&inode->i_mutex);
2989 if (retval < 0)
2990 return retval;
2992 return 0;
2995 static const struct file_operations perf_fops = {
2996 .llseek = no_llseek,
2997 .release = perf_release,
2998 .read = perf_read,
2999 .poll = perf_poll,
3000 .unlocked_ioctl = perf_ioctl,
3001 .compat_ioctl = perf_ioctl,
3002 .mmap = perf_mmap,
3003 .fasync = perf_fasync,
3007 * Perf event wakeup
3009 * If there's data, ensure we set the poll() state and publish everything
3010 * to user-space before waking everybody up.
3013 void perf_event_wakeup(struct perf_event *event)
3015 wake_up_all(&event->waitq);
3017 if (event->pending_kill) {
3018 kill_fasync(&event->fasync, SIGIO, event->pending_kill);
3019 event->pending_kill = 0;
3024 * Pending wakeups
3026 * Handle the case where we need to wakeup up from NMI (or rq->lock) context.
3028 * The NMI bit means we cannot possibly take locks. Therefore, maintain a
3029 * single linked list and use cmpxchg() to add entries lockless.
3032 static void perf_pending_event(struct perf_pending_entry *entry)
3034 struct perf_event *event = container_of(entry,
3035 struct perf_event, pending);
3037 if (event->pending_disable) {
3038 event->pending_disable = 0;
3039 __perf_event_disable(event);
3042 if (event->pending_wakeup) {
3043 event->pending_wakeup = 0;
3044 perf_event_wakeup(event);
3048 #define PENDING_TAIL ((struct perf_pending_entry *)-1UL)
3050 static DEFINE_PER_CPU(struct perf_pending_entry *, perf_pending_head) = {
3051 PENDING_TAIL,
3054 static void perf_pending_queue(struct perf_pending_entry *entry,
3055 void (*func)(struct perf_pending_entry *))
3057 struct perf_pending_entry **head;
3059 if (cmpxchg(&entry->next, NULL, PENDING_TAIL) != NULL)
3060 return;
3062 entry->func = func;
3064 head = &get_cpu_var(perf_pending_head);
3066 do {
3067 entry->next = *head;
3068 } while (cmpxchg(head, entry->next, entry) != entry->next);
3070 set_perf_event_pending();
3072 put_cpu_var(perf_pending_head);
3075 static int __perf_pending_run(void)
3077 struct perf_pending_entry *list;
3078 int nr = 0;
3080 list = xchg(&__get_cpu_var(perf_pending_head), PENDING_TAIL);
3081 while (list != PENDING_TAIL) {
3082 void (*func)(struct perf_pending_entry *);
3083 struct perf_pending_entry *entry = list;
3085 list = list->next;
3087 func = entry->func;
3088 entry->next = NULL;
3090 * Ensure we observe the unqueue before we issue the wakeup,
3091 * so that we won't be waiting forever.
3092 * -- see perf_not_pending().
3094 smp_wmb();
3096 func(entry);
3097 nr++;
3100 return nr;
3103 static inline int perf_not_pending(struct perf_event *event)
3106 * If we flush on whatever cpu we run, there is a chance we don't
3107 * need to wait.
3109 get_cpu();
3110 __perf_pending_run();
3111 put_cpu();
3114 * Ensure we see the proper queue state before going to sleep
3115 * so that we do not miss the wakeup. -- see perf_pending_handle()
3117 smp_rmb();
3118 return event->pending.next == NULL;
3121 static void perf_pending_sync(struct perf_event *event)
3123 wait_event(event->waitq, perf_not_pending(event));
3126 void perf_event_do_pending(void)
3128 __perf_pending_run();
3132 * We assume there is only KVM supporting the callbacks.
3133 * Later on, we might change it to a list if there is
3134 * another virtualization implementation supporting the callbacks.
3136 struct perf_guest_info_callbacks *perf_guest_cbs;
3138 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
3140 perf_guest_cbs = cbs;
3141 return 0;
3143 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
3145 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
3147 perf_guest_cbs = NULL;
3148 return 0;
3150 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
3153 * Output
3155 static bool perf_output_space(struct perf_buffer *buffer, unsigned long tail,
3156 unsigned long offset, unsigned long head)
3158 unsigned long mask;
3160 if (!buffer->writable)
3161 return true;
3163 mask = perf_data_size(buffer) - 1;
3165 offset = (offset - tail) & mask;
3166 head = (head - tail) & mask;
3168 if ((int)(head - offset) < 0)
3169 return false;
3171 return true;
3174 static void perf_output_wakeup(struct perf_output_handle *handle)
3176 atomic_set(&handle->buffer->poll, POLL_IN);
3178 if (handle->nmi) {
3179 handle->event->pending_wakeup = 1;
3180 perf_pending_queue(&handle->event->pending,
3181 perf_pending_event);
3182 } else
3183 perf_event_wakeup(handle->event);
3187 * We need to ensure a later event_id doesn't publish a head when a former
3188 * event isn't done writing. However since we need to deal with NMIs we
3189 * cannot fully serialize things.
3191 * We only publish the head (and generate a wakeup) when the outer-most
3192 * event completes.
3194 static void perf_output_get_handle(struct perf_output_handle *handle)
3196 struct perf_buffer *buffer = handle->buffer;
3198 preempt_disable();
3199 local_inc(&buffer->nest);
3200 handle->wakeup = local_read(&buffer->wakeup);
3203 static void perf_output_put_handle(struct perf_output_handle *handle)
3205 struct perf_buffer *buffer = handle->buffer;
3206 unsigned long head;
3208 again:
3209 head = local_read(&buffer->head);
3212 * IRQ/NMI can happen here, which means we can miss a head update.
3215 if (!local_dec_and_test(&buffer->nest))
3216 goto out;
3219 * Publish the known good head. Rely on the full barrier implied
3220 * by atomic_dec_and_test() order the buffer->head read and this
3221 * write.
3223 buffer->user_page->data_head = head;
3226 * Now check if we missed an update, rely on the (compiler)
3227 * barrier in atomic_dec_and_test() to re-read buffer->head.
3229 if (unlikely(head != local_read(&buffer->head))) {
3230 local_inc(&buffer->nest);
3231 goto again;
3234 if (handle->wakeup != local_read(&buffer->wakeup))
3235 perf_output_wakeup(handle);
3237 out:
3238 preempt_enable();
3241 __always_inline void perf_output_copy(struct perf_output_handle *handle,
3242 const void *buf, unsigned int len)
3244 do {
3245 unsigned long size = min_t(unsigned long, handle->size, len);
3247 memcpy(handle->addr, buf, size);
3249 len -= size;
3250 handle->addr += size;
3251 buf += size;
3252 handle->size -= size;
3253 if (!handle->size) {
3254 struct perf_buffer *buffer = handle->buffer;
3256 handle->page++;
3257 handle->page &= buffer->nr_pages - 1;
3258 handle->addr = buffer->data_pages[handle->page];
3259 handle->size = PAGE_SIZE << page_order(buffer);
3261 } while (len);
3264 int perf_output_begin(struct perf_output_handle *handle,
3265 struct perf_event *event, unsigned int size,
3266 int nmi, int sample)
3268 struct perf_buffer *buffer;
3269 unsigned long tail, offset, head;
3270 int have_lost;
3271 struct {
3272 struct perf_event_header header;
3273 u64 id;
3274 u64 lost;
3275 } lost_event;
3277 rcu_read_lock();
3279 * For inherited events we send all the output towards the parent.
3281 if (event->parent)
3282 event = event->parent;
3284 buffer = rcu_dereference(event->buffer);
3285 if (!buffer)
3286 goto out;
3288 handle->buffer = buffer;
3289 handle->event = event;
3290 handle->nmi = nmi;
3291 handle->sample = sample;
3293 if (!buffer->nr_pages)
3294 goto out;
3296 have_lost = local_read(&buffer->lost);
3297 if (have_lost)
3298 size += sizeof(lost_event);
3300 perf_output_get_handle(handle);
3302 do {
3304 * Userspace could choose to issue a mb() before updating the
3305 * tail pointer. So that all reads will be completed before the
3306 * write is issued.
3308 tail = ACCESS_ONCE(buffer->user_page->data_tail);
3309 smp_rmb();
3310 offset = head = local_read(&buffer->head);
3311 head += size;
3312 if (unlikely(!perf_output_space(buffer, tail, offset, head)))
3313 goto fail;
3314 } while (local_cmpxchg(&buffer->head, offset, head) != offset);
3316 if (head - local_read(&buffer->wakeup) > buffer->watermark)
3317 local_add(buffer->watermark, &buffer->wakeup);
3319 handle->page = offset >> (PAGE_SHIFT + page_order(buffer));
3320 handle->page &= buffer->nr_pages - 1;
3321 handle->size = offset & ((PAGE_SIZE << page_order(buffer)) - 1);
3322 handle->addr = buffer->data_pages[handle->page];
3323 handle->addr += handle->size;
3324 handle->size = (PAGE_SIZE << page_order(buffer)) - handle->size;
3326 if (have_lost) {
3327 lost_event.header.type = PERF_RECORD_LOST;
3328 lost_event.header.misc = 0;
3329 lost_event.header.size = sizeof(lost_event);
3330 lost_event.id = event->id;
3331 lost_event.lost = local_xchg(&buffer->lost, 0);
3333 perf_output_put(handle, lost_event);
3336 return 0;
3338 fail:
3339 local_inc(&buffer->lost);
3340 perf_output_put_handle(handle);
3341 out:
3342 rcu_read_unlock();
3344 return -ENOSPC;
3347 void perf_output_end(struct perf_output_handle *handle)
3349 struct perf_event *event = handle->event;
3350 struct perf_buffer *buffer = handle->buffer;
3352 int wakeup_events = event->attr.wakeup_events;
3354 if (handle->sample && wakeup_events) {
3355 int events = local_inc_return(&buffer->events);
3356 if (events >= wakeup_events) {
3357 local_sub(wakeup_events, &buffer->events);
3358 local_inc(&buffer->wakeup);
3362 perf_output_put_handle(handle);
3363 rcu_read_unlock();
3366 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
3369 * only top level events have the pid namespace they were created in
3371 if (event->parent)
3372 event = event->parent;
3374 return task_tgid_nr_ns(p, event->ns);
3377 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
3380 * only top level events have the pid namespace they were created in
3382 if (event->parent)
3383 event = event->parent;
3385 return task_pid_nr_ns(p, event->ns);
3388 static void perf_output_read_one(struct perf_output_handle *handle,
3389 struct perf_event *event)
3391 u64 read_format = event->attr.read_format;
3392 u64 values[4];
3393 int n = 0;
3395 values[n++] = perf_event_count(event);
3396 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
3397 values[n++] = event->total_time_enabled +
3398 atomic64_read(&event->child_total_time_enabled);
3400 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
3401 values[n++] = event->total_time_running +
3402 atomic64_read(&event->child_total_time_running);
3404 if (read_format & PERF_FORMAT_ID)
3405 values[n++] = primary_event_id(event);
3407 perf_output_copy(handle, values, n * sizeof(u64));
3411 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
3413 static void perf_output_read_group(struct perf_output_handle *handle,
3414 struct perf_event *event)
3416 struct perf_event *leader = event->group_leader, *sub;
3417 u64 read_format = event->attr.read_format;
3418 u64 values[5];
3419 int n = 0;
3421 values[n++] = 1 + leader->nr_siblings;
3423 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3424 values[n++] = leader->total_time_enabled;
3426 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3427 values[n++] = leader->total_time_running;
3429 if (leader != event)
3430 leader->pmu->read(leader);
3432 values[n++] = perf_event_count(leader);
3433 if (read_format & PERF_FORMAT_ID)
3434 values[n++] = primary_event_id(leader);
3436 perf_output_copy(handle, values, n * sizeof(u64));
3438 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3439 n = 0;
3441 if (sub != event)
3442 sub->pmu->read(sub);
3444 values[n++] = perf_event_count(sub);
3445 if (read_format & PERF_FORMAT_ID)
3446 values[n++] = primary_event_id(sub);
3448 perf_output_copy(handle, values, n * sizeof(u64));
3452 static void perf_output_read(struct perf_output_handle *handle,
3453 struct perf_event *event)
3455 if (event->attr.read_format & PERF_FORMAT_GROUP)
3456 perf_output_read_group(handle, event);
3457 else
3458 perf_output_read_one(handle, event);
3461 void perf_output_sample(struct perf_output_handle *handle,
3462 struct perf_event_header *header,
3463 struct perf_sample_data *data,
3464 struct perf_event *event)
3466 u64 sample_type = data->type;
3468 perf_output_put(handle, *header);
3470 if (sample_type & PERF_SAMPLE_IP)
3471 perf_output_put(handle, data->ip);
3473 if (sample_type & PERF_SAMPLE_TID)
3474 perf_output_put(handle, data->tid_entry);
3476 if (sample_type & PERF_SAMPLE_TIME)
3477 perf_output_put(handle, data->time);
3479 if (sample_type & PERF_SAMPLE_ADDR)
3480 perf_output_put(handle, data->addr);
3482 if (sample_type & PERF_SAMPLE_ID)
3483 perf_output_put(handle, data->id);
3485 if (sample_type & PERF_SAMPLE_STREAM_ID)
3486 perf_output_put(handle, data->stream_id);
3488 if (sample_type & PERF_SAMPLE_CPU)
3489 perf_output_put(handle, data->cpu_entry);
3491 if (sample_type & PERF_SAMPLE_PERIOD)
3492 perf_output_put(handle, data->period);
3494 if (sample_type & PERF_SAMPLE_READ)
3495 perf_output_read(handle, event);
3497 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
3498 if (data->callchain) {
3499 int size = 1;
3501 if (data->callchain)
3502 size += data->callchain->nr;
3504 size *= sizeof(u64);
3506 perf_output_copy(handle, data->callchain, size);
3507 } else {
3508 u64 nr = 0;
3509 perf_output_put(handle, nr);
3513 if (sample_type & PERF_SAMPLE_RAW) {
3514 if (data->raw) {
3515 perf_output_put(handle, data->raw->size);
3516 perf_output_copy(handle, data->raw->data,
3517 data->raw->size);
3518 } else {
3519 struct {
3520 u32 size;
3521 u32 data;
3522 } raw = {
3523 .size = sizeof(u32),
3524 .data = 0,
3526 perf_output_put(handle, raw);
3531 void perf_prepare_sample(struct perf_event_header *header,
3532 struct perf_sample_data *data,
3533 struct perf_event *event,
3534 struct pt_regs *regs)
3536 u64 sample_type = event->attr.sample_type;
3538 data->type = sample_type;
3540 header->type = PERF_RECORD_SAMPLE;
3541 header->size = sizeof(*header);
3543 header->misc = 0;
3544 header->misc |= perf_misc_flags(regs);
3546 if (sample_type & PERF_SAMPLE_IP) {
3547 data->ip = perf_instruction_pointer(regs);
3549 header->size += sizeof(data->ip);
3552 if (sample_type & PERF_SAMPLE_TID) {
3553 /* namespace issues */
3554 data->tid_entry.pid = perf_event_pid(event, current);
3555 data->tid_entry.tid = perf_event_tid(event, current);
3557 header->size += sizeof(data->tid_entry);
3560 if (sample_type & PERF_SAMPLE_TIME) {
3561 data->time = perf_clock();
3563 header->size += sizeof(data->time);
3566 if (sample_type & PERF_SAMPLE_ADDR)
3567 header->size += sizeof(data->addr);
3569 if (sample_type & PERF_SAMPLE_ID) {
3570 data->id = primary_event_id(event);
3572 header->size += sizeof(data->id);
3575 if (sample_type & PERF_SAMPLE_STREAM_ID) {
3576 data->stream_id = event->id;
3578 header->size += sizeof(data->stream_id);
3581 if (sample_type & PERF_SAMPLE_CPU) {
3582 data->cpu_entry.cpu = raw_smp_processor_id();
3583 data->cpu_entry.reserved = 0;
3585 header->size += sizeof(data->cpu_entry);
3588 if (sample_type & PERF_SAMPLE_PERIOD)
3589 header->size += sizeof(data->period);
3591 if (sample_type & PERF_SAMPLE_READ)
3592 header->size += perf_event_read_size(event);
3594 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
3595 int size = 1;
3597 data->callchain = perf_callchain(regs);
3599 if (data->callchain)
3600 size += data->callchain->nr;
3602 header->size += size * sizeof(u64);
3605 if (sample_type & PERF_SAMPLE_RAW) {
3606 int size = sizeof(u32);
3608 if (data->raw)
3609 size += data->raw->size;
3610 else
3611 size += sizeof(u32);
3613 WARN_ON_ONCE(size & (sizeof(u64)-1));
3614 header->size += size;
3618 static void perf_event_output(struct perf_event *event, int nmi,
3619 struct perf_sample_data *data,
3620 struct pt_regs *regs)
3622 struct perf_output_handle handle;
3623 struct perf_event_header header;
3625 /* protect the callchain buffers */
3626 rcu_read_lock();
3628 perf_prepare_sample(&header, data, event, regs);
3630 if (perf_output_begin(&handle, event, header.size, nmi, 1))
3631 goto exit;
3633 perf_output_sample(&handle, &header, data, event);
3635 perf_output_end(&handle);
3637 exit:
3638 rcu_read_unlock();
3642 * read event_id
3645 struct perf_read_event {
3646 struct perf_event_header header;
3648 u32 pid;
3649 u32 tid;
3652 static void
3653 perf_event_read_event(struct perf_event *event,
3654 struct task_struct *task)
3656 struct perf_output_handle handle;
3657 struct perf_read_event read_event = {
3658 .header = {
3659 .type = PERF_RECORD_READ,
3660 .misc = 0,
3661 .size = sizeof(read_event) + perf_event_read_size(event),
3663 .pid = perf_event_pid(event, task),
3664 .tid = perf_event_tid(event, task),
3666 int ret;
3668 ret = perf_output_begin(&handle, event, read_event.header.size, 0, 0);
3669 if (ret)
3670 return;
3672 perf_output_put(&handle, read_event);
3673 perf_output_read(&handle, event);
3675 perf_output_end(&handle);
3679 * task tracking -- fork/exit
3681 * enabled by: attr.comm | attr.mmap | attr.mmap_data | attr.task
3684 struct perf_task_event {
3685 struct task_struct *task;
3686 struct perf_event_context *task_ctx;
3688 struct {
3689 struct perf_event_header header;
3691 u32 pid;
3692 u32 ppid;
3693 u32 tid;
3694 u32 ptid;
3695 u64 time;
3696 } event_id;
3699 static void perf_event_task_output(struct perf_event *event,
3700 struct perf_task_event *task_event)
3702 struct perf_output_handle handle;
3703 struct task_struct *task = task_event->task;
3704 int size, ret;
3706 size = task_event->event_id.header.size;
3707 ret = perf_output_begin(&handle, event, size, 0, 0);
3709 if (ret)
3710 return;
3712 task_event->event_id.pid = perf_event_pid(event, task);
3713 task_event->event_id.ppid = perf_event_pid(event, current);
3715 task_event->event_id.tid = perf_event_tid(event, task);
3716 task_event->event_id.ptid = perf_event_tid(event, current);
3718 perf_output_put(&handle, task_event->event_id);
3720 perf_output_end(&handle);
3723 static int perf_event_task_match(struct perf_event *event)
3725 if (event->state < PERF_EVENT_STATE_INACTIVE)
3726 return 0;
3728 if (event->cpu != -1 && event->cpu != smp_processor_id())
3729 return 0;
3731 if (event->attr.comm || event->attr.mmap ||
3732 event->attr.mmap_data || event->attr.task)
3733 return 1;
3735 return 0;
3738 static void perf_event_task_ctx(struct perf_event_context *ctx,
3739 struct perf_task_event *task_event)
3741 struct perf_event *event;
3743 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3744 if (perf_event_task_match(event))
3745 perf_event_task_output(event, task_event);
3749 static void perf_event_task_event(struct perf_task_event *task_event)
3751 struct perf_cpu_context *cpuctx;
3752 struct perf_event_context *ctx = task_event->task_ctx;
3754 rcu_read_lock();
3755 cpuctx = &get_cpu_var(perf_cpu_context);
3756 perf_event_task_ctx(&cpuctx->ctx, task_event);
3757 if (!ctx)
3758 ctx = rcu_dereference(current->perf_event_ctxp);
3759 if (ctx)
3760 perf_event_task_ctx(ctx, task_event);
3761 put_cpu_var(perf_cpu_context);
3762 rcu_read_unlock();
3765 static void perf_event_task(struct task_struct *task,
3766 struct perf_event_context *task_ctx,
3767 int new)
3769 struct perf_task_event task_event;
3771 if (!atomic_read(&nr_comm_events) &&
3772 !atomic_read(&nr_mmap_events) &&
3773 !atomic_read(&nr_task_events))
3774 return;
3776 task_event = (struct perf_task_event){
3777 .task = task,
3778 .task_ctx = task_ctx,
3779 .event_id = {
3780 .header = {
3781 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
3782 .misc = 0,
3783 .size = sizeof(task_event.event_id),
3785 /* .pid */
3786 /* .ppid */
3787 /* .tid */
3788 /* .ptid */
3789 .time = perf_clock(),
3793 perf_event_task_event(&task_event);
3796 void perf_event_fork(struct task_struct *task)
3798 perf_event_task(task, NULL, 1);
3802 * comm tracking
3805 struct perf_comm_event {
3806 struct task_struct *task;
3807 char *comm;
3808 int comm_size;
3810 struct {
3811 struct perf_event_header header;
3813 u32 pid;
3814 u32 tid;
3815 } event_id;
3818 static void perf_event_comm_output(struct perf_event *event,
3819 struct perf_comm_event *comm_event)
3821 struct perf_output_handle handle;
3822 int size = comm_event->event_id.header.size;
3823 int ret = perf_output_begin(&handle, event, size, 0, 0);
3825 if (ret)
3826 return;
3828 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
3829 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
3831 perf_output_put(&handle, comm_event->event_id);
3832 perf_output_copy(&handle, comm_event->comm,
3833 comm_event->comm_size);
3834 perf_output_end(&handle);
3837 static int perf_event_comm_match(struct perf_event *event)
3839 if (event->state < PERF_EVENT_STATE_INACTIVE)
3840 return 0;
3842 if (event->cpu != -1 && event->cpu != smp_processor_id())
3843 return 0;
3845 if (event->attr.comm)
3846 return 1;
3848 return 0;
3851 static void perf_event_comm_ctx(struct perf_event_context *ctx,
3852 struct perf_comm_event *comm_event)
3854 struct perf_event *event;
3856 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3857 if (perf_event_comm_match(event))
3858 perf_event_comm_output(event, comm_event);
3862 static void perf_event_comm_event(struct perf_comm_event *comm_event)
3864 struct perf_cpu_context *cpuctx;
3865 struct perf_event_context *ctx;
3866 unsigned int size;
3867 char comm[TASK_COMM_LEN];
3869 memset(comm, 0, sizeof(comm));
3870 strlcpy(comm, comm_event->task->comm, sizeof(comm));
3871 size = ALIGN(strlen(comm)+1, sizeof(u64));
3873 comm_event->comm = comm;
3874 comm_event->comm_size = size;
3876 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
3878 rcu_read_lock();
3879 cpuctx = &get_cpu_var(perf_cpu_context);
3880 perf_event_comm_ctx(&cpuctx->ctx, comm_event);
3881 ctx = rcu_dereference(current->perf_event_ctxp);
3882 if (ctx)
3883 perf_event_comm_ctx(ctx, comm_event);
3884 put_cpu_var(perf_cpu_context);
3885 rcu_read_unlock();
3888 void perf_event_comm(struct task_struct *task)
3890 struct perf_comm_event comm_event;
3892 if (task->perf_event_ctxp)
3893 perf_event_enable_on_exec(task);
3895 if (!atomic_read(&nr_comm_events))
3896 return;
3898 comm_event = (struct perf_comm_event){
3899 .task = task,
3900 /* .comm */
3901 /* .comm_size */
3902 .event_id = {
3903 .header = {
3904 .type = PERF_RECORD_COMM,
3905 .misc = 0,
3906 /* .size */
3908 /* .pid */
3909 /* .tid */
3913 perf_event_comm_event(&comm_event);
3917 * mmap tracking
3920 struct perf_mmap_event {
3921 struct vm_area_struct *vma;
3923 const char *file_name;
3924 int file_size;
3926 struct {
3927 struct perf_event_header header;
3929 u32 pid;
3930 u32 tid;
3931 u64 start;
3932 u64 len;
3933 u64 pgoff;
3934 } event_id;
3937 static void perf_event_mmap_output(struct perf_event *event,
3938 struct perf_mmap_event *mmap_event)
3940 struct perf_output_handle handle;
3941 int size = mmap_event->event_id.header.size;
3942 int ret = perf_output_begin(&handle, event, size, 0, 0);
3944 if (ret)
3945 return;
3947 mmap_event->event_id.pid = perf_event_pid(event, current);
3948 mmap_event->event_id.tid = perf_event_tid(event, current);
3950 perf_output_put(&handle, mmap_event->event_id);
3951 perf_output_copy(&handle, mmap_event->file_name,
3952 mmap_event->file_size);
3953 perf_output_end(&handle);
3956 static int perf_event_mmap_match(struct perf_event *event,
3957 struct perf_mmap_event *mmap_event,
3958 int executable)
3960 if (event->state < PERF_EVENT_STATE_INACTIVE)
3961 return 0;
3963 if (event->cpu != -1 && event->cpu != smp_processor_id())
3964 return 0;
3966 if ((!executable && event->attr.mmap_data) ||
3967 (executable && event->attr.mmap))
3968 return 1;
3970 return 0;
3973 static void perf_event_mmap_ctx(struct perf_event_context *ctx,
3974 struct perf_mmap_event *mmap_event,
3975 int executable)
3977 struct perf_event *event;
3979 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3980 if (perf_event_mmap_match(event, mmap_event, executable))
3981 perf_event_mmap_output(event, mmap_event);
3985 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
3987 struct perf_cpu_context *cpuctx;
3988 struct perf_event_context *ctx;
3989 struct vm_area_struct *vma = mmap_event->vma;
3990 struct file *file = vma->vm_file;
3991 unsigned int size;
3992 char tmp[16];
3993 char *buf = NULL;
3994 const char *name;
3996 memset(tmp, 0, sizeof(tmp));
3998 if (file) {
4000 * d_path works from the end of the buffer backwards, so we
4001 * need to add enough zero bytes after the string to handle
4002 * the 64bit alignment we do later.
4004 buf = kzalloc(PATH_MAX + sizeof(u64), GFP_KERNEL);
4005 if (!buf) {
4006 name = strncpy(tmp, "//enomem", sizeof(tmp));
4007 goto got_name;
4009 name = d_path(&file->f_path, buf, PATH_MAX);
4010 if (IS_ERR(name)) {
4011 name = strncpy(tmp, "//toolong", sizeof(tmp));
4012 goto got_name;
4014 } else {
4015 if (arch_vma_name(mmap_event->vma)) {
4016 name = strncpy(tmp, arch_vma_name(mmap_event->vma),
4017 sizeof(tmp));
4018 goto got_name;
4021 if (!vma->vm_mm) {
4022 name = strncpy(tmp, "[vdso]", sizeof(tmp));
4023 goto got_name;
4024 } else if (vma->vm_start <= vma->vm_mm->start_brk &&
4025 vma->vm_end >= vma->vm_mm->brk) {
4026 name = strncpy(tmp, "[heap]", sizeof(tmp));
4027 goto got_name;
4028 } else if (vma->vm_start <= vma->vm_mm->start_stack &&
4029 vma->vm_end >= vma->vm_mm->start_stack) {
4030 name = strncpy(tmp, "[stack]", sizeof(tmp));
4031 goto got_name;
4034 name = strncpy(tmp, "//anon", sizeof(tmp));
4035 goto got_name;
4038 got_name:
4039 size = ALIGN(strlen(name)+1, sizeof(u64));
4041 mmap_event->file_name = name;
4042 mmap_event->file_size = size;
4044 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
4046 rcu_read_lock();
4047 cpuctx = &get_cpu_var(perf_cpu_context);
4048 perf_event_mmap_ctx(&cpuctx->ctx, mmap_event, vma->vm_flags & VM_EXEC);
4049 ctx = rcu_dereference(current->perf_event_ctxp);
4050 if (ctx)
4051 perf_event_mmap_ctx(ctx, mmap_event, vma->vm_flags & VM_EXEC);
4052 put_cpu_var(perf_cpu_context);
4053 rcu_read_unlock();
4055 kfree(buf);
4058 void perf_event_mmap(struct vm_area_struct *vma)
4060 struct perf_mmap_event mmap_event;
4062 if (!atomic_read(&nr_mmap_events))
4063 return;
4065 mmap_event = (struct perf_mmap_event){
4066 .vma = vma,
4067 /* .file_name */
4068 /* .file_size */
4069 .event_id = {
4070 .header = {
4071 .type = PERF_RECORD_MMAP,
4072 .misc = PERF_RECORD_MISC_USER,
4073 /* .size */
4075 /* .pid */
4076 /* .tid */
4077 .start = vma->vm_start,
4078 .len = vma->vm_end - vma->vm_start,
4079 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
4083 perf_event_mmap_event(&mmap_event);
4087 * IRQ throttle logging
4090 static void perf_log_throttle(struct perf_event *event, int enable)
4092 struct perf_output_handle handle;
4093 int ret;
4095 struct {
4096 struct perf_event_header header;
4097 u64 time;
4098 u64 id;
4099 u64 stream_id;
4100 } throttle_event = {
4101 .header = {
4102 .type = PERF_RECORD_THROTTLE,
4103 .misc = 0,
4104 .size = sizeof(throttle_event),
4106 .time = perf_clock(),
4107 .id = primary_event_id(event),
4108 .stream_id = event->id,
4111 if (enable)
4112 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
4114 ret = perf_output_begin(&handle, event, sizeof(throttle_event), 1, 0);
4115 if (ret)
4116 return;
4118 perf_output_put(&handle, throttle_event);
4119 perf_output_end(&handle);
4123 * Generic event overflow handling, sampling.
4126 static int __perf_event_overflow(struct perf_event *event, int nmi,
4127 int throttle, struct perf_sample_data *data,
4128 struct pt_regs *regs)
4130 int events = atomic_read(&event->event_limit);
4131 struct hw_perf_event *hwc = &event->hw;
4132 int ret = 0;
4134 throttle = (throttle && event->pmu->unthrottle != NULL);
4136 if (!throttle) {
4137 hwc->interrupts++;
4138 } else {
4139 if (hwc->interrupts != MAX_INTERRUPTS) {
4140 hwc->interrupts++;
4141 if (HZ * hwc->interrupts >
4142 (u64)sysctl_perf_event_sample_rate) {
4143 hwc->interrupts = MAX_INTERRUPTS;
4144 perf_log_throttle(event, 0);
4145 ret = 1;
4147 } else {
4149 * Keep re-disabling events even though on the previous
4150 * pass we disabled it - just in case we raced with a
4151 * sched-in and the event got enabled again:
4153 ret = 1;
4157 if (event->attr.freq) {
4158 u64 now = perf_clock();
4159 s64 delta = now - hwc->freq_time_stamp;
4161 hwc->freq_time_stamp = now;
4163 if (delta > 0 && delta < 2*TICK_NSEC)
4164 perf_adjust_period(event, delta, hwc->last_period);
4168 * XXX event_limit might not quite work as expected on inherited
4169 * events
4172 event->pending_kill = POLL_IN;
4173 if (events && atomic_dec_and_test(&event->event_limit)) {
4174 ret = 1;
4175 event->pending_kill = POLL_HUP;
4176 if (nmi) {
4177 event->pending_disable = 1;
4178 perf_pending_queue(&event->pending,
4179 perf_pending_event);
4180 } else
4181 perf_event_disable(event);
4184 if (event->overflow_handler)
4185 event->overflow_handler(event, nmi, data, regs);
4186 else
4187 perf_event_output(event, nmi, data, regs);
4189 return ret;
4192 int perf_event_overflow(struct perf_event *event, int nmi,
4193 struct perf_sample_data *data,
4194 struct pt_regs *regs)
4196 return __perf_event_overflow(event, nmi, 1, data, regs);
4200 * Generic software event infrastructure
4204 * We directly increment event->count and keep a second value in
4205 * event->hw.period_left to count intervals. This period event
4206 * is kept in the range [-sample_period, 0] so that we can use the
4207 * sign as trigger.
4210 static u64 perf_swevent_set_period(struct perf_event *event)
4212 struct hw_perf_event *hwc = &event->hw;
4213 u64 period = hwc->last_period;
4214 u64 nr, offset;
4215 s64 old, val;
4217 hwc->last_period = hwc->sample_period;
4219 again:
4220 old = val = local64_read(&hwc->period_left);
4221 if (val < 0)
4222 return 0;
4224 nr = div64_u64(period + val, period);
4225 offset = nr * period;
4226 val -= offset;
4227 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
4228 goto again;
4230 return nr;
4233 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
4234 int nmi, struct perf_sample_data *data,
4235 struct pt_regs *regs)
4237 struct hw_perf_event *hwc = &event->hw;
4238 int throttle = 0;
4240 data->period = event->hw.last_period;
4241 if (!overflow)
4242 overflow = perf_swevent_set_period(event);
4244 if (hwc->interrupts == MAX_INTERRUPTS)
4245 return;
4247 for (; overflow; overflow--) {
4248 if (__perf_event_overflow(event, nmi, throttle,
4249 data, regs)) {
4251 * We inhibit the overflow from happening when
4252 * hwc->interrupts == MAX_INTERRUPTS.
4254 break;
4256 throttle = 1;
4260 static void perf_swevent_add(struct perf_event *event, u64 nr,
4261 int nmi, struct perf_sample_data *data,
4262 struct pt_regs *regs)
4264 struct hw_perf_event *hwc = &event->hw;
4266 local64_add(nr, &event->count);
4268 if (!regs)
4269 return;
4271 if (!hwc->sample_period)
4272 return;
4274 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
4275 return perf_swevent_overflow(event, 1, nmi, data, regs);
4277 if (local64_add_negative(nr, &hwc->period_left))
4278 return;
4280 perf_swevent_overflow(event, 0, nmi, data, regs);
4283 static int perf_exclude_event(struct perf_event *event,
4284 struct pt_regs *regs)
4286 if (regs) {
4287 if (event->attr.exclude_user && user_mode(regs))
4288 return 1;
4290 if (event->attr.exclude_kernel && !user_mode(regs))
4291 return 1;
4294 return 0;
4297 static int perf_swevent_match(struct perf_event *event,
4298 enum perf_type_id type,
4299 u32 event_id,
4300 struct perf_sample_data *data,
4301 struct pt_regs *regs)
4303 if (event->attr.type != type)
4304 return 0;
4306 if (event->attr.config != event_id)
4307 return 0;
4309 if (perf_exclude_event(event, regs))
4310 return 0;
4312 return 1;
4315 static inline u64 swevent_hash(u64 type, u32 event_id)
4317 u64 val = event_id | (type << 32);
4319 return hash_64(val, SWEVENT_HLIST_BITS);
4322 static inline struct hlist_head *
4323 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
4325 u64 hash = swevent_hash(type, event_id);
4327 return &hlist->heads[hash];
4330 /* For the read side: events when they trigger */
4331 static inline struct hlist_head *
4332 find_swevent_head_rcu(struct perf_cpu_context *ctx, u64 type, u32 event_id)
4334 struct swevent_hlist *hlist;
4336 hlist = rcu_dereference(ctx->swevent_hlist);
4337 if (!hlist)
4338 return NULL;
4340 return __find_swevent_head(hlist, type, event_id);
4343 /* For the event head insertion and removal in the hlist */
4344 static inline struct hlist_head *
4345 find_swevent_head(struct perf_cpu_context *ctx, struct perf_event *event)
4347 struct swevent_hlist *hlist;
4348 u32 event_id = event->attr.config;
4349 u64 type = event->attr.type;
4352 * Event scheduling is always serialized against hlist allocation
4353 * and release. Which makes the protected version suitable here.
4354 * The context lock guarantees that.
4356 hlist = rcu_dereference_protected(ctx->swevent_hlist,
4357 lockdep_is_held(&event->ctx->lock));
4358 if (!hlist)
4359 return NULL;
4361 return __find_swevent_head(hlist, type, event_id);
4364 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
4365 u64 nr, int nmi,
4366 struct perf_sample_data *data,
4367 struct pt_regs *regs)
4369 struct perf_cpu_context *cpuctx;
4370 struct perf_event *event;
4371 struct hlist_node *node;
4372 struct hlist_head *head;
4374 cpuctx = &__get_cpu_var(perf_cpu_context);
4376 rcu_read_lock();
4378 head = find_swevent_head_rcu(cpuctx, type, event_id);
4380 if (!head)
4381 goto end;
4383 hlist_for_each_entry_rcu(event, node, head, hlist_entry) {
4384 if (perf_swevent_match(event, type, event_id, data, regs))
4385 perf_swevent_add(event, nr, nmi, data, regs);
4387 end:
4388 rcu_read_unlock();
4391 int perf_swevent_get_recursion_context(void)
4393 struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
4395 return get_recursion_context(cpuctx->recursion);
4397 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
4399 void inline perf_swevent_put_recursion_context(int rctx)
4401 struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
4403 put_recursion_context(cpuctx->recursion, rctx);
4406 void __perf_sw_event(u32 event_id, u64 nr, int nmi,
4407 struct pt_regs *regs, u64 addr)
4409 struct perf_sample_data data;
4410 int rctx;
4412 preempt_disable_notrace();
4413 rctx = perf_swevent_get_recursion_context();
4414 if (rctx < 0)
4415 return;
4417 perf_sample_data_init(&data, addr);
4419 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, nmi, &data, regs);
4421 perf_swevent_put_recursion_context(rctx);
4422 preempt_enable_notrace();
4425 static void perf_swevent_read(struct perf_event *event)
4429 static int perf_swevent_enable(struct perf_event *event)
4431 struct hw_perf_event *hwc = &event->hw;
4432 struct perf_cpu_context *cpuctx;
4433 struct hlist_head *head;
4435 cpuctx = &__get_cpu_var(perf_cpu_context);
4437 if (hwc->sample_period) {
4438 hwc->last_period = hwc->sample_period;
4439 perf_swevent_set_period(event);
4442 head = find_swevent_head(cpuctx, event);
4443 if (WARN_ON_ONCE(!head))
4444 return -EINVAL;
4446 hlist_add_head_rcu(&event->hlist_entry, head);
4448 return 0;
4451 static void perf_swevent_disable(struct perf_event *event)
4453 hlist_del_rcu(&event->hlist_entry);
4456 static void perf_swevent_void(struct perf_event *event)
4460 static int perf_swevent_int(struct perf_event *event)
4462 return 0;
4465 /* Deref the hlist from the update side */
4466 static inline struct swevent_hlist *
4467 swevent_hlist_deref(struct perf_cpu_context *cpuctx)
4469 return rcu_dereference_protected(cpuctx->swevent_hlist,
4470 lockdep_is_held(&cpuctx->hlist_mutex));
4473 static void swevent_hlist_release_rcu(struct rcu_head *rcu_head)
4475 struct swevent_hlist *hlist;
4477 hlist = container_of(rcu_head, struct swevent_hlist, rcu_head);
4478 kfree(hlist);
4481 static void swevent_hlist_release(struct perf_cpu_context *cpuctx)
4483 struct swevent_hlist *hlist = swevent_hlist_deref(cpuctx);
4485 if (!hlist)
4486 return;
4488 rcu_assign_pointer(cpuctx->swevent_hlist, NULL);
4489 call_rcu(&hlist->rcu_head, swevent_hlist_release_rcu);
4492 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
4494 struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
4496 mutex_lock(&cpuctx->hlist_mutex);
4498 if (!--cpuctx->hlist_refcount)
4499 swevent_hlist_release(cpuctx);
4501 mutex_unlock(&cpuctx->hlist_mutex);
4504 static void swevent_hlist_put(struct perf_event *event)
4506 int cpu;
4508 if (event->cpu != -1) {
4509 swevent_hlist_put_cpu(event, event->cpu);
4510 return;
4513 for_each_possible_cpu(cpu)
4514 swevent_hlist_put_cpu(event, cpu);
4517 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
4519 struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
4520 int err = 0;
4522 mutex_lock(&cpuctx->hlist_mutex);
4524 if (!swevent_hlist_deref(cpuctx) && cpu_online(cpu)) {
4525 struct swevent_hlist *hlist;
4527 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
4528 if (!hlist) {
4529 err = -ENOMEM;
4530 goto exit;
4532 rcu_assign_pointer(cpuctx->swevent_hlist, hlist);
4534 cpuctx->hlist_refcount++;
4535 exit:
4536 mutex_unlock(&cpuctx->hlist_mutex);
4538 return err;
4541 static int swevent_hlist_get(struct perf_event *event)
4543 int err;
4544 int cpu, failed_cpu;
4546 if (event->cpu != -1)
4547 return swevent_hlist_get_cpu(event, event->cpu);
4549 get_online_cpus();
4550 for_each_possible_cpu(cpu) {
4551 err = swevent_hlist_get_cpu(event, cpu);
4552 if (err) {
4553 failed_cpu = cpu;
4554 goto fail;
4557 put_online_cpus();
4559 return 0;
4560 fail:
4561 for_each_possible_cpu(cpu) {
4562 if (cpu == failed_cpu)
4563 break;
4564 swevent_hlist_put_cpu(event, cpu);
4567 put_online_cpus();
4568 return err;
4571 atomic_t perf_swevent_enabled[PERF_COUNT_SW_MAX];
4573 static void sw_perf_event_destroy(struct perf_event *event)
4575 u64 event_id = event->attr.config;
4577 WARN_ON(event->parent);
4579 atomic_dec(&perf_swevent_enabled[event_id]);
4580 swevent_hlist_put(event);
4583 static int perf_swevent_init(struct perf_event *event)
4585 int event_id = event->attr.config;
4587 if (event->attr.type != PERF_TYPE_SOFTWARE)
4588 return -ENOENT;
4590 switch (event_id) {
4591 case PERF_COUNT_SW_CPU_CLOCK:
4592 case PERF_COUNT_SW_TASK_CLOCK:
4593 return -ENOENT;
4595 default:
4596 break;
4599 if (event_id > PERF_COUNT_SW_MAX)
4600 return -ENOENT;
4602 if (!event->parent) {
4603 int err;
4605 err = swevent_hlist_get(event);
4606 if (err)
4607 return err;
4609 atomic_inc(&perf_swevent_enabled[event_id]);
4610 event->destroy = sw_perf_event_destroy;
4613 return 0;
4616 static struct pmu perf_swevent = {
4617 .event_init = perf_swevent_init,
4618 .enable = perf_swevent_enable,
4619 .disable = perf_swevent_disable,
4620 .start = perf_swevent_int,
4621 .stop = perf_swevent_void,
4622 .read = perf_swevent_read,
4623 .unthrottle = perf_swevent_void, /* hwc->interrupts already reset */
4626 #ifdef CONFIG_EVENT_TRACING
4628 static int perf_tp_filter_match(struct perf_event *event,
4629 struct perf_sample_data *data)
4631 void *record = data->raw->data;
4633 if (likely(!event->filter) || filter_match_preds(event->filter, record))
4634 return 1;
4635 return 0;
4638 static int perf_tp_event_match(struct perf_event *event,
4639 struct perf_sample_data *data,
4640 struct pt_regs *regs)
4643 * All tracepoints are from kernel-space.
4645 if (event->attr.exclude_kernel)
4646 return 0;
4648 if (!perf_tp_filter_match(event, data))
4649 return 0;
4651 return 1;
4654 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
4655 struct pt_regs *regs, struct hlist_head *head, int rctx)
4657 struct perf_sample_data data;
4658 struct perf_event *event;
4659 struct hlist_node *node;
4661 struct perf_raw_record raw = {
4662 .size = entry_size,
4663 .data = record,
4666 perf_sample_data_init(&data, addr);
4667 data.raw = &raw;
4669 hlist_for_each_entry_rcu(event, node, head, hlist_entry) {
4670 if (perf_tp_event_match(event, &data, regs))
4671 perf_swevent_add(event, count, 1, &data, regs);
4674 perf_swevent_put_recursion_context(rctx);
4676 EXPORT_SYMBOL_GPL(perf_tp_event);
4678 static void tp_perf_event_destroy(struct perf_event *event)
4680 perf_trace_destroy(event);
4683 static int perf_tp_event_init(struct perf_event *event)
4685 int err;
4687 if (event->attr.type != PERF_TYPE_TRACEPOINT)
4688 return -ENOENT;
4691 * Raw tracepoint data is a severe data leak, only allow root to
4692 * have these.
4694 if ((event->attr.sample_type & PERF_SAMPLE_RAW) &&
4695 perf_paranoid_tracepoint_raw() &&
4696 !capable(CAP_SYS_ADMIN))
4697 return -EPERM;
4699 err = perf_trace_init(event);
4700 if (err)
4701 return err;
4703 event->destroy = tp_perf_event_destroy;
4705 return 0;
4708 static struct pmu perf_tracepoint = {
4709 .event_init = perf_tp_event_init,
4710 .enable = perf_trace_enable,
4711 .disable = perf_trace_disable,
4712 .start = perf_swevent_int,
4713 .stop = perf_swevent_void,
4714 .read = perf_swevent_read,
4715 .unthrottle = perf_swevent_void,
4718 static inline void perf_tp_register(void)
4720 perf_pmu_register(&perf_tracepoint);
4723 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
4725 char *filter_str;
4726 int ret;
4728 if (event->attr.type != PERF_TYPE_TRACEPOINT)
4729 return -EINVAL;
4731 filter_str = strndup_user(arg, PAGE_SIZE);
4732 if (IS_ERR(filter_str))
4733 return PTR_ERR(filter_str);
4735 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
4737 kfree(filter_str);
4738 return ret;
4741 static void perf_event_free_filter(struct perf_event *event)
4743 ftrace_profile_free_filter(event);
4746 #else
4748 static inline void perf_tp_register(void)
4752 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
4754 return -ENOENT;
4757 static void perf_event_free_filter(struct perf_event *event)
4761 #endif /* CONFIG_EVENT_TRACING */
4763 #ifdef CONFIG_HAVE_HW_BREAKPOINT
4764 void perf_bp_event(struct perf_event *bp, void *data)
4766 struct perf_sample_data sample;
4767 struct pt_regs *regs = data;
4769 perf_sample_data_init(&sample, bp->attr.bp_addr);
4771 if (!perf_exclude_event(bp, regs))
4772 perf_swevent_add(bp, 1, 1, &sample, regs);
4774 #endif
4777 * hrtimer based swevent callback
4780 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
4782 enum hrtimer_restart ret = HRTIMER_RESTART;
4783 struct perf_sample_data data;
4784 struct pt_regs *regs;
4785 struct perf_event *event;
4786 u64 period;
4788 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
4789 event->pmu->read(event);
4791 perf_sample_data_init(&data, 0);
4792 data.period = event->hw.last_period;
4793 regs = get_irq_regs();
4795 if (regs && !perf_exclude_event(event, regs)) {
4796 if (!(event->attr.exclude_idle && current->pid == 0))
4797 if (perf_event_overflow(event, 0, &data, regs))
4798 ret = HRTIMER_NORESTART;
4801 period = max_t(u64, 10000, event->hw.sample_period);
4802 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
4804 return ret;
4807 static void perf_swevent_start_hrtimer(struct perf_event *event)
4809 struct hw_perf_event *hwc = &event->hw;
4811 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
4812 hwc->hrtimer.function = perf_swevent_hrtimer;
4813 if (hwc->sample_period) {
4814 u64 period;
4816 if (hwc->remaining) {
4817 if (hwc->remaining < 0)
4818 period = 10000;
4819 else
4820 period = hwc->remaining;
4821 hwc->remaining = 0;
4822 } else {
4823 period = max_t(u64, 10000, hwc->sample_period);
4825 __hrtimer_start_range_ns(&hwc->hrtimer,
4826 ns_to_ktime(period), 0,
4827 HRTIMER_MODE_REL, 0);
4831 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
4833 struct hw_perf_event *hwc = &event->hw;
4835 if (hwc->sample_period) {
4836 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
4837 hwc->remaining = ktime_to_ns(remaining);
4839 hrtimer_cancel(&hwc->hrtimer);
4844 * Software event: cpu wall time clock
4847 static void cpu_clock_event_update(struct perf_event *event)
4849 int cpu = raw_smp_processor_id();
4850 s64 prev;
4851 u64 now;
4853 now = cpu_clock(cpu);
4854 prev = local64_xchg(&event->hw.prev_count, now);
4855 local64_add(now - prev, &event->count);
4858 static int cpu_clock_event_enable(struct perf_event *event)
4860 struct hw_perf_event *hwc = &event->hw;
4861 int cpu = raw_smp_processor_id();
4863 local64_set(&hwc->prev_count, cpu_clock(cpu));
4864 perf_swevent_start_hrtimer(event);
4866 return 0;
4869 static void cpu_clock_event_disable(struct perf_event *event)
4871 perf_swevent_cancel_hrtimer(event);
4872 cpu_clock_event_update(event);
4875 static void cpu_clock_event_read(struct perf_event *event)
4877 cpu_clock_event_update(event);
4880 static int cpu_clock_event_init(struct perf_event *event)
4882 if (event->attr.type != PERF_TYPE_SOFTWARE)
4883 return -ENOENT;
4885 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
4886 return -ENOENT;
4888 return 0;
4891 static struct pmu perf_cpu_clock = {
4892 .event_init = cpu_clock_event_init,
4893 .enable = cpu_clock_event_enable,
4894 .disable = cpu_clock_event_disable,
4895 .read = cpu_clock_event_read,
4899 * Software event: task time clock
4902 static void task_clock_event_update(struct perf_event *event, u64 now)
4904 u64 prev;
4905 s64 delta;
4907 prev = local64_xchg(&event->hw.prev_count, now);
4908 delta = now - prev;
4909 local64_add(delta, &event->count);
4912 static int task_clock_event_enable(struct perf_event *event)
4914 struct hw_perf_event *hwc = &event->hw;
4915 u64 now;
4917 now = event->ctx->time;
4919 local64_set(&hwc->prev_count, now);
4921 perf_swevent_start_hrtimer(event);
4923 return 0;
4926 static void task_clock_event_disable(struct perf_event *event)
4928 perf_swevent_cancel_hrtimer(event);
4929 task_clock_event_update(event, event->ctx->time);
4933 static void task_clock_event_read(struct perf_event *event)
4935 u64 time;
4937 if (!in_nmi()) {
4938 update_context_time(event->ctx);
4939 time = event->ctx->time;
4940 } else {
4941 u64 now = perf_clock();
4942 u64 delta = now - event->ctx->timestamp;
4943 time = event->ctx->time + delta;
4946 task_clock_event_update(event, time);
4949 static int task_clock_event_init(struct perf_event *event)
4951 if (event->attr.type != PERF_TYPE_SOFTWARE)
4952 return -ENOENT;
4954 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
4955 return -ENOENT;
4957 return 0;
4960 static struct pmu perf_task_clock = {
4961 .event_init = task_clock_event_init,
4962 .enable = task_clock_event_enable,
4963 .disable = task_clock_event_disable,
4964 .read = task_clock_event_read,
4967 static LIST_HEAD(pmus);
4968 static DEFINE_MUTEX(pmus_lock);
4969 static struct srcu_struct pmus_srcu;
4971 int perf_pmu_register(struct pmu *pmu)
4973 mutex_lock(&pmus_lock);
4974 list_add_rcu(&pmu->entry, &pmus);
4975 mutex_unlock(&pmus_lock);
4977 return 0;
4980 void perf_pmu_unregister(struct pmu *pmu)
4982 mutex_lock(&pmus_lock);
4983 list_del_rcu(&pmu->entry);
4984 mutex_unlock(&pmus_lock);
4986 synchronize_srcu(&pmus_srcu);
4989 struct pmu *perf_init_event(struct perf_event *event)
4991 struct pmu *pmu = NULL;
4992 int idx;
4994 idx = srcu_read_lock(&pmus_srcu);
4995 list_for_each_entry_rcu(pmu, &pmus, entry) {
4996 int ret = pmu->event_init(event);
4997 if (!ret)
4998 break;
4999 if (ret != -ENOENT) {
5000 pmu = ERR_PTR(ret);
5001 break;
5004 srcu_read_unlock(&pmus_srcu, idx);
5006 return pmu;
5010 * Allocate and initialize a event structure
5012 static struct perf_event *
5013 perf_event_alloc(struct perf_event_attr *attr,
5014 int cpu,
5015 struct perf_event_context *ctx,
5016 struct perf_event *group_leader,
5017 struct perf_event *parent_event,
5018 perf_overflow_handler_t overflow_handler,
5019 gfp_t gfpflags)
5021 struct pmu *pmu;
5022 struct perf_event *event;
5023 struct hw_perf_event *hwc;
5024 long err;
5026 event = kzalloc(sizeof(*event), gfpflags);
5027 if (!event)
5028 return ERR_PTR(-ENOMEM);
5031 * Single events are their own group leaders, with an
5032 * empty sibling list:
5034 if (!group_leader)
5035 group_leader = event;
5037 mutex_init(&event->child_mutex);
5038 INIT_LIST_HEAD(&event->child_list);
5040 INIT_LIST_HEAD(&event->group_entry);
5041 INIT_LIST_HEAD(&event->event_entry);
5042 INIT_LIST_HEAD(&event->sibling_list);
5043 init_waitqueue_head(&event->waitq);
5045 mutex_init(&event->mmap_mutex);
5047 event->cpu = cpu;
5048 event->attr = *attr;
5049 event->group_leader = group_leader;
5050 event->pmu = NULL;
5051 event->ctx = ctx;
5052 event->oncpu = -1;
5054 event->parent = parent_event;
5056 event->ns = get_pid_ns(current->nsproxy->pid_ns);
5057 event->id = atomic64_inc_return(&perf_event_id);
5059 event->state = PERF_EVENT_STATE_INACTIVE;
5061 if (!overflow_handler && parent_event)
5062 overflow_handler = parent_event->overflow_handler;
5064 event->overflow_handler = overflow_handler;
5066 if (attr->disabled)
5067 event->state = PERF_EVENT_STATE_OFF;
5069 pmu = NULL;
5071 hwc = &event->hw;
5072 hwc->sample_period = attr->sample_period;
5073 if (attr->freq && attr->sample_freq)
5074 hwc->sample_period = 1;
5075 hwc->last_period = hwc->sample_period;
5077 local64_set(&hwc->period_left, hwc->sample_period);
5080 * we currently do not support PERF_FORMAT_GROUP on inherited events
5082 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
5083 goto done;
5085 pmu = perf_init_event(event);
5087 done:
5088 err = 0;
5089 if (!pmu)
5090 err = -EINVAL;
5091 else if (IS_ERR(pmu))
5092 err = PTR_ERR(pmu);
5094 if (err) {
5095 if (event->ns)
5096 put_pid_ns(event->ns);
5097 kfree(event);
5098 return ERR_PTR(err);
5101 event->pmu = pmu;
5103 if (!event->parent) {
5104 atomic_inc(&nr_events);
5105 if (event->attr.mmap || event->attr.mmap_data)
5106 atomic_inc(&nr_mmap_events);
5107 if (event->attr.comm)
5108 atomic_inc(&nr_comm_events);
5109 if (event->attr.task)
5110 atomic_inc(&nr_task_events);
5111 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
5112 err = get_callchain_buffers();
5113 if (err) {
5114 free_event(event);
5115 return ERR_PTR(err);
5120 return event;
5123 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5124 struct perf_event_attr *attr)
5126 u32 size;
5127 int ret;
5129 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
5130 return -EFAULT;
5133 * zero the full structure, so that a short copy will be nice.
5135 memset(attr, 0, sizeof(*attr));
5137 ret = get_user(size, &uattr->size);
5138 if (ret)
5139 return ret;
5141 if (size > PAGE_SIZE) /* silly large */
5142 goto err_size;
5144 if (!size) /* abi compat */
5145 size = PERF_ATTR_SIZE_VER0;
5147 if (size < PERF_ATTR_SIZE_VER0)
5148 goto err_size;
5151 * If we're handed a bigger struct than we know of,
5152 * ensure all the unknown bits are 0 - i.e. new
5153 * user-space does not rely on any kernel feature
5154 * extensions we dont know about yet.
5156 if (size > sizeof(*attr)) {
5157 unsigned char __user *addr;
5158 unsigned char __user *end;
5159 unsigned char val;
5161 addr = (void __user *)uattr + sizeof(*attr);
5162 end = (void __user *)uattr + size;
5164 for (; addr < end; addr++) {
5165 ret = get_user(val, addr);
5166 if (ret)
5167 return ret;
5168 if (val)
5169 goto err_size;
5171 size = sizeof(*attr);
5174 ret = copy_from_user(attr, uattr, size);
5175 if (ret)
5176 return -EFAULT;
5179 * If the type exists, the corresponding creation will verify
5180 * the attr->config.
5182 if (attr->type >= PERF_TYPE_MAX)
5183 return -EINVAL;
5185 if (attr->__reserved_1)
5186 return -EINVAL;
5188 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
5189 return -EINVAL;
5191 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
5192 return -EINVAL;
5194 out:
5195 return ret;
5197 err_size:
5198 put_user(sizeof(*attr), &uattr->size);
5199 ret = -E2BIG;
5200 goto out;
5203 static int
5204 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
5206 struct perf_buffer *buffer = NULL, *old_buffer = NULL;
5207 int ret = -EINVAL;
5209 if (!output_event)
5210 goto set;
5212 /* don't allow circular references */
5213 if (event == output_event)
5214 goto out;
5217 * Don't allow cross-cpu buffers
5219 if (output_event->cpu != event->cpu)
5220 goto out;
5223 * If its not a per-cpu buffer, it must be the same task.
5225 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
5226 goto out;
5228 set:
5229 mutex_lock(&event->mmap_mutex);
5230 /* Can't redirect output if we've got an active mmap() */
5231 if (atomic_read(&event->mmap_count))
5232 goto unlock;
5234 if (output_event) {
5235 /* get the buffer we want to redirect to */
5236 buffer = perf_buffer_get(output_event);
5237 if (!buffer)
5238 goto unlock;
5241 old_buffer = event->buffer;
5242 rcu_assign_pointer(event->buffer, buffer);
5243 ret = 0;
5244 unlock:
5245 mutex_unlock(&event->mmap_mutex);
5247 if (old_buffer)
5248 perf_buffer_put(old_buffer);
5249 out:
5250 return ret;
5254 * sys_perf_event_open - open a performance event, associate it to a task/cpu
5256 * @attr_uptr: event_id type attributes for monitoring/sampling
5257 * @pid: target pid
5258 * @cpu: target cpu
5259 * @group_fd: group leader event fd
5261 SYSCALL_DEFINE5(perf_event_open,
5262 struct perf_event_attr __user *, attr_uptr,
5263 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
5265 struct perf_event *event, *group_leader = NULL, *output_event = NULL;
5266 struct perf_event_attr attr;
5267 struct perf_event_context *ctx;
5268 struct file *event_file = NULL;
5269 struct file *group_file = NULL;
5270 int event_fd;
5271 int fput_needed = 0;
5272 int err;
5274 /* for future expandability... */
5275 if (flags & ~(PERF_FLAG_FD_NO_GROUP | PERF_FLAG_FD_OUTPUT))
5276 return -EINVAL;
5278 err = perf_copy_attr(attr_uptr, &attr);
5279 if (err)
5280 return err;
5282 if (!attr.exclude_kernel) {
5283 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
5284 return -EACCES;
5287 if (attr.freq) {
5288 if (attr.sample_freq > sysctl_perf_event_sample_rate)
5289 return -EINVAL;
5292 event_fd = get_unused_fd_flags(O_RDWR);
5293 if (event_fd < 0)
5294 return event_fd;
5297 * Get the target context (task or percpu):
5299 ctx = find_get_context(pid, cpu);
5300 if (IS_ERR(ctx)) {
5301 err = PTR_ERR(ctx);
5302 goto err_fd;
5305 if (group_fd != -1) {
5306 group_leader = perf_fget_light(group_fd, &fput_needed);
5307 if (IS_ERR(group_leader)) {
5308 err = PTR_ERR(group_leader);
5309 goto err_put_context;
5311 group_file = group_leader->filp;
5312 if (flags & PERF_FLAG_FD_OUTPUT)
5313 output_event = group_leader;
5314 if (flags & PERF_FLAG_FD_NO_GROUP)
5315 group_leader = NULL;
5319 * Look up the group leader (we will attach this event to it):
5321 if (group_leader) {
5322 err = -EINVAL;
5325 * Do not allow a recursive hierarchy (this new sibling
5326 * becoming part of another group-sibling):
5328 if (group_leader->group_leader != group_leader)
5329 goto err_put_context;
5331 * Do not allow to attach to a group in a different
5332 * task or CPU context:
5334 if (group_leader->ctx != ctx)
5335 goto err_put_context;
5337 * Only a group leader can be exclusive or pinned
5339 if (attr.exclusive || attr.pinned)
5340 goto err_put_context;
5343 event = perf_event_alloc(&attr, cpu, ctx, group_leader,
5344 NULL, NULL, GFP_KERNEL);
5345 if (IS_ERR(event)) {
5346 err = PTR_ERR(event);
5347 goto err_put_context;
5350 if (output_event) {
5351 err = perf_event_set_output(event, output_event);
5352 if (err)
5353 goto err_free_put_context;
5356 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, O_RDWR);
5357 if (IS_ERR(event_file)) {
5358 err = PTR_ERR(event_file);
5359 goto err_free_put_context;
5362 event->filp = event_file;
5363 WARN_ON_ONCE(ctx->parent_ctx);
5364 mutex_lock(&ctx->mutex);
5365 perf_install_in_context(ctx, event, cpu);
5366 ++ctx->generation;
5367 mutex_unlock(&ctx->mutex);
5369 event->owner = current;
5370 get_task_struct(current);
5371 mutex_lock(&current->perf_event_mutex);
5372 list_add_tail(&event->owner_entry, &current->perf_event_list);
5373 mutex_unlock(&current->perf_event_mutex);
5376 * Drop the reference on the group_event after placing the
5377 * new event on the sibling_list. This ensures destruction
5378 * of the group leader will find the pointer to itself in
5379 * perf_group_detach().
5381 fput_light(group_file, fput_needed);
5382 fd_install(event_fd, event_file);
5383 return event_fd;
5385 err_free_put_context:
5386 free_event(event);
5387 err_put_context:
5388 fput_light(group_file, fput_needed);
5389 put_ctx(ctx);
5390 err_fd:
5391 put_unused_fd(event_fd);
5392 return err;
5396 * perf_event_create_kernel_counter
5398 * @attr: attributes of the counter to create
5399 * @cpu: cpu in which the counter is bound
5400 * @pid: task to profile
5402 struct perf_event *
5403 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
5404 pid_t pid,
5405 perf_overflow_handler_t overflow_handler)
5407 struct perf_event *event;
5408 struct perf_event_context *ctx;
5409 int err;
5412 * Get the target context (task or percpu):
5415 ctx = find_get_context(pid, cpu);
5416 if (IS_ERR(ctx)) {
5417 err = PTR_ERR(ctx);
5418 goto err_exit;
5421 event = perf_event_alloc(attr, cpu, ctx, NULL,
5422 NULL, overflow_handler, GFP_KERNEL);
5423 if (IS_ERR(event)) {
5424 err = PTR_ERR(event);
5425 goto err_put_context;
5428 event->filp = NULL;
5429 WARN_ON_ONCE(ctx->parent_ctx);
5430 mutex_lock(&ctx->mutex);
5431 perf_install_in_context(ctx, event, cpu);
5432 ++ctx->generation;
5433 mutex_unlock(&ctx->mutex);
5435 event->owner = current;
5436 get_task_struct(current);
5437 mutex_lock(&current->perf_event_mutex);
5438 list_add_tail(&event->owner_entry, &current->perf_event_list);
5439 mutex_unlock(&current->perf_event_mutex);
5441 return event;
5443 err_put_context:
5444 put_ctx(ctx);
5445 err_exit:
5446 return ERR_PTR(err);
5448 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
5451 * inherit a event from parent task to child task:
5453 static struct perf_event *
5454 inherit_event(struct perf_event *parent_event,
5455 struct task_struct *parent,
5456 struct perf_event_context *parent_ctx,
5457 struct task_struct *child,
5458 struct perf_event *group_leader,
5459 struct perf_event_context *child_ctx)
5461 struct perf_event *child_event;
5464 * Instead of creating recursive hierarchies of events,
5465 * we link inherited events back to the original parent,
5466 * which has a filp for sure, which we use as the reference
5467 * count:
5469 if (parent_event->parent)
5470 parent_event = parent_event->parent;
5472 child_event = perf_event_alloc(&parent_event->attr,
5473 parent_event->cpu, child_ctx,
5474 group_leader, parent_event,
5475 NULL, GFP_KERNEL);
5476 if (IS_ERR(child_event))
5477 return child_event;
5478 get_ctx(child_ctx);
5481 * Make the child state follow the state of the parent event,
5482 * not its attr.disabled bit. We hold the parent's mutex,
5483 * so we won't race with perf_event_{en, dis}able_family.
5485 if (parent_event->state >= PERF_EVENT_STATE_INACTIVE)
5486 child_event->state = PERF_EVENT_STATE_INACTIVE;
5487 else
5488 child_event->state = PERF_EVENT_STATE_OFF;
5490 if (parent_event->attr.freq) {
5491 u64 sample_period = parent_event->hw.sample_period;
5492 struct hw_perf_event *hwc = &child_event->hw;
5494 hwc->sample_period = sample_period;
5495 hwc->last_period = sample_period;
5497 local64_set(&hwc->period_left, sample_period);
5500 child_event->overflow_handler = parent_event->overflow_handler;
5503 * Link it up in the child's context:
5505 add_event_to_ctx(child_event, child_ctx);
5508 * Get a reference to the parent filp - we will fput it
5509 * when the child event exits. This is safe to do because
5510 * we are in the parent and we know that the filp still
5511 * exists and has a nonzero count:
5513 atomic_long_inc(&parent_event->filp->f_count);
5516 * Link this into the parent event's child list
5518 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
5519 mutex_lock(&parent_event->child_mutex);
5520 list_add_tail(&child_event->child_list, &parent_event->child_list);
5521 mutex_unlock(&parent_event->child_mutex);
5523 return child_event;
5526 static int inherit_group(struct perf_event *parent_event,
5527 struct task_struct *parent,
5528 struct perf_event_context *parent_ctx,
5529 struct task_struct *child,
5530 struct perf_event_context *child_ctx)
5532 struct perf_event *leader;
5533 struct perf_event *sub;
5534 struct perf_event *child_ctr;
5536 leader = inherit_event(parent_event, parent, parent_ctx,
5537 child, NULL, child_ctx);
5538 if (IS_ERR(leader))
5539 return PTR_ERR(leader);
5540 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
5541 child_ctr = inherit_event(sub, parent, parent_ctx,
5542 child, leader, child_ctx);
5543 if (IS_ERR(child_ctr))
5544 return PTR_ERR(child_ctr);
5546 return 0;
5549 static void sync_child_event(struct perf_event *child_event,
5550 struct task_struct *child)
5552 struct perf_event *parent_event = child_event->parent;
5553 u64 child_val;
5555 if (child_event->attr.inherit_stat)
5556 perf_event_read_event(child_event, child);
5558 child_val = perf_event_count(child_event);
5561 * Add back the child's count to the parent's count:
5563 atomic64_add(child_val, &parent_event->child_count);
5564 atomic64_add(child_event->total_time_enabled,
5565 &parent_event->child_total_time_enabled);
5566 atomic64_add(child_event->total_time_running,
5567 &parent_event->child_total_time_running);
5570 * Remove this event from the parent's list
5572 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
5573 mutex_lock(&parent_event->child_mutex);
5574 list_del_init(&child_event->child_list);
5575 mutex_unlock(&parent_event->child_mutex);
5578 * Release the parent event, if this was the last
5579 * reference to it.
5581 fput(parent_event->filp);
5584 static void
5585 __perf_event_exit_task(struct perf_event *child_event,
5586 struct perf_event_context *child_ctx,
5587 struct task_struct *child)
5589 struct perf_event *parent_event;
5591 perf_event_remove_from_context(child_event);
5593 parent_event = child_event->parent;
5595 * It can happen that parent exits first, and has events
5596 * that are still around due to the child reference. These
5597 * events need to be zapped - but otherwise linger.
5599 if (parent_event) {
5600 sync_child_event(child_event, child);
5601 free_event(child_event);
5606 * When a child task exits, feed back event values to parent events.
5608 void perf_event_exit_task(struct task_struct *child)
5610 struct perf_event *child_event, *tmp;
5611 struct perf_event_context *child_ctx;
5612 unsigned long flags;
5614 if (likely(!child->perf_event_ctxp)) {
5615 perf_event_task(child, NULL, 0);
5616 return;
5619 local_irq_save(flags);
5621 * We can't reschedule here because interrupts are disabled,
5622 * and either child is current or it is a task that can't be
5623 * scheduled, so we are now safe from rescheduling changing
5624 * our context.
5626 child_ctx = child->perf_event_ctxp;
5627 __perf_event_task_sched_out(child_ctx);
5630 * Take the context lock here so that if find_get_context is
5631 * reading child->perf_event_ctxp, we wait until it has
5632 * incremented the context's refcount before we do put_ctx below.
5634 raw_spin_lock(&child_ctx->lock);
5635 child->perf_event_ctxp = NULL;
5637 * If this context is a clone; unclone it so it can't get
5638 * swapped to another process while we're removing all
5639 * the events from it.
5641 unclone_ctx(child_ctx);
5642 update_context_time(child_ctx);
5643 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
5646 * Report the task dead after unscheduling the events so that we
5647 * won't get any samples after PERF_RECORD_EXIT. We can however still
5648 * get a few PERF_RECORD_READ events.
5650 perf_event_task(child, child_ctx, 0);
5653 * We can recurse on the same lock type through:
5655 * __perf_event_exit_task()
5656 * sync_child_event()
5657 * fput(parent_event->filp)
5658 * perf_release()
5659 * mutex_lock(&ctx->mutex)
5661 * But since its the parent context it won't be the same instance.
5663 mutex_lock(&child_ctx->mutex);
5665 again:
5666 list_for_each_entry_safe(child_event, tmp, &child_ctx->pinned_groups,
5667 group_entry)
5668 __perf_event_exit_task(child_event, child_ctx, child);
5670 list_for_each_entry_safe(child_event, tmp, &child_ctx->flexible_groups,
5671 group_entry)
5672 __perf_event_exit_task(child_event, child_ctx, child);
5675 * If the last event was a group event, it will have appended all
5676 * its siblings to the list, but we obtained 'tmp' before that which
5677 * will still point to the list head terminating the iteration.
5679 if (!list_empty(&child_ctx->pinned_groups) ||
5680 !list_empty(&child_ctx->flexible_groups))
5681 goto again;
5683 mutex_unlock(&child_ctx->mutex);
5685 put_ctx(child_ctx);
5688 static void perf_free_event(struct perf_event *event,
5689 struct perf_event_context *ctx)
5691 struct perf_event *parent = event->parent;
5693 if (WARN_ON_ONCE(!parent))
5694 return;
5696 mutex_lock(&parent->child_mutex);
5697 list_del_init(&event->child_list);
5698 mutex_unlock(&parent->child_mutex);
5700 fput(parent->filp);
5702 perf_group_detach(event);
5703 list_del_event(event, ctx);
5704 free_event(event);
5708 * free an unexposed, unused context as created by inheritance by
5709 * init_task below, used by fork() in case of fail.
5711 void perf_event_free_task(struct task_struct *task)
5713 struct perf_event_context *ctx = task->perf_event_ctxp;
5714 struct perf_event *event, *tmp;
5716 if (!ctx)
5717 return;
5719 mutex_lock(&ctx->mutex);
5720 again:
5721 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups, group_entry)
5722 perf_free_event(event, ctx);
5724 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
5725 group_entry)
5726 perf_free_event(event, ctx);
5728 if (!list_empty(&ctx->pinned_groups) ||
5729 !list_empty(&ctx->flexible_groups))
5730 goto again;
5732 mutex_unlock(&ctx->mutex);
5734 put_ctx(ctx);
5737 static int
5738 inherit_task_group(struct perf_event *event, struct task_struct *parent,
5739 struct perf_event_context *parent_ctx,
5740 struct task_struct *child,
5741 int *inherited_all)
5743 int ret;
5744 struct perf_event_context *child_ctx = child->perf_event_ctxp;
5746 if (!event->attr.inherit) {
5747 *inherited_all = 0;
5748 return 0;
5751 if (!child_ctx) {
5753 * This is executed from the parent task context, so
5754 * inherit events that have been marked for cloning.
5755 * First allocate and initialize a context for the
5756 * child.
5759 child_ctx = kzalloc(sizeof(struct perf_event_context),
5760 GFP_KERNEL);
5761 if (!child_ctx)
5762 return -ENOMEM;
5764 __perf_event_init_context(child_ctx, child);
5765 child->perf_event_ctxp = child_ctx;
5766 get_task_struct(child);
5769 ret = inherit_group(event, parent, parent_ctx,
5770 child, child_ctx);
5772 if (ret)
5773 *inherited_all = 0;
5775 return ret;
5780 * Initialize the perf_event context in task_struct
5782 int perf_event_init_task(struct task_struct *child)
5784 struct perf_event_context *child_ctx, *parent_ctx;
5785 struct perf_event_context *cloned_ctx;
5786 struct perf_event *event;
5787 struct task_struct *parent = current;
5788 int inherited_all = 1;
5789 int ret = 0;
5791 child->perf_event_ctxp = NULL;
5793 mutex_init(&child->perf_event_mutex);
5794 INIT_LIST_HEAD(&child->perf_event_list);
5796 if (likely(!parent->perf_event_ctxp))
5797 return 0;
5800 * If the parent's context is a clone, pin it so it won't get
5801 * swapped under us.
5803 parent_ctx = perf_pin_task_context(parent);
5806 * No need to check if parent_ctx != NULL here; since we saw
5807 * it non-NULL earlier, the only reason for it to become NULL
5808 * is if we exit, and since we're currently in the middle of
5809 * a fork we can't be exiting at the same time.
5813 * Lock the parent list. No need to lock the child - not PID
5814 * hashed yet and not running, so nobody can access it.
5816 mutex_lock(&parent_ctx->mutex);
5819 * We dont have to disable NMIs - we are only looking at
5820 * the list, not manipulating it:
5822 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
5823 ret = inherit_task_group(event, parent, parent_ctx, child,
5824 &inherited_all);
5825 if (ret)
5826 break;
5829 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
5830 ret = inherit_task_group(event, parent, parent_ctx, child,
5831 &inherited_all);
5832 if (ret)
5833 break;
5836 child_ctx = child->perf_event_ctxp;
5838 if (child_ctx && inherited_all) {
5840 * Mark the child context as a clone of the parent
5841 * context, or of whatever the parent is a clone of.
5842 * Note that if the parent is a clone, it could get
5843 * uncloned at any point, but that doesn't matter
5844 * because the list of events and the generation
5845 * count can't have changed since we took the mutex.
5847 cloned_ctx = rcu_dereference(parent_ctx->parent_ctx);
5848 if (cloned_ctx) {
5849 child_ctx->parent_ctx = cloned_ctx;
5850 child_ctx->parent_gen = parent_ctx->parent_gen;
5851 } else {
5852 child_ctx->parent_ctx = parent_ctx;
5853 child_ctx->parent_gen = parent_ctx->generation;
5855 get_ctx(child_ctx->parent_ctx);
5858 mutex_unlock(&parent_ctx->mutex);
5860 perf_unpin_context(parent_ctx);
5862 return ret;
5865 static void __init perf_event_init_all_cpus(void)
5867 int cpu;
5868 struct perf_cpu_context *cpuctx;
5870 for_each_possible_cpu(cpu) {
5871 cpuctx = &per_cpu(perf_cpu_context, cpu);
5872 mutex_init(&cpuctx->hlist_mutex);
5873 __perf_event_init_context(&cpuctx->ctx, NULL);
5877 static void __cpuinit perf_event_init_cpu(int cpu)
5879 struct perf_cpu_context *cpuctx;
5881 cpuctx = &per_cpu(perf_cpu_context, cpu);
5883 spin_lock(&perf_resource_lock);
5884 cpuctx->max_pertask = perf_max_events - perf_reserved_percpu;
5885 spin_unlock(&perf_resource_lock);
5887 mutex_lock(&cpuctx->hlist_mutex);
5888 if (cpuctx->hlist_refcount > 0) {
5889 struct swevent_hlist *hlist;
5891 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
5892 WARN_ON_ONCE(!hlist);
5893 rcu_assign_pointer(cpuctx->swevent_hlist, hlist);
5895 mutex_unlock(&cpuctx->hlist_mutex);
5898 #ifdef CONFIG_HOTPLUG_CPU
5899 static void __perf_event_exit_cpu(void *info)
5901 struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
5902 struct perf_event_context *ctx = &cpuctx->ctx;
5903 struct perf_event *event, *tmp;
5905 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups, group_entry)
5906 __perf_event_remove_from_context(event);
5907 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups, group_entry)
5908 __perf_event_remove_from_context(event);
5910 static void perf_event_exit_cpu(int cpu)
5912 struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
5913 struct perf_event_context *ctx = &cpuctx->ctx;
5915 mutex_lock(&cpuctx->hlist_mutex);
5916 swevent_hlist_release(cpuctx);
5917 mutex_unlock(&cpuctx->hlist_mutex);
5919 mutex_lock(&ctx->mutex);
5920 smp_call_function_single(cpu, __perf_event_exit_cpu, NULL, 1);
5921 mutex_unlock(&ctx->mutex);
5923 #else
5924 static inline void perf_event_exit_cpu(int cpu) { }
5925 #endif
5927 static int __cpuinit
5928 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
5930 unsigned int cpu = (long)hcpu;
5932 switch (action & ~CPU_TASKS_FROZEN) {
5934 case CPU_UP_PREPARE:
5935 case CPU_DOWN_FAILED:
5936 perf_event_init_cpu(cpu);
5937 break;
5939 case CPU_UP_CANCELED:
5940 case CPU_DOWN_PREPARE:
5941 perf_event_exit_cpu(cpu);
5942 break;
5944 default:
5945 break;
5948 return NOTIFY_OK;
5951 void __init perf_event_init(void)
5953 perf_event_init_all_cpus();
5954 init_srcu_struct(&pmus_srcu);
5955 perf_pmu_register(&perf_swevent);
5956 perf_pmu_register(&perf_cpu_clock);
5957 perf_pmu_register(&perf_task_clock);
5958 perf_tp_register();
5959 perf_cpu_notifier(perf_cpu_notify);
5962 static ssize_t perf_show_reserve_percpu(struct sysdev_class *class,
5963 struct sysdev_class_attribute *attr,
5964 char *buf)
5966 return sprintf(buf, "%d\n", perf_reserved_percpu);
5969 static ssize_t
5970 perf_set_reserve_percpu(struct sysdev_class *class,
5971 struct sysdev_class_attribute *attr,
5972 const char *buf,
5973 size_t count)
5975 struct perf_cpu_context *cpuctx;
5976 unsigned long val;
5977 int err, cpu, mpt;
5979 err = strict_strtoul(buf, 10, &val);
5980 if (err)
5981 return err;
5982 if (val > perf_max_events)
5983 return -EINVAL;
5985 spin_lock(&perf_resource_lock);
5986 perf_reserved_percpu = val;
5987 for_each_online_cpu(cpu) {
5988 cpuctx = &per_cpu(perf_cpu_context, cpu);
5989 raw_spin_lock_irq(&cpuctx->ctx.lock);
5990 mpt = min(perf_max_events - cpuctx->ctx.nr_events,
5991 perf_max_events - perf_reserved_percpu);
5992 cpuctx->max_pertask = mpt;
5993 raw_spin_unlock_irq(&cpuctx->ctx.lock);
5995 spin_unlock(&perf_resource_lock);
5997 return count;
6000 static ssize_t perf_show_overcommit(struct sysdev_class *class,
6001 struct sysdev_class_attribute *attr,
6002 char *buf)
6004 return sprintf(buf, "%d\n", perf_overcommit);
6007 static ssize_t
6008 perf_set_overcommit(struct sysdev_class *class,
6009 struct sysdev_class_attribute *attr,
6010 const char *buf, size_t count)
6012 unsigned long val;
6013 int err;
6015 err = strict_strtoul(buf, 10, &val);
6016 if (err)
6017 return err;
6018 if (val > 1)
6019 return -EINVAL;
6021 spin_lock(&perf_resource_lock);
6022 perf_overcommit = val;
6023 spin_unlock(&perf_resource_lock);
6025 return count;
6028 static SYSDEV_CLASS_ATTR(
6029 reserve_percpu,
6030 0644,
6031 perf_show_reserve_percpu,
6032 perf_set_reserve_percpu
6035 static SYSDEV_CLASS_ATTR(
6036 overcommit,
6037 0644,
6038 perf_show_overcommit,
6039 perf_set_overcommit
6042 static struct attribute *perfclass_attrs[] = {
6043 &attr_reserve_percpu.attr,
6044 &attr_overcommit.attr,
6045 NULL
6048 static struct attribute_group perfclass_attr_group = {
6049 .attrs = perfclass_attrs,
6050 .name = "perf_events",
6053 static int __init perf_event_sysfs_init(void)
6055 return sysfs_create_group(&cpu_sysdev_class.kset.kobj,
6056 &perfclass_attr_group);
6058 device_initcall(perf_event_sysfs_init);