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
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:
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)
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(); }
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)
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)
121 void perf_enable(void)
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);
140 static void put_ctx(struct perf_counter_context *ctx)
142 if (atomic_dec_and_test(&ctx->refcount)) {
144 put_ctx(ctx->parent_ctx);
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
163 static u64 primary_counter_id(struct perf_counter *counter)
165 u64 id = counter->id;
168 id = counter->parent->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;
185 ctx = rcu_dereference(task->perf_counter_ctxp);
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);
203 if (!atomic_inc_not_zero(&ctx->refcount)) {
204 spin_unlock_irqrestore(&ctx->lock, *flags);
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;
222 ctx = perf_lock_task_context(task, &flags);
225 spin_unlock_irqrestore(&ctx->lock, flags);
230 static void perf_unpin_context(struct perf_counter_context *ctx)
234 spin_lock_irqsave(&ctx->lock, flags);
236 spin_unlock_irqrestore(&ctx->lock, flags);
241 * Add a counter from the lists for its context.
242 * Must be called with ctx->mutex and ctx->lock held.
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);
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);
263 if (counter->attr.inherit_stat)
268 * Remove a counter from the lists for its context.
269 * Must be called with ctx->mutex and ctx->lock held.
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))
279 if (counter->attr.inherit_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;
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)
309 counter->state = PERF_COUNTER_STATE_INACTIVE;
310 counter->tstamp_stopped = ctx->time;
311 counter->pmu->disable(counter);
314 if (!is_software_counter(counter))
315 cpuctx->active_oncpu--;
317 if (counter->attr.exclusive || !cpuctx->active_oncpu)
318 cpuctx->exclusive = 0;
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)
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)
363 spin_lock(&ctx->lock);
365 * Protect the list operation against NMI by disabling the
366 * counters on a global level.
370 counter_sched_out(counter, cpuctx, ctx);
372 list_del_counter(counter, ctx);
376 * Allow more per task counters with respect to the
379 cpuctx->max_pertask =
380 min(perf_max_counters - ctx->nr_counters,
381 perf_max_counters - perf_reserved_percpu);
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;
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,
421 task_oncpu_function_call(task, __perf_counter_remove_from_context,
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);
434 * The lock prevents that this context is scheduled in so we
435 * can remove the counter safely, if the call above did not
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;
468 if (counter->state < PERF_COUNTER_STATE_INACTIVE)
471 counter->total_time_enabled = ctx->time - counter->tstamp_enabled;
473 if (counter->state == PERF_COUNTER_STATE_INACTIVE)
474 run_end = counter->tstamp_stopped;
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)
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);
521 counter_sched_out(counter, cpuctx, ctx);
522 counter->state = PERF_COUNTER_STATE_OFF;
525 spin_unlock(&ctx->lock);
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;
548 * Disable the counter on the cpu that it's on
550 smp_call_function_single(counter->cpu, __perf_counter_disable,
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);
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);
580 counter_sched_in(struct perf_counter *counter,
581 struct perf_cpu_context *cpuctx,
582 struct perf_counter_context *ctx,
585 if (counter->state <= PERF_COUNTER_STATE_OFF)
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:
595 if (counter->pmu->enable(counter)) {
596 counter->state = PERF_COUNTER_STATE_INACTIVE;
601 counter->tstamp_running += ctx->time - counter->tstamp_stopped;
603 if (!is_software_counter(counter))
604 cpuctx->active_oncpu++;
607 if (counter->attr.exclusive)
608 cpuctx->exclusive = 1;
614 group_sched_in(struct perf_counter *group_counter,
615 struct perf_cpu_context *cpuctx,
616 struct perf_counter_context *ctx,
619 struct perf_counter *counter, *partial_group;
622 if (group_counter->state == PERF_COUNTER_STATE_OFF)
625 ret = hw_perf_group_sched_in(group_counter, cpuctx, ctx, cpu);
627 return ret < 0 ? ret : 0;
629 if (counter_sched_in(group_counter, cpuctx, ctx, cpu))
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;
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)
652 counter_sched_out(counter, cpuctx, ctx);
654 counter_sched_out(group_counter, cpuctx, ctx);
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))
670 list_for_each_entry(counter, &leader->sibling_list, list_entry)
671 if (!is_software_counter(counter))
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,
685 * Groups consisting entirely of software counters can always go on.
687 if (is_software_only_group(counter))
690 * If an exclusive group is already on, no other hardware
691 * counters can go on.
693 if (cpuctx->exclusive)
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)
702 * Otherwise, try to add it if all previous groups were able
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();
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)
741 cpuctx->task_ctx = ctx;
744 spin_lock(&ctx->lock);
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.
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))
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))
772 err = counter_sched_in(counter, cpuctx, ctx, cpu);
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--;
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.
810 perf_install_in_context(struct perf_counter_context *ctx,
811 struct perf_counter *counter,
814 struct task_struct *task = ctx->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,
827 task_oncpu_function_call(task, __perf_install_in_context,
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);
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
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;
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)
867 cpuctx->task_ctx = ctx;
870 spin_lock(&ctx->lock);
872 update_context_time(ctx);
874 if (counter->state >= PERF_COUNTER_STATE_INACTIVE)
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)
886 if (!group_can_go_on(counter, cpuctx, 1)) {
890 if (counter == leader)
891 err = group_sched_in(counter, cpuctx, ctx,
894 err = counter_sched_in(counter, cpuctx, ctx,
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;
913 spin_unlock(&ctx->lock);
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;
932 * Enable the counter on the cpu that it's on
934 smp_call_function_single(counter->cpu, __perf_counter_enable,
939 spin_lock_irq(&ctx->lock);
940 if (counter->state >= PERF_COUNTER_STATE_INACTIVE)
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;
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)
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;
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)
987 atomic_add(refresh, &counter->event_limit);
988 perf_counter_enable(counter);
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);
1000 if (likely(!ctx->nr_counters))
1002 update_context_time(ctx);
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);
1010 group_sched_out(counter, cpuctx, ctx);
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)
1044 if (!counter->attr.inherit_stat)
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);
1059 case PERF_COUNTER_STATE_INACTIVE:
1060 update_counter_times(counter);
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;
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;
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))
1139 update_context_time(ctx);
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;
1165 next_ctx->task = task;
1168 perf_counter_sync_stat(ctx, next_ctx);
1170 spin_unlock(&next_ctx->lock);
1171 spin_unlock(&ctx->lock);
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)
1191 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
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);
1207 __perf_counter_sched_in(struct perf_counter_context *ctx,
1208 struct perf_cpu_context *cpuctx, int cpu)
1210 struct perf_counter *counter;
1213 spin_lock(&ctx->lock);
1215 if (likely(!ctx->nr_counters))
1218 ctx->timestamp = perf_clock();
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)
1230 if (counter->cpu != -1 && counter->cpu != cpu)
1233 if (counter != counter->group_leader)
1234 counter_sched_in(counter, cpuctx, ctx, cpu);
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)
1260 * Listen to the 'cpu' scheduling filter constraint
1263 if (counter->cpu != -1 && counter->cpu != cpu)
1266 if (counter != counter->group_leader) {
1267 if (counter_sched_in(counter, cpuctx, ctx, cpu))
1270 if (group_can_go_on(counter, cpuctx, can_add_hw)) {
1271 if (group_sched_in(counter, cpuctx, ctx, cpu))
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;
1299 if (cpuctx->task_ctx == ctx)
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;
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;
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)
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)
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)
1376 interrupts = hwc->freq_interrupts;
1377 hwc->freq_interrupts = 0;
1378 hwc->freq_count -= 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.
1391 counter->pmu->disable(counter);
1392 atomic64_set(&hwc->period_left, 0);
1393 counter->pmu->enable(counter);
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)
1410 spin_lock(&ctx->lock);
1412 * Rotate the first entry last (works just fine for group counters too):
1415 list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1416 list_move_tail(&counter->list_entry, &ctx->counter_list);
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))
1432 cpuctx = &per_cpu(perf_cpu_context, cpu);
1433 ctx = curr->perf_counter_ctxp;
1435 perf_ctx_adjust_freq(&cpuctx->ctx);
1437 perf_ctx_adjust_freq(ctx);
1439 perf_counter_cpu_sched_out(cpuctx);
1441 __perf_counter_task_sched_out(ctx);
1443 rotate_ctx(&cpuctx->ctx);
1447 perf_counter_cpu_sched_in(cpuctx, cpu);
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;
1463 local_irq_save(flags);
1464 ctx = task->perf_counter_ctxp;
1465 if (!ctx || !ctx->nr_counters)
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)
1475 counter->attr.enable_on_exec = 0;
1476 if (counter->state >= PERF_COUNTER_STATE_INACTIVE)
1478 counter->state = PERF_COUNTER_STATE_INACTIVE;
1479 counter->tstamp_enabled =
1480 ctx->time - counter->total_time_enabled;
1485 * Unclone this context if we enabled any counter.
1490 spin_unlock(&ctx->lock);
1492 perf_counter_task_sched_in(task, smp_processor_id());
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);
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:
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);
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;
1555 * If cpu is not a wildcard then this is a percpu counter:
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
1570 if (!cpu_isset(cpu, cpu_online_map))
1571 return ERR_PTR(-ENODEV);
1573 cpuctx = &per_cpu(perf_cpu_context, cpu);
1584 task = find_task_by_vpid(pid);
1586 get_task_struct(task);
1590 return ERR_PTR(-ESRCH);
1593 * Can't attach counters to a dying task.
1596 if (task->flags & PF_EXITING)
1599 /* Reuse ptrace permission checks for now. */
1601 if (!ptrace_may_access(task, PTRACE_MODE_READ))
1605 ctx = perf_lock_task_context(task, &flags);
1608 spin_unlock_irqrestore(&ctx->lock, flags);
1612 ctx = kmalloc(sizeof(struct perf_counter_context), GFP_KERNEL);
1616 __perf_counter_init_context(ctx, task);
1618 if (cmpxchg(&task->perf_counter_ctxp, NULL, ctx)) {
1620 * We raced with some other task; use
1621 * the context they set.
1626 get_task_struct(task);
1629 put_task_struct(task);
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);
1643 put_pid_ns(counter->ns);
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);
1695 static int perf_counter_read_size(struct perf_counter *counter)
1697 int entry = sizeof(u64); /* value */
1701 if (counter->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1702 size += sizeof(u64);
1704 if (counter->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1705 size += sizeof(u64);
1707 if (counter->attr.read_format & PERF_FORMAT_ID)
1708 entry += sizeof(u64);
1710 if (counter->attr.read_format & PERF_FORMAT_GROUP) {
1711 nr += counter->group_leader->nr_siblings;
1712 size += sizeof(u64);
1720 static u64 perf_counter_read_value(struct perf_counter *counter)
1722 struct perf_counter *child;
1725 total += perf_counter_read(counter);
1726 list_for_each_entry(child, &counter->child_list, child_list)
1727 total += perf_counter_read(child);
1732 static int perf_counter_read_entry(struct perf_counter *counter,
1733 u64 read_format, char __user *buf)
1735 int n = 0, count = 0;
1738 values[n++] = perf_counter_read_value(counter);
1739 if (read_format & PERF_FORMAT_ID)
1740 values[n++] = primary_counter_id(counter);
1742 count = n * sizeof(u64);
1744 if (copy_to_user(buf, values, count))
1750 static int perf_counter_read_group(struct perf_counter *counter,
1751 u64 read_format, char __user *buf)
1753 struct perf_counter *leader = counter->group_leader, *sub;
1754 int n = 0, size = 0, err = -EFAULT;
1757 values[n++] = 1 + leader->nr_siblings;
1758 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
1759 values[n++] = leader->total_time_enabled +
1760 atomic64_read(&leader->child_total_time_enabled);
1762 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
1763 values[n++] = leader->total_time_running +
1764 atomic64_read(&leader->child_total_time_running);
1767 size = n * sizeof(u64);
1769 if (copy_to_user(buf, values, size))
1772 err = perf_counter_read_entry(leader, read_format, buf + size);
1778 list_for_each_entry(sub, &leader->sibling_list, list_entry) {
1779 err = perf_counter_read_entry(counter, read_format,
1790 static int perf_counter_read_one(struct perf_counter *counter,
1791 u64 read_format, char __user *buf)
1796 values[n++] = perf_counter_read_value(counter);
1797 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
1798 values[n++] = counter->total_time_enabled +
1799 atomic64_read(&counter->child_total_time_enabled);
1801 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
1802 values[n++] = counter->total_time_running +
1803 atomic64_read(&counter->child_total_time_running);
1805 if (read_format & PERF_FORMAT_ID)
1806 values[n++] = primary_counter_id(counter);
1808 if (copy_to_user(buf, values, n * sizeof(u64)))
1811 return n * sizeof(u64);
1815 * Read the performance counter - simple non blocking version for now
1818 perf_read_hw(struct perf_counter *counter, char __user *buf, size_t count)
1820 u64 read_format = counter->attr.read_format;
1824 * Return end-of-file for a read on a counter that is in
1825 * error state (i.e. because it was pinned but it couldn't be
1826 * scheduled on to the CPU at some point).
1828 if (counter->state == PERF_COUNTER_STATE_ERROR)
1831 if (count < perf_counter_read_size(counter))
1834 WARN_ON_ONCE(counter->ctx->parent_ctx);
1835 mutex_lock(&counter->child_mutex);
1836 if (read_format & PERF_FORMAT_GROUP)
1837 ret = perf_counter_read_group(counter, read_format, buf);
1839 ret = perf_counter_read_one(counter, read_format, buf);
1840 mutex_unlock(&counter->child_mutex);
1846 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
1848 struct perf_counter *counter = file->private_data;
1850 return perf_read_hw(counter, buf, count);
1853 static unsigned int perf_poll(struct file *file, poll_table *wait)
1855 struct perf_counter *counter = file->private_data;
1856 struct perf_mmap_data *data;
1857 unsigned int events = POLL_HUP;
1860 data = rcu_dereference(counter->data);
1862 events = atomic_xchg(&data->poll, 0);
1865 poll_wait(file, &counter->waitq, wait);
1870 static void perf_counter_reset(struct perf_counter *counter)
1872 (void)perf_counter_read(counter);
1873 atomic64_set(&counter->count, 0);
1874 perf_counter_update_userpage(counter);
1878 * Holding the top-level counter's child_mutex means that any
1879 * descendant process that has inherited this counter will block
1880 * in sync_child_counter if it goes to exit, thus satisfying the
1881 * task existence requirements of perf_counter_enable/disable.
1883 static void perf_counter_for_each_child(struct perf_counter *counter,
1884 void (*func)(struct perf_counter *))
1886 struct perf_counter *child;
1888 WARN_ON_ONCE(counter->ctx->parent_ctx);
1889 mutex_lock(&counter->child_mutex);
1891 list_for_each_entry(child, &counter->child_list, child_list)
1893 mutex_unlock(&counter->child_mutex);
1896 static void perf_counter_for_each(struct perf_counter *counter,
1897 void (*func)(struct perf_counter *))
1899 struct perf_counter_context *ctx = counter->ctx;
1900 struct perf_counter *sibling;
1902 WARN_ON_ONCE(ctx->parent_ctx);
1903 mutex_lock(&ctx->mutex);
1904 counter = counter->group_leader;
1906 perf_counter_for_each_child(counter, func);
1908 list_for_each_entry(sibling, &counter->sibling_list, list_entry)
1909 perf_counter_for_each_child(counter, func);
1910 mutex_unlock(&ctx->mutex);
1913 static int perf_counter_period(struct perf_counter *counter, u64 __user *arg)
1915 struct perf_counter_context *ctx = counter->ctx;
1920 if (!counter->attr.sample_period)
1923 size = copy_from_user(&value, arg, sizeof(value));
1924 if (size != sizeof(value))
1930 spin_lock_irq(&ctx->lock);
1931 if (counter->attr.freq) {
1932 if (value > sysctl_perf_counter_sample_rate) {
1937 counter->attr.sample_freq = value;
1939 counter->attr.sample_period = value;
1940 counter->hw.sample_period = value;
1943 spin_unlock_irq(&ctx->lock);
1948 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
1950 struct perf_counter *counter = file->private_data;
1951 void (*func)(struct perf_counter *);
1955 case PERF_COUNTER_IOC_ENABLE:
1956 func = perf_counter_enable;
1958 case PERF_COUNTER_IOC_DISABLE:
1959 func = perf_counter_disable;
1961 case PERF_COUNTER_IOC_RESET:
1962 func = perf_counter_reset;
1965 case PERF_COUNTER_IOC_REFRESH:
1966 return perf_counter_refresh(counter, arg);
1968 case PERF_COUNTER_IOC_PERIOD:
1969 return perf_counter_period(counter, (u64 __user *)arg);
1975 if (flags & PERF_IOC_FLAG_GROUP)
1976 perf_counter_for_each(counter, func);
1978 perf_counter_for_each_child(counter, func);
1983 int perf_counter_task_enable(void)
1985 struct perf_counter *counter;
1987 mutex_lock(¤t->perf_counter_mutex);
1988 list_for_each_entry(counter, ¤t->perf_counter_list, owner_entry)
1989 perf_counter_for_each_child(counter, perf_counter_enable);
1990 mutex_unlock(¤t->perf_counter_mutex);
1995 int perf_counter_task_disable(void)
1997 struct perf_counter *counter;
1999 mutex_lock(¤t->perf_counter_mutex);
2000 list_for_each_entry(counter, ¤t->perf_counter_list, owner_entry)
2001 perf_counter_for_each_child(counter, perf_counter_disable);
2002 mutex_unlock(¤t->perf_counter_mutex);
2007 static int perf_counter_index(struct perf_counter *counter)
2009 if (counter->state != PERF_COUNTER_STATE_ACTIVE)
2012 return counter->hw.idx + 1 - PERF_COUNTER_INDEX_OFFSET;
2016 * Callers need to ensure there can be no nesting of this function, otherwise
2017 * the seqlock logic goes bad. We can not serialize this because the arch
2018 * code calls this from NMI context.
2020 void perf_counter_update_userpage(struct perf_counter *counter)
2022 struct perf_counter_mmap_page *userpg;
2023 struct perf_mmap_data *data;
2026 data = rcu_dereference(counter->data);
2030 userpg = data->user_page;
2033 * Disable preemption so as to not let the corresponding user-space
2034 * spin too long if we get preempted.
2039 userpg->index = perf_counter_index(counter);
2040 userpg->offset = atomic64_read(&counter->count);
2041 if (counter->state == PERF_COUNTER_STATE_ACTIVE)
2042 userpg->offset -= atomic64_read(&counter->hw.prev_count);
2044 userpg->time_enabled = counter->total_time_enabled +
2045 atomic64_read(&counter->child_total_time_enabled);
2047 userpg->time_running = counter->total_time_running +
2048 atomic64_read(&counter->child_total_time_running);
2057 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
2059 struct perf_counter *counter = vma->vm_file->private_data;
2060 struct perf_mmap_data *data;
2061 int ret = VM_FAULT_SIGBUS;
2063 if (vmf->flags & FAULT_FLAG_MKWRITE) {
2064 if (vmf->pgoff == 0)
2070 data = rcu_dereference(counter->data);
2074 if (vmf->pgoff == 0) {
2075 vmf->page = virt_to_page(data->user_page);
2077 int nr = vmf->pgoff - 1;
2079 if ((unsigned)nr > data->nr_pages)
2082 if (vmf->flags & FAULT_FLAG_WRITE)
2085 vmf->page = virt_to_page(data->data_pages[nr]);
2088 get_page(vmf->page);
2089 vmf->page->mapping = vma->vm_file->f_mapping;
2090 vmf->page->index = vmf->pgoff;
2099 static int perf_mmap_data_alloc(struct perf_counter *counter, int nr_pages)
2101 struct perf_mmap_data *data;
2105 WARN_ON(atomic_read(&counter->mmap_count));
2107 size = sizeof(struct perf_mmap_data);
2108 size += nr_pages * sizeof(void *);
2110 data = kzalloc(size, GFP_KERNEL);
2114 data->user_page = (void *)get_zeroed_page(GFP_KERNEL);
2115 if (!data->user_page)
2116 goto fail_user_page;
2118 for (i = 0; i < nr_pages; i++) {
2119 data->data_pages[i] = (void *)get_zeroed_page(GFP_KERNEL);
2120 if (!data->data_pages[i])
2121 goto fail_data_pages;
2124 data->nr_pages = nr_pages;
2125 atomic_set(&data->lock, -1);
2127 rcu_assign_pointer(counter->data, data);
2132 for (i--; i >= 0; i--)
2133 free_page((unsigned long)data->data_pages[i]);
2135 free_page((unsigned long)data->user_page);
2144 static void perf_mmap_free_page(unsigned long addr)
2146 struct page *page = virt_to_page((void *)addr);
2148 page->mapping = NULL;
2152 static void __perf_mmap_data_free(struct rcu_head *rcu_head)
2154 struct perf_mmap_data *data;
2157 data = container_of(rcu_head, struct perf_mmap_data, rcu_head);
2159 perf_mmap_free_page((unsigned long)data->user_page);
2160 for (i = 0; i < data->nr_pages; i++)
2161 perf_mmap_free_page((unsigned long)data->data_pages[i]);
2166 static void perf_mmap_data_free(struct perf_counter *counter)
2168 struct perf_mmap_data *data = counter->data;
2170 WARN_ON(atomic_read(&counter->mmap_count));
2172 rcu_assign_pointer(counter->data, NULL);
2173 call_rcu(&data->rcu_head, __perf_mmap_data_free);
2176 static void perf_mmap_open(struct vm_area_struct *vma)
2178 struct perf_counter *counter = vma->vm_file->private_data;
2180 atomic_inc(&counter->mmap_count);
2183 static void perf_mmap_close(struct vm_area_struct *vma)
2185 struct perf_counter *counter = vma->vm_file->private_data;
2187 WARN_ON_ONCE(counter->ctx->parent_ctx);
2188 if (atomic_dec_and_mutex_lock(&counter->mmap_count, &counter->mmap_mutex)) {
2189 struct user_struct *user = current_user();
2191 atomic_long_sub(counter->data->nr_pages + 1, &user->locked_vm);
2192 vma->vm_mm->locked_vm -= counter->data->nr_locked;
2193 perf_mmap_data_free(counter);
2194 mutex_unlock(&counter->mmap_mutex);
2198 static struct vm_operations_struct perf_mmap_vmops = {
2199 .open = perf_mmap_open,
2200 .close = perf_mmap_close,
2201 .fault = perf_mmap_fault,
2202 .page_mkwrite = perf_mmap_fault,
2205 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
2207 struct perf_counter *counter = file->private_data;
2208 unsigned long user_locked, user_lock_limit;
2209 struct user_struct *user = current_user();
2210 unsigned long locked, lock_limit;
2211 unsigned long vma_size;
2212 unsigned long nr_pages;
2213 long user_extra, extra;
2216 if (!(vma->vm_flags & VM_SHARED))
2219 vma_size = vma->vm_end - vma->vm_start;
2220 nr_pages = (vma_size / PAGE_SIZE) - 1;
2223 * If we have data pages ensure they're a power-of-two number, so we
2224 * can do bitmasks instead of modulo.
2226 if (nr_pages != 0 && !is_power_of_2(nr_pages))
2229 if (vma_size != PAGE_SIZE * (1 + nr_pages))
2232 if (vma->vm_pgoff != 0)
2235 WARN_ON_ONCE(counter->ctx->parent_ctx);
2236 mutex_lock(&counter->mmap_mutex);
2237 if (atomic_inc_not_zero(&counter->mmap_count)) {
2238 if (nr_pages != counter->data->nr_pages)
2243 user_extra = nr_pages + 1;
2244 user_lock_limit = sysctl_perf_counter_mlock >> (PAGE_SHIFT - 10);
2247 * Increase the limit linearly with more CPUs:
2249 user_lock_limit *= num_online_cpus();
2251 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
2254 if (user_locked > user_lock_limit)
2255 extra = user_locked - user_lock_limit;
2257 lock_limit = current->signal->rlim[RLIMIT_MEMLOCK].rlim_cur;
2258 lock_limit >>= PAGE_SHIFT;
2259 locked = vma->vm_mm->locked_vm + extra;
2261 if ((locked > lock_limit) && !capable(CAP_IPC_LOCK)) {
2266 WARN_ON(counter->data);
2267 ret = perf_mmap_data_alloc(counter, nr_pages);
2271 atomic_set(&counter->mmap_count, 1);
2272 atomic_long_add(user_extra, &user->locked_vm);
2273 vma->vm_mm->locked_vm += extra;
2274 counter->data->nr_locked = extra;
2275 if (vma->vm_flags & VM_WRITE)
2276 counter->data->writable = 1;
2279 mutex_unlock(&counter->mmap_mutex);
2281 vma->vm_flags |= VM_RESERVED;
2282 vma->vm_ops = &perf_mmap_vmops;
2287 static int perf_fasync(int fd, struct file *filp, int on)
2289 struct inode *inode = filp->f_path.dentry->d_inode;
2290 struct perf_counter *counter = filp->private_data;
2293 mutex_lock(&inode->i_mutex);
2294 retval = fasync_helper(fd, filp, on, &counter->fasync);
2295 mutex_unlock(&inode->i_mutex);
2303 static const struct file_operations perf_fops = {
2304 .release = perf_release,
2307 .unlocked_ioctl = perf_ioctl,
2308 .compat_ioctl = perf_ioctl,
2310 .fasync = perf_fasync,
2314 * Perf counter wakeup
2316 * If there's data, ensure we set the poll() state and publish everything
2317 * to user-space before waking everybody up.
2320 void perf_counter_wakeup(struct perf_counter *counter)
2322 wake_up_all(&counter->waitq);
2324 if (counter->pending_kill) {
2325 kill_fasync(&counter->fasync, SIGIO, counter->pending_kill);
2326 counter->pending_kill = 0;
2333 * Handle the case where we need to wakeup up from NMI (or rq->lock) context.
2335 * The NMI bit means we cannot possibly take locks. Therefore, maintain a
2336 * single linked list and use cmpxchg() to add entries lockless.
2339 static void perf_pending_counter(struct perf_pending_entry *entry)
2341 struct perf_counter *counter = container_of(entry,
2342 struct perf_counter, pending);
2344 if (counter->pending_disable) {
2345 counter->pending_disable = 0;
2346 perf_counter_disable(counter);
2349 if (counter->pending_wakeup) {
2350 counter->pending_wakeup = 0;
2351 perf_counter_wakeup(counter);
2355 #define PENDING_TAIL ((struct perf_pending_entry *)-1UL)
2357 static DEFINE_PER_CPU(struct perf_pending_entry *, perf_pending_head) = {
2361 static void perf_pending_queue(struct perf_pending_entry *entry,
2362 void (*func)(struct perf_pending_entry *))
2364 struct perf_pending_entry **head;
2366 if (cmpxchg(&entry->next, NULL, PENDING_TAIL) != NULL)
2371 head = &get_cpu_var(perf_pending_head);
2374 entry->next = *head;
2375 } while (cmpxchg(head, entry->next, entry) != entry->next);
2377 set_perf_counter_pending();
2379 put_cpu_var(perf_pending_head);
2382 static int __perf_pending_run(void)
2384 struct perf_pending_entry *list;
2387 list = xchg(&__get_cpu_var(perf_pending_head), PENDING_TAIL);
2388 while (list != PENDING_TAIL) {
2389 void (*func)(struct perf_pending_entry *);
2390 struct perf_pending_entry *entry = list;
2397 * Ensure we observe the unqueue before we issue the wakeup,
2398 * so that we won't be waiting forever.
2399 * -- see perf_not_pending().
2410 static inline int perf_not_pending(struct perf_counter *counter)
2413 * If we flush on whatever cpu we run, there is a chance we don't
2417 __perf_pending_run();
2421 * Ensure we see the proper queue state before going to sleep
2422 * so that we do not miss the wakeup. -- see perf_pending_handle()
2425 return counter->pending.next == NULL;
2428 static void perf_pending_sync(struct perf_counter *counter)
2430 wait_event(counter->waitq, perf_not_pending(counter));
2433 void perf_counter_do_pending(void)
2435 __perf_pending_run();
2439 * Callchain support -- arch specific
2442 __weak struct perf_callchain_entry *perf_callchain(struct pt_regs *regs)
2451 struct perf_output_handle {
2452 struct perf_counter *counter;
2453 struct perf_mmap_data *data;
2455 unsigned long offset;
2459 unsigned long flags;
2462 static bool perf_output_space(struct perf_mmap_data *data,
2463 unsigned int offset, unsigned int head)
2468 if (!data->writable)
2471 mask = (data->nr_pages << PAGE_SHIFT) - 1;
2473 * Userspace could choose to issue a mb() before updating the tail
2474 * pointer. So that all reads will be completed before the write is
2477 tail = ACCESS_ONCE(data->user_page->data_tail);
2480 offset = (offset - tail) & mask;
2481 head = (head - tail) & mask;
2483 if ((int)(head - offset) < 0)
2489 static void perf_output_wakeup(struct perf_output_handle *handle)
2491 atomic_set(&handle->data->poll, POLL_IN);
2494 handle->counter->pending_wakeup = 1;
2495 perf_pending_queue(&handle->counter->pending,
2496 perf_pending_counter);
2498 perf_counter_wakeup(handle->counter);
2502 * Curious locking construct.
2504 * We need to ensure a later event doesn't publish a head when a former
2505 * event isn't done writing. However since we need to deal with NMIs we
2506 * cannot fully serialize things.
2508 * What we do is serialize between CPUs so we only have to deal with NMI
2509 * nesting on a single CPU.
2511 * We only publish the head (and generate a wakeup) when the outer-most
2514 static void perf_output_lock(struct perf_output_handle *handle)
2516 struct perf_mmap_data *data = handle->data;
2521 local_irq_save(handle->flags);
2522 cpu = smp_processor_id();
2524 if (in_nmi() && atomic_read(&data->lock) == cpu)
2527 while (atomic_cmpxchg(&data->lock, -1, cpu) != -1)
2533 static void perf_output_unlock(struct perf_output_handle *handle)
2535 struct perf_mmap_data *data = handle->data;
2539 data->done_head = data->head;
2541 if (!handle->locked)
2546 * The xchg implies a full barrier that ensures all writes are done
2547 * before we publish the new head, matched by a rmb() in userspace when
2548 * reading this position.
2550 while ((head = atomic_long_xchg(&data->done_head, 0)))
2551 data->user_page->data_head = head;
2554 * NMI can happen here, which means we can miss a done_head update.
2557 cpu = atomic_xchg(&data->lock, -1);
2558 WARN_ON_ONCE(cpu != smp_processor_id());
2561 * Therefore we have to validate we did not indeed do so.
2563 if (unlikely(atomic_long_read(&data->done_head))) {
2565 * Since we had it locked, we can lock it again.
2567 while (atomic_cmpxchg(&data->lock, -1, cpu) != -1)
2573 if (atomic_xchg(&data->wakeup, 0))
2574 perf_output_wakeup(handle);
2576 local_irq_restore(handle->flags);
2579 static void perf_output_copy(struct perf_output_handle *handle,
2580 const void *buf, unsigned int len)
2582 unsigned int pages_mask;
2583 unsigned int offset;
2587 offset = handle->offset;
2588 pages_mask = handle->data->nr_pages - 1;
2589 pages = handle->data->data_pages;
2592 unsigned int page_offset;
2595 nr = (offset >> PAGE_SHIFT) & pages_mask;
2596 page_offset = offset & (PAGE_SIZE - 1);
2597 size = min_t(unsigned int, PAGE_SIZE - page_offset, len);
2599 memcpy(pages[nr] + page_offset, buf, size);
2606 handle->offset = offset;
2609 * Check we didn't copy past our reservation window, taking the
2610 * possible unsigned int wrap into account.
2612 WARN_ON_ONCE(((long)(handle->head - handle->offset)) < 0);
2615 #define perf_output_put(handle, x) \
2616 perf_output_copy((handle), &(x), sizeof(x))
2618 static int perf_output_begin(struct perf_output_handle *handle,
2619 struct perf_counter *counter, unsigned int size,
2620 int nmi, int sample)
2622 struct perf_mmap_data *data;
2623 unsigned int offset, head;
2626 struct perf_event_header header;
2632 * For inherited counters we send all the output towards the parent.
2634 if (counter->parent)
2635 counter = counter->parent;
2638 data = rcu_dereference(counter->data);
2642 handle->data = data;
2643 handle->counter = counter;
2645 handle->sample = sample;
2647 if (!data->nr_pages)
2650 have_lost = atomic_read(&data->lost);
2652 size += sizeof(lost_event);
2654 perf_output_lock(handle);
2657 offset = head = atomic_long_read(&data->head);
2659 if (unlikely(!perf_output_space(data, offset, head)))
2661 } while (atomic_long_cmpxchg(&data->head, offset, head) != offset);
2663 handle->offset = offset;
2664 handle->head = head;
2666 if ((offset >> PAGE_SHIFT) != (head >> PAGE_SHIFT))
2667 atomic_set(&data->wakeup, 1);
2670 lost_event.header.type = PERF_EVENT_LOST;
2671 lost_event.header.misc = 0;
2672 lost_event.header.size = sizeof(lost_event);
2673 lost_event.id = counter->id;
2674 lost_event.lost = atomic_xchg(&data->lost, 0);
2676 perf_output_put(handle, lost_event);
2682 atomic_inc(&data->lost);
2683 perf_output_unlock(handle);
2690 static void perf_output_end(struct perf_output_handle *handle)
2692 struct perf_counter *counter = handle->counter;
2693 struct perf_mmap_data *data = handle->data;
2695 int wakeup_events = counter->attr.wakeup_events;
2697 if (handle->sample && wakeup_events) {
2698 int events = atomic_inc_return(&data->events);
2699 if (events >= wakeup_events) {
2700 atomic_sub(wakeup_events, &data->events);
2701 atomic_set(&data->wakeup, 1);
2705 perf_output_unlock(handle);
2709 static u32 perf_counter_pid(struct perf_counter *counter, struct task_struct *p)
2712 * only top level counters have the pid namespace they were created in
2714 if (counter->parent)
2715 counter = counter->parent;
2717 return task_tgid_nr_ns(p, counter->ns);
2720 static u32 perf_counter_tid(struct perf_counter *counter, struct task_struct *p)
2723 * only top level counters have the pid namespace they were created in
2725 if (counter->parent)
2726 counter = counter->parent;
2728 return task_pid_nr_ns(p, counter->ns);
2731 static void perf_output_read_one(struct perf_output_handle *handle,
2732 struct perf_counter *counter)
2734 u64 read_format = counter->attr.read_format;
2738 values[n++] = atomic64_read(&counter->count);
2739 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
2740 values[n++] = counter->total_time_enabled +
2741 atomic64_read(&counter->child_total_time_enabled);
2743 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
2744 values[n++] = counter->total_time_running +
2745 atomic64_read(&counter->child_total_time_running);
2747 if (read_format & PERF_FORMAT_ID)
2748 values[n++] = primary_counter_id(counter);
2750 perf_output_copy(handle, values, n * sizeof(u64));
2754 * XXX PERF_FORMAT_GROUP vs inherited counters seems difficult.
2756 static void perf_output_read_group(struct perf_output_handle *handle,
2757 struct perf_counter *counter)
2759 struct perf_counter *leader = counter->group_leader, *sub;
2760 u64 read_format = counter->attr.read_format;
2764 values[n++] = 1 + leader->nr_siblings;
2766 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
2767 values[n++] = leader->total_time_enabled;
2769 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
2770 values[n++] = leader->total_time_running;
2772 if (leader != counter)
2773 leader->pmu->read(leader);
2775 values[n++] = atomic64_read(&leader->count);
2776 if (read_format & PERF_FORMAT_ID)
2777 values[n++] = primary_counter_id(leader);
2779 perf_output_copy(handle, values, n * sizeof(u64));
2781 list_for_each_entry(sub, &leader->sibling_list, list_entry) {
2785 sub->pmu->read(sub);
2787 values[n++] = atomic64_read(&sub->count);
2788 if (read_format & PERF_FORMAT_ID)
2789 values[n++] = primary_counter_id(sub);
2791 perf_output_copy(handle, values, n * sizeof(u64));
2795 static void perf_output_read(struct perf_output_handle *handle,
2796 struct perf_counter *counter)
2798 if (counter->attr.read_format & PERF_FORMAT_GROUP)
2799 perf_output_read_group(handle, counter);
2801 perf_output_read_one(handle, counter);
2804 void perf_counter_output(struct perf_counter *counter, int nmi,
2805 struct perf_sample_data *data)
2808 u64 sample_type = counter->attr.sample_type;
2809 struct perf_output_handle handle;
2810 struct perf_event_header header;
2815 struct perf_callchain_entry *callchain = NULL;
2816 int callchain_size = 0;
2822 header.type = PERF_EVENT_SAMPLE;
2823 header.size = sizeof(header);
2826 header.misc |= perf_misc_flags(data->regs);
2828 if (sample_type & PERF_SAMPLE_IP) {
2829 ip = perf_instruction_pointer(data->regs);
2830 header.size += sizeof(ip);
2833 if (sample_type & PERF_SAMPLE_TID) {
2834 /* namespace issues */
2835 tid_entry.pid = perf_counter_pid(counter, current);
2836 tid_entry.tid = perf_counter_tid(counter, current);
2838 header.size += sizeof(tid_entry);
2841 if (sample_type & PERF_SAMPLE_TIME) {
2843 * Maybe do better on x86 and provide cpu_clock_nmi()
2845 time = sched_clock();
2847 header.size += sizeof(u64);
2850 if (sample_type & PERF_SAMPLE_ADDR)
2851 header.size += sizeof(u64);
2853 if (sample_type & PERF_SAMPLE_ID)
2854 header.size += sizeof(u64);
2856 if (sample_type & PERF_SAMPLE_STREAM_ID)
2857 header.size += sizeof(u64);
2859 if (sample_type & PERF_SAMPLE_CPU) {
2860 header.size += sizeof(cpu_entry);
2862 cpu_entry.cpu = raw_smp_processor_id();
2863 cpu_entry.reserved = 0;
2866 if (sample_type & PERF_SAMPLE_PERIOD)
2867 header.size += sizeof(u64);
2869 if (sample_type & PERF_SAMPLE_READ)
2870 header.size += perf_counter_read_size(counter);
2872 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
2873 callchain = perf_callchain(data->regs);
2876 callchain_size = (1 + callchain->nr) * sizeof(u64);
2877 header.size += callchain_size;
2879 header.size += sizeof(u64);
2882 if (sample_type & PERF_SAMPLE_RAW) {
2883 int size = sizeof(u32);
2886 size += data->raw->size;
2888 size += sizeof(u32);
2890 WARN_ON_ONCE(size & (sizeof(u64)-1));
2891 header.size += size;
2894 ret = perf_output_begin(&handle, counter, header.size, nmi, 1);
2898 perf_output_put(&handle, header);
2900 if (sample_type & PERF_SAMPLE_IP)
2901 perf_output_put(&handle, ip);
2903 if (sample_type & PERF_SAMPLE_TID)
2904 perf_output_put(&handle, tid_entry);
2906 if (sample_type & PERF_SAMPLE_TIME)
2907 perf_output_put(&handle, time);
2909 if (sample_type & PERF_SAMPLE_ADDR)
2910 perf_output_put(&handle, data->addr);
2912 if (sample_type & PERF_SAMPLE_ID) {
2913 u64 id = primary_counter_id(counter);
2915 perf_output_put(&handle, id);
2918 if (sample_type & PERF_SAMPLE_STREAM_ID)
2919 perf_output_put(&handle, counter->id);
2921 if (sample_type & PERF_SAMPLE_CPU)
2922 perf_output_put(&handle, cpu_entry);
2924 if (sample_type & PERF_SAMPLE_PERIOD)
2925 perf_output_put(&handle, data->period);
2927 if (sample_type & PERF_SAMPLE_READ)
2928 perf_output_read(&handle, counter);
2930 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
2932 perf_output_copy(&handle, callchain, callchain_size);
2935 perf_output_put(&handle, nr);
2939 if (sample_type & PERF_SAMPLE_RAW) {
2941 perf_output_put(&handle, data->raw->size);
2942 perf_output_copy(&handle, data->raw->data, data->raw->size);
2948 .size = sizeof(u32),
2951 perf_output_put(&handle, raw);
2955 perf_output_end(&handle);
2962 struct perf_read_event {
2963 struct perf_event_header header;
2970 perf_counter_read_event(struct perf_counter *counter,
2971 struct task_struct *task)
2973 struct perf_output_handle handle;
2974 struct perf_read_event event = {
2976 .type = PERF_EVENT_READ,
2978 .size = sizeof(event) + perf_counter_read_size(counter),
2980 .pid = perf_counter_pid(counter, task),
2981 .tid = perf_counter_tid(counter, task),
2985 ret = perf_output_begin(&handle, counter, event.header.size, 0, 0);
2989 perf_output_put(&handle, event);
2990 perf_output_read(&handle, counter);
2992 perf_output_end(&handle);
2996 * task tracking -- fork/exit
2998 * enabled by: attr.comm | attr.mmap | attr.task
3001 struct perf_task_event {
3002 struct task_struct *task;
3003 struct perf_counter_context *task_ctx;
3006 struct perf_event_header header;
3015 static void perf_counter_task_output(struct perf_counter *counter,
3016 struct perf_task_event *task_event)
3018 struct perf_output_handle handle;
3019 int size = task_event->event.header.size;
3020 struct task_struct *task = task_event->task;
3021 int ret = perf_output_begin(&handle, counter, size, 0, 0);
3026 task_event->event.pid = perf_counter_pid(counter, task);
3027 task_event->event.ppid = perf_counter_pid(counter, task->real_parent);
3029 task_event->event.tid = perf_counter_tid(counter, task);
3030 task_event->event.ptid = perf_counter_tid(counter, task->real_parent);
3032 perf_output_put(&handle, task_event->event);
3033 perf_output_end(&handle);
3036 static int perf_counter_task_match(struct perf_counter *counter)
3038 if (counter->attr.comm || counter->attr.mmap || counter->attr.task)
3044 static void perf_counter_task_ctx(struct perf_counter_context *ctx,
3045 struct perf_task_event *task_event)
3047 struct perf_counter *counter;
3049 if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
3053 list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
3054 if (perf_counter_task_match(counter))
3055 perf_counter_task_output(counter, task_event);
3060 static void perf_counter_task_event(struct perf_task_event *task_event)
3062 struct perf_cpu_context *cpuctx;
3063 struct perf_counter_context *ctx = task_event->task_ctx;
3065 cpuctx = &get_cpu_var(perf_cpu_context);
3066 perf_counter_task_ctx(&cpuctx->ctx, task_event);
3067 put_cpu_var(perf_cpu_context);
3071 ctx = rcu_dereference(task_event->task->perf_counter_ctxp);
3073 perf_counter_task_ctx(ctx, task_event);
3077 static void perf_counter_task(struct task_struct *task,
3078 struct perf_counter_context *task_ctx,
3081 struct perf_task_event task_event;
3083 if (!atomic_read(&nr_comm_counters) &&
3084 !atomic_read(&nr_mmap_counters) &&
3085 !atomic_read(&nr_task_counters))
3088 task_event = (struct perf_task_event){
3090 .task_ctx = task_ctx,
3093 .type = new ? PERF_EVENT_FORK : PERF_EVENT_EXIT,
3095 .size = sizeof(task_event.event),
3104 perf_counter_task_event(&task_event);
3107 void perf_counter_fork(struct task_struct *task)
3109 perf_counter_task(task, NULL, 1);
3116 struct perf_comm_event {
3117 struct task_struct *task;
3122 struct perf_event_header header;
3129 static void perf_counter_comm_output(struct perf_counter *counter,
3130 struct perf_comm_event *comm_event)
3132 struct perf_output_handle handle;
3133 int size = comm_event->event.header.size;
3134 int ret = perf_output_begin(&handle, counter, size, 0, 0);
3139 comm_event->event.pid = perf_counter_pid(counter, comm_event->task);
3140 comm_event->event.tid = perf_counter_tid(counter, comm_event->task);
3142 perf_output_put(&handle, comm_event->event);
3143 perf_output_copy(&handle, comm_event->comm,
3144 comm_event->comm_size);
3145 perf_output_end(&handle);
3148 static int perf_counter_comm_match(struct perf_counter *counter)
3150 if (counter->attr.comm)
3156 static void perf_counter_comm_ctx(struct perf_counter_context *ctx,
3157 struct perf_comm_event *comm_event)
3159 struct perf_counter *counter;
3161 if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
3165 list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
3166 if (perf_counter_comm_match(counter))
3167 perf_counter_comm_output(counter, comm_event);
3172 static void perf_counter_comm_event(struct perf_comm_event *comm_event)
3174 struct perf_cpu_context *cpuctx;
3175 struct perf_counter_context *ctx;
3177 char comm[TASK_COMM_LEN];
3179 memset(comm, 0, sizeof(comm));
3180 strncpy(comm, comm_event->task->comm, sizeof(comm));
3181 size = ALIGN(strlen(comm)+1, sizeof(u64));
3183 comm_event->comm = comm;
3184 comm_event->comm_size = size;
3186 comm_event->event.header.size = sizeof(comm_event->event) + size;
3188 cpuctx = &get_cpu_var(perf_cpu_context);
3189 perf_counter_comm_ctx(&cpuctx->ctx, comm_event);
3190 put_cpu_var(perf_cpu_context);
3194 * doesn't really matter which of the child contexts the
3195 * events ends up in.
3197 ctx = rcu_dereference(current->perf_counter_ctxp);
3199 perf_counter_comm_ctx(ctx, comm_event);
3203 void perf_counter_comm(struct task_struct *task)
3205 struct perf_comm_event comm_event;
3207 if (task->perf_counter_ctxp)
3208 perf_counter_enable_on_exec(task);
3210 if (!atomic_read(&nr_comm_counters))
3213 comm_event = (struct perf_comm_event){
3219 .type = PERF_EVENT_COMM,
3228 perf_counter_comm_event(&comm_event);
3235 struct perf_mmap_event {
3236 struct vm_area_struct *vma;
3238 const char *file_name;
3242 struct perf_event_header header;
3252 static void perf_counter_mmap_output(struct perf_counter *counter,
3253 struct perf_mmap_event *mmap_event)
3255 struct perf_output_handle handle;
3256 int size = mmap_event->event.header.size;
3257 int ret = perf_output_begin(&handle, counter, size, 0, 0);
3262 mmap_event->event.pid = perf_counter_pid(counter, current);
3263 mmap_event->event.tid = perf_counter_tid(counter, current);
3265 perf_output_put(&handle, mmap_event->event);
3266 perf_output_copy(&handle, mmap_event->file_name,
3267 mmap_event->file_size);
3268 perf_output_end(&handle);
3271 static int perf_counter_mmap_match(struct perf_counter *counter,
3272 struct perf_mmap_event *mmap_event)
3274 if (counter->attr.mmap)
3280 static void perf_counter_mmap_ctx(struct perf_counter_context *ctx,
3281 struct perf_mmap_event *mmap_event)
3283 struct perf_counter *counter;
3285 if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
3289 list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
3290 if (perf_counter_mmap_match(counter, mmap_event))
3291 perf_counter_mmap_output(counter, mmap_event);
3296 static void perf_counter_mmap_event(struct perf_mmap_event *mmap_event)
3298 struct perf_cpu_context *cpuctx;
3299 struct perf_counter_context *ctx;
3300 struct vm_area_struct *vma = mmap_event->vma;
3301 struct file *file = vma->vm_file;
3307 memset(tmp, 0, sizeof(tmp));
3311 * d_path works from the end of the buffer backwards, so we
3312 * need to add enough zero bytes after the string to handle
3313 * the 64bit alignment we do later.
3315 buf = kzalloc(PATH_MAX + sizeof(u64), GFP_KERNEL);
3317 name = strncpy(tmp, "//enomem", sizeof(tmp));
3320 name = d_path(&file->f_path, buf, PATH_MAX);
3322 name = strncpy(tmp, "//toolong", sizeof(tmp));
3326 if (arch_vma_name(mmap_event->vma)) {
3327 name = strncpy(tmp, arch_vma_name(mmap_event->vma),
3333 name = strncpy(tmp, "[vdso]", sizeof(tmp));
3337 name = strncpy(tmp, "//anon", sizeof(tmp));
3342 size = ALIGN(strlen(name)+1, sizeof(u64));
3344 mmap_event->file_name = name;
3345 mmap_event->file_size = size;
3347 mmap_event->event.header.size = sizeof(mmap_event->event) + size;
3349 cpuctx = &get_cpu_var(perf_cpu_context);
3350 perf_counter_mmap_ctx(&cpuctx->ctx, mmap_event);
3351 put_cpu_var(perf_cpu_context);
3355 * doesn't really matter which of the child contexts the
3356 * events ends up in.
3358 ctx = rcu_dereference(current->perf_counter_ctxp);
3360 perf_counter_mmap_ctx(ctx, mmap_event);
3366 void __perf_counter_mmap(struct vm_area_struct *vma)
3368 struct perf_mmap_event mmap_event;
3370 if (!atomic_read(&nr_mmap_counters))
3373 mmap_event = (struct perf_mmap_event){
3379 .type = PERF_EVENT_MMAP,
3385 .start = vma->vm_start,
3386 .len = vma->vm_end - vma->vm_start,
3387 .pgoff = vma->vm_pgoff,
3391 perf_counter_mmap_event(&mmap_event);
3395 * IRQ throttle logging
3398 static void perf_log_throttle(struct perf_counter *counter, int enable)
3400 struct perf_output_handle handle;
3404 struct perf_event_header header;
3408 } throttle_event = {
3410 .type = PERF_EVENT_THROTTLE,
3412 .size = sizeof(throttle_event),
3414 .time = sched_clock(),
3415 .id = primary_counter_id(counter),
3416 .stream_id = counter->id,
3420 throttle_event.header.type = PERF_EVENT_UNTHROTTLE;
3422 ret = perf_output_begin(&handle, counter, sizeof(throttle_event), 1, 0);
3426 perf_output_put(&handle, throttle_event);
3427 perf_output_end(&handle);
3431 * Generic counter overflow handling, sampling.
3434 int perf_counter_overflow(struct perf_counter *counter, int nmi,
3435 struct perf_sample_data *data)
3437 int events = atomic_read(&counter->event_limit);
3438 int throttle = counter->pmu->unthrottle != NULL;
3439 struct hw_perf_counter *hwc = &counter->hw;
3445 if (hwc->interrupts != MAX_INTERRUPTS) {
3447 if (HZ * hwc->interrupts >
3448 (u64)sysctl_perf_counter_sample_rate) {
3449 hwc->interrupts = MAX_INTERRUPTS;
3450 perf_log_throttle(counter, 0);
3455 * Keep re-disabling counters even though on the previous
3456 * pass we disabled it - just in case we raced with a
3457 * sched-in and the counter got enabled again:
3463 if (counter->attr.freq) {
3464 u64 now = sched_clock();
3465 s64 delta = now - hwc->freq_stamp;
3467 hwc->freq_stamp = now;
3469 if (delta > 0 && delta < TICK_NSEC)
3470 perf_adjust_period(counter, NSEC_PER_SEC / (int)delta);
3474 * XXX event_limit might not quite work as expected on inherited
3478 counter->pending_kill = POLL_IN;
3479 if (events && atomic_dec_and_test(&counter->event_limit)) {
3481 counter->pending_kill = POLL_HUP;
3483 counter->pending_disable = 1;
3484 perf_pending_queue(&counter->pending,
3485 perf_pending_counter);
3487 perf_counter_disable(counter);
3490 perf_counter_output(counter, nmi, data);
3495 * Generic software counter infrastructure
3499 * We directly increment counter->count and keep a second value in
3500 * counter->hw.period_left to count intervals. This period counter
3501 * is kept in the range [-sample_period, 0] so that we can use the
3505 static u64 perf_swcounter_set_period(struct perf_counter *counter)
3507 struct hw_perf_counter *hwc = &counter->hw;
3508 u64 period = hwc->last_period;
3512 hwc->last_period = hwc->sample_period;
3515 old = val = atomic64_read(&hwc->period_left);
3519 nr = div64_u64(period + val, period);
3520 offset = nr * period;
3522 if (atomic64_cmpxchg(&hwc->period_left, old, val) != old)
3528 static void perf_swcounter_overflow(struct perf_counter *counter,
3529 int nmi, struct perf_sample_data *data)
3531 struct hw_perf_counter *hwc = &counter->hw;
3534 data->period = counter->hw.last_period;
3535 overflow = perf_swcounter_set_period(counter);
3537 if (hwc->interrupts == MAX_INTERRUPTS)
3540 for (; overflow; overflow--) {
3541 if (perf_counter_overflow(counter, nmi, data)) {
3543 * We inhibit the overflow from happening when
3544 * hwc->interrupts == MAX_INTERRUPTS.
3551 static void perf_swcounter_unthrottle(struct perf_counter *counter)
3554 * Nothing to do, we already reset hwc->interrupts.
3558 static void perf_swcounter_add(struct perf_counter *counter, u64 nr,
3559 int nmi, struct perf_sample_data *data)
3561 struct hw_perf_counter *hwc = &counter->hw;
3563 atomic64_add(nr, &counter->count);
3565 if (!hwc->sample_period)
3571 if (!atomic64_add_negative(nr, &hwc->period_left))
3572 perf_swcounter_overflow(counter, nmi, data);
3575 static int perf_swcounter_is_counting(struct perf_counter *counter)
3578 * The counter is active, we're good!
3580 if (counter->state == PERF_COUNTER_STATE_ACTIVE)
3584 * The counter is off/error, not counting.
3586 if (counter->state != PERF_COUNTER_STATE_INACTIVE)
3590 * The counter is inactive, if the context is active
3591 * we're part of a group that didn't make it on the 'pmu',
3594 if (counter->ctx->is_active)
3598 * We're inactive and the context is too, this means the
3599 * task is scheduled out, we're counting events that happen
3600 * to us, like migration events.
3605 static int perf_swcounter_match(struct perf_counter *counter,
3606 enum perf_type_id type,
3607 u32 event, struct pt_regs *regs)
3609 if (!perf_swcounter_is_counting(counter))
3612 if (counter->attr.type != type)
3614 if (counter->attr.config != event)
3618 if (counter->attr.exclude_user && user_mode(regs))
3621 if (counter->attr.exclude_kernel && !user_mode(regs))
3628 static void perf_swcounter_ctx_event(struct perf_counter_context *ctx,
3629 enum perf_type_id type,
3630 u32 event, u64 nr, int nmi,
3631 struct perf_sample_data *data)
3633 struct perf_counter *counter;
3635 if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
3639 list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
3640 if (perf_swcounter_match(counter, type, event, data->regs))
3641 perf_swcounter_add(counter, nr, nmi, data);
3646 static int *perf_swcounter_recursion_context(struct perf_cpu_context *cpuctx)
3649 return &cpuctx->recursion[3];
3652 return &cpuctx->recursion[2];
3655 return &cpuctx->recursion[1];
3657 return &cpuctx->recursion[0];
3660 static void do_perf_swcounter_event(enum perf_type_id type, u32 event,
3662 struct perf_sample_data *data)
3664 struct perf_cpu_context *cpuctx = &get_cpu_var(perf_cpu_context);
3665 int *recursion = perf_swcounter_recursion_context(cpuctx);
3666 struct perf_counter_context *ctx;
3674 perf_swcounter_ctx_event(&cpuctx->ctx, type, event,
3678 * doesn't really matter which of the child contexts the
3679 * events ends up in.
3681 ctx = rcu_dereference(current->perf_counter_ctxp);
3683 perf_swcounter_ctx_event(ctx, type, event, nr, nmi, data);
3690 put_cpu_var(perf_cpu_context);
3693 void __perf_swcounter_event(u32 event, u64 nr, int nmi,
3694 struct pt_regs *regs, u64 addr)
3696 struct perf_sample_data data = {
3701 do_perf_swcounter_event(PERF_TYPE_SOFTWARE, event, nr, nmi, &data);
3704 static void perf_swcounter_read(struct perf_counter *counter)
3708 static int perf_swcounter_enable(struct perf_counter *counter)
3710 struct hw_perf_counter *hwc = &counter->hw;
3712 if (hwc->sample_period) {
3713 hwc->last_period = hwc->sample_period;
3714 perf_swcounter_set_period(counter);
3719 static void perf_swcounter_disable(struct perf_counter *counter)
3723 static const struct pmu perf_ops_generic = {
3724 .enable = perf_swcounter_enable,
3725 .disable = perf_swcounter_disable,
3726 .read = perf_swcounter_read,
3727 .unthrottle = perf_swcounter_unthrottle,
3731 * hrtimer based swcounter callback
3734 static enum hrtimer_restart perf_swcounter_hrtimer(struct hrtimer *hrtimer)
3736 enum hrtimer_restart ret = HRTIMER_RESTART;
3737 struct perf_sample_data data;
3738 struct perf_counter *counter;
3741 counter = container_of(hrtimer, struct perf_counter, hw.hrtimer);
3742 counter->pmu->read(counter);
3745 data.regs = get_irq_regs();
3747 * In case we exclude kernel IPs or are somehow not in interrupt
3748 * context, provide the next best thing, the user IP.
3750 if ((counter->attr.exclude_kernel || !data.regs) &&
3751 !counter->attr.exclude_user)
3752 data.regs = task_pt_regs(current);
3755 if (perf_counter_overflow(counter, 0, &data))
3756 ret = HRTIMER_NORESTART;
3759 period = max_t(u64, 10000, counter->hw.sample_period);
3760 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
3766 * Software counter: cpu wall time clock
3769 static void cpu_clock_perf_counter_update(struct perf_counter *counter)
3771 int cpu = raw_smp_processor_id();
3775 now = cpu_clock(cpu);
3776 prev = atomic64_read(&counter->hw.prev_count);
3777 atomic64_set(&counter->hw.prev_count, now);
3778 atomic64_add(now - prev, &counter->count);
3781 static int cpu_clock_perf_counter_enable(struct perf_counter *counter)
3783 struct hw_perf_counter *hwc = &counter->hw;
3784 int cpu = raw_smp_processor_id();
3786 atomic64_set(&hwc->prev_count, cpu_clock(cpu));
3787 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3788 hwc->hrtimer.function = perf_swcounter_hrtimer;
3789 if (hwc->sample_period) {
3790 u64 period = max_t(u64, 10000, hwc->sample_period);
3791 __hrtimer_start_range_ns(&hwc->hrtimer,
3792 ns_to_ktime(period), 0,
3793 HRTIMER_MODE_REL, 0);
3799 static void cpu_clock_perf_counter_disable(struct perf_counter *counter)
3801 if (counter->hw.sample_period)
3802 hrtimer_cancel(&counter->hw.hrtimer);
3803 cpu_clock_perf_counter_update(counter);
3806 static void cpu_clock_perf_counter_read(struct perf_counter *counter)
3808 cpu_clock_perf_counter_update(counter);
3811 static const struct pmu perf_ops_cpu_clock = {
3812 .enable = cpu_clock_perf_counter_enable,
3813 .disable = cpu_clock_perf_counter_disable,
3814 .read = cpu_clock_perf_counter_read,
3818 * Software counter: task time clock
3821 static void task_clock_perf_counter_update(struct perf_counter *counter, u64 now)
3826 prev = atomic64_xchg(&counter->hw.prev_count, now);
3828 atomic64_add(delta, &counter->count);
3831 static int task_clock_perf_counter_enable(struct perf_counter *counter)
3833 struct hw_perf_counter *hwc = &counter->hw;
3836 now = counter->ctx->time;
3838 atomic64_set(&hwc->prev_count, now);
3839 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3840 hwc->hrtimer.function = perf_swcounter_hrtimer;
3841 if (hwc->sample_period) {
3842 u64 period = max_t(u64, 10000, hwc->sample_period);
3843 __hrtimer_start_range_ns(&hwc->hrtimer,
3844 ns_to_ktime(period), 0,
3845 HRTIMER_MODE_REL, 0);
3851 static void task_clock_perf_counter_disable(struct perf_counter *counter)
3853 if (counter->hw.sample_period)
3854 hrtimer_cancel(&counter->hw.hrtimer);
3855 task_clock_perf_counter_update(counter, counter->ctx->time);
3859 static void task_clock_perf_counter_read(struct perf_counter *counter)
3864 update_context_time(counter->ctx);
3865 time = counter->ctx->time;
3867 u64 now = perf_clock();
3868 u64 delta = now - counter->ctx->timestamp;
3869 time = counter->ctx->time + delta;
3872 task_clock_perf_counter_update(counter, time);
3875 static const struct pmu perf_ops_task_clock = {
3876 .enable = task_clock_perf_counter_enable,
3877 .disable = task_clock_perf_counter_disable,
3878 .read = task_clock_perf_counter_read,
3881 #ifdef CONFIG_EVENT_PROFILE
3882 void perf_tpcounter_event(int event_id, u64 addr, u64 count, void *record,
3885 struct perf_raw_record raw = {
3890 struct perf_sample_data data = {
3891 .regs = get_irq_regs(),
3897 data.regs = task_pt_regs(current);
3899 do_perf_swcounter_event(PERF_TYPE_TRACEPOINT, event_id, count, 1, &data);
3901 EXPORT_SYMBOL_GPL(perf_tpcounter_event);
3903 extern int ftrace_profile_enable(int);
3904 extern void ftrace_profile_disable(int);
3906 static void tp_perf_counter_destroy(struct perf_counter *counter)
3908 ftrace_profile_disable(counter->attr.config);
3911 static const struct pmu *tp_perf_counter_init(struct perf_counter *counter)
3914 * Raw tracepoint data is a severe data leak, only allow root to
3917 if ((counter->attr.sample_type & PERF_SAMPLE_RAW) &&
3918 !capable(CAP_SYS_ADMIN))
3919 return ERR_PTR(-EPERM);
3921 if (ftrace_profile_enable(counter->attr.config))
3924 counter->destroy = tp_perf_counter_destroy;
3926 return &perf_ops_generic;
3929 static const struct pmu *tp_perf_counter_init(struct perf_counter *counter)
3935 atomic_t perf_swcounter_enabled[PERF_COUNT_SW_MAX];
3937 static void sw_perf_counter_destroy(struct perf_counter *counter)
3939 u64 event = counter->attr.config;
3941 WARN_ON(counter->parent);
3943 atomic_dec(&perf_swcounter_enabled[event]);
3946 static const struct pmu *sw_perf_counter_init(struct perf_counter *counter)
3948 const struct pmu *pmu = NULL;
3949 u64 event = counter->attr.config;
3952 * Software counters (currently) can't in general distinguish
3953 * between user, kernel and hypervisor events.
3954 * However, context switches and cpu migrations are considered
3955 * to be kernel events, and page faults are never hypervisor
3959 case PERF_COUNT_SW_CPU_CLOCK:
3960 pmu = &perf_ops_cpu_clock;
3963 case PERF_COUNT_SW_TASK_CLOCK:
3965 * If the user instantiates this as a per-cpu counter,
3966 * use the cpu_clock counter instead.
3968 if (counter->ctx->task)
3969 pmu = &perf_ops_task_clock;
3971 pmu = &perf_ops_cpu_clock;
3974 case PERF_COUNT_SW_PAGE_FAULTS:
3975 case PERF_COUNT_SW_PAGE_FAULTS_MIN:
3976 case PERF_COUNT_SW_PAGE_FAULTS_MAJ:
3977 case PERF_COUNT_SW_CONTEXT_SWITCHES:
3978 case PERF_COUNT_SW_CPU_MIGRATIONS:
3979 if (!counter->parent) {
3980 atomic_inc(&perf_swcounter_enabled[event]);
3981 counter->destroy = sw_perf_counter_destroy;
3983 pmu = &perf_ops_generic;
3991 * Allocate and initialize a counter structure
3993 static struct perf_counter *
3994 perf_counter_alloc(struct perf_counter_attr *attr,
3996 struct perf_counter_context *ctx,
3997 struct perf_counter *group_leader,
3998 struct perf_counter *parent_counter,
4001 const struct pmu *pmu;
4002 struct perf_counter *counter;
4003 struct hw_perf_counter *hwc;
4006 counter = kzalloc(sizeof(*counter), gfpflags);
4008 return ERR_PTR(-ENOMEM);
4011 * Single counters are their own group leaders, with an
4012 * empty sibling list:
4015 group_leader = counter;
4017 mutex_init(&counter->child_mutex);
4018 INIT_LIST_HEAD(&counter->child_list);
4020 INIT_LIST_HEAD(&counter->list_entry);
4021 INIT_LIST_HEAD(&counter->event_entry);
4022 INIT_LIST_HEAD(&counter->sibling_list);
4023 init_waitqueue_head(&counter->waitq);
4025 mutex_init(&counter->mmap_mutex);
4028 counter->attr = *attr;
4029 counter->group_leader = group_leader;
4030 counter->pmu = NULL;
4032 counter->oncpu = -1;
4034 counter->parent = parent_counter;
4036 counter->ns = get_pid_ns(current->nsproxy->pid_ns);
4037 counter->id = atomic64_inc_return(&perf_counter_id);
4039 counter->state = PERF_COUNTER_STATE_INACTIVE;
4042 counter->state = PERF_COUNTER_STATE_OFF;
4047 hwc->sample_period = attr->sample_period;
4048 if (attr->freq && attr->sample_freq)
4049 hwc->sample_period = 1;
4051 atomic64_set(&hwc->period_left, hwc->sample_period);
4054 * we currently do not support PERF_FORMAT_GROUP on inherited counters
4056 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
4059 switch (attr->type) {
4061 case PERF_TYPE_HARDWARE:
4062 case PERF_TYPE_HW_CACHE:
4063 pmu = hw_perf_counter_init(counter);
4066 case PERF_TYPE_SOFTWARE:
4067 pmu = sw_perf_counter_init(counter);
4070 case PERF_TYPE_TRACEPOINT:
4071 pmu = tp_perf_counter_init(counter);
4081 else if (IS_ERR(pmu))
4086 put_pid_ns(counter->ns);
4088 return ERR_PTR(err);
4093 if (!counter->parent) {
4094 atomic_inc(&nr_counters);
4095 if (counter->attr.mmap)
4096 atomic_inc(&nr_mmap_counters);
4097 if (counter->attr.comm)
4098 atomic_inc(&nr_comm_counters);
4099 if (counter->attr.task)
4100 atomic_inc(&nr_task_counters);
4106 static int perf_copy_attr(struct perf_counter_attr __user *uattr,
4107 struct perf_counter_attr *attr)
4112 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
4116 * zero the full structure, so that a short copy will be nice.
4118 memset(attr, 0, sizeof(*attr));
4120 ret = get_user(size, &uattr->size);
4124 if (size > PAGE_SIZE) /* silly large */
4127 if (!size) /* abi compat */
4128 size = PERF_ATTR_SIZE_VER0;
4130 if (size < PERF_ATTR_SIZE_VER0)
4134 * If we're handed a bigger struct than we know of,
4135 * ensure all the unknown bits are 0.
4137 if (size > sizeof(*attr)) {
4139 unsigned long __user *addr;
4140 unsigned long __user *end;
4142 addr = PTR_ALIGN((void __user *)uattr + sizeof(*attr),
4143 sizeof(unsigned long));
4144 end = PTR_ALIGN((void __user *)uattr + size,
4145 sizeof(unsigned long));
4147 for (; addr < end; addr += sizeof(unsigned long)) {
4148 ret = get_user(val, addr);
4156 ret = copy_from_user(attr, uattr, size);
4161 * If the type exists, the corresponding creation will verify
4164 if (attr->type >= PERF_TYPE_MAX)
4167 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
4170 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
4173 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
4180 put_user(sizeof(*attr), &uattr->size);
4186 * sys_perf_counter_open - open a performance counter, associate it to a task/cpu
4188 * @attr_uptr: event type attributes for monitoring/sampling
4191 * @group_fd: group leader counter fd
4193 SYSCALL_DEFINE5(perf_counter_open,
4194 struct perf_counter_attr __user *, attr_uptr,
4195 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
4197 struct perf_counter *counter, *group_leader;
4198 struct perf_counter_attr attr;
4199 struct perf_counter_context *ctx;
4200 struct file *counter_file = NULL;
4201 struct file *group_file = NULL;
4202 int fput_needed = 0;
4203 int fput_needed2 = 0;
4206 /* for future expandability... */
4210 ret = perf_copy_attr(attr_uptr, &attr);
4214 if (!attr.exclude_kernel) {
4215 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
4220 if (attr.sample_freq > sysctl_perf_counter_sample_rate)
4225 * Get the target context (task or percpu):
4227 ctx = find_get_context(pid, cpu);
4229 return PTR_ERR(ctx);
4232 * Look up the group leader (we will attach this counter to it):
4234 group_leader = NULL;
4235 if (group_fd != -1) {
4237 group_file = fget_light(group_fd, &fput_needed);
4239 goto err_put_context;
4240 if (group_file->f_op != &perf_fops)
4241 goto err_put_context;
4243 group_leader = group_file->private_data;
4245 * Do not allow a recursive hierarchy (this new sibling
4246 * becoming part of another group-sibling):
4248 if (group_leader->group_leader != group_leader)
4249 goto err_put_context;
4251 * Do not allow to attach to a group in a different
4252 * task or CPU context:
4254 if (group_leader->ctx != ctx)
4255 goto err_put_context;
4257 * Only a group leader can be exclusive or pinned
4259 if (attr.exclusive || attr.pinned)
4260 goto err_put_context;
4263 counter = perf_counter_alloc(&attr, cpu, ctx, group_leader,
4265 ret = PTR_ERR(counter);
4266 if (IS_ERR(counter))
4267 goto err_put_context;
4269 ret = anon_inode_getfd("[perf_counter]", &perf_fops, counter, 0);
4271 goto err_free_put_context;
4273 counter_file = fget_light(ret, &fput_needed2);
4275 goto err_free_put_context;
4277 counter->filp = counter_file;
4278 WARN_ON_ONCE(ctx->parent_ctx);
4279 mutex_lock(&ctx->mutex);
4280 perf_install_in_context(ctx, counter, cpu);
4282 mutex_unlock(&ctx->mutex);
4284 counter->owner = current;
4285 get_task_struct(current);
4286 mutex_lock(¤t->perf_counter_mutex);
4287 list_add_tail(&counter->owner_entry, ¤t->perf_counter_list);
4288 mutex_unlock(¤t->perf_counter_mutex);
4290 fput_light(counter_file, fput_needed2);
4293 fput_light(group_file, fput_needed);
4297 err_free_put_context:
4307 * inherit a counter from parent task to child task:
4309 static struct perf_counter *
4310 inherit_counter(struct perf_counter *parent_counter,
4311 struct task_struct *parent,
4312 struct perf_counter_context *parent_ctx,
4313 struct task_struct *child,
4314 struct perf_counter *group_leader,
4315 struct perf_counter_context *child_ctx)
4317 struct perf_counter *child_counter;
4320 * Instead of creating recursive hierarchies of counters,
4321 * we link inherited counters back to the original parent,
4322 * which has a filp for sure, which we use as the reference
4325 if (parent_counter->parent)
4326 parent_counter = parent_counter->parent;
4328 child_counter = perf_counter_alloc(&parent_counter->attr,
4329 parent_counter->cpu, child_ctx,
4330 group_leader, parent_counter,
4332 if (IS_ERR(child_counter))
4333 return child_counter;
4337 * Make the child state follow the state of the parent counter,
4338 * not its attr.disabled bit. We hold the parent's mutex,
4339 * so we won't race with perf_counter_{en, dis}able_family.
4341 if (parent_counter->state >= PERF_COUNTER_STATE_INACTIVE)
4342 child_counter->state = PERF_COUNTER_STATE_INACTIVE;
4344 child_counter->state = PERF_COUNTER_STATE_OFF;
4346 if (parent_counter->attr.freq)
4347 child_counter->hw.sample_period = parent_counter->hw.sample_period;
4350 * Link it up in the child's context:
4352 add_counter_to_ctx(child_counter, child_ctx);
4355 * Get a reference to the parent filp - we will fput it
4356 * when the child counter exits. This is safe to do because
4357 * we are in the parent and we know that the filp still
4358 * exists and has a nonzero count:
4360 atomic_long_inc(&parent_counter->filp->f_count);
4363 * Link this into the parent counter's child list
4365 WARN_ON_ONCE(parent_counter->ctx->parent_ctx);
4366 mutex_lock(&parent_counter->child_mutex);
4367 list_add_tail(&child_counter->child_list, &parent_counter->child_list);
4368 mutex_unlock(&parent_counter->child_mutex);
4370 return child_counter;
4373 static int inherit_group(struct perf_counter *parent_counter,
4374 struct task_struct *parent,
4375 struct perf_counter_context *parent_ctx,
4376 struct task_struct *child,
4377 struct perf_counter_context *child_ctx)
4379 struct perf_counter *leader;
4380 struct perf_counter *sub;
4381 struct perf_counter *child_ctr;
4383 leader = inherit_counter(parent_counter, parent, parent_ctx,
4384 child, NULL, child_ctx);
4386 return PTR_ERR(leader);
4387 list_for_each_entry(sub, &parent_counter->sibling_list, list_entry) {
4388 child_ctr = inherit_counter(sub, parent, parent_ctx,
4389 child, leader, child_ctx);
4390 if (IS_ERR(child_ctr))
4391 return PTR_ERR(child_ctr);
4396 static void sync_child_counter(struct perf_counter *child_counter,
4397 struct task_struct *child)
4399 struct perf_counter *parent_counter = child_counter->parent;
4402 if (child_counter->attr.inherit_stat)
4403 perf_counter_read_event(child_counter, child);
4405 child_val = atomic64_read(&child_counter->count);
4408 * Add back the child's count to the parent's count:
4410 atomic64_add(child_val, &parent_counter->count);
4411 atomic64_add(child_counter->total_time_enabled,
4412 &parent_counter->child_total_time_enabled);
4413 atomic64_add(child_counter->total_time_running,
4414 &parent_counter->child_total_time_running);
4417 * Remove this counter from the parent's list
4419 WARN_ON_ONCE(parent_counter->ctx->parent_ctx);
4420 mutex_lock(&parent_counter->child_mutex);
4421 list_del_init(&child_counter->child_list);
4422 mutex_unlock(&parent_counter->child_mutex);
4425 * Release the parent counter, if this was the last
4428 fput(parent_counter->filp);
4432 __perf_counter_exit_task(struct perf_counter *child_counter,
4433 struct perf_counter_context *child_ctx,
4434 struct task_struct *child)
4436 struct perf_counter *parent_counter;
4438 update_counter_times(child_counter);
4439 perf_counter_remove_from_context(child_counter);
4441 parent_counter = child_counter->parent;
4443 * It can happen that parent exits first, and has counters
4444 * that are still around due to the child reference. These
4445 * counters need to be zapped - but otherwise linger.
4447 if (parent_counter) {
4448 sync_child_counter(child_counter, child);
4449 free_counter(child_counter);
4454 * When a child task exits, feed back counter values to parent counters.
4456 void perf_counter_exit_task(struct task_struct *child)
4458 struct perf_counter *child_counter, *tmp;
4459 struct perf_counter_context *child_ctx;
4460 unsigned long flags;
4462 if (likely(!child->perf_counter_ctxp)) {
4463 perf_counter_task(child, NULL, 0);
4467 local_irq_save(flags);
4469 * We can't reschedule here because interrupts are disabled,
4470 * and either child is current or it is a task that can't be
4471 * scheduled, so we are now safe from rescheduling changing
4474 child_ctx = child->perf_counter_ctxp;
4475 __perf_counter_task_sched_out(child_ctx);
4478 * Take the context lock here so that if find_get_context is
4479 * reading child->perf_counter_ctxp, we wait until it has
4480 * incremented the context's refcount before we do put_ctx below.
4482 spin_lock(&child_ctx->lock);
4483 child->perf_counter_ctxp = NULL;
4485 * If this context is a clone; unclone it so it can't get
4486 * swapped to another process while we're removing all
4487 * the counters from it.
4489 unclone_ctx(child_ctx);
4490 spin_unlock_irqrestore(&child_ctx->lock, flags);
4493 * Report the task dead after unscheduling the counters so that we
4494 * won't get any samples after PERF_EVENT_EXIT. We can however still
4495 * get a few PERF_EVENT_READ events.
4497 perf_counter_task(child, child_ctx, 0);
4500 * We can recurse on the same lock type through:
4502 * __perf_counter_exit_task()
4503 * sync_child_counter()
4504 * fput(parent_counter->filp)
4506 * mutex_lock(&ctx->mutex)
4508 * But since its the parent context it won't be the same instance.
4510 mutex_lock_nested(&child_ctx->mutex, SINGLE_DEPTH_NESTING);
4513 list_for_each_entry_safe(child_counter, tmp, &child_ctx->counter_list,
4515 __perf_counter_exit_task(child_counter, child_ctx, child);
4518 * If the last counter was a group counter, it will have appended all
4519 * its siblings to the list, but we obtained 'tmp' before that which
4520 * will still point to the list head terminating the iteration.
4522 if (!list_empty(&child_ctx->counter_list))
4525 mutex_unlock(&child_ctx->mutex);
4531 * free an unexposed, unused context as created by inheritance by
4532 * init_task below, used by fork() in case of fail.
4534 void perf_counter_free_task(struct task_struct *task)
4536 struct perf_counter_context *ctx = task->perf_counter_ctxp;
4537 struct perf_counter *counter, *tmp;
4542 mutex_lock(&ctx->mutex);
4544 list_for_each_entry_safe(counter, tmp, &ctx->counter_list, list_entry) {
4545 struct perf_counter *parent = counter->parent;
4547 if (WARN_ON_ONCE(!parent))
4550 mutex_lock(&parent->child_mutex);
4551 list_del_init(&counter->child_list);
4552 mutex_unlock(&parent->child_mutex);
4556 list_del_counter(counter, ctx);
4557 free_counter(counter);
4560 if (!list_empty(&ctx->counter_list))
4563 mutex_unlock(&ctx->mutex);
4569 * Initialize the perf_counter context in task_struct
4571 int perf_counter_init_task(struct task_struct *child)
4573 struct perf_counter_context *child_ctx, *parent_ctx;
4574 struct perf_counter_context *cloned_ctx;
4575 struct perf_counter *counter;
4576 struct task_struct *parent = current;
4577 int inherited_all = 1;
4580 child->perf_counter_ctxp = NULL;
4582 mutex_init(&child->perf_counter_mutex);
4583 INIT_LIST_HEAD(&child->perf_counter_list);
4585 if (likely(!parent->perf_counter_ctxp))
4589 * This is executed from the parent task context, so inherit
4590 * counters that have been marked for cloning.
4591 * First allocate and initialize a context for the child.
4594 child_ctx = kmalloc(sizeof(struct perf_counter_context), GFP_KERNEL);
4598 __perf_counter_init_context(child_ctx, child);
4599 child->perf_counter_ctxp = child_ctx;
4600 get_task_struct(child);
4603 * If the parent's context is a clone, pin it so it won't get
4606 parent_ctx = perf_pin_task_context(parent);
4609 * No need to check if parent_ctx != NULL here; since we saw
4610 * it non-NULL earlier, the only reason for it to become NULL
4611 * is if we exit, and since we're currently in the middle of
4612 * a fork we can't be exiting at the same time.
4616 * Lock the parent list. No need to lock the child - not PID
4617 * hashed yet and not running, so nobody can access it.
4619 mutex_lock(&parent_ctx->mutex);
4622 * We dont have to disable NMIs - we are only looking at
4623 * the list, not manipulating it:
4625 list_for_each_entry_rcu(counter, &parent_ctx->event_list, event_entry) {
4626 if (counter != counter->group_leader)
4629 if (!counter->attr.inherit) {
4634 ret = inherit_group(counter, parent, parent_ctx,
4642 if (inherited_all) {
4644 * Mark the child context as a clone of the parent
4645 * context, or of whatever the parent is a clone of.
4646 * Note that if the parent is a clone, it could get
4647 * uncloned at any point, but that doesn't matter
4648 * because the list of counters and the generation
4649 * count can't have changed since we took the mutex.
4651 cloned_ctx = rcu_dereference(parent_ctx->parent_ctx);
4653 child_ctx->parent_ctx = cloned_ctx;
4654 child_ctx->parent_gen = parent_ctx->parent_gen;
4656 child_ctx->parent_ctx = parent_ctx;
4657 child_ctx->parent_gen = parent_ctx->generation;
4659 get_ctx(child_ctx->parent_ctx);
4662 mutex_unlock(&parent_ctx->mutex);
4664 perf_unpin_context(parent_ctx);
4669 static void __cpuinit perf_counter_init_cpu(int cpu)
4671 struct perf_cpu_context *cpuctx;
4673 cpuctx = &per_cpu(perf_cpu_context, cpu);
4674 __perf_counter_init_context(&cpuctx->ctx, NULL);
4676 spin_lock(&perf_resource_lock);
4677 cpuctx->max_pertask = perf_max_counters - perf_reserved_percpu;
4678 spin_unlock(&perf_resource_lock);
4680 hw_perf_counter_setup(cpu);
4683 #ifdef CONFIG_HOTPLUG_CPU
4684 static void __perf_counter_exit_cpu(void *info)
4686 struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
4687 struct perf_counter_context *ctx = &cpuctx->ctx;
4688 struct perf_counter *counter, *tmp;
4690 list_for_each_entry_safe(counter, tmp, &ctx->counter_list, list_entry)
4691 __perf_counter_remove_from_context(counter);
4693 static void perf_counter_exit_cpu(int cpu)
4695 struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
4696 struct perf_counter_context *ctx = &cpuctx->ctx;
4698 mutex_lock(&ctx->mutex);
4699 smp_call_function_single(cpu, __perf_counter_exit_cpu, NULL, 1);
4700 mutex_unlock(&ctx->mutex);
4703 static inline void perf_counter_exit_cpu(int cpu) { }
4706 static int __cpuinit
4707 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
4709 unsigned int cpu = (long)hcpu;
4713 case CPU_UP_PREPARE:
4714 case CPU_UP_PREPARE_FROZEN:
4715 perf_counter_init_cpu(cpu);
4719 case CPU_ONLINE_FROZEN:
4720 hw_perf_counter_setup_online(cpu);
4723 case CPU_DOWN_PREPARE:
4724 case CPU_DOWN_PREPARE_FROZEN:
4725 perf_counter_exit_cpu(cpu);
4736 * This has to have a higher priority than migration_notifier in sched.c.
4738 static struct notifier_block __cpuinitdata perf_cpu_nb = {
4739 .notifier_call = perf_cpu_notify,
4743 void __init perf_counter_init(void)
4745 perf_cpu_notify(&perf_cpu_nb, (unsigned long)CPU_UP_PREPARE,
4746 (void *)(long)smp_processor_id());
4747 perf_cpu_notify(&perf_cpu_nb, (unsigned long)CPU_ONLINE,
4748 (void *)(long)smp_processor_id());
4749 register_cpu_notifier(&perf_cpu_nb);
4752 static ssize_t perf_show_reserve_percpu(struct sysdev_class *class, char *buf)
4754 return sprintf(buf, "%d\n", perf_reserved_percpu);
4758 perf_set_reserve_percpu(struct sysdev_class *class,
4762 struct perf_cpu_context *cpuctx;
4766 err = strict_strtoul(buf, 10, &val);
4769 if (val > perf_max_counters)
4772 spin_lock(&perf_resource_lock);
4773 perf_reserved_percpu = val;
4774 for_each_online_cpu(cpu) {
4775 cpuctx = &per_cpu(perf_cpu_context, cpu);
4776 spin_lock_irq(&cpuctx->ctx.lock);
4777 mpt = min(perf_max_counters - cpuctx->ctx.nr_counters,
4778 perf_max_counters - perf_reserved_percpu);
4779 cpuctx->max_pertask = mpt;
4780 spin_unlock_irq(&cpuctx->ctx.lock);
4782 spin_unlock(&perf_resource_lock);
4787 static ssize_t perf_show_overcommit(struct sysdev_class *class, char *buf)
4789 return sprintf(buf, "%d\n", perf_overcommit);
4793 perf_set_overcommit(struct sysdev_class *class, const char *buf, size_t count)
4798 err = strict_strtoul(buf, 10, &val);
4804 spin_lock(&perf_resource_lock);
4805 perf_overcommit = val;
4806 spin_unlock(&perf_resource_lock);
4811 static SYSDEV_CLASS_ATTR(
4814 perf_show_reserve_percpu,
4815 perf_set_reserve_percpu
4818 static SYSDEV_CLASS_ATTR(
4821 perf_show_overcommit,
4825 static struct attribute *perfclass_attrs[] = {
4826 &attr_reserve_percpu.attr,
4827 &attr_overcommit.attr,
4831 static struct attribute_group perfclass_attr_group = {
4832 .attrs = perfclass_attrs,
4833 .name = "perf_counters",
4836 static int __init perf_counter_sysfs_init(void)
4838 return sysfs_create_group(&cpu_sysdev_class.kset.kobj,
4839 &perfclass_attr_group);
4841 device_initcall(perf_counter_sysfs_init);