perf_counter: Fix swcounter context invariance
[linux-2.6/verdex.git] / kernel / perf_counter.c
blob3dd4339589a073dec64998153fadc1cfcdb2fdf7
1 /*
2 * Performance counter 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/sysfs.h>
19 #include <linux/dcache.h>
20 #include <linux/percpu.h>
21 #include <linux/ptrace.h>
22 #include <linux/vmstat.h>
23 #include <linux/hardirq.h>
24 #include <linux/rculist.h>
25 #include <linux/uaccess.h>
26 #include <linux/syscalls.h>
27 #include <linux/anon_inodes.h>
28 #include <linux/kernel_stat.h>
29 #include <linux/perf_counter.h>
31 #include <asm/irq_regs.h>
34 * Each CPU has a list of per CPU counters:
36 DEFINE_PER_CPU(struct perf_cpu_context, perf_cpu_context);
38 int perf_max_counters __read_mostly = 1;
39 static int perf_reserved_percpu __read_mostly;
40 static int perf_overcommit __read_mostly = 1;
42 static atomic_t nr_counters __read_mostly;
43 static atomic_t nr_mmap_counters __read_mostly;
44 static atomic_t nr_comm_counters __read_mostly;
45 static atomic_t nr_task_counters __read_mostly;
48 * perf counter paranoia level:
49 * 0 - not paranoid
50 * 1 - disallow cpu counters to unpriv
51 * 2 - disallow kernel profiling to unpriv
53 int sysctl_perf_counter_paranoid __read_mostly;
55 static inline bool perf_paranoid_cpu(void)
57 return sysctl_perf_counter_paranoid > 0;
60 static inline bool perf_paranoid_kernel(void)
62 return sysctl_perf_counter_paranoid > 1;
65 int sysctl_perf_counter_mlock __read_mostly = 512; /* 'free' kb per user */
68 * max perf counter sample rate
70 int sysctl_perf_counter_sample_rate __read_mostly = 100000;
72 static atomic64_t perf_counter_id;
75 * Lock for (sysadmin-configurable) counter reservations:
77 static DEFINE_SPINLOCK(perf_resource_lock);
80 * Architecture provided APIs - weak aliases:
82 extern __weak const struct pmu *hw_perf_counter_init(struct perf_counter *counter)
84 return NULL;
87 void __weak hw_perf_disable(void) { barrier(); }
88 void __weak hw_perf_enable(void) { barrier(); }
90 void __weak hw_perf_counter_setup(int cpu) { barrier(); }
91 void __weak hw_perf_counter_setup_online(int cpu) { barrier(); }
93 int __weak
94 hw_perf_group_sched_in(struct perf_counter *group_leader,
95 struct perf_cpu_context *cpuctx,
96 struct perf_counter_context *ctx, int cpu)
98 return 0;
101 void __weak perf_counter_print_debug(void) { }
103 static DEFINE_PER_CPU(int, disable_count);
105 void __perf_disable(void)
107 __get_cpu_var(disable_count)++;
110 bool __perf_enable(void)
112 return !--__get_cpu_var(disable_count);
115 void perf_disable(void)
117 __perf_disable();
118 hw_perf_disable();
121 void perf_enable(void)
123 if (__perf_enable())
124 hw_perf_enable();
127 static void get_ctx(struct perf_counter_context *ctx)
129 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
132 static void free_ctx(struct rcu_head *head)
134 struct perf_counter_context *ctx;
136 ctx = container_of(head, struct perf_counter_context, rcu_head);
137 kfree(ctx);
140 static void put_ctx(struct perf_counter_context *ctx)
142 if (atomic_dec_and_test(&ctx->refcount)) {
143 if (ctx->parent_ctx)
144 put_ctx(ctx->parent_ctx);
145 if (ctx->task)
146 put_task_struct(ctx->task);
147 call_rcu(&ctx->rcu_head, free_ctx);
151 static void unclone_ctx(struct perf_counter_context *ctx)
153 if (ctx->parent_ctx) {
154 put_ctx(ctx->parent_ctx);
155 ctx->parent_ctx = NULL;
160 * If we inherit counters we want to return the parent counter id
161 * to userspace.
163 static u64 primary_counter_id(struct perf_counter *counter)
165 u64 id = counter->id;
167 if (counter->parent)
168 id = counter->parent->id;
170 return id;
174 * Get the perf_counter_context for a task and lock it.
175 * This has to cope with with the fact that until it is locked,
176 * the context could get moved to another task.
178 static struct perf_counter_context *
179 perf_lock_task_context(struct task_struct *task, unsigned long *flags)
181 struct perf_counter_context *ctx;
183 rcu_read_lock();
184 retry:
185 ctx = rcu_dereference(task->perf_counter_ctxp);
186 if (ctx) {
188 * If this context is a clone of another, it might
189 * get swapped for another underneath us by
190 * perf_counter_task_sched_out, though the
191 * rcu_read_lock() protects us from any context
192 * getting freed. Lock the context and check if it
193 * got swapped before we could get the lock, and retry
194 * if so. If we locked the right context, then it
195 * can't get swapped on us any more.
197 spin_lock_irqsave(&ctx->lock, *flags);
198 if (ctx != rcu_dereference(task->perf_counter_ctxp)) {
199 spin_unlock_irqrestore(&ctx->lock, *flags);
200 goto retry;
203 if (!atomic_inc_not_zero(&ctx->refcount)) {
204 spin_unlock_irqrestore(&ctx->lock, *flags);
205 ctx = NULL;
208 rcu_read_unlock();
209 return ctx;
213 * Get the context for a task and increment its pin_count so it
214 * can't get swapped to another task. This also increments its
215 * reference count so that the context can't get freed.
217 static struct perf_counter_context *perf_pin_task_context(struct task_struct *task)
219 struct perf_counter_context *ctx;
220 unsigned long flags;
222 ctx = perf_lock_task_context(task, &flags);
223 if (ctx) {
224 ++ctx->pin_count;
225 spin_unlock_irqrestore(&ctx->lock, flags);
227 return ctx;
230 static void perf_unpin_context(struct perf_counter_context *ctx)
232 unsigned long flags;
234 spin_lock_irqsave(&ctx->lock, flags);
235 --ctx->pin_count;
236 spin_unlock_irqrestore(&ctx->lock, flags);
237 put_ctx(ctx);
241 * Add a counter from the lists for its context.
242 * Must be called with ctx->mutex and ctx->lock held.
244 static void
245 list_add_counter(struct perf_counter *counter, struct perf_counter_context *ctx)
247 struct perf_counter *group_leader = counter->group_leader;
250 * Depending on whether it is a standalone or sibling counter,
251 * add it straight to the context's counter list, or to the group
252 * leader's sibling list:
254 if (group_leader == counter)
255 list_add_tail(&counter->list_entry, &ctx->counter_list);
256 else {
257 list_add_tail(&counter->list_entry, &group_leader->sibling_list);
258 group_leader->nr_siblings++;
261 list_add_rcu(&counter->event_entry, &ctx->event_list);
262 ctx->nr_counters++;
263 if (counter->attr.inherit_stat)
264 ctx->nr_stat++;
268 * Remove a counter from the lists for its context.
269 * Must be called with ctx->mutex and ctx->lock held.
271 static void
272 list_del_counter(struct perf_counter *counter, struct perf_counter_context *ctx)
274 struct perf_counter *sibling, *tmp;
276 if (list_empty(&counter->list_entry))
277 return;
278 ctx->nr_counters--;
279 if (counter->attr.inherit_stat)
280 ctx->nr_stat--;
282 list_del_init(&counter->list_entry);
283 list_del_rcu(&counter->event_entry);
285 if (counter->group_leader != counter)
286 counter->group_leader->nr_siblings--;
289 * If this was a group counter with sibling counters then
290 * upgrade the siblings to singleton counters by adding them
291 * to the context list directly:
293 list_for_each_entry_safe(sibling, tmp,
294 &counter->sibling_list, list_entry) {
296 list_move_tail(&sibling->list_entry, &ctx->counter_list);
297 sibling->group_leader = sibling;
301 static void
302 counter_sched_out(struct perf_counter *counter,
303 struct perf_cpu_context *cpuctx,
304 struct perf_counter_context *ctx)
306 if (counter->state != PERF_COUNTER_STATE_ACTIVE)
307 return;
309 counter->state = PERF_COUNTER_STATE_INACTIVE;
310 counter->tstamp_stopped = ctx->time;
311 counter->pmu->disable(counter);
312 counter->oncpu = -1;
314 if (!is_software_counter(counter))
315 cpuctx->active_oncpu--;
316 ctx->nr_active--;
317 if (counter->attr.exclusive || !cpuctx->active_oncpu)
318 cpuctx->exclusive = 0;
321 static void
322 group_sched_out(struct perf_counter *group_counter,
323 struct perf_cpu_context *cpuctx,
324 struct perf_counter_context *ctx)
326 struct perf_counter *counter;
328 if (group_counter->state != PERF_COUNTER_STATE_ACTIVE)
329 return;
331 counter_sched_out(group_counter, cpuctx, ctx);
334 * Schedule out siblings (if any):
336 list_for_each_entry(counter, &group_counter->sibling_list, list_entry)
337 counter_sched_out(counter, cpuctx, ctx);
339 if (group_counter->attr.exclusive)
340 cpuctx->exclusive = 0;
344 * Cross CPU call to remove a performance counter
346 * We disable the counter on the hardware level first. After that we
347 * remove it from the context list.
349 static void __perf_counter_remove_from_context(void *info)
351 struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
352 struct perf_counter *counter = info;
353 struct perf_counter_context *ctx = counter->ctx;
356 * If this is a task context, we need to check whether it is
357 * the current task context of this cpu. If not it has been
358 * scheduled out before the smp call arrived.
360 if (ctx->task && cpuctx->task_ctx != ctx)
361 return;
363 spin_lock(&ctx->lock);
365 * Protect the list operation against NMI by disabling the
366 * counters on a global level.
368 perf_disable();
370 counter_sched_out(counter, cpuctx, ctx);
372 list_del_counter(counter, ctx);
374 if (!ctx->task) {
376 * Allow more per task counters with respect to the
377 * reservation:
379 cpuctx->max_pertask =
380 min(perf_max_counters - ctx->nr_counters,
381 perf_max_counters - perf_reserved_percpu);
384 perf_enable();
385 spin_unlock(&ctx->lock);
390 * Remove the counter from a task's (or a CPU's) list of counters.
392 * Must be called with ctx->mutex held.
394 * CPU counters are removed with a smp call. For task counters we only
395 * call when the task is on a CPU.
397 * If counter->ctx is a cloned context, callers must make sure that
398 * every task struct that counter->ctx->task could possibly point to
399 * remains valid. This is OK when called from perf_release since
400 * that only calls us on the top-level context, which can't be a clone.
401 * When called from perf_counter_exit_task, it's OK because the
402 * context has been detached from its task.
404 static void perf_counter_remove_from_context(struct perf_counter *counter)
406 struct perf_counter_context *ctx = counter->ctx;
407 struct task_struct *task = ctx->task;
409 if (!task) {
411 * Per cpu counters are removed via an smp call and
412 * the removal is always sucessful.
414 smp_call_function_single(counter->cpu,
415 __perf_counter_remove_from_context,
416 counter, 1);
417 return;
420 retry:
421 task_oncpu_function_call(task, __perf_counter_remove_from_context,
422 counter);
424 spin_lock_irq(&ctx->lock);
426 * If the context is active we need to retry the smp call.
428 if (ctx->nr_active && !list_empty(&counter->list_entry)) {
429 spin_unlock_irq(&ctx->lock);
430 goto retry;
434 * The lock prevents that this context is scheduled in so we
435 * can remove the counter safely, if the call above did not
436 * succeed.
438 if (!list_empty(&counter->list_entry)) {
439 list_del_counter(counter, ctx);
441 spin_unlock_irq(&ctx->lock);
444 static inline u64 perf_clock(void)
446 return cpu_clock(smp_processor_id());
450 * Update the record of the current time in a context.
452 static void update_context_time(struct perf_counter_context *ctx)
454 u64 now = perf_clock();
456 ctx->time += now - ctx->timestamp;
457 ctx->timestamp = now;
461 * Update the total_time_enabled and total_time_running fields for a counter.
463 static void update_counter_times(struct perf_counter *counter)
465 struct perf_counter_context *ctx = counter->ctx;
466 u64 run_end;
468 if (counter->state < PERF_COUNTER_STATE_INACTIVE)
469 return;
471 counter->total_time_enabled = ctx->time - counter->tstamp_enabled;
473 if (counter->state == PERF_COUNTER_STATE_INACTIVE)
474 run_end = counter->tstamp_stopped;
475 else
476 run_end = ctx->time;
478 counter->total_time_running = run_end - counter->tstamp_running;
482 * Update total_time_enabled and total_time_running for all counters in a group.
484 static void update_group_times(struct perf_counter *leader)
486 struct perf_counter *counter;
488 update_counter_times(leader);
489 list_for_each_entry(counter, &leader->sibling_list, list_entry)
490 update_counter_times(counter);
494 * Cross CPU call to disable a performance counter
496 static void __perf_counter_disable(void *info)
498 struct perf_counter *counter = info;
499 struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
500 struct perf_counter_context *ctx = counter->ctx;
503 * If this is a per-task counter, need to check whether this
504 * counter's task is the current task on this cpu.
506 if (ctx->task && cpuctx->task_ctx != ctx)
507 return;
509 spin_lock(&ctx->lock);
512 * If the counter is on, turn it off.
513 * If it is in error state, leave it in error state.
515 if (counter->state >= PERF_COUNTER_STATE_INACTIVE) {
516 update_context_time(ctx);
517 update_counter_times(counter);
518 if (counter == counter->group_leader)
519 group_sched_out(counter, cpuctx, ctx);
520 else
521 counter_sched_out(counter, cpuctx, ctx);
522 counter->state = PERF_COUNTER_STATE_OFF;
525 spin_unlock(&ctx->lock);
529 * Disable a counter.
531 * If counter->ctx is a cloned context, callers must make sure that
532 * every task struct that counter->ctx->task could possibly point to
533 * remains valid. This condition is satisifed when called through
534 * perf_counter_for_each_child or perf_counter_for_each because they
535 * hold the top-level counter's child_mutex, so any descendant that
536 * goes to exit will block in sync_child_counter.
537 * When called from perf_pending_counter it's OK because counter->ctx
538 * is the current context on this CPU and preemption is disabled,
539 * hence we can't get into perf_counter_task_sched_out for this context.
541 static void perf_counter_disable(struct perf_counter *counter)
543 struct perf_counter_context *ctx = counter->ctx;
544 struct task_struct *task = ctx->task;
546 if (!task) {
548 * Disable the counter on the cpu that it's on
550 smp_call_function_single(counter->cpu, __perf_counter_disable,
551 counter, 1);
552 return;
555 retry:
556 task_oncpu_function_call(task, __perf_counter_disable, counter);
558 spin_lock_irq(&ctx->lock);
560 * If the counter is still active, we need to retry the cross-call.
562 if (counter->state == PERF_COUNTER_STATE_ACTIVE) {
563 spin_unlock_irq(&ctx->lock);
564 goto retry;
568 * Since we have the lock this context can't be scheduled
569 * in, so we can change the state safely.
571 if (counter->state == PERF_COUNTER_STATE_INACTIVE) {
572 update_counter_times(counter);
573 counter->state = PERF_COUNTER_STATE_OFF;
576 spin_unlock_irq(&ctx->lock);
579 static int
580 counter_sched_in(struct perf_counter *counter,
581 struct perf_cpu_context *cpuctx,
582 struct perf_counter_context *ctx,
583 int cpu)
585 if (counter->state <= PERF_COUNTER_STATE_OFF)
586 return 0;
588 counter->state = PERF_COUNTER_STATE_ACTIVE;
589 counter->oncpu = cpu; /* TODO: put 'cpu' into cpuctx->cpu */
591 * The new state must be visible before we turn it on in the hardware:
593 smp_wmb();
595 if (counter->pmu->enable(counter)) {
596 counter->state = PERF_COUNTER_STATE_INACTIVE;
597 counter->oncpu = -1;
598 return -EAGAIN;
601 counter->tstamp_running += ctx->time - counter->tstamp_stopped;
603 if (!is_software_counter(counter))
604 cpuctx->active_oncpu++;
605 ctx->nr_active++;
607 if (counter->attr.exclusive)
608 cpuctx->exclusive = 1;
610 return 0;
613 static int
614 group_sched_in(struct perf_counter *group_counter,
615 struct perf_cpu_context *cpuctx,
616 struct perf_counter_context *ctx,
617 int cpu)
619 struct perf_counter *counter, *partial_group;
620 int ret;
622 if (group_counter->state == PERF_COUNTER_STATE_OFF)
623 return 0;
625 ret = hw_perf_group_sched_in(group_counter, cpuctx, ctx, cpu);
626 if (ret)
627 return ret < 0 ? ret : 0;
629 if (counter_sched_in(group_counter, cpuctx, ctx, cpu))
630 return -EAGAIN;
633 * Schedule in siblings as one group (if any):
635 list_for_each_entry(counter, &group_counter->sibling_list, list_entry) {
636 if (counter_sched_in(counter, cpuctx, ctx, cpu)) {
637 partial_group = counter;
638 goto group_error;
642 return 0;
644 group_error:
646 * Groups can be scheduled in as one unit only, so undo any
647 * partial group before returning:
649 list_for_each_entry(counter, &group_counter->sibling_list, list_entry) {
650 if (counter == partial_group)
651 break;
652 counter_sched_out(counter, cpuctx, ctx);
654 counter_sched_out(group_counter, cpuctx, ctx);
656 return -EAGAIN;
660 * Return 1 for a group consisting entirely of software counters,
661 * 0 if the group contains any hardware counters.
663 static int is_software_only_group(struct perf_counter *leader)
665 struct perf_counter *counter;
667 if (!is_software_counter(leader))
668 return 0;
670 list_for_each_entry(counter, &leader->sibling_list, list_entry)
671 if (!is_software_counter(counter))
672 return 0;
674 return 1;
678 * Work out whether we can put this counter group on the CPU now.
680 static int group_can_go_on(struct perf_counter *counter,
681 struct perf_cpu_context *cpuctx,
682 int can_add_hw)
685 * Groups consisting entirely of software counters can always go on.
687 if (is_software_only_group(counter))
688 return 1;
690 * If an exclusive group is already on, no other hardware
691 * counters can go on.
693 if (cpuctx->exclusive)
694 return 0;
696 * If this group is exclusive and there are already
697 * counters on the CPU, it can't go on.
699 if (counter->attr.exclusive && cpuctx->active_oncpu)
700 return 0;
702 * Otherwise, try to add it if all previous groups were able
703 * to go on.
705 return can_add_hw;
708 static void add_counter_to_ctx(struct perf_counter *counter,
709 struct perf_counter_context *ctx)
711 list_add_counter(counter, ctx);
712 counter->tstamp_enabled = ctx->time;
713 counter->tstamp_running = ctx->time;
714 counter->tstamp_stopped = ctx->time;
718 * Cross CPU call to install and enable a performance counter
720 * Must be called with ctx->mutex held
722 static void __perf_install_in_context(void *info)
724 struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
725 struct perf_counter *counter = info;
726 struct perf_counter_context *ctx = counter->ctx;
727 struct perf_counter *leader = counter->group_leader;
728 int cpu = smp_processor_id();
729 int err;
732 * If this is a task context, we need to check whether it is
733 * the current task context of this cpu. If not it has been
734 * scheduled out before the smp call arrived.
735 * Or possibly this is the right context but it isn't
736 * on this cpu because it had no counters.
738 if (ctx->task && cpuctx->task_ctx != ctx) {
739 if (cpuctx->task_ctx || ctx->task != current)
740 return;
741 cpuctx->task_ctx = ctx;
744 spin_lock(&ctx->lock);
745 ctx->is_active = 1;
746 update_context_time(ctx);
749 * Protect the list operation against NMI by disabling the
750 * counters on a global level. NOP for non NMI based counters.
752 perf_disable();
754 add_counter_to_ctx(counter, ctx);
757 * Don't put the counter on if it is disabled or if
758 * it is in a group and the group isn't on.
760 if (counter->state != PERF_COUNTER_STATE_INACTIVE ||
761 (leader != counter && leader->state != PERF_COUNTER_STATE_ACTIVE))
762 goto unlock;
765 * An exclusive counter can't go on if there are already active
766 * hardware counters, and no hardware counter can go on if there
767 * is already an exclusive counter on.
769 if (!group_can_go_on(counter, cpuctx, 1))
770 err = -EEXIST;
771 else
772 err = counter_sched_in(counter, cpuctx, ctx, cpu);
774 if (err) {
776 * This counter couldn't go on. If it is in a group
777 * then we have to pull the whole group off.
778 * If the counter group is pinned then put it in error state.
780 if (leader != counter)
781 group_sched_out(leader, cpuctx, ctx);
782 if (leader->attr.pinned) {
783 update_group_times(leader);
784 leader->state = PERF_COUNTER_STATE_ERROR;
788 if (!err && !ctx->task && cpuctx->max_pertask)
789 cpuctx->max_pertask--;
791 unlock:
792 perf_enable();
794 spin_unlock(&ctx->lock);
798 * Attach a performance counter to a context
800 * First we add the counter to the list with the hardware enable bit
801 * in counter->hw_config cleared.
803 * If the counter is attached to a task which is on a CPU we use a smp
804 * call to enable it in the task context. The task might have been
805 * scheduled away, but we check this in the smp call again.
807 * Must be called with ctx->mutex held.
809 static void
810 perf_install_in_context(struct perf_counter_context *ctx,
811 struct perf_counter *counter,
812 int cpu)
814 struct task_struct *task = ctx->task;
816 if (!task) {
818 * Per cpu counters are installed via an smp call and
819 * the install is always sucessful.
821 smp_call_function_single(cpu, __perf_install_in_context,
822 counter, 1);
823 return;
826 retry:
827 task_oncpu_function_call(task, __perf_install_in_context,
828 counter);
830 spin_lock_irq(&ctx->lock);
832 * we need to retry the smp call.
834 if (ctx->is_active && list_empty(&counter->list_entry)) {
835 spin_unlock_irq(&ctx->lock);
836 goto retry;
840 * The lock prevents that this context is scheduled in so we
841 * can add the counter safely, if it the call above did not
842 * succeed.
844 if (list_empty(&counter->list_entry))
845 add_counter_to_ctx(counter, ctx);
846 spin_unlock_irq(&ctx->lock);
850 * Cross CPU call to enable a performance counter
852 static void __perf_counter_enable(void *info)
854 struct perf_counter *counter = info;
855 struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
856 struct perf_counter_context *ctx = counter->ctx;
857 struct perf_counter *leader = counter->group_leader;
858 int err;
861 * If this is a per-task counter, need to check whether this
862 * counter's task is the current task on this cpu.
864 if (ctx->task && cpuctx->task_ctx != ctx) {
865 if (cpuctx->task_ctx || ctx->task != current)
866 return;
867 cpuctx->task_ctx = ctx;
870 spin_lock(&ctx->lock);
871 ctx->is_active = 1;
872 update_context_time(ctx);
874 if (counter->state >= PERF_COUNTER_STATE_INACTIVE)
875 goto unlock;
876 counter->state = PERF_COUNTER_STATE_INACTIVE;
877 counter->tstamp_enabled = ctx->time - counter->total_time_enabled;
880 * If the counter is in a group and isn't the group leader,
881 * then don't put it on unless the group is on.
883 if (leader != counter && leader->state != PERF_COUNTER_STATE_ACTIVE)
884 goto unlock;
886 if (!group_can_go_on(counter, cpuctx, 1)) {
887 err = -EEXIST;
888 } else {
889 perf_disable();
890 if (counter == leader)
891 err = group_sched_in(counter, cpuctx, ctx,
892 smp_processor_id());
893 else
894 err = counter_sched_in(counter, cpuctx, ctx,
895 smp_processor_id());
896 perf_enable();
899 if (err) {
901 * If this counter can't go on and it's part of a
902 * group, then the whole group has to come off.
904 if (leader != counter)
905 group_sched_out(leader, cpuctx, ctx);
906 if (leader->attr.pinned) {
907 update_group_times(leader);
908 leader->state = PERF_COUNTER_STATE_ERROR;
912 unlock:
913 spin_unlock(&ctx->lock);
917 * Enable a counter.
919 * If counter->ctx is a cloned context, callers must make sure that
920 * every task struct that counter->ctx->task could possibly point to
921 * remains valid. This condition is satisfied when called through
922 * perf_counter_for_each_child or perf_counter_for_each as described
923 * for perf_counter_disable.
925 static void perf_counter_enable(struct perf_counter *counter)
927 struct perf_counter_context *ctx = counter->ctx;
928 struct task_struct *task = ctx->task;
930 if (!task) {
932 * Enable the counter on the cpu that it's on
934 smp_call_function_single(counter->cpu, __perf_counter_enable,
935 counter, 1);
936 return;
939 spin_lock_irq(&ctx->lock);
940 if (counter->state >= PERF_COUNTER_STATE_INACTIVE)
941 goto out;
944 * If the counter is in error state, clear that first.
945 * That way, if we see the counter in error state below, we
946 * know that it has gone back into error state, as distinct
947 * from the task having been scheduled away before the
948 * cross-call arrived.
950 if (counter->state == PERF_COUNTER_STATE_ERROR)
951 counter->state = PERF_COUNTER_STATE_OFF;
953 retry:
954 spin_unlock_irq(&ctx->lock);
955 task_oncpu_function_call(task, __perf_counter_enable, counter);
957 spin_lock_irq(&ctx->lock);
960 * If the context is active and the counter is still off,
961 * we need to retry the cross-call.
963 if (ctx->is_active && counter->state == PERF_COUNTER_STATE_OFF)
964 goto retry;
967 * Since we have the lock this context can't be scheduled
968 * in, so we can change the state safely.
970 if (counter->state == PERF_COUNTER_STATE_OFF) {
971 counter->state = PERF_COUNTER_STATE_INACTIVE;
972 counter->tstamp_enabled =
973 ctx->time - counter->total_time_enabled;
975 out:
976 spin_unlock_irq(&ctx->lock);
979 static int perf_counter_refresh(struct perf_counter *counter, int refresh)
982 * not supported on inherited counters
984 if (counter->attr.inherit)
985 return -EINVAL;
987 atomic_add(refresh, &counter->event_limit);
988 perf_counter_enable(counter);
990 return 0;
993 void __perf_counter_sched_out(struct perf_counter_context *ctx,
994 struct perf_cpu_context *cpuctx)
996 struct perf_counter *counter;
998 spin_lock(&ctx->lock);
999 ctx->is_active = 0;
1000 if (likely(!ctx->nr_counters))
1001 goto out;
1002 update_context_time(ctx);
1004 perf_disable();
1005 if (ctx->nr_active) {
1006 list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1007 if (counter != counter->group_leader)
1008 counter_sched_out(counter, cpuctx, ctx);
1009 else
1010 group_sched_out(counter, cpuctx, ctx);
1013 perf_enable();
1014 out:
1015 spin_unlock(&ctx->lock);
1019 * Test whether two contexts are equivalent, i.e. whether they
1020 * have both been cloned from the same version of the same context
1021 * and they both have the same number of enabled counters.
1022 * If the number of enabled counters is the same, then the set
1023 * of enabled counters should be the same, because these are both
1024 * inherited contexts, therefore we can't access individual counters
1025 * in them directly with an fd; we can only enable/disable all
1026 * counters via prctl, or enable/disable all counters in a family
1027 * via ioctl, which will have the same effect on both contexts.
1029 static int context_equiv(struct perf_counter_context *ctx1,
1030 struct perf_counter_context *ctx2)
1032 return ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx
1033 && ctx1->parent_gen == ctx2->parent_gen
1034 && !ctx1->pin_count && !ctx2->pin_count;
1037 static void __perf_counter_read(void *counter);
1039 static void __perf_counter_sync_stat(struct perf_counter *counter,
1040 struct perf_counter *next_counter)
1042 u64 value;
1044 if (!counter->attr.inherit_stat)
1045 return;
1048 * Update the counter value, we cannot use perf_counter_read()
1049 * because we're in the middle of a context switch and have IRQs
1050 * disabled, which upsets smp_call_function_single(), however
1051 * we know the counter must be on the current CPU, therefore we
1052 * don't need to use it.
1054 switch (counter->state) {
1055 case PERF_COUNTER_STATE_ACTIVE:
1056 __perf_counter_read(counter);
1057 break;
1059 case PERF_COUNTER_STATE_INACTIVE:
1060 update_counter_times(counter);
1061 break;
1063 default:
1064 break;
1068 * In order to keep per-task stats reliable we need to flip the counter
1069 * values when we flip the contexts.
1071 value = atomic64_read(&next_counter->count);
1072 value = atomic64_xchg(&counter->count, value);
1073 atomic64_set(&next_counter->count, value);
1075 swap(counter->total_time_enabled, next_counter->total_time_enabled);
1076 swap(counter->total_time_running, next_counter->total_time_running);
1079 * Since we swizzled the values, update the user visible data too.
1081 perf_counter_update_userpage(counter);
1082 perf_counter_update_userpage(next_counter);
1085 #define list_next_entry(pos, member) \
1086 list_entry(pos->member.next, typeof(*pos), member)
1088 static void perf_counter_sync_stat(struct perf_counter_context *ctx,
1089 struct perf_counter_context *next_ctx)
1091 struct perf_counter *counter, *next_counter;
1093 if (!ctx->nr_stat)
1094 return;
1096 counter = list_first_entry(&ctx->event_list,
1097 struct perf_counter, event_entry);
1099 next_counter = list_first_entry(&next_ctx->event_list,
1100 struct perf_counter, event_entry);
1102 while (&counter->event_entry != &ctx->event_list &&
1103 &next_counter->event_entry != &next_ctx->event_list) {
1105 __perf_counter_sync_stat(counter, next_counter);
1107 counter = list_next_entry(counter, event_entry);
1108 next_counter = list_next_entry(next_counter, event_entry);
1113 * Called from scheduler to remove the counters of the current task,
1114 * with interrupts disabled.
1116 * We stop each counter and update the counter value in counter->count.
1118 * This does not protect us against NMI, but disable()
1119 * sets the disabled bit in the control field of counter _before_
1120 * accessing the counter control register. If a NMI hits, then it will
1121 * not restart the counter.
1123 void perf_counter_task_sched_out(struct task_struct *task,
1124 struct task_struct *next, int cpu)
1126 struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
1127 struct perf_counter_context *ctx = task->perf_counter_ctxp;
1128 struct perf_counter_context *next_ctx;
1129 struct perf_counter_context *parent;
1130 struct pt_regs *regs;
1131 int do_switch = 1;
1133 regs = task_pt_regs(task);
1134 perf_swcounter_event(PERF_COUNT_SW_CONTEXT_SWITCHES, 1, 1, regs, 0);
1136 if (likely(!ctx || !cpuctx->task_ctx))
1137 return;
1139 update_context_time(ctx);
1141 rcu_read_lock();
1142 parent = rcu_dereference(ctx->parent_ctx);
1143 next_ctx = next->perf_counter_ctxp;
1144 if (parent && next_ctx &&
1145 rcu_dereference(next_ctx->parent_ctx) == parent) {
1147 * Looks like the two contexts are clones, so we might be
1148 * able to optimize the context switch. We lock both
1149 * contexts and check that they are clones under the
1150 * lock (including re-checking that neither has been
1151 * uncloned in the meantime). It doesn't matter which
1152 * order we take the locks because no other cpu could
1153 * be trying to lock both of these tasks.
1155 spin_lock(&ctx->lock);
1156 spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
1157 if (context_equiv(ctx, next_ctx)) {
1159 * XXX do we need a memory barrier of sorts
1160 * wrt to rcu_dereference() of perf_counter_ctxp
1162 task->perf_counter_ctxp = next_ctx;
1163 next->perf_counter_ctxp = ctx;
1164 ctx->task = next;
1165 next_ctx->task = task;
1166 do_switch = 0;
1168 perf_counter_sync_stat(ctx, next_ctx);
1170 spin_unlock(&next_ctx->lock);
1171 spin_unlock(&ctx->lock);
1173 rcu_read_unlock();
1175 if (do_switch) {
1176 __perf_counter_sched_out(ctx, cpuctx);
1177 cpuctx->task_ctx = NULL;
1182 * Called with IRQs disabled
1184 static void __perf_counter_task_sched_out(struct perf_counter_context *ctx)
1186 struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
1188 if (!cpuctx->task_ctx)
1189 return;
1191 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
1192 return;
1194 __perf_counter_sched_out(ctx, cpuctx);
1195 cpuctx->task_ctx = NULL;
1199 * Called with IRQs disabled
1201 static void perf_counter_cpu_sched_out(struct perf_cpu_context *cpuctx)
1203 __perf_counter_sched_out(&cpuctx->ctx, cpuctx);
1206 static void
1207 __perf_counter_sched_in(struct perf_counter_context *ctx,
1208 struct perf_cpu_context *cpuctx, int cpu)
1210 struct perf_counter *counter;
1211 int can_add_hw = 1;
1213 spin_lock(&ctx->lock);
1214 ctx->is_active = 1;
1215 if (likely(!ctx->nr_counters))
1216 goto out;
1218 ctx->timestamp = perf_clock();
1220 perf_disable();
1223 * First go through the list and put on any pinned groups
1224 * in order to give them the best chance of going on.
1226 list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1227 if (counter->state <= PERF_COUNTER_STATE_OFF ||
1228 !counter->attr.pinned)
1229 continue;
1230 if (counter->cpu != -1 && counter->cpu != cpu)
1231 continue;
1233 if (counter != counter->group_leader)
1234 counter_sched_in(counter, cpuctx, ctx, cpu);
1235 else {
1236 if (group_can_go_on(counter, cpuctx, 1))
1237 group_sched_in(counter, cpuctx, ctx, cpu);
1241 * If this pinned group hasn't been scheduled,
1242 * put it in error state.
1244 if (counter->state == PERF_COUNTER_STATE_INACTIVE) {
1245 update_group_times(counter);
1246 counter->state = PERF_COUNTER_STATE_ERROR;
1250 list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1252 * Ignore counters in OFF or ERROR state, and
1253 * ignore pinned counters since we did them already.
1255 if (counter->state <= PERF_COUNTER_STATE_OFF ||
1256 counter->attr.pinned)
1257 continue;
1260 * Listen to the 'cpu' scheduling filter constraint
1261 * of counters:
1263 if (counter->cpu != -1 && counter->cpu != cpu)
1264 continue;
1266 if (counter != counter->group_leader) {
1267 if (counter_sched_in(counter, cpuctx, ctx, cpu))
1268 can_add_hw = 0;
1269 } else {
1270 if (group_can_go_on(counter, cpuctx, can_add_hw)) {
1271 if (group_sched_in(counter, cpuctx, ctx, cpu))
1272 can_add_hw = 0;
1276 perf_enable();
1277 out:
1278 spin_unlock(&ctx->lock);
1282 * Called from scheduler to add the counters of the current task
1283 * with interrupts disabled.
1285 * We restore the counter value and then enable it.
1287 * This does not protect us against NMI, but enable()
1288 * sets the enabled bit in the control field of counter _before_
1289 * accessing the counter control register. If a NMI hits, then it will
1290 * keep the counter running.
1292 void perf_counter_task_sched_in(struct task_struct *task, int cpu)
1294 struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
1295 struct perf_counter_context *ctx = task->perf_counter_ctxp;
1297 if (likely(!ctx))
1298 return;
1299 if (cpuctx->task_ctx == ctx)
1300 return;
1301 __perf_counter_sched_in(ctx, cpuctx, cpu);
1302 cpuctx->task_ctx = ctx;
1305 static void perf_counter_cpu_sched_in(struct perf_cpu_context *cpuctx, int cpu)
1307 struct perf_counter_context *ctx = &cpuctx->ctx;
1309 __perf_counter_sched_in(ctx, cpuctx, cpu);
1312 #define MAX_INTERRUPTS (~0ULL)
1314 static void perf_log_throttle(struct perf_counter *counter, int enable);
1316 static void perf_adjust_period(struct perf_counter *counter, u64 events)
1318 struct hw_perf_counter *hwc = &counter->hw;
1319 u64 period, sample_period;
1320 s64 delta;
1322 events *= hwc->sample_period;
1323 period = div64_u64(events, counter->attr.sample_freq);
1325 delta = (s64)(period - hwc->sample_period);
1326 delta = (delta + 7) / 8; /* low pass filter */
1328 sample_period = hwc->sample_period + delta;
1330 if (!sample_period)
1331 sample_period = 1;
1333 hwc->sample_period = sample_period;
1336 static void perf_ctx_adjust_freq(struct perf_counter_context *ctx)
1338 struct perf_counter *counter;
1339 struct hw_perf_counter *hwc;
1340 u64 interrupts, freq;
1342 spin_lock(&ctx->lock);
1343 list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1344 if (counter->state != PERF_COUNTER_STATE_ACTIVE)
1345 continue;
1347 hwc = &counter->hw;
1349 interrupts = hwc->interrupts;
1350 hwc->interrupts = 0;
1353 * unthrottle counters on the tick
1355 if (interrupts == MAX_INTERRUPTS) {
1356 perf_log_throttle(counter, 1);
1357 counter->pmu->unthrottle(counter);
1358 interrupts = 2*sysctl_perf_counter_sample_rate/HZ;
1361 if (!counter->attr.freq || !counter->attr.sample_freq)
1362 continue;
1365 * if the specified freq < HZ then we need to skip ticks
1367 if (counter->attr.sample_freq < HZ) {
1368 freq = counter->attr.sample_freq;
1370 hwc->freq_count += freq;
1371 hwc->freq_interrupts += interrupts;
1373 if (hwc->freq_count < HZ)
1374 continue;
1376 interrupts = hwc->freq_interrupts;
1377 hwc->freq_interrupts = 0;
1378 hwc->freq_count -= HZ;
1379 } else
1380 freq = HZ;
1382 perf_adjust_period(counter, freq * interrupts);
1385 * In order to avoid being stalled by an (accidental) huge
1386 * sample period, force reset the sample period if we didn't
1387 * get any events in this freq period.
1389 if (!interrupts) {
1390 perf_disable();
1391 counter->pmu->disable(counter);
1392 atomic64_set(&hwc->period_left, 0);
1393 counter->pmu->enable(counter);
1394 perf_enable();
1397 spin_unlock(&ctx->lock);
1401 * Round-robin a context's counters:
1403 static void rotate_ctx(struct perf_counter_context *ctx)
1405 struct perf_counter *counter;
1407 if (!ctx->nr_counters)
1408 return;
1410 spin_lock(&ctx->lock);
1412 * Rotate the first entry last (works just fine for group counters too):
1414 perf_disable();
1415 list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1416 list_move_tail(&counter->list_entry, &ctx->counter_list);
1417 break;
1419 perf_enable();
1421 spin_unlock(&ctx->lock);
1424 void perf_counter_task_tick(struct task_struct *curr, int cpu)
1426 struct perf_cpu_context *cpuctx;
1427 struct perf_counter_context *ctx;
1429 if (!atomic_read(&nr_counters))
1430 return;
1432 cpuctx = &per_cpu(perf_cpu_context, cpu);
1433 ctx = curr->perf_counter_ctxp;
1435 perf_ctx_adjust_freq(&cpuctx->ctx);
1436 if (ctx)
1437 perf_ctx_adjust_freq(ctx);
1439 perf_counter_cpu_sched_out(cpuctx);
1440 if (ctx)
1441 __perf_counter_task_sched_out(ctx);
1443 rotate_ctx(&cpuctx->ctx);
1444 if (ctx)
1445 rotate_ctx(ctx);
1447 perf_counter_cpu_sched_in(cpuctx, cpu);
1448 if (ctx)
1449 perf_counter_task_sched_in(curr, cpu);
1453 * Enable all of a task's counters that have been marked enable-on-exec.
1454 * This expects task == current.
1456 static void perf_counter_enable_on_exec(struct task_struct *task)
1458 struct perf_counter_context *ctx;
1459 struct perf_counter *counter;
1460 unsigned long flags;
1461 int enabled = 0;
1463 local_irq_save(flags);
1464 ctx = task->perf_counter_ctxp;
1465 if (!ctx || !ctx->nr_counters)
1466 goto out;
1468 __perf_counter_task_sched_out(ctx);
1470 spin_lock(&ctx->lock);
1472 list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1473 if (!counter->attr.enable_on_exec)
1474 continue;
1475 counter->attr.enable_on_exec = 0;
1476 if (counter->state >= PERF_COUNTER_STATE_INACTIVE)
1477 continue;
1478 counter->state = PERF_COUNTER_STATE_INACTIVE;
1479 counter->tstamp_enabled =
1480 ctx->time - counter->total_time_enabled;
1481 enabled = 1;
1485 * Unclone this context if we enabled any counter.
1487 if (enabled)
1488 unclone_ctx(ctx);
1490 spin_unlock(&ctx->lock);
1492 perf_counter_task_sched_in(task, smp_processor_id());
1493 out:
1494 local_irq_restore(flags);
1498 * Cross CPU call to read the hardware counter
1500 static void __perf_counter_read(void *info)
1502 struct perf_counter *counter = info;
1503 struct perf_counter_context *ctx = counter->ctx;
1504 unsigned long flags;
1506 local_irq_save(flags);
1507 if (ctx->is_active)
1508 update_context_time(ctx);
1509 counter->pmu->read(counter);
1510 update_counter_times(counter);
1511 local_irq_restore(flags);
1514 static u64 perf_counter_read(struct perf_counter *counter)
1517 * If counter is enabled and currently active on a CPU, update the
1518 * value in the counter structure:
1520 if (counter->state == PERF_COUNTER_STATE_ACTIVE) {
1521 smp_call_function_single(counter->oncpu,
1522 __perf_counter_read, counter, 1);
1523 } else if (counter->state == PERF_COUNTER_STATE_INACTIVE) {
1524 update_counter_times(counter);
1527 return atomic64_read(&counter->count);
1531 * Initialize the perf_counter context in a task_struct:
1533 static void
1534 __perf_counter_init_context(struct perf_counter_context *ctx,
1535 struct task_struct *task)
1537 memset(ctx, 0, sizeof(*ctx));
1538 spin_lock_init(&ctx->lock);
1539 mutex_init(&ctx->mutex);
1540 INIT_LIST_HEAD(&ctx->counter_list);
1541 INIT_LIST_HEAD(&ctx->event_list);
1542 atomic_set(&ctx->refcount, 1);
1543 ctx->task = task;
1546 static struct perf_counter_context *find_get_context(pid_t pid, int cpu)
1548 struct perf_counter_context *ctx;
1549 struct perf_cpu_context *cpuctx;
1550 struct task_struct *task;
1551 unsigned long flags;
1552 int err;
1555 * If cpu is not a wildcard then this is a percpu counter:
1557 if (cpu != -1) {
1558 /* Must be root to operate on a CPU counter: */
1559 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
1560 return ERR_PTR(-EACCES);
1562 if (cpu < 0 || cpu > num_possible_cpus())
1563 return ERR_PTR(-EINVAL);
1566 * We could be clever and allow to attach a counter to an
1567 * offline CPU and activate it when the CPU comes up, but
1568 * that's for later.
1570 if (!cpu_isset(cpu, cpu_online_map))
1571 return ERR_PTR(-ENODEV);
1573 cpuctx = &per_cpu(perf_cpu_context, cpu);
1574 ctx = &cpuctx->ctx;
1575 get_ctx(ctx);
1577 return ctx;
1580 rcu_read_lock();
1581 if (!pid)
1582 task = current;
1583 else
1584 task = find_task_by_vpid(pid);
1585 if (task)
1586 get_task_struct(task);
1587 rcu_read_unlock();
1589 if (!task)
1590 return ERR_PTR(-ESRCH);
1593 * Can't attach counters to a dying task.
1595 err = -ESRCH;
1596 if (task->flags & PF_EXITING)
1597 goto errout;
1599 /* Reuse ptrace permission checks for now. */
1600 err = -EACCES;
1601 if (!ptrace_may_access(task, PTRACE_MODE_READ))
1602 goto errout;
1604 retry:
1605 ctx = perf_lock_task_context(task, &flags);
1606 if (ctx) {
1607 unclone_ctx(ctx);
1608 spin_unlock_irqrestore(&ctx->lock, flags);
1611 if (!ctx) {
1612 ctx = kmalloc(sizeof(struct perf_counter_context), GFP_KERNEL);
1613 err = -ENOMEM;
1614 if (!ctx)
1615 goto errout;
1616 __perf_counter_init_context(ctx, task);
1617 get_ctx(ctx);
1618 if (cmpxchg(&task->perf_counter_ctxp, NULL, ctx)) {
1620 * We raced with some other task; use
1621 * the context they set.
1623 kfree(ctx);
1624 goto retry;
1626 get_task_struct(task);
1629 put_task_struct(task);
1630 return ctx;
1632 errout:
1633 put_task_struct(task);
1634 return ERR_PTR(err);
1637 static void free_counter_rcu(struct rcu_head *head)
1639 struct perf_counter *counter;
1641 counter = container_of(head, struct perf_counter, rcu_head);
1642 if (counter->ns)
1643 put_pid_ns(counter->ns);
1644 kfree(counter);
1647 static void perf_pending_sync(struct perf_counter *counter);
1649 static void free_counter(struct perf_counter *counter)
1651 perf_pending_sync(counter);
1653 if (!counter->parent) {
1654 atomic_dec(&nr_counters);
1655 if (counter->attr.mmap)
1656 atomic_dec(&nr_mmap_counters);
1657 if (counter->attr.comm)
1658 atomic_dec(&nr_comm_counters);
1659 if (counter->attr.task)
1660 atomic_dec(&nr_task_counters);
1663 if (counter->destroy)
1664 counter->destroy(counter);
1666 put_ctx(counter->ctx);
1667 call_rcu(&counter->rcu_head, free_counter_rcu);
1671 * Called when the last reference to the file is gone.
1673 static int perf_release(struct inode *inode, struct file *file)
1675 struct perf_counter *counter = file->private_data;
1676 struct perf_counter_context *ctx = counter->ctx;
1678 file->private_data = NULL;
1680 WARN_ON_ONCE(ctx->parent_ctx);
1681 mutex_lock(&ctx->mutex);
1682 perf_counter_remove_from_context(counter);
1683 mutex_unlock(&ctx->mutex);
1685 mutex_lock(&counter->owner->perf_counter_mutex);
1686 list_del_init(&counter->owner_entry);
1687 mutex_unlock(&counter->owner->perf_counter_mutex);
1688 put_task_struct(counter->owner);
1690 free_counter(counter);
1692 return 0;
1695 static u64 perf_counter_read_tree(struct perf_counter *counter)
1697 struct perf_counter *child;
1698 u64 total = 0;
1700 total += perf_counter_read(counter);
1701 list_for_each_entry(child, &counter->child_list, child_list)
1702 total += perf_counter_read(child);
1704 return total;
1708 * Read the performance counter - simple non blocking version for now
1710 static ssize_t
1711 perf_read_hw(struct perf_counter *counter, char __user *buf, size_t count)
1713 u64 values[4];
1714 int n;
1717 * Return end-of-file for a read on a counter that is in
1718 * error state (i.e. because it was pinned but it couldn't be
1719 * scheduled on to the CPU at some point).
1721 if (counter->state == PERF_COUNTER_STATE_ERROR)
1722 return 0;
1724 WARN_ON_ONCE(counter->ctx->parent_ctx);
1725 mutex_lock(&counter->child_mutex);
1726 values[0] = perf_counter_read_tree(counter);
1727 n = 1;
1728 if (counter->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1729 values[n++] = counter->total_time_enabled +
1730 atomic64_read(&counter->child_total_time_enabled);
1731 if (counter->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1732 values[n++] = counter->total_time_running +
1733 atomic64_read(&counter->child_total_time_running);
1734 if (counter->attr.read_format & PERF_FORMAT_ID)
1735 values[n++] = primary_counter_id(counter);
1736 mutex_unlock(&counter->child_mutex);
1738 if (count < n * sizeof(u64))
1739 return -EINVAL;
1740 count = n * sizeof(u64);
1742 if (copy_to_user(buf, values, count))
1743 return -EFAULT;
1745 return count;
1748 static ssize_t
1749 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
1751 struct perf_counter *counter = file->private_data;
1753 return perf_read_hw(counter, buf, count);
1756 static unsigned int perf_poll(struct file *file, poll_table *wait)
1758 struct perf_counter *counter = file->private_data;
1759 struct perf_mmap_data *data;
1760 unsigned int events = POLL_HUP;
1762 rcu_read_lock();
1763 data = rcu_dereference(counter->data);
1764 if (data)
1765 events = atomic_xchg(&data->poll, 0);
1766 rcu_read_unlock();
1768 poll_wait(file, &counter->waitq, wait);
1770 return events;
1773 static void perf_counter_reset(struct perf_counter *counter)
1775 (void)perf_counter_read(counter);
1776 atomic64_set(&counter->count, 0);
1777 perf_counter_update_userpage(counter);
1781 * Holding the top-level counter's child_mutex means that any
1782 * descendant process that has inherited this counter will block
1783 * in sync_child_counter if it goes to exit, thus satisfying the
1784 * task existence requirements of perf_counter_enable/disable.
1786 static void perf_counter_for_each_child(struct perf_counter *counter,
1787 void (*func)(struct perf_counter *))
1789 struct perf_counter *child;
1791 WARN_ON_ONCE(counter->ctx->parent_ctx);
1792 mutex_lock(&counter->child_mutex);
1793 func(counter);
1794 list_for_each_entry(child, &counter->child_list, child_list)
1795 func(child);
1796 mutex_unlock(&counter->child_mutex);
1799 static void perf_counter_for_each(struct perf_counter *counter,
1800 void (*func)(struct perf_counter *))
1802 struct perf_counter_context *ctx = counter->ctx;
1803 struct perf_counter *sibling;
1805 WARN_ON_ONCE(ctx->parent_ctx);
1806 mutex_lock(&ctx->mutex);
1807 counter = counter->group_leader;
1809 perf_counter_for_each_child(counter, func);
1810 func(counter);
1811 list_for_each_entry(sibling, &counter->sibling_list, list_entry)
1812 perf_counter_for_each_child(counter, func);
1813 mutex_unlock(&ctx->mutex);
1816 static int perf_counter_period(struct perf_counter *counter, u64 __user *arg)
1818 struct perf_counter_context *ctx = counter->ctx;
1819 unsigned long size;
1820 int ret = 0;
1821 u64 value;
1823 if (!counter->attr.sample_period)
1824 return -EINVAL;
1826 size = copy_from_user(&value, arg, sizeof(value));
1827 if (size != sizeof(value))
1828 return -EFAULT;
1830 if (!value)
1831 return -EINVAL;
1833 spin_lock_irq(&ctx->lock);
1834 if (counter->attr.freq) {
1835 if (value > sysctl_perf_counter_sample_rate) {
1836 ret = -EINVAL;
1837 goto unlock;
1840 counter->attr.sample_freq = value;
1841 } else {
1842 counter->attr.sample_period = value;
1843 counter->hw.sample_period = value;
1845 unlock:
1846 spin_unlock_irq(&ctx->lock);
1848 return ret;
1851 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
1853 struct perf_counter *counter = file->private_data;
1854 void (*func)(struct perf_counter *);
1855 u32 flags = arg;
1857 switch (cmd) {
1858 case PERF_COUNTER_IOC_ENABLE:
1859 func = perf_counter_enable;
1860 break;
1861 case PERF_COUNTER_IOC_DISABLE:
1862 func = perf_counter_disable;
1863 break;
1864 case PERF_COUNTER_IOC_RESET:
1865 func = perf_counter_reset;
1866 break;
1868 case PERF_COUNTER_IOC_REFRESH:
1869 return perf_counter_refresh(counter, arg);
1871 case PERF_COUNTER_IOC_PERIOD:
1872 return perf_counter_period(counter, (u64 __user *)arg);
1874 default:
1875 return -ENOTTY;
1878 if (flags & PERF_IOC_FLAG_GROUP)
1879 perf_counter_for_each(counter, func);
1880 else
1881 perf_counter_for_each_child(counter, func);
1883 return 0;
1886 int perf_counter_task_enable(void)
1888 struct perf_counter *counter;
1890 mutex_lock(&current->perf_counter_mutex);
1891 list_for_each_entry(counter, &current->perf_counter_list, owner_entry)
1892 perf_counter_for_each_child(counter, perf_counter_enable);
1893 mutex_unlock(&current->perf_counter_mutex);
1895 return 0;
1898 int perf_counter_task_disable(void)
1900 struct perf_counter *counter;
1902 mutex_lock(&current->perf_counter_mutex);
1903 list_for_each_entry(counter, &current->perf_counter_list, owner_entry)
1904 perf_counter_for_each_child(counter, perf_counter_disable);
1905 mutex_unlock(&current->perf_counter_mutex);
1907 return 0;
1910 static int perf_counter_index(struct perf_counter *counter)
1912 if (counter->state != PERF_COUNTER_STATE_ACTIVE)
1913 return 0;
1915 return counter->hw.idx + 1 - PERF_COUNTER_INDEX_OFFSET;
1919 * Callers need to ensure there can be no nesting of this function, otherwise
1920 * the seqlock logic goes bad. We can not serialize this because the arch
1921 * code calls this from NMI context.
1923 void perf_counter_update_userpage(struct perf_counter *counter)
1925 struct perf_counter_mmap_page *userpg;
1926 struct perf_mmap_data *data;
1928 rcu_read_lock();
1929 data = rcu_dereference(counter->data);
1930 if (!data)
1931 goto unlock;
1933 userpg = data->user_page;
1936 * Disable preemption so as to not let the corresponding user-space
1937 * spin too long if we get preempted.
1939 preempt_disable();
1940 ++userpg->lock;
1941 barrier();
1942 userpg->index = perf_counter_index(counter);
1943 userpg->offset = atomic64_read(&counter->count);
1944 if (counter->state == PERF_COUNTER_STATE_ACTIVE)
1945 userpg->offset -= atomic64_read(&counter->hw.prev_count);
1947 userpg->time_enabled = counter->total_time_enabled +
1948 atomic64_read(&counter->child_total_time_enabled);
1950 userpg->time_running = counter->total_time_running +
1951 atomic64_read(&counter->child_total_time_running);
1953 barrier();
1954 ++userpg->lock;
1955 preempt_enable();
1956 unlock:
1957 rcu_read_unlock();
1960 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1962 struct perf_counter *counter = vma->vm_file->private_data;
1963 struct perf_mmap_data *data;
1964 int ret = VM_FAULT_SIGBUS;
1966 if (vmf->flags & FAULT_FLAG_MKWRITE) {
1967 if (vmf->pgoff == 0)
1968 ret = 0;
1969 return ret;
1972 rcu_read_lock();
1973 data = rcu_dereference(counter->data);
1974 if (!data)
1975 goto unlock;
1977 if (vmf->pgoff == 0) {
1978 vmf->page = virt_to_page(data->user_page);
1979 } else {
1980 int nr = vmf->pgoff - 1;
1982 if ((unsigned)nr > data->nr_pages)
1983 goto unlock;
1985 if (vmf->flags & FAULT_FLAG_WRITE)
1986 goto unlock;
1988 vmf->page = virt_to_page(data->data_pages[nr]);
1991 get_page(vmf->page);
1992 vmf->page->mapping = vma->vm_file->f_mapping;
1993 vmf->page->index = vmf->pgoff;
1995 ret = 0;
1996 unlock:
1997 rcu_read_unlock();
1999 return ret;
2002 static int perf_mmap_data_alloc(struct perf_counter *counter, int nr_pages)
2004 struct perf_mmap_data *data;
2005 unsigned long size;
2006 int i;
2008 WARN_ON(atomic_read(&counter->mmap_count));
2010 size = sizeof(struct perf_mmap_data);
2011 size += nr_pages * sizeof(void *);
2013 data = kzalloc(size, GFP_KERNEL);
2014 if (!data)
2015 goto fail;
2017 data->user_page = (void *)get_zeroed_page(GFP_KERNEL);
2018 if (!data->user_page)
2019 goto fail_user_page;
2021 for (i = 0; i < nr_pages; i++) {
2022 data->data_pages[i] = (void *)get_zeroed_page(GFP_KERNEL);
2023 if (!data->data_pages[i])
2024 goto fail_data_pages;
2027 data->nr_pages = nr_pages;
2028 atomic_set(&data->lock, -1);
2030 rcu_assign_pointer(counter->data, data);
2032 return 0;
2034 fail_data_pages:
2035 for (i--; i >= 0; i--)
2036 free_page((unsigned long)data->data_pages[i]);
2038 free_page((unsigned long)data->user_page);
2040 fail_user_page:
2041 kfree(data);
2043 fail:
2044 return -ENOMEM;
2047 static void perf_mmap_free_page(unsigned long addr)
2049 struct page *page = virt_to_page((void *)addr);
2051 page->mapping = NULL;
2052 __free_page(page);
2055 static void __perf_mmap_data_free(struct rcu_head *rcu_head)
2057 struct perf_mmap_data *data;
2058 int i;
2060 data = container_of(rcu_head, struct perf_mmap_data, rcu_head);
2062 perf_mmap_free_page((unsigned long)data->user_page);
2063 for (i = 0; i < data->nr_pages; i++)
2064 perf_mmap_free_page((unsigned long)data->data_pages[i]);
2066 kfree(data);
2069 static void perf_mmap_data_free(struct perf_counter *counter)
2071 struct perf_mmap_data *data = counter->data;
2073 WARN_ON(atomic_read(&counter->mmap_count));
2075 rcu_assign_pointer(counter->data, NULL);
2076 call_rcu(&data->rcu_head, __perf_mmap_data_free);
2079 static void perf_mmap_open(struct vm_area_struct *vma)
2081 struct perf_counter *counter = vma->vm_file->private_data;
2083 atomic_inc(&counter->mmap_count);
2086 static void perf_mmap_close(struct vm_area_struct *vma)
2088 struct perf_counter *counter = vma->vm_file->private_data;
2090 WARN_ON_ONCE(counter->ctx->parent_ctx);
2091 if (atomic_dec_and_mutex_lock(&counter->mmap_count, &counter->mmap_mutex)) {
2092 struct user_struct *user = current_user();
2094 atomic_long_sub(counter->data->nr_pages + 1, &user->locked_vm);
2095 vma->vm_mm->locked_vm -= counter->data->nr_locked;
2096 perf_mmap_data_free(counter);
2097 mutex_unlock(&counter->mmap_mutex);
2101 static struct vm_operations_struct perf_mmap_vmops = {
2102 .open = perf_mmap_open,
2103 .close = perf_mmap_close,
2104 .fault = perf_mmap_fault,
2105 .page_mkwrite = perf_mmap_fault,
2108 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
2110 struct perf_counter *counter = file->private_data;
2111 unsigned long user_locked, user_lock_limit;
2112 struct user_struct *user = current_user();
2113 unsigned long locked, lock_limit;
2114 unsigned long vma_size;
2115 unsigned long nr_pages;
2116 long user_extra, extra;
2117 int ret = 0;
2119 if (!(vma->vm_flags & VM_SHARED))
2120 return -EINVAL;
2122 vma_size = vma->vm_end - vma->vm_start;
2123 nr_pages = (vma_size / PAGE_SIZE) - 1;
2126 * If we have data pages ensure they're a power-of-two number, so we
2127 * can do bitmasks instead of modulo.
2129 if (nr_pages != 0 && !is_power_of_2(nr_pages))
2130 return -EINVAL;
2132 if (vma_size != PAGE_SIZE * (1 + nr_pages))
2133 return -EINVAL;
2135 if (vma->vm_pgoff != 0)
2136 return -EINVAL;
2138 WARN_ON_ONCE(counter->ctx->parent_ctx);
2139 mutex_lock(&counter->mmap_mutex);
2140 if (atomic_inc_not_zero(&counter->mmap_count)) {
2141 if (nr_pages != counter->data->nr_pages)
2142 ret = -EINVAL;
2143 goto unlock;
2146 user_extra = nr_pages + 1;
2147 user_lock_limit = sysctl_perf_counter_mlock >> (PAGE_SHIFT - 10);
2150 * Increase the limit linearly with more CPUs:
2152 user_lock_limit *= num_online_cpus();
2154 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
2156 extra = 0;
2157 if (user_locked > user_lock_limit)
2158 extra = user_locked - user_lock_limit;
2160 lock_limit = current->signal->rlim[RLIMIT_MEMLOCK].rlim_cur;
2161 lock_limit >>= PAGE_SHIFT;
2162 locked = vma->vm_mm->locked_vm + extra;
2164 if ((locked > lock_limit) && !capable(CAP_IPC_LOCK)) {
2165 ret = -EPERM;
2166 goto unlock;
2169 WARN_ON(counter->data);
2170 ret = perf_mmap_data_alloc(counter, nr_pages);
2171 if (ret)
2172 goto unlock;
2174 atomic_set(&counter->mmap_count, 1);
2175 atomic_long_add(user_extra, &user->locked_vm);
2176 vma->vm_mm->locked_vm += extra;
2177 counter->data->nr_locked = extra;
2178 if (vma->vm_flags & VM_WRITE)
2179 counter->data->writable = 1;
2181 unlock:
2182 mutex_unlock(&counter->mmap_mutex);
2184 vma->vm_flags |= VM_RESERVED;
2185 vma->vm_ops = &perf_mmap_vmops;
2187 return ret;
2190 static int perf_fasync(int fd, struct file *filp, int on)
2192 struct inode *inode = filp->f_path.dentry->d_inode;
2193 struct perf_counter *counter = filp->private_data;
2194 int retval;
2196 mutex_lock(&inode->i_mutex);
2197 retval = fasync_helper(fd, filp, on, &counter->fasync);
2198 mutex_unlock(&inode->i_mutex);
2200 if (retval < 0)
2201 return retval;
2203 return 0;
2206 static const struct file_operations perf_fops = {
2207 .release = perf_release,
2208 .read = perf_read,
2209 .poll = perf_poll,
2210 .unlocked_ioctl = perf_ioctl,
2211 .compat_ioctl = perf_ioctl,
2212 .mmap = perf_mmap,
2213 .fasync = perf_fasync,
2217 * Perf counter wakeup
2219 * If there's data, ensure we set the poll() state and publish everything
2220 * to user-space before waking everybody up.
2223 void perf_counter_wakeup(struct perf_counter *counter)
2225 wake_up_all(&counter->waitq);
2227 if (counter->pending_kill) {
2228 kill_fasync(&counter->fasync, SIGIO, counter->pending_kill);
2229 counter->pending_kill = 0;
2234 * Pending wakeups
2236 * Handle the case where we need to wakeup up from NMI (or rq->lock) context.
2238 * The NMI bit means we cannot possibly take locks. Therefore, maintain a
2239 * single linked list and use cmpxchg() to add entries lockless.
2242 static void perf_pending_counter(struct perf_pending_entry *entry)
2244 struct perf_counter *counter = container_of(entry,
2245 struct perf_counter, pending);
2247 if (counter->pending_disable) {
2248 counter->pending_disable = 0;
2249 perf_counter_disable(counter);
2252 if (counter->pending_wakeup) {
2253 counter->pending_wakeup = 0;
2254 perf_counter_wakeup(counter);
2258 #define PENDING_TAIL ((struct perf_pending_entry *)-1UL)
2260 static DEFINE_PER_CPU(struct perf_pending_entry *, perf_pending_head) = {
2261 PENDING_TAIL,
2264 static void perf_pending_queue(struct perf_pending_entry *entry,
2265 void (*func)(struct perf_pending_entry *))
2267 struct perf_pending_entry **head;
2269 if (cmpxchg(&entry->next, NULL, PENDING_TAIL) != NULL)
2270 return;
2272 entry->func = func;
2274 head = &get_cpu_var(perf_pending_head);
2276 do {
2277 entry->next = *head;
2278 } while (cmpxchg(head, entry->next, entry) != entry->next);
2280 set_perf_counter_pending();
2282 put_cpu_var(perf_pending_head);
2285 static int __perf_pending_run(void)
2287 struct perf_pending_entry *list;
2288 int nr = 0;
2290 list = xchg(&__get_cpu_var(perf_pending_head), PENDING_TAIL);
2291 while (list != PENDING_TAIL) {
2292 void (*func)(struct perf_pending_entry *);
2293 struct perf_pending_entry *entry = list;
2295 list = list->next;
2297 func = entry->func;
2298 entry->next = NULL;
2300 * Ensure we observe the unqueue before we issue the wakeup,
2301 * so that we won't be waiting forever.
2302 * -- see perf_not_pending().
2304 smp_wmb();
2306 func(entry);
2307 nr++;
2310 return nr;
2313 static inline int perf_not_pending(struct perf_counter *counter)
2316 * If we flush on whatever cpu we run, there is a chance we don't
2317 * need to wait.
2319 get_cpu();
2320 __perf_pending_run();
2321 put_cpu();
2324 * Ensure we see the proper queue state before going to sleep
2325 * so that we do not miss the wakeup. -- see perf_pending_handle()
2327 smp_rmb();
2328 return counter->pending.next == NULL;
2331 static void perf_pending_sync(struct perf_counter *counter)
2333 wait_event(counter->waitq, perf_not_pending(counter));
2336 void perf_counter_do_pending(void)
2338 __perf_pending_run();
2342 * Callchain support -- arch specific
2345 __weak struct perf_callchain_entry *perf_callchain(struct pt_regs *regs)
2347 return NULL;
2351 * Output
2354 struct perf_output_handle {
2355 struct perf_counter *counter;
2356 struct perf_mmap_data *data;
2357 unsigned long head;
2358 unsigned long offset;
2359 int nmi;
2360 int sample;
2361 int locked;
2362 unsigned long flags;
2365 static bool perf_output_space(struct perf_mmap_data *data,
2366 unsigned int offset, unsigned int head)
2368 unsigned long tail;
2369 unsigned long mask;
2371 if (!data->writable)
2372 return true;
2374 mask = (data->nr_pages << PAGE_SHIFT) - 1;
2376 * Userspace could choose to issue a mb() before updating the tail
2377 * pointer. So that all reads will be completed before the write is
2378 * issued.
2380 tail = ACCESS_ONCE(data->user_page->data_tail);
2381 smp_rmb();
2383 offset = (offset - tail) & mask;
2384 head = (head - tail) & mask;
2386 if ((int)(head - offset) < 0)
2387 return false;
2389 return true;
2392 static void perf_output_wakeup(struct perf_output_handle *handle)
2394 atomic_set(&handle->data->poll, POLL_IN);
2396 if (handle->nmi) {
2397 handle->counter->pending_wakeup = 1;
2398 perf_pending_queue(&handle->counter->pending,
2399 perf_pending_counter);
2400 } else
2401 perf_counter_wakeup(handle->counter);
2405 * Curious locking construct.
2407 * We need to ensure a later event doesn't publish a head when a former
2408 * event isn't done writing. However since we need to deal with NMIs we
2409 * cannot fully serialize things.
2411 * What we do is serialize between CPUs so we only have to deal with NMI
2412 * nesting on a single CPU.
2414 * We only publish the head (and generate a wakeup) when the outer-most
2415 * event completes.
2417 static void perf_output_lock(struct perf_output_handle *handle)
2419 struct perf_mmap_data *data = handle->data;
2420 int cpu;
2422 handle->locked = 0;
2424 local_irq_save(handle->flags);
2425 cpu = smp_processor_id();
2427 if (in_nmi() && atomic_read(&data->lock) == cpu)
2428 return;
2430 while (atomic_cmpxchg(&data->lock, -1, cpu) != -1)
2431 cpu_relax();
2433 handle->locked = 1;
2436 static void perf_output_unlock(struct perf_output_handle *handle)
2438 struct perf_mmap_data *data = handle->data;
2439 unsigned long head;
2440 int cpu;
2442 data->done_head = data->head;
2444 if (!handle->locked)
2445 goto out;
2447 again:
2449 * The xchg implies a full barrier that ensures all writes are done
2450 * before we publish the new head, matched by a rmb() in userspace when
2451 * reading this position.
2453 while ((head = atomic_long_xchg(&data->done_head, 0)))
2454 data->user_page->data_head = head;
2457 * NMI can happen here, which means we can miss a done_head update.
2460 cpu = atomic_xchg(&data->lock, -1);
2461 WARN_ON_ONCE(cpu != smp_processor_id());
2464 * Therefore we have to validate we did not indeed do so.
2466 if (unlikely(atomic_long_read(&data->done_head))) {
2468 * Since we had it locked, we can lock it again.
2470 while (atomic_cmpxchg(&data->lock, -1, cpu) != -1)
2471 cpu_relax();
2473 goto again;
2476 if (atomic_xchg(&data->wakeup, 0))
2477 perf_output_wakeup(handle);
2478 out:
2479 local_irq_restore(handle->flags);
2482 static void perf_output_copy(struct perf_output_handle *handle,
2483 const void *buf, unsigned int len)
2485 unsigned int pages_mask;
2486 unsigned int offset;
2487 unsigned int size;
2488 void **pages;
2490 offset = handle->offset;
2491 pages_mask = handle->data->nr_pages - 1;
2492 pages = handle->data->data_pages;
2494 do {
2495 unsigned int page_offset;
2496 int nr;
2498 nr = (offset >> PAGE_SHIFT) & pages_mask;
2499 page_offset = offset & (PAGE_SIZE - 1);
2500 size = min_t(unsigned int, PAGE_SIZE - page_offset, len);
2502 memcpy(pages[nr] + page_offset, buf, size);
2504 len -= size;
2505 buf += size;
2506 offset += size;
2507 } while (len);
2509 handle->offset = offset;
2512 * Check we didn't copy past our reservation window, taking the
2513 * possible unsigned int wrap into account.
2515 WARN_ON_ONCE(((long)(handle->head - handle->offset)) < 0);
2518 #define perf_output_put(handle, x) \
2519 perf_output_copy((handle), &(x), sizeof(x))
2521 static int perf_output_begin(struct perf_output_handle *handle,
2522 struct perf_counter *counter, unsigned int size,
2523 int nmi, int sample)
2525 struct perf_mmap_data *data;
2526 unsigned int offset, head;
2527 int have_lost;
2528 struct {
2529 struct perf_event_header header;
2530 u64 id;
2531 u64 lost;
2532 } lost_event;
2535 * For inherited counters we send all the output towards the parent.
2537 if (counter->parent)
2538 counter = counter->parent;
2540 rcu_read_lock();
2541 data = rcu_dereference(counter->data);
2542 if (!data)
2543 goto out;
2545 handle->data = data;
2546 handle->counter = counter;
2547 handle->nmi = nmi;
2548 handle->sample = sample;
2550 if (!data->nr_pages)
2551 goto fail;
2553 have_lost = atomic_read(&data->lost);
2554 if (have_lost)
2555 size += sizeof(lost_event);
2557 perf_output_lock(handle);
2559 do {
2560 offset = head = atomic_long_read(&data->head);
2561 head += size;
2562 if (unlikely(!perf_output_space(data, offset, head)))
2563 goto fail;
2564 } while (atomic_long_cmpxchg(&data->head, offset, head) != offset);
2566 handle->offset = offset;
2567 handle->head = head;
2569 if ((offset >> PAGE_SHIFT) != (head >> PAGE_SHIFT))
2570 atomic_set(&data->wakeup, 1);
2572 if (have_lost) {
2573 lost_event.header.type = PERF_EVENT_LOST;
2574 lost_event.header.misc = 0;
2575 lost_event.header.size = sizeof(lost_event);
2576 lost_event.id = counter->id;
2577 lost_event.lost = atomic_xchg(&data->lost, 0);
2579 perf_output_put(handle, lost_event);
2582 return 0;
2584 fail:
2585 atomic_inc(&data->lost);
2586 perf_output_unlock(handle);
2587 out:
2588 rcu_read_unlock();
2590 return -ENOSPC;
2593 static void perf_output_end(struct perf_output_handle *handle)
2595 struct perf_counter *counter = handle->counter;
2596 struct perf_mmap_data *data = handle->data;
2598 int wakeup_events = counter->attr.wakeup_events;
2600 if (handle->sample && wakeup_events) {
2601 int events = atomic_inc_return(&data->events);
2602 if (events >= wakeup_events) {
2603 atomic_sub(wakeup_events, &data->events);
2604 atomic_set(&data->wakeup, 1);
2608 perf_output_unlock(handle);
2609 rcu_read_unlock();
2612 static u32 perf_counter_pid(struct perf_counter *counter, struct task_struct *p)
2615 * only top level counters have the pid namespace they were created in
2617 if (counter->parent)
2618 counter = counter->parent;
2620 return task_tgid_nr_ns(p, counter->ns);
2623 static u32 perf_counter_tid(struct perf_counter *counter, struct task_struct *p)
2626 * only top level counters have the pid namespace they were created in
2628 if (counter->parent)
2629 counter = counter->parent;
2631 return task_pid_nr_ns(p, counter->ns);
2634 void perf_counter_output(struct perf_counter *counter, int nmi,
2635 struct perf_sample_data *data)
2637 int ret;
2638 u64 sample_type = counter->attr.sample_type;
2639 struct perf_output_handle handle;
2640 struct perf_event_header header;
2641 u64 ip;
2642 struct {
2643 u32 pid, tid;
2644 } tid_entry;
2645 struct {
2646 u64 id;
2647 u64 counter;
2648 } group_entry;
2649 struct perf_callchain_entry *callchain = NULL;
2650 int callchain_size = 0;
2651 u64 time;
2652 struct {
2653 u32 cpu, reserved;
2654 } cpu_entry;
2656 header.type = PERF_EVENT_SAMPLE;
2657 header.size = sizeof(header);
2659 header.misc = 0;
2660 header.misc |= perf_misc_flags(data->regs);
2662 if (sample_type & PERF_SAMPLE_IP) {
2663 ip = perf_instruction_pointer(data->regs);
2664 header.size += sizeof(ip);
2667 if (sample_type & PERF_SAMPLE_TID) {
2668 /* namespace issues */
2669 tid_entry.pid = perf_counter_pid(counter, current);
2670 tid_entry.tid = perf_counter_tid(counter, current);
2672 header.size += sizeof(tid_entry);
2675 if (sample_type & PERF_SAMPLE_TIME) {
2677 * Maybe do better on x86 and provide cpu_clock_nmi()
2679 time = sched_clock();
2681 header.size += sizeof(u64);
2684 if (sample_type & PERF_SAMPLE_ADDR)
2685 header.size += sizeof(u64);
2687 if (sample_type & PERF_SAMPLE_ID)
2688 header.size += sizeof(u64);
2690 if (sample_type & PERF_SAMPLE_STREAM_ID)
2691 header.size += sizeof(u64);
2693 if (sample_type & PERF_SAMPLE_CPU) {
2694 header.size += sizeof(cpu_entry);
2696 cpu_entry.cpu = raw_smp_processor_id();
2697 cpu_entry.reserved = 0;
2700 if (sample_type & PERF_SAMPLE_PERIOD)
2701 header.size += sizeof(u64);
2703 if (sample_type & PERF_SAMPLE_GROUP) {
2704 header.size += sizeof(u64) +
2705 counter->nr_siblings * sizeof(group_entry);
2708 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
2709 callchain = perf_callchain(data->regs);
2711 if (callchain) {
2712 callchain_size = (1 + callchain->nr) * sizeof(u64);
2713 header.size += callchain_size;
2714 } else
2715 header.size += sizeof(u64);
2718 if (sample_type & PERF_SAMPLE_RAW) {
2719 int size = sizeof(u32);
2721 if (data->raw)
2722 size += data->raw->size;
2723 else
2724 size += sizeof(u32);
2726 WARN_ON_ONCE(size & (sizeof(u64)-1));
2727 header.size += size;
2730 ret = perf_output_begin(&handle, counter, header.size, nmi, 1);
2731 if (ret)
2732 return;
2734 perf_output_put(&handle, header);
2736 if (sample_type & PERF_SAMPLE_IP)
2737 perf_output_put(&handle, ip);
2739 if (sample_type & PERF_SAMPLE_TID)
2740 perf_output_put(&handle, tid_entry);
2742 if (sample_type & PERF_SAMPLE_TIME)
2743 perf_output_put(&handle, time);
2745 if (sample_type & PERF_SAMPLE_ADDR)
2746 perf_output_put(&handle, data->addr);
2748 if (sample_type & PERF_SAMPLE_ID) {
2749 u64 id = primary_counter_id(counter);
2751 perf_output_put(&handle, id);
2754 if (sample_type & PERF_SAMPLE_STREAM_ID)
2755 perf_output_put(&handle, counter->id);
2757 if (sample_type & PERF_SAMPLE_CPU)
2758 perf_output_put(&handle, cpu_entry);
2760 if (sample_type & PERF_SAMPLE_PERIOD)
2761 perf_output_put(&handle, data->period);
2764 * XXX PERF_SAMPLE_GROUP vs inherited counters seems difficult.
2766 if (sample_type & PERF_SAMPLE_GROUP) {
2767 struct perf_counter *leader, *sub;
2768 u64 nr = counter->nr_siblings;
2770 perf_output_put(&handle, nr);
2772 leader = counter->group_leader;
2773 list_for_each_entry(sub, &leader->sibling_list, list_entry) {
2774 if (sub != counter)
2775 sub->pmu->read(sub);
2777 group_entry.id = primary_counter_id(sub);
2778 group_entry.counter = atomic64_read(&sub->count);
2780 perf_output_put(&handle, group_entry);
2784 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
2785 if (callchain)
2786 perf_output_copy(&handle, callchain, callchain_size);
2787 else {
2788 u64 nr = 0;
2789 perf_output_put(&handle, nr);
2793 if (sample_type & PERF_SAMPLE_RAW) {
2794 if (data->raw) {
2795 perf_output_put(&handle, data->raw->size);
2796 perf_output_copy(&handle, data->raw->data, data->raw->size);
2797 } else {
2798 struct {
2799 u32 size;
2800 u32 data;
2801 } raw = {
2802 .size = sizeof(u32),
2803 .data = 0,
2805 perf_output_put(&handle, raw);
2809 perf_output_end(&handle);
2813 * read event
2816 struct perf_read_event {
2817 struct perf_event_header header;
2819 u32 pid;
2820 u32 tid;
2821 u64 value;
2822 u64 format[3];
2825 static void
2826 perf_counter_read_event(struct perf_counter *counter,
2827 struct task_struct *task)
2829 struct perf_output_handle handle;
2830 struct perf_read_event event = {
2831 .header = {
2832 .type = PERF_EVENT_READ,
2833 .misc = 0,
2834 .size = sizeof(event) - sizeof(event.format),
2836 .pid = perf_counter_pid(counter, task),
2837 .tid = perf_counter_tid(counter, task),
2838 .value = atomic64_read(&counter->count),
2840 int ret, i = 0;
2842 if (counter->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
2843 event.header.size += sizeof(u64);
2844 event.format[i++] = counter->total_time_enabled;
2847 if (counter->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
2848 event.header.size += sizeof(u64);
2849 event.format[i++] = counter->total_time_running;
2852 if (counter->attr.read_format & PERF_FORMAT_ID) {
2853 event.header.size += sizeof(u64);
2854 event.format[i++] = primary_counter_id(counter);
2857 ret = perf_output_begin(&handle, counter, event.header.size, 0, 0);
2858 if (ret)
2859 return;
2861 perf_output_copy(&handle, &event, event.header.size);
2862 perf_output_end(&handle);
2866 * task tracking -- fork/exit
2868 * enabled by: attr.comm | attr.mmap | attr.task
2871 struct perf_task_event {
2872 struct task_struct *task;
2873 struct perf_counter_context *task_ctx;
2875 struct {
2876 struct perf_event_header header;
2878 u32 pid;
2879 u32 ppid;
2880 u32 tid;
2881 u32 ptid;
2882 } event;
2885 static void perf_counter_task_output(struct perf_counter *counter,
2886 struct perf_task_event *task_event)
2888 struct perf_output_handle handle;
2889 int size = task_event->event.header.size;
2890 struct task_struct *task = task_event->task;
2891 int ret = perf_output_begin(&handle, counter, size, 0, 0);
2893 if (ret)
2894 return;
2896 task_event->event.pid = perf_counter_pid(counter, task);
2897 task_event->event.ppid = perf_counter_pid(counter, task->real_parent);
2899 task_event->event.tid = perf_counter_tid(counter, task);
2900 task_event->event.ptid = perf_counter_tid(counter, task->real_parent);
2902 perf_output_put(&handle, task_event->event);
2903 perf_output_end(&handle);
2906 static int perf_counter_task_match(struct perf_counter *counter)
2908 if (counter->attr.comm || counter->attr.mmap || counter->attr.task)
2909 return 1;
2911 return 0;
2914 static void perf_counter_task_ctx(struct perf_counter_context *ctx,
2915 struct perf_task_event *task_event)
2917 struct perf_counter *counter;
2919 if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
2920 return;
2922 rcu_read_lock();
2923 list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
2924 if (perf_counter_task_match(counter))
2925 perf_counter_task_output(counter, task_event);
2927 rcu_read_unlock();
2930 static void perf_counter_task_event(struct perf_task_event *task_event)
2932 struct perf_cpu_context *cpuctx;
2933 struct perf_counter_context *ctx = task_event->task_ctx;
2935 cpuctx = &get_cpu_var(perf_cpu_context);
2936 perf_counter_task_ctx(&cpuctx->ctx, task_event);
2937 put_cpu_var(perf_cpu_context);
2939 rcu_read_lock();
2940 if (!ctx)
2941 ctx = rcu_dereference(task_event->task->perf_counter_ctxp);
2942 if (ctx)
2943 perf_counter_task_ctx(ctx, task_event);
2944 rcu_read_unlock();
2947 static void perf_counter_task(struct task_struct *task,
2948 struct perf_counter_context *task_ctx,
2949 int new)
2951 struct perf_task_event task_event;
2953 if (!atomic_read(&nr_comm_counters) &&
2954 !atomic_read(&nr_mmap_counters) &&
2955 !atomic_read(&nr_task_counters))
2956 return;
2958 task_event = (struct perf_task_event){
2959 .task = task,
2960 .task_ctx = task_ctx,
2961 .event = {
2962 .header = {
2963 .type = new ? PERF_EVENT_FORK : PERF_EVENT_EXIT,
2964 .misc = 0,
2965 .size = sizeof(task_event.event),
2967 /* .pid */
2968 /* .ppid */
2969 /* .tid */
2970 /* .ptid */
2974 perf_counter_task_event(&task_event);
2977 void perf_counter_fork(struct task_struct *task)
2979 perf_counter_task(task, NULL, 1);
2983 * comm tracking
2986 struct perf_comm_event {
2987 struct task_struct *task;
2988 char *comm;
2989 int comm_size;
2991 struct {
2992 struct perf_event_header header;
2994 u32 pid;
2995 u32 tid;
2996 } event;
2999 static void perf_counter_comm_output(struct perf_counter *counter,
3000 struct perf_comm_event *comm_event)
3002 struct perf_output_handle handle;
3003 int size = comm_event->event.header.size;
3004 int ret = perf_output_begin(&handle, counter, size, 0, 0);
3006 if (ret)
3007 return;
3009 comm_event->event.pid = perf_counter_pid(counter, comm_event->task);
3010 comm_event->event.tid = perf_counter_tid(counter, comm_event->task);
3012 perf_output_put(&handle, comm_event->event);
3013 perf_output_copy(&handle, comm_event->comm,
3014 comm_event->comm_size);
3015 perf_output_end(&handle);
3018 static int perf_counter_comm_match(struct perf_counter *counter)
3020 if (counter->attr.comm)
3021 return 1;
3023 return 0;
3026 static void perf_counter_comm_ctx(struct perf_counter_context *ctx,
3027 struct perf_comm_event *comm_event)
3029 struct perf_counter *counter;
3031 if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
3032 return;
3034 rcu_read_lock();
3035 list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
3036 if (perf_counter_comm_match(counter))
3037 perf_counter_comm_output(counter, comm_event);
3039 rcu_read_unlock();
3042 static void perf_counter_comm_event(struct perf_comm_event *comm_event)
3044 struct perf_cpu_context *cpuctx;
3045 struct perf_counter_context *ctx;
3046 unsigned int size;
3047 char comm[TASK_COMM_LEN];
3049 memset(comm, 0, sizeof(comm));
3050 strncpy(comm, comm_event->task->comm, sizeof(comm));
3051 size = ALIGN(strlen(comm)+1, sizeof(u64));
3053 comm_event->comm = comm;
3054 comm_event->comm_size = size;
3056 comm_event->event.header.size = sizeof(comm_event->event) + size;
3058 cpuctx = &get_cpu_var(perf_cpu_context);
3059 perf_counter_comm_ctx(&cpuctx->ctx, comm_event);
3060 put_cpu_var(perf_cpu_context);
3062 rcu_read_lock();
3064 * doesn't really matter which of the child contexts the
3065 * events ends up in.
3067 ctx = rcu_dereference(current->perf_counter_ctxp);
3068 if (ctx)
3069 perf_counter_comm_ctx(ctx, comm_event);
3070 rcu_read_unlock();
3073 void perf_counter_comm(struct task_struct *task)
3075 struct perf_comm_event comm_event;
3077 if (task->perf_counter_ctxp)
3078 perf_counter_enable_on_exec(task);
3080 if (!atomic_read(&nr_comm_counters))
3081 return;
3083 comm_event = (struct perf_comm_event){
3084 .task = task,
3085 /* .comm */
3086 /* .comm_size */
3087 .event = {
3088 .header = {
3089 .type = PERF_EVENT_COMM,
3090 .misc = 0,
3091 /* .size */
3093 /* .pid */
3094 /* .tid */
3098 perf_counter_comm_event(&comm_event);
3102 * mmap tracking
3105 struct perf_mmap_event {
3106 struct vm_area_struct *vma;
3108 const char *file_name;
3109 int file_size;
3111 struct {
3112 struct perf_event_header header;
3114 u32 pid;
3115 u32 tid;
3116 u64 start;
3117 u64 len;
3118 u64 pgoff;
3119 } event;
3122 static void perf_counter_mmap_output(struct perf_counter *counter,
3123 struct perf_mmap_event *mmap_event)
3125 struct perf_output_handle handle;
3126 int size = mmap_event->event.header.size;
3127 int ret = perf_output_begin(&handle, counter, size, 0, 0);
3129 if (ret)
3130 return;
3132 mmap_event->event.pid = perf_counter_pid(counter, current);
3133 mmap_event->event.tid = perf_counter_tid(counter, current);
3135 perf_output_put(&handle, mmap_event->event);
3136 perf_output_copy(&handle, mmap_event->file_name,
3137 mmap_event->file_size);
3138 perf_output_end(&handle);
3141 static int perf_counter_mmap_match(struct perf_counter *counter,
3142 struct perf_mmap_event *mmap_event)
3144 if (counter->attr.mmap)
3145 return 1;
3147 return 0;
3150 static void perf_counter_mmap_ctx(struct perf_counter_context *ctx,
3151 struct perf_mmap_event *mmap_event)
3153 struct perf_counter *counter;
3155 if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
3156 return;
3158 rcu_read_lock();
3159 list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
3160 if (perf_counter_mmap_match(counter, mmap_event))
3161 perf_counter_mmap_output(counter, mmap_event);
3163 rcu_read_unlock();
3166 static void perf_counter_mmap_event(struct perf_mmap_event *mmap_event)
3168 struct perf_cpu_context *cpuctx;
3169 struct perf_counter_context *ctx;
3170 struct vm_area_struct *vma = mmap_event->vma;
3171 struct file *file = vma->vm_file;
3172 unsigned int size;
3173 char tmp[16];
3174 char *buf = NULL;
3175 const char *name;
3177 memset(tmp, 0, sizeof(tmp));
3179 if (file) {
3181 * d_path works from the end of the buffer backwards, so we
3182 * need to add enough zero bytes after the string to handle
3183 * the 64bit alignment we do later.
3185 buf = kzalloc(PATH_MAX + sizeof(u64), GFP_KERNEL);
3186 if (!buf) {
3187 name = strncpy(tmp, "//enomem", sizeof(tmp));
3188 goto got_name;
3190 name = d_path(&file->f_path, buf, PATH_MAX);
3191 if (IS_ERR(name)) {
3192 name = strncpy(tmp, "//toolong", sizeof(tmp));
3193 goto got_name;
3195 } else {
3196 if (arch_vma_name(mmap_event->vma)) {
3197 name = strncpy(tmp, arch_vma_name(mmap_event->vma),
3198 sizeof(tmp));
3199 goto got_name;
3202 if (!vma->vm_mm) {
3203 name = strncpy(tmp, "[vdso]", sizeof(tmp));
3204 goto got_name;
3207 name = strncpy(tmp, "//anon", sizeof(tmp));
3208 goto got_name;
3211 got_name:
3212 size = ALIGN(strlen(name)+1, sizeof(u64));
3214 mmap_event->file_name = name;
3215 mmap_event->file_size = size;
3217 mmap_event->event.header.size = sizeof(mmap_event->event) + size;
3219 cpuctx = &get_cpu_var(perf_cpu_context);
3220 perf_counter_mmap_ctx(&cpuctx->ctx, mmap_event);
3221 put_cpu_var(perf_cpu_context);
3223 rcu_read_lock();
3225 * doesn't really matter which of the child contexts the
3226 * events ends up in.
3228 ctx = rcu_dereference(current->perf_counter_ctxp);
3229 if (ctx)
3230 perf_counter_mmap_ctx(ctx, mmap_event);
3231 rcu_read_unlock();
3233 kfree(buf);
3236 void __perf_counter_mmap(struct vm_area_struct *vma)
3238 struct perf_mmap_event mmap_event;
3240 if (!atomic_read(&nr_mmap_counters))
3241 return;
3243 mmap_event = (struct perf_mmap_event){
3244 .vma = vma,
3245 /* .file_name */
3246 /* .file_size */
3247 .event = {
3248 .header = {
3249 .type = PERF_EVENT_MMAP,
3250 .misc = 0,
3251 /* .size */
3253 /* .pid */
3254 /* .tid */
3255 .start = vma->vm_start,
3256 .len = vma->vm_end - vma->vm_start,
3257 .pgoff = vma->vm_pgoff,
3261 perf_counter_mmap_event(&mmap_event);
3265 * IRQ throttle logging
3268 static void perf_log_throttle(struct perf_counter *counter, int enable)
3270 struct perf_output_handle handle;
3271 int ret;
3273 struct {
3274 struct perf_event_header header;
3275 u64 time;
3276 u64 id;
3277 u64 stream_id;
3278 } throttle_event = {
3279 .header = {
3280 .type = PERF_EVENT_THROTTLE,
3281 .misc = 0,
3282 .size = sizeof(throttle_event),
3284 .time = sched_clock(),
3285 .id = primary_counter_id(counter),
3286 .stream_id = counter->id,
3289 if (enable)
3290 throttle_event.header.type = PERF_EVENT_UNTHROTTLE;
3292 ret = perf_output_begin(&handle, counter, sizeof(throttle_event), 1, 0);
3293 if (ret)
3294 return;
3296 perf_output_put(&handle, throttle_event);
3297 perf_output_end(&handle);
3301 * Generic counter overflow handling, sampling.
3304 int perf_counter_overflow(struct perf_counter *counter, int nmi,
3305 struct perf_sample_data *data)
3307 int events = atomic_read(&counter->event_limit);
3308 int throttle = counter->pmu->unthrottle != NULL;
3309 struct hw_perf_counter *hwc = &counter->hw;
3310 int ret = 0;
3312 if (!throttle) {
3313 hwc->interrupts++;
3314 } else {
3315 if (hwc->interrupts != MAX_INTERRUPTS) {
3316 hwc->interrupts++;
3317 if (HZ * hwc->interrupts >
3318 (u64)sysctl_perf_counter_sample_rate) {
3319 hwc->interrupts = MAX_INTERRUPTS;
3320 perf_log_throttle(counter, 0);
3321 ret = 1;
3323 } else {
3325 * Keep re-disabling counters even though on the previous
3326 * pass we disabled it - just in case we raced with a
3327 * sched-in and the counter got enabled again:
3329 ret = 1;
3333 if (counter->attr.freq) {
3334 u64 now = sched_clock();
3335 s64 delta = now - hwc->freq_stamp;
3337 hwc->freq_stamp = now;
3339 if (delta > 0 && delta < TICK_NSEC)
3340 perf_adjust_period(counter, NSEC_PER_SEC / (int)delta);
3344 * XXX event_limit might not quite work as expected on inherited
3345 * counters
3348 counter->pending_kill = POLL_IN;
3349 if (events && atomic_dec_and_test(&counter->event_limit)) {
3350 ret = 1;
3351 counter->pending_kill = POLL_HUP;
3352 if (nmi) {
3353 counter->pending_disable = 1;
3354 perf_pending_queue(&counter->pending,
3355 perf_pending_counter);
3356 } else
3357 perf_counter_disable(counter);
3360 perf_counter_output(counter, nmi, data);
3361 return ret;
3365 * Generic software counter infrastructure
3369 * We directly increment counter->count and keep a second value in
3370 * counter->hw.period_left to count intervals. This period counter
3371 * is kept in the range [-sample_period, 0] so that we can use the
3372 * sign as trigger.
3375 static u64 perf_swcounter_set_period(struct perf_counter *counter)
3377 struct hw_perf_counter *hwc = &counter->hw;
3378 u64 period = hwc->last_period;
3379 u64 nr, offset;
3380 s64 old, val;
3382 hwc->last_period = hwc->sample_period;
3384 again:
3385 old = val = atomic64_read(&hwc->period_left);
3386 if (val < 0)
3387 return 0;
3389 nr = div64_u64(period + val, period);
3390 offset = nr * period;
3391 val -= offset;
3392 if (atomic64_cmpxchg(&hwc->period_left, old, val) != old)
3393 goto again;
3395 return nr;
3398 static void perf_swcounter_overflow(struct perf_counter *counter,
3399 int nmi, struct perf_sample_data *data)
3401 struct hw_perf_counter *hwc = &counter->hw;
3402 u64 overflow;
3404 data->period = counter->hw.last_period;
3405 overflow = perf_swcounter_set_period(counter);
3407 if (hwc->interrupts == MAX_INTERRUPTS)
3408 return;
3410 for (; overflow; overflow--) {
3411 if (perf_counter_overflow(counter, nmi, data)) {
3413 * We inhibit the overflow from happening when
3414 * hwc->interrupts == MAX_INTERRUPTS.
3416 break;
3421 static void perf_swcounter_unthrottle(struct perf_counter *counter)
3424 * Nothing to do, we already reset hwc->interrupts.
3428 static void perf_swcounter_add(struct perf_counter *counter, u64 nr,
3429 int nmi, struct perf_sample_data *data)
3431 struct hw_perf_counter *hwc = &counter->hw;
3433 atomic64_add(nr, &counter->count);
3435 if (!hwc->sample_period)
3436 return;
3438 if (!data->regs)
3439 return;
3441 if (!atomic64_add_negative(nr, &hwc->period_left))
3442 perf_swcounter_overflow(counter, nmi, data);
3445 static int perf_swcounter_is_counting(struct perf_counter *counter)
3448 * The counter is active, we're good!
3450 if (counter->state == PERF_COUNTER_STATE_ACTIVE)
3451 return 1;
3454 * The counter is off/error, not counting.
3456 if (counter->state != PERF_COUNTER_STATE_INACTIVE)
3457 return 0;
3460 * The counter is inactive, if the context is active
3461 * we're part of a group that didn't make it on the 'pmu',
3462 * not counting.
3464 if (counter->ctx->is_active)
3465 return 0;
3468 * We're inactive and the context is too, this means the
3469 * task is scheduled out, we're counting events that happen
3470 * to us, like migration events.
3472 return 1;
3475 static int perf_swcounter_match(struct perf_counter *counter,
3476 enum perf_type_id type,
3477 u32 event, struct pt_regs *regs)
3479 if (!perf_swcounter_is_counting(counter))
3480 return 0;
3482 if (counter->attr.type != type)
3483 return 0;
3484 if (counter->attr.config != event)
3485 return 0;
3487 if (regs) {
3488 if (counter->attr.exclude_user && user_mode(regs))
3489 return 0;
3491 if (counter->attr.exclude_kernel && !user_mode(regs))
3492 return 0;
3495 return 1;
3498 static void perf_swcounter_ctx_event(struct perf_counter_context *ctx,
3499 enum perf_type_id type,
3500 u32 event, u64 nr, int nmi,
3501 struct perf_sample_data *data)
3503 struct perf_counter *counter;
3505 if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
3506 return;
3508 rcu_read_lock();
3509 list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
3510 if (perf_swcounter_match(counter, type, event, data->regs))
3511 perf_swcounter_add(counter, nr, nmi, data);
3513 rcu_read_unlock();
3516 static int *perf_swcounter_recursion_context(struct perf_cpu_context *cpuctx)
3518 if (in_nmi())
3519 return &cpuctx->recursion[3];
3521 if (in_irq())
3522 return &cpuctx->recursion[2];
3524 if (in_softirq())
3525 return &cpuctx->recursion[1];
3527 return &cpuctx->recursion[0];
3530 static void do_perf_swcounter_event(enum perf_type_id type, u32 event,
3531 u64 nr, int nmi,
3532 struct perf_sample_data *data)
3534 struct perf_cpu_context *cpuctx = &get_cpu_var(perf_cpu_context);
3535 int *recursion = perf_swcounter_recursion_context(cpuctx);
3536 struct perf_counter_context *ctx;
3538 if (*recursion)
3539 goto out;
3541 (*recursion)++;
3542 barrier();
3544 perf_swcounter_ctx_event(&cpuctx->ctx, type, event,
3545 nr, nmi, data);
3546 rcu_read_lock();
3548 * doesn't really matter which of the child contexts the
3549 * events ends up in.
3551 ctx = rcu_dereference(current->perf_counter_ctxp);
3552 if (ctx)
3553 perf_swcounter_ctx_event(ctx, type, event, nr, nmi, data);
3554 rcu_read_unlock();
3556 barrier();
3557 (*recursion)--;
3559 out:
3560 put_cpu_var(perf_cpu_context);
3563 void __perf_swcounter_event(u32 event, u64 nr, int nmi,
3564 struct pt_regs *regs, u64 addr)
3566 struct perf_sample_data data = {
3567 .regs = regs,
3568 .addr = addr,
3571 do_perf_swcounter_event(PERF_TYPE_SOFTWARE, event, nr, nmi, &data);
3574 static void perf_swcounter_read(struct perf_counter *counter)
3578 static int perf_swcounter_enable(struct perf_counter *counter)
3580 struct hw_perf_counter *hwc = &counter->hw;
3582 if (hwc->sample_period) {
3583 hwc->last_period = hwc->sample_period;
3584 perf_swcounter_set_period(counter);
3586 return 0;
3589 static void perf_swcounter_disable(struct perf_counter *counter)
3593 static const struct pmu perf_ops_generic = {
3594 .enable = perf_swcounter_enable,
3595 .disable = perf_swcounter_disable,
3596 .read = perf_swcounter_read,
3597 .unthrottle = perf_swcounter_unthrottle,
3601 * hrtimer based swcounter callback
3604 static enum hrtimer_restart perf_swcounter_hrtimer(struct hrtimer *hrtimer)
3606 enum hrtimer_restart ret = HRTIMER_RESTART;
3607 struct perf_sample_data data;
3608 struct perf_counter *counter;
3609 u64 period;
3611 counter = container_of(hrtimer, struct perf_counter, hw.hrtimer);
3612 counter->pmu->read(counter);
3614 data.addr = 0;
3615 data.regs = get_irq_regs();
3617 * In case we exclude kernel IPs or are somehow not in interrupt
3618 * context, provide the next best thing, the user IP.
3620 if ((counter->attr.exclude_kernel || !data.regs) &&
3621 !counter->attr.exclude_user)
3622 data.regs = task_pt_regs(current);
3624 if (data.regs) {
3625 if (perf_counter_overflow(counter, 0, &data))
3626 ret = HRTIMER_NORESTART;
3629 period = max_t(u64, 10000, counter->hw.sample_period);
3630 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
3632 return ret;
3636 * Software counter: cpu wall time clock
3639 static void cpu_clock_perf_counter_update(struct perf_counter *counter)
3641 int cpu = raw_smp_processor_id();
3642 s64 prev;
3643 u64 now;
3645 now = cpu_clock(cpu);
3646 prev = atomic64_read(&counter->hw.prev_count);
3647 atomic64_set(&counter->hw.prev_count, now);
3648 atomic64_add(now - prev, &counter->count);
3651 static int cpu_clock_perf_counter_enable(struct perf_counter *counter)
3653 struct hw_perf_counter *hwc = &counter->hw;
3654 int cpu = raw_smp_processor_id();
3656 atomic64_set(&hwc->prev_count, cpu_clock(cpu));
3657 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3658 hwc->hrtimer.function = perf_swcounter_hrtimer;
3659 if (hwc->sample_period) {
3660 u64 period = max_t(u64, 10000, hwc->sample_period);
3661 __hrtimer_start_range_ns(&hwc->hrtimer,
3662 ns_to_ktime(period), 0,
3663 HRTIMER_MODE_REL, 0);
3666 return 0;
3669 static void cpu_clock_perf_counter_disable(struct perf_counter *counter)
3671 if (counter->hw.sample_period)
3672 hrtimer_cancel(&counter->hw.hrtimer);
3673 cpu_clock_perf_counter_update(counter);
3676 static void cpu_clock_perf_counter_read(struct perf_counter *counter)
3678 cpu_clock_perf_counter_update(counter);
3681 static const struct pmu perf_ops_cpu_clock = {
3682 .enable = cpu_clock_perf_counter_enable,
3683 .disable = cpu_clock_perf_counter_disable,
3684 .read = cpu_clock_perf_counter_read,
3688 * Software counter: task time clock
3691 static void task_clock_perf_counter_update(struct perf_counter *counter, u64 now)
3693 u64 prev;
3694 s64 delta;
3696 prev = atomic64_xchg(&counter->hw.prev_count, now);
3697 delta = now - prev;
3698 atomic64_add(delta, &counter->count);
3701 static int task_clock_perf_counter_enable(struct perf_counter *counter)
3703 struct hw_perf_counter *hwc = &counter->hw;
3704 u64 now;
3706 now = counter->ctx->time;
3708 atomic64_set(&hwc->prev_count, now);
3709 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3710 hwc->hrtimer.function = perf_swcounter_hrtimer;
3711 if (hwc->sample_period) {
3712 u64 period = max_t(u64, 10000, hwc->sample_period);
3713 __hrtimer_start_range_ns(&hwc->hrtimer,
3714 ns_to_ktime(period), 0,
3715 HRTIMER_MODE_REL, 0);
3718 return 0;
3721 static void task_clock_perf_counter_disable(struct perf_counter *counter)
3723 if (counter->hw.sample_period)
3724 hrtimer_cancel(&counter->hw.hrtimer);
3725 task_clock_perf_counter_update(counter, counter->ctx->time);
3729 static void task_clock_perf_counter_read(struct perf_counter *counter)
3731 u64 time;
3733 if (!in_nmi()) {
3734 update_context_time(counter->ctx);
3735 time = counter->ctx->time;
3736 } else {
3737 u64 now = perf_clock();
3738 u64 delta = now - counter->ctx->timestamp;
3739 time = counter->ctx->time + delta;
3742 task_clock_perf_counter_update(counter, time);
3745 static const struct pmu perf_ops_task_clock = {
3746 .enable = task_clock_perf_counter_enable,
3747 .disable = task_clock_perf_counter_disable,
3748 .read = task_clock_perf_counter_read,
3751 #ifdef CONFIG_EVENT_PROFILE
3752 void perf_tpcounter_event(int event_id, u64 addr, u64 count, void *record,
3753 int entry_size)
3755 struct perf_raw_record raw = {
3756 .size = entry_size,
3757 .data = record,
3760 struct perf_sample_data data = {
3761 .regs = get_irq_regs(),
3762 .addr = addr,
3763 .raw = &raw,
3766 if (!data.regs)
3767 data.regs = task_pt_regs(current);
3769 do_perf_swcounter_event(PERF_TYPE_TRACEPOINT, event_id, count, 1, &data);
3771 EXPORT_SYMBOL_GPL(perf_tpcounter_event);
3773 extern int ftrace_profile_enable(int);
3774 extern void ftrace_profile_disable(int);
3776 static void tp_perf_counter_destroy(struct perf_counter *counter)
3778 ftrace_profile_disable(counter->attr.config);
3781 static const struct pmu *tp_perf_counter_init(struct perf_counter *counter)
3784 * Raw tracepoint data is a severe data leak, only allow root to
3785 * have these.
3787 if ((counter->attr.sample_type & PERF_SAMPLE_RAW) &&
3788 !capable(CAP_SYS_ADMIN))
3789 return ERR_PTR(-EPERM);
3791 if (ftrace_profile_enable(counter->attr.config))
3792 return NULL;
3794 counter->destroy = tp_perf_counter_destroy;
3796 return &perf_ops_generic;
3798 #else
3799 static const struct pmu *tp_perf_counter_init(struct perf_counter *counter)
3801 return NULL;
3803 #endif
3805 atomic_t perf_swcounter_enabled[PERF_COUNT_SW_MAX];
3807 static void sw_perf_counter_destroy(struct perf_counter *counter)
3809 u64 event = counter->attr.config;
3811 WARN_ON(counter->parent);
3813 atomic_dec(&perf_swcounter_enabled[event]);
3816 static const struct pmu *sw_perf_counter_init(struct perf_counter *counter)
3818 const struct pmu *pmu = NULL;
3819 u64 event = counter->attr.config;
3822 * Software counters (currently) can't in general distinguish
3823 * between user, kernel and hypervisor events.
3824 * However, context switches and cpu migrations are considered
3825 * to be kernel events, and page faults are never hypervisor
3826 * events.
3828 switch (event) {
3829 case PERF_COUNT_SW_CPU_CLOCK:
3830 pmu = &perf_ops_cpu_clock;
3832 break;
3833 case PERF_COUNT_SW_TASK_CLOCK:
3835 * If the user instantiates this as a per-cpu counter,
3836 * use the cpu_clock counter instead.
3838 if (counter->ctx->task)
3839 pmu = &perf_ops_task_clock;
3840 else
3841 pmu = &perf_ops_cpu_clock;
3843 break;
3844 case PERF_COUNT_SW_PAGE_FAULTS:
3845 case PERF_COUNT_SW_PAGE_FAULTS_MIN:
3846 case PERF_COUNT_SW_PAGE_FAULTS_MAJ:
3847 case PERF_COUNT_SW_CONTEXT_SWITCHES:
3848 case PERF_COUNT_SW_CPU_MIGRATIONS:
3849 if (!counter->parent) {
3850 atomic_inc(&perf_swcounter_enabled[event]);
3851 counter->destroy = sw_perf_counter_destroy;
3853 pmu = &perf_ops_generic;
3854 break;
3857 return pmu;
3861 * Allocate and initialize a counter structure
3863 static struct perf_counter *
3864 perf_counter_alloc(struct perf_counter_attr *attr,
3865 int cpu,
3866 struct perf_counter_context *ctx,
3867 struct perf_counter *group_leader,
3868 struct perf_counter *parent_counter,
3869 gfp_t gfpflags)
3871 const struct pmu *pmu;
3872 struct perf_counter *counter;
3873 struct hw_perf_counter *hwc;
3874 long err;
3876 counter = kzalloc(sizeof(*counter), gfpflags);
3877 if (!counter)
3878 return ERR_PTR(-ENOMEM);
3881 * Single counters are their own group leaders, with an
3882 * empty sibling list:
3884 if (!group_leader)
3885 group_leader = counter;
3887 mutex_init(&counter->child_mutex);
3888 INIT_LIST_HEAD(&counter->child_list);
3890 INIT_LIST_HEAD(&counter->list_entry);
3891 INIT_LIST_HEAD(&counter->event_entry);
3892 INIT_LIST_HEAD(&counter->sibling_list);
3893 init_waitqueue_head(&counter->waitq);
3895 mutex_init(&counter->mmap_mutex);
3897 counter->cpu = cpu;
3898 counter->attr = *attr;
3899 counter->group_leader = group_leader;
3900 counter->pmu = NULL;
3901 counter->ctx = ctx;
3902 counter->oncpu = -1;
3904 counter->parent = parent_counter;
3906 counter->ns = get_pid_ns(current->nsproxy->pid_ns);
3907 counter->id = atomic64_inc_return(&perf_counter_id);
3909 counter->state = PERF_COUNTER_STATE_INACTIVE;
3911 if (attr->disabled)
3912 counter->state = PERF_COUNTER_STATE_OFF;
3914 pmu = NULL;
3916 hwc = &counter->hw;
3917 hwc->sample_period = attr->sample_period;
3918 if (attr->freq && attr->sample_freq)
3919 hwc->sample_period = 1;
3921 atomic64_set(&hwc->period_left, hwc->sample_period);
3924 * we currently do not support PERF_SAMPLE_GROUP on inherited counters
3926 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_GROUP))
3927 goto done;
3929 switch (attr->type) {
3930 case PERF_TYPE_RAW:
3931 case PERF_TYPE_HARDWARE:
3932 case PERF_TYPE_HW_CACHE:
3933 pmu = hw_perf_counter_init(counter);
3934 break;
3936 case PERF_TYPE_SOFTWARE:
3937 pmu = sw_perf_counter_init(counter);
3938 break;
3940 case PERF_TYPE_TRACEPOINT:
3941 pmu = tp_perf_counter_init(counter);
3942 break;
3944 default:
3945 break;
3947 done:
3948 err = 0;
3949 if (!pmu)
3950 err = -EINVAL;
3951 else if (IS_ERR(pmu))
3952 err = PTR_ERR(pmu);
3954 if (err) {
3955 if (counter->ns)
3956 put_pid_ns(counter->ns);
3957 kfree(counter);
3958 return ERR_PTR(err);
3961 counter->pmu = pmu;
3963 if (!counter->parent) {
3964 atomic_inc(&nr_counters);
3965 if (counter->attr.mmap)
3966 atomic_inc(&nr_mmap_counters);
3967 if (counter->attr.comm)
3968 atomic_inc(&nr_comm_counters);
3969 if (counter->attr.task)
3970 atomic_inc(&nr_task_counters);
3973 return counter;
3976 static int perf_copy_attr(struct perf_counter_attr __user *uattr,
3977 struct perf_counter_attr *attr)
3979 int ret;
3980 u32 size;
3982 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
3983 return -EFAULT;
3986 * zero the full structure, so that a short copy will be nice.
3988 memset(attr, 0, sizeof(*attr));
3990 ret = get_user(size, &uattr->size);
3991 if (ret)
3992 return ret;
3994 if (size > PAGE_SIZE) /* silly large */
3995 goto err_size;
3997 if (!size) /* abi compat */
3998 size = PERF_ATTR_SIZE_VER0;
4000 if (size < PERF_ATTR_SIZE_VER0)
4001 goto err_size;
4004 * If we're handed a bigger struct than we know of,
4005 * ensure all the unknown bits are 0.
4007 if (size > sizeof(*attr)) {
4008 unsigned long val;
4009 unsigned long __user *addr;
4010 unsigned long __user *end;
4012 addr = PTR_ALIGN((void __user *)uattr + sizeof(*attr),
4013 sizeof(unsigned long));
4014 end = PTR_ALIGN((void __user *)uattr + size,
4015 sizeof(unsigned long));
4017 for (; addr < end; addr += sizeof(unsigned long)) {
4018 ret = get_user(val, addr);
4019 if (ret)
4020 return ret;
4021 if (val)
4022 goto err_size;
4026 ret = copy_from_user(attr, uattr, size);
4027 if (ret)
4028 return -EFAULT;
4031 * If the type exists, the corresponding creation will verify
4032 * the attr->config.
4034 if (attr->type >= PERF_TYPE_MAX)
4035 return -EINVAL;
4037 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
4038 return -EINVAL;
4040 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
4041 return -EINVAL;
4043 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
4044 return -EINVAL;
4046 out:
4047 return ret;
4049 err_size:
4050 put_user(sizeof(*attr), &uattr->size);
4051 ret = -E2BIG;
4052 goto out;
4056 * sys_perf_counter_open - open a performance counter, associate it to a task/cpu
4058 * @attr_uptr: event type attributes for monitoring/sampling
4059 * @pid: target pid
4060 * @cpu: target cpu
4061 * @group_fd: group leader counter fd
4063 SYSCALL_DEFINE5(perf_counter_open,
4064 struct perf_counter_attr __user *, attr_uptr,
4065 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
4067 struct perf_counter *counter, *group_leader;
4068 struct perf_counter_attr attr;
4069 struct perf_counter_context *ctx;
4070 struct file *counter_file = NULL;
4071 struct file *group_file = NULL;
4072 int fput_needed = 0;
4073 int fput_needed2 = 0;
4074 int ret;
4076 /* for future expandability... */
4077 if (flags)
4078 return -EINVAL;
4080 ret = perf_copy_attr(attr_uptr, &attr);
4081 if (ret)
4082 return ret;
4084 if (!attr.exclude_kernel) {
4085 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
4086 return -EACCES;
4089 if (attr.freq) {
4090 if (attr.sample_freq > sysctl_perf_counter_sample_rate)
4091 return -EINVAL;
4095 * Get the target context (task or percpu):
4097 ctx = find_get_context(pid, cpu);
4098 if (IS_ERR(ctx))
4099 return PTR_ERR(ctx);
4102 * Look up the group leader (we will attach this counter to it):
4104 group_leader = NULL;
4105 if (group_fd != -1) {
4106 ret = -EINVAL;
4107 group_file = fget_light(group_fd, &fput_needed);
4108 if (!group_file)
4109 goto err_put_context;
4110 if (group_file->f_op != &perf_fops)
4111 goto err_put_context;
4113 group_leader = group_file->private_data;
4115 * Do not allow a recursive hierarchy (this new sibling
4116 * becoming part of another group-sibling):
4118 if (group_leader->group_leader != group_leader)
4119 goto err_put_context;
4121 * Do not allow to attach to a group in a different
4122 * task or CPU context:
4124 if (group_leader->ctx != ctx)
4125 goto err_put_context;
4127 * Only a group leader can be exclusive or pinned
4129 if (attr.exclusive || attr.pinned)
4130 goto err_put_context;
4133 counter = perf_counter_alloc(&attr, cpu, ctx, group_leader,
4134 NULL, GFP_KERNEL);
4135 ret = PTR_ERR(counter);
4136 if (IS_ERR(counter))
4137 goto err_put_context;
4139 ret = anon_inode_getfd("[perf_counter]", &perf_fops, counter, 0);
4140 if (ret < 0)
4141 goto err_free_put_context;
4143 counter_file = fget_light(ret, &fput_needed2);
4144 if (!counter_file)
4145 goto err_free_put_context;
4147 counter->filp = counter_file;
4148 WARN_ON_ONCE(ctx->parent_ctx);
4149 mutex_lock(&ctx->mutex);
4150 perf_install_in_context(ctx, counter, cpu);
4151 ++ctx->generation;
4152 mutex_unlock(&ctx->mutex);
4154 counter->owner = current;
4155 get_task_struct(current);
4156 mutex_lock(&current->perf_counter_mutex);
4157 list_add_tail(&counter->owner_entry, &current->perf_counter_list);
4158 mutex_unlock(&current->perf_counter_mutex);
4160 fput_light(counter_file, fput_needed2);
4162 out_fput:
4163 fput_light(group_file, fput_needed);
4165 return ret;
4167 err_free_put_context:
4168 kfree(counter);
4170 err_put_context:
4171 put_ctx(ctx);
4173 goto out_fput;
4177 * inherit a counter from parent task to child task:
4179 static struct perf_counter *
4180 inherit_counter(struct perf_counter *parent_counter,
4181 struct task_struct *parent,
4182 struct perf_counter_context *parent_ctx,
4183 struct task_struct *child,
4184 struct perf_counter *group_leader,
4185 struct perf_counter_context *child_ctx)
4187 struct perf_counter *child_counter;
4190 * Instead of creating recursive hierarchies of counters,
4191 * we link inherited counters back to the original parent,
4192 * which has a filp for sure, which we use as the reference
4193 * count:
4195 if (parent_counter->parent)
4196 parent_counter = parent_counter->parent;
4198 child_counter = perf_counter_alloc(&parent_counter->attr,
4199 parent_counter->cpu, child_ctx,
4200 group_leader, parent_counter,
4201 GFP_KERNEL);
4202 if (IS_ERR(child_counter))
4203 return child_counter;
4204 get_ctx(child_ctx);
4207 * Make the child state follow the state of the parent counter,
4208 * not its attr.disabled bit. We hold the parent's mutex,
4209 * so we won't race with perf_counter_{en, dis}able_family.
4211 if (parent_counter->state >= PERF_COUNTER_STATE_INACTIVE)
4212 child_counter->state = PERF_COUNTER_STATE_INACTIVE;
4213 else
4214 child_counter->state = PERF_COUNTER_STATE_OFF;
4216 if (parent_counter->attr.freq)
4217 child_counter->hw.sample_period = parent_counter->hw.sample_period;
4220 * Link it up in the child's context:
4222 add_counter_to_ctx(child_counter, child_ctx);
4225 * Get a reference to the parent filp - we will fput it
4226 * when the child counter exits. This is safe to do because
4227 * we are in the parent and we know that the filp still
4228 * exists and has a nonzero count:
4230 atomic_long_inc(&parent_counter->filp->f_count);
4233 * Link this into the parent counter's child list
4235 WARN_ON_ONCE(parent_counter->ctx->parent_ctx);
4236 mutex_lock(&parent_counter->child_mutex);
4237 list_add_tail(&child_counter->child_list, &parent_counter->child_list);
4238 mutex_unlock(&parent_counter->child_mutex);
4240 return child_counter;
4243 static int inherit_group(struct perf_counter *parent_counter,
4244 struct task_struct *parent,
4245 struct perf_counter_context *parent_ctx,
4246 struct task_struct *child,
4247 struct perf_counter_context *child_ctx)
4249 struct perf_counter *leader;
4250 struct perf_counter *sub;
4251 struct perf_counter *child_ctr;
4253 leader = inherit_counter(parent_counter, parent, parent_ctx,
4254 child, NULL, child_ctx);
4255 if (IS_ERR(leader))
4256 return PTR_ERR(leader);
4257 list_for_each_entry(sub, &parent_counter->sibling_list, list_entry) {
4258 child_ctr = inherit_counter(sub, parent, parent_ctx,
4259 child, leader, child_ctx);
4260 if (IS_ERR(child_ctr))
4261 return PTR_ERR(child_ctr);
4263 return 0;
4266 static void sync_child_counter(struct perf_counter *child_counter,
4267 struct task_struct *child)
4269 struct perf_counter *parent_counter = child_counter->parent;
4270 u64 child_val;
4272 if (child_counter->attr.inherit_stat)
4273 perf_counter_read_event(child_counter, child);
4275 child_val = atomic64_read(&child_counter->count);
4278 * Add back the child's count to the parent's count:
4280 atomic64_add(child_val, &parent_counter->count);
4281 atomic64_add(child_counter->total_time_enabled,
4282 &parent_counter->child_total_time_enabled);
4283 atomic64_add(child_counter->total_time_running,
4284 &parent_counter->child_total_time_running);
4287 * Remove this counter from the parent's list
4289 WARN_ON_ONCE(parent_counter->ctx->parent_ctx);
4290 mutex_lock(&parent_counter->child_mutex);
4291 list_del_init(&child_counter->child_list);
4292 mutex_unlock(&parent_counter->child_mutex);
4295 * Release the parent counter, if this was the last
4296 * reference to it.
4298 fput(parent_counter->filp);
4301 static void
4302 __perf_counter_exit_task(struct perf_counter *child_counter,
4303 struct perf_counter_context *child_ctx,
4304 struct task_struct *child)
4306 struct perf_counter *parent_counter;
4308 update_counter_times(child_counter);
4309 perf_counter_remove_from_context(child_counter);
4311 parent_counter = child_counter->parent;
4313 * It can happen that parent exits first, and has counters
4314 * that are still around due to the child reference. These
4315 * counters need to be zapped - but otherwise linger.
4317 if (parent_counter) {
4318 sync_child_counter(child_counter, child);
4319 free_counter(child_counter);
4324 * When a child task exits, feed back counter values to parent counters.
4326 void perf_counter_exit_task(struct task_struct *child)
4328 struct perf_counter *child_counter, *tmp;
4329 struct perf_counter_context *child_ctx;
4330 unsigned long flags;
4332 if (likely(!child->perf_counter_ctxp)) {
4333 perf_counter_task(child, NULL, 0);
4334 return;
4337 local_irq_save(flags);
4339 * We can't reschedule here because interrupts are disabled,
4340 * and either child is current or it is a task that can't be
4341 * scheduled, so we are now safe from rescheduling changing
4342 * our context.
4344 child_ctx = child->perf_counter_ctxp;
4345 __perf_counter_task_sched_out(child_ctx);
4348 * Take the context lock here so that if find_get_context is
4349 * reading child->perf_counter_ctxp, we wait until it has
4350 * incremented the context's refcount before we do put_ctx below.
4352 spin_lock(&child_ctx->lock);
4353 child->perf_counter_ctxp = NULL;
4355 * If this context is a clone; unclone it so it can't get
4356 * swapped to another process while we're removing all
4357 * the counters from it.
4359 unclone_ctx(child_ctx);
4360 spin_unlock_irqrestore(&child_ctx->lock, flags);
4363 * Report the task dead after unscheduling the counters so that we
4364 * won't get any samples after PERF_EVENT_EXIT. We can however still
4365 * get a few PERF_EVENT_READ events.
4367 perf_counter_task(child, child_ctx, 0);
4370 * We can recurse on the same lock type through:
4372 * __perf_counter_exit_task()
4373 * sync_child_counter()
4374 * fput(parent_counter->filp)
4375 * perf_release()
4376 * mutex_lock(&ctx->mutex)
4378 * But since its the parent context it won't be the same instance.
4380 mutex_lock_nested(&child_ctx->mutex, SINGLE_DEPTH_NESTING);
4382 again:
4383 list_for_each_entry_safe(child_counter, tmp, &child_ctx->counter_list,
4384 list_entry)
4385 __perf_counter_exit_task(child_counter, child_ctx, child);
4388 * If the last counter was a group counter, it will have appended all
4389 * its siblings to the list, but we obtained 'tmp' before that which
4390 * will still point to the list head terminating the iteration.
4392 if (!list_empty(&child_ctx->counter_list))
4393 goto again;
4395 mutex_unlock(&child_ctx->mutex);
4397 put_ctx(child_ctx);
4401 * free an unexposed, unused context as created by inheritance by
4402 * init_task below, used by fork() in case of fail.
4404 void perf_counter_free_task(struct task_struct *task)
4406 struct perf_counter_context *ctx = task->perf_counter_ctxp;
4407 struct perf_counter *counter, *tmp;
4409 if (!ctx)
4410 return;
4412 mutex_lock(&ctx->mutex);
4413 again:
4414 list_for_each_entry_safe(counter, tmp, &ctx->counter_list, list_entry) {
4415 struct perf_counter *parent = counter->parent;
4417 if (WARN_ON_ONCE(!parent))
4418 continue;
4420 mutex_lock(&parent->child_mutex);
4421 list_del_init(&counter->child_list);
4422 mutex_unlock(&parent->child_mutex);
4424 fput(parent->filp);
4426 list_del_counter(counter, ctx);
4427 free_counter(counter);
4430 if (!list_empty(&ctx->counter_list))
4431 goto again;
4433 mutex_unlock(&ctx->mutex);
4435 put_ctx(ctx);
4439 * Initialize the perf_counter context in task_struct
4441 int perf_counter_init_task(struct task_struct *child)
4443 struct perf_counter_context *child_ctx, *parent_ctx;
4444 struct perf_counter_context *cloned_ctx;
4445 struct perf_counter *counter;
4446 struct task_struct *parent = current;
4447 int inherited_all = 1;
4448 int ret = 0;
4450 child->perf_counter_ctxp = NULL;
4452 mutex_init(&child->perf_counter_mutex);
4453 INIT_LIST_HEAD(&child->perf_counter_list);
4455 if (likely(!parent->perf_counter_ctxp))
4456 return 0;
4459 * This is executed from the parent task context, so inherit
4460 * counters that have been marked for cloning.
4461 * First allocate and initialize a context for the child.
4464 child_ctx = kmalloc(sizeof(struct perf_counter_context), GFP_KERNEL);
4465 if (!child_ctx)
4466 return -ENOMEM;
4468 __perf_counter_init_context(child_ctx, child);
4469 child->perf_counter_ctxp = child_ctx;
4470 get_task_struct(child);
4473 * If the parent's context is a clone, pin it so it won't get
4474 * swapped under us.
4476 parent_ctx = perf_pin_task_context(parent);
4479 * No need to check if parent_ctx != NULL here; since we saw
4480 * it non-NULL earlier, the only reason for it to become NULL
4481 * is if we exit, and since we're currently in the middle of
4482 * a fork we can't be exiting at the same time.
4486 * Lock the parent list. No need to lock the child - not PID
4487 * hashed yet and not running, so nobody can access it.
4489 mutex_lock(&parent_ctx->mutex);
4492 * We dont have to disable NMIs - we are only looking at
4493 * the list, not manipulating it:
4495 list_for_each_entry_rcu(counter, &parent_ctx->event_list, event_entry) {
4496 if (counter != counter->group_leader)
4497 continue;
4499 if (!counter->attr.inherit) {
4500 inherited_all = 0;
4501 continue;
4504 ret = inherit_group(counter, parent, parent_ctx,
4505 child, child_ctx);
4506 if (ret) {
4507 inherited_all = 0;
4508 break;
4512 if (inherited_all) {
4514 * Mark the child context as a clone of the parent
4515 * context, or of whatever the parent is a clone of.
4516 * Note that if the parent is a clone, it could get
4517 * uncloned at any point, but that doesn't matter
4518 * because the list of counters and the generation
4519 * count can't have changed since we took the mutex.
4521 cloned_ctx = rcu_dereference(parent_ctx->parent_ctx);
4522 if (cloned_ctx) {
4523 child_ctx->parent_ctx = cloned_ctx;
4524 child_ctx->parent_gen = parent_ctx->parent_gen;
4525 } else {
4526 child_ctx->parent_ctx = parent_ctx;
4527 child_ctx->parent_gen = parent_ctx->generation;
4529 get_ctx(child_ctx->parent_ctx);
4532 mutex_unlock(&parent_ctx->mutex);
4534 perf_unpin_context(parent_ctx);
4536 return ret;
4539 static void __cpuinit perf_counter_init_cpu(int cpu)
4541 struct perf_cpu_context *cpuctx;
4543 cpuctx = &per_cpu(perf_cpu_context, cpu);
4544 __perf_counter_init_context(&cpuctx->ctx, NULL);
4546 spin_lock(&perf_resource_lock);
4547 cpuctx->max_pertask = perf_max_counters - perf_reserved_percpu;
4548 spin_unlock(&perf_resource_lock);
4550 hw_perf_counter_setup(cpu);
4553 #ifdef CONFIG_HOTPLUG_CPU
4554 static void __perf_counter_exit_cpu(void *info)
4556 struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
4557 struct perf_counter_context *ctx = &cpuctx->ctx;
4558 struct perf_counter *counter, *tmp;
4560 list_for_each_entry_safe(counter, tmp, &ctx->counter_list, list_entry)
4561 __perf_counter_remove_from_context(counter);
4563 static void perf_counter_exit_cpu(int cpu)
4565 struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
4566 struct perf_counter_context *ctx = &cpuctx->ctx;
4568 mutex_lock(&ctx->mutex);
4569 smp_call_function_single(cpu, __perf_counter_exit_cpu, NULL, 1);
4570 mutex_unlock(&ctx->mutex);
4572 #else
4573 static inline void perf_counter_exit_cpu(int cpu) { }
4574 #endif
4576 static int __cpuinit
4577 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
4579 unsigned int cpu = (long)hcpu;
4581 switch (action) {
4583 case CPU_UP_PREPARE:
4584 case CPU_UP_PREPARE_FROZEN:
4585 perf_counter_init_cpu(cpu);
4586 break;
4588 case CPU_ONLINE:
4589 case CPU_ONLINE_FROZEN:
4590 hw_perf_counter_setup_online(cpu);
4591 break;
4593 case CPU_DOWN_PREPARE:
4594 case CPU_DOWN_PREPARE_FROZEN:
4595 perf_counter_exit_cpu(cpu);
4596 break;
4598 default:
4599 break;
4602 return NOTIFY_OK;
4606 * This has to have a higher priority than migration_notifier in sched.c.
4608 static struct notifier_block __cpuinitdata perf_cpu_nb = {
4609 .notifier_call = perf_cpu_notify,
4610 .priority = 20,
4613 void __init perf_counter_init(void)
4615 perf_cpu_notify(&perf_cpu_nb, (unsigned long)CPU_UP_PREPARE,
4616 (void *)(long)smp_processor_id());
4617 perf_cpu_notify(&perf_cpu_nb, (unsigned long)CPU_ONLINE,
4618 (void *)(long)smp_processor_id());
4619 register_cpu_notifier(&perf_cpu_nb);
4622 static ssize_t perf_show_reserve_percpu(struct sysdev_class *class, char *buf)
4624 return sprintf(buf, "%d\n", perf_reserved_percpu);
4627 static ssize_t
4628 perf_set_reserve_percpu(struct sysdev_class *class,
4629 const char *buf,
4630 size_t count)
4632 struct perf_cpu_context *cpuctx;
4633 unsigned long val;
4634 int err, cpu, mpt;
4636 err = strict_strtoul(buf, 10, &val);
4637 if (err)
4638 return err;
4639 if (val > perf_max_counters)
4640 return -EINVAL;
4642 spin_lock(&perf_resource_lock);
4643 perf_reserved_percpu = val;
4644 for_each_online_cpu(cpu) {
4645 cpuctx = &per_cpu(perf_cpu_context, cpu);
4646 spin_lock_irq(&cpuctx->ctx.lock);
4647 mpt = min(perf_max_counters - cpuctx->ctx.nr_counters,
4648 perf_max_counters - perf_reserved_percpu);
4649 cpuctx->max_pertask = mpt;
4650 spin_unlock_irq(&cpuctx->ctx.lock);
4652 spin_unlock(&perf_resource_lock);
4654 return count;
4657 static ssize_t perf_show_overcommit(struct sysdev_class *class, char *buf)
4659 return sprintf(buf, "%d\n", perf_overcommit);
4662 static ssize_t
4663 perf_set_overcommit(struct sysdev_class *class, const char *buf, size_t count)
4665 unsigned long val;
4666 int err;
4668 err = strict_strtoul(buf, 10, &val);
4669 if (err)
4670 return err;
4671 if (val > 1)
4672 return -EINVAL;
4674 spin_lock(&perf_resource_lock);
4675 perf_overcommit = val;
4676 spin_unlock(&perf_resource_lock);
4678 return count;
4681 static SYSDEV_CLASS_ATTR(
4682 reserve_percpu,
4683 0644,
4684 perf_show_reserve_percpu,
4685 perf_set_reserve_percpu
4688 static SYSDEV_CLASS_ATTR(
4689 overcommit,
4690 0644,
4691 perf_show_overcommit,
4692 perf_set_overcommit
4695 static struct attribute *perfclass_attrs[] = {
4696 &attr_reserve_percpu.attr,
4697 &attr_overcommit.attr,
4698 NULL
4701 static struct attribute_group perfclass_attr_group = {
4702 .attrs = perfclass_attrs,
4703 .name = "perf_counters",
4706 static int __init perf_counter_sysfs_init(void)
4708 return sysfs_create_group(&cpu_sysdev_class.kset.kobj,
4709 &perfclass_attr_group);
4711 device_initcall(perf_counter_sysfs_init);