Merge branch 'for-linus' of git://git.kernel.dk/linux-2.6-block
[pandora-kernel.git] / kernel / perf_counter.c
1 /*
2  * Performance counter core code
3  *
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>
8  *
9  *  For licensing details see kernel-base/COPYING
10  */
11
12 #include <linux/fs.h>
13 #include <linux/mm.h>
14 #include <linux/cpu.h>
15 #include <linux/smp.h>
16 #include <linux/file.h>
17 #include <linux/poll.h>
18 #include <linux/sysfs.h>
19 #include <linux/dcache.h>
20 #include <linux/percpu.h>
21 #include <linux/ptrace.h>
22 #include <linux/vmstat.h>
23 #include <linux/hardirq.h>
24 #include <linux/rculist.h>
25 #include <linux/uaccess.h>
26 #include <linux/syscalls.h>
27 #include <linux/anon_inodes.h>
28 #include <linux/kernel_stat.h>
29 #include <linux/perf_counter.h>
30
31 #include <asm/irq_regs.h>
32
33 /*
34  * Each CPU has a list of per CPU counters:
35  */
36 DEFINE_PER_CPU(struct perf_cpu_context, perf_cpu_context);
37
38 int perf_max_counters __read_mostly = 1;
39 static int perf_reserved_percpu __read_mostly;
40 static int perf_overcommit __read_mostly = 1;
41
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;
46
47 /*
48  * perf counter paranoia level:
49  *  0 - not paranoid
50  *  1 - disallow cpu counters to unpriv
51  *  2 - disallow kernel profiling to unpriv
52  */
53 int sysctl_perf_counter_paranoid __read_mostly;
54
55 static inline bool perf_paranoid_cpu(void)
56 {
57         return sysctl_perf_counter_paranoid > 0;
58 }
59
60 static inline bool perf_paranoid_kernel(void)
61 {
62         return sysctl_perf_counter_paranoid > 1;
63 }
64
65 int sysctl_perf_counter_mlock __read_mostly = 512; /* 'free' kb per user */
66
67 /*
68  * max perf counter sample rate
69  */
70 int sysctl_perf_counter_sample_rate __read_mostly = 100000;
71
72 static atomic64_t perf_counter_id;
73
74 /*
75  * Lock for (sysadmin-configurable) counter reservations:
76  */
77 static DEFINE_SPINLOCK(perf_resource_lock);
78
79 /*
80  * Architecture provided APIs - weak aliases:
81  */
82 extern __weak const struct pmu *hw_perf_counter_init(struct perf_counter *counter)
83 {
84         return NULL;
85 }
86
87 void __weak hw_perf_disable(void)               { barrier(); }
88 void __weak hw_perf_enable(void)                { barrier(); }
89
90 void __weak hw_perf_counter_setup(int cpu)      { barrier(); }
91
92 int __weak
93 hw_perf_group_sched_in(struct perf_counter *group_leader,
94                struct perf_cpu_context *cpuctx,
95                struct perf_counter_context *ctx, int cpu)
96 {
97         return 0;
98 }
99
100 void __weak perf_counter_print_debug(void)      { }
101
102 static DEFINE_PER_CPU(int, disable_count);
103
104 void __perf_disable(void)
105 {
106         __get_cpu_var(disable_count)++;
107 }
108
109 bool __perf_enable(void)
110 {
111         return !--__get_cpu_var(disable_count);
112 }
113
114 void perf_disable(void)
115 {
116         __perf_disable();
117         hw_perf_disable();
118 }
119
120 void perf_enable(void)
121 {
122         if (__perf_enable())
123                 hw_perf_enable();
124 }
125
126 static void get_ctx(struct perf_counter_context *ctx)
127 {
128         WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
129 }
130
131 static void free_ctx(struct rcu_head *head)
132 {
133         struct perf_counter_context *ctx;
134
135         ctx = container_of(head, struct perf_counter_context, rcu_head);
136         kfree(ctx);
137 }
138
139 static void put_ctx(struct perf_counter_context *ctx)
140 {
141         if (atomic_dec_and_test(&ctx->refcount)) {
142                 if (ctx->parent_ctx)
143                         put_ctx(ctx->parent_ctx);
144                 if (ctx->task)
145                         put_task_struct(ctx->task);
146                 call_rcu(&ctx->rcu_head, free_ctx);
147         }
148 }
149
150 static void unclone_ctx(struct perf_counter_context *ctx)
151 {
152         if (ctx->parent_ctx) {
153                 put_ctx(ctx->parent_ctx);
154                 ctx->parent_ctx = NULL;
155         }
156 }
157
158 /*
159  * If we inherit counters we want to return the parent counter id
160  * to userspace.
161  */
162 static u64 primary_counter_id(struct perf_counter *counter)
163 {
164         u64 id = counter->id;
165
166         if (counter->parent)
167                 id = counter->parent->id;
168
169         return id;
170 }
171
172 /*
173  * Get the perf_counter_context for a task and lock it.
174  * This has to cope with with the fact that until it is locked,
175  * the context could get moved to another task.
176  */
177 static struct perf_counter_context *
178 perf_lock_task_context(struct task_struct *task, unsigned long *flags)
179 {
180         struct perf_counter_context *ctx;
181
182         rcu_read_lock();
183  retry:
184         ctx = rcu_dereference(task->perf_counter_ctxp);
185         if (ctx) {
186                 /*
187                  * If this context is a clone of another, it might
188                  * get swapped for another underneath us by
189                  * perf_counter_task_sched_out, though the
190                  * rcu_read_lock() protects us from any context
191                  * getting freed.  Lock the context and check if it
192                  * got swapped before we could get the lock, and retry
193                  * if so.  If we locked the right context, then it
194                  * can't get swapped on us any more.
195                  */
196                 spin_lock_irqsave(&ctx->lock, *flags);
197                 if (ctx != rcu_dereference(task->perf_counter_ctxp)) {
198                         spin_unlock_irqrestore(&ctx->lock, *flags);
199                         goto retry;
200                 }
201
202                 if (!atomic_inc_not_zero(&ctx->refcount)) {
203                         spin_unlock_irqrestore(&ctx->lock, *flags);
204                         ctx = NULL;
205                 }
206         }
207         rcu_read_unlock();
208         return ctx;
209 }
210
211 /*
212  * Get the context for a task and increment its pin_count so it
213  * can't get swapped to another task.  This also increments its
214  * reference count so that the context can't get freed.
215  */
216 static struct perf_counter_context *perf_pin_task_context(struct task_struct *task)
217 {
218         struct perf_counter_context *ctx;
219         unsigned long flags;
220
221         ctx = perf_lock_task_context(task, &flags);
222         if (ctx) {
223                 ++ctx->pin_count;
224                 spin_unlock_irqrestore(&ctx->lock, flags);
225         }
226         return ctx;
227 }
228
229 static void perf_unpin_context(struct perf_counter_context *ctx)
230 {
231         unsigned long flags;
232
233         spin_lock_irqsave(&ctx->lock, flags);
234         --ctx->pin_count;
235         spin_unlock_irqrestore(&ctx->lock, flags);
236         put_ctx(ctx);
237 }
238
239 /*
240  * Add a counter from the lists for its context.
241  * Must be called with ctx->mutex and ctx->lock held.
242  */
243 static void
244 list_add_counter(struct perf_counter *counter, struct perf_counter_context *ctx)
245 {
246         struct perf_counter *group_leader = counter->group_leader;
247
248         /*
249          * Depending on whether it is a standalone or sibling counter,
250          * add it straight to the context's counter list, or to the group
251          * leader's sibling list:
252          */
253         if (group_leader == counter)
254                 list_add_tail(&counter->list_entry, &ctx->counter_list);
255         else {
256                 list_add_tail(&counter->list_entry, &group_leader->sibling_list);
257                 group_leader->nr_siblings++;
258         }
259
260         list_add_rcu(&counter->event_entry, &ctx->event_list);
261         ctx->nr_counters++;
262         if (counter->attr.inherit_stat)
263                 ctx->nr_stat++;
264 }
265
266 /*
267  * Remove a counter from the lists for its context.
268  * Must be called with ctx->mutex and ctx->lock held.
269  */
270 static void
271 list_del_counter(struct perf_counter *counter, struct perf_counter_context *ctx)
272 {
273         struct perf_counter *sibling, *tmp;
274
275         if (list_empty(&counter->list_entry))
276                 return;
277         ctx->nr_counters--;
278         if (counter->attr.inherit_stat)
279                 ctx->nr_stat--;
280
281         list_del_init(&counter->list_entry);
282         list_del_rcu(&counter->event_entry);
283
284         if (counter->group_leader != counter)
285                 counter->group_leader->nr_siblings--;
286
287         /*
288          * If this was a group counter with sibling counters then
289          * upgrade the siblings to singleton counters by adding them
290          * to the context list directly:
291          */
292         list_for_each_entry_safe(sibling, tmp,
293                                  &counter->sibling_list, list_entry) {
294
295                 list_move_tail(&sibling->list_entry, &ctx->counter_list);
296                 sibling->group_leader = sibling;
297         }
298 }
299
300 static void
301 counter_sched_out(struct perf_counter *counter,
302                   struct perf_cpu_context *cpuctx,
303                   struct perf_counter_context *ctx)
304 {
305         if (counter->state != PERF_COUNTER_STATE_ACTIVE)
306                 return;
307
308         counter->state = PERF_COUNTER_STATE_INACTIVE;
309         counter->tstamp_stopped = ctx->time;
310         counter->pmu->disable(counter);
311         counter->oncpu = -1;
312
313         if (!is_software_counter(counter))
314                 cpuctx->active_oncpu--;
315         ctx->nr_active--;
316         if (counter->attr.exclusive || !cpuctx->active_oncpu)
317                 cpuctx->exclusive = 0;
318 }
319
320 static void
321 group_sched_out(struct perf_counter *group_counter,
322                 struct perf_cpu_context *cpuctx,
323                 struct perf_counter_context *ctx)
324 {
325         struct perf_counter *counter;
326
327         if (group_counter->state != PERF_COUNTER_STATE_ACTIVE)
328                 return;
329
330         counter_sched_out(group_counter, cpuctx, ctx);
331
332         /*
333          * Schedule out siblings (if any):
334          */
335         list_for_each_entry(counter, &group_counter->sibling_list, list_entry)
336                 counter_sched_out(counter, cpuctx, ctx);
337
338         if (group_counter->attr.exclusive)
339                 cpuctx->exclusive = 0;
340 }
341
342 /*
343  * Cross CPU call to remove a performance counter
344  *
345  * We disable the counter on the hardware level first. After that we
346  * remove it from the context list.
347  */
348 static void __perf_counter_remove_from_context(void *info)
349 {
350         struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
351         struct perf_counter *counter = info;
352         struct perf_counter_context *ctx = counter->ctx;
353
354         /*
355          * If this is a task context, we need to check whether it is
356          * the current task context of this cpu. If not it has been
357          * scheduled out before the smp call arrived.
358          */
359         if (ctx->task && cpuctx->task_ctx != ctx)
360                 return;
361
362         spin_lock(&ctx->lock);
363         /*
364          * Protect the list operation against NMI by disabling the
365          * counters on a global level.
366          */
367         perf_disable();
368
369         counter_sched_out(counter, cpuctx, ctx);
370
371         list_del_counter(counter, ctx);
372
373         if (!ctx->task) {
374                 /*
375                  * Allow more per task counters with respect to the
376                  * reservation:
377                  */
378                 cpuctx->max_pertask =
379                         min(perf_max_counters - ctx->nr_counters,
380                             perf_max_counters - perf_reserved_percpu);
381         }
382
383         perf_enable();
384         spin_unlock(&ctx->lock);
385 }
386
387
388 /*
389  * Remove the counter from a task's (or a CPU's) list of counters.
390  *
391  * Must be called with ctx->mutex held.
392  *
393  * CPU counters are removed with a smp call. For task counters we only
394  * call when the task is on a CPU.
395  *
396  * If counter->ctx is a cloned context, callers must make sure that
397  * every task struct that counter->ctx->task could possibly point to
398  * remains valid.  This is OK when called from perf_release since
399  * that only calls us on the top-level context, which can't be a clone.
400  * When called from perf_counter_exit_task, it's OK because the
401  * context has been detached from its task.
402  */
403 static void perf_counter_remove_from_context(struct perf_counter *counter)
404 {
405         struct perf_counter_context *ctx = counter->ctx;
406         struct task_struct *task = ctx->task;
407
408         if (!task) {
409                 /*
410                  * Per cpu counters are removed via an smp call and
411                  * the removal is always sucessful.
412                  */
413                 smp_call_function_single(counter->cpu,
414                                          __perf_counter_remove_from_context,
415                                          counter, 1);
416                 return;
417         }
418
419 retry:
420         task_oncpu_function_call(task, __perf_counter_remove_from_context,
421                                  counter);
422
423         spin_lock_irq(&ctx->lock);
424         /*
425          * If the context is active we need to retry the smp call.
426          */
427         if (ctx->nr_active && !list_empty(&counter->list_entry)) {
428                 spin_unlock_irq(&ctx->lock);
429                 goto retry;
430         }
431
432         /*
433          * The lock prevents that this context is scheduled in so we
434          * can remove the counter safely, if the call above did not
435          * succeed.
436          */
437         if (!list_empty(&counter->list_entry)) {
438                 list_del_counter(counter, ctx);
439         }
440         spin_unlock_irq(&ctx->lock);
441 }
442
443 static inline u64 perf_clock(void)
444 {
445         return cpu_clock(smp_processor_id());
446 }
447
448 /*
449  * Update the record of the current time in a context.
450  */
451 static void update_context_time(struct perf_counter_context *ctx)
452 {
453         u64 now = perf_clock();
454
455         ctx->time += now - ctx->timestamp;
456         ctx->timestamp = now;
457 }
458
459 /*
460  * Update the total_time_enabled and total_time_running fields for a counter.
461  */
462 static void update_counter_times(struct perf_counter *counter)
463 {
464         struct perf_counter_context *ctx = counter->ctx;
465         u64 run_end;
466
467         if (counter->state < PERF_COUNTER_STATE_INACTIVE)
468                 return;
469
470         counter->total_time_enabled = ctx->time - counter->tstamp_enabled;
471
472         if (counter->state == PERF_COUNTER_STATE_INACTIVE)
473                 run_end = counter->tstamp_stopped;
474         else
475                 run_end = ctx->time;
476
477         counter->total_time_running = run_end - counter->tstamp_running;
478 }
479
480 /*
481  * Update total_time_enabled and total_time_running for all counters in a group.
482  */
483 static void update_group_times(struct perf_counter *leader)
484 {
485         struct perf_counter *counter;
486
487         update_counter_times(leader);
488         list_for_each_entry(counter, &leader->sibling_list, list_entry)
489                 update_counter_times(counter);
490 }
491
492 /*
493  * Cross CPU call to disable a performance counter
494  */
495 static void __perf_counter_disable(void *info)
496 {
497         struct perf_counter *counter = info;
498         struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
499         struct perf_counter_context *ctx = counter->ctx;
500
501         /*
502          * If this is a per-task counter, need to check whether this
503          * counter's task is the current task on this cpu.
504          */
505         if (ctx->task && cpuctx->task_ctx != ctx)
506                 return;
507
508         spin_lock(&ctx->lock);
509
510         /*
511          * If the counter is on, turn it off.
512          * If it is in error state, leave it in error state.
513          */
514         if (counter->state >= PERF_COUNTER_STATE_INACTIVE) {
515                 update_context_time(ctx);
516                 update_counter_times(counter);
517                 if (counter == counter->group_leader)
518                         group_sched_out(counter, cpuctx, ctx);
519                 else
520                         counter_sched_out(counter, cpuctx, ctx);
521                 counter->state = PERF_COUNTER_STATE_OFF;
522         }
523
524         spin_unlock(&ctx->lock);
525 }
526
527 /*
528  * Disable a counter.
529  *
530  * If counter->ctx is a cloned context, callers must make sure that
531  * every task struct that counter->ctx->task could possibly point to
532  * remains valid.  This condition is satisifed when called through
533  * perf_counter_for_each_child or perf_counter_for_each because they
534  * hold the top-level counter's child_mutex, so any descendant that
535  * goes to exit will block in sync_child_counter.
536  * When called from perf_pending_counter it's OK because counter->ctx
537  * is the current context on this CPU and preemption is disabled,
538  * hence we can't get into perf_counter_task_sched_out for this context.
539  */
540 static void perf_counter_disable(struct perf_counter *counter)
541 {
542         struct perf_counter_context *ctx = counter->ctx;
543         struct task_struct *task = ctx->task;
544
545         if (!task) {
546                 /*
547                  * Disable the counter on the cpu that it's on
548                  */
549                 smp_call_function_single(counter->cpu, __perf_counter_disable,
550                                          counter, 1);
551                 return;
552         }
553
554  retry:
555         task_oncpu_function_call(task, __perf_counter_disable, counter);
556
557         spin_lock_irq(&ctx->lock);
558         /*
559          * If the counter is still active, we need to retry the cross-call.
560          */
561         if (counter->state == PERF_COUNTER_STATE_ACTIVE) {
562                 spin_unlock_irq(&ctx->lock);
563                 goto retry;
564         }
565
566         /*
567          * Since we have the lock this context can't be scheduled
568          * in, so we can change the state safely.
569          */
570         if (counter->state == PERF_COUNTER_STATE_INACTIVE) {
571                 update_counter_times(counter);
572                 counter->state = PERF_COUNTER_STATE_OFF;
573         }
574
575         spin_unlock_irq(&ctx->lock);
576 }
577
578 static int
579 counter_sched_in(struct perf_counter *counter,
580                  struct perf_cpu_context *cpuctx,
581                  struct perf_counter_context *ctx,
582                  int cpu)
583 {
584         if (counter->state <= PERF_COUNTER_STATE_OFF)
585                 return 0;
586
587         counter->state = PERF_COUNTER_STATE_ACTIVE;
588         counter->oncpu = cpu;   /* TODO: put 'cpu' into cpuctx->cpu */
589         /*
590          * The new state must be visible before we turn it on in the hardware:
591          */
592         smp_wmb();
593
594         if (counter->pmu->enable(counter)) {
595                 counter->state = PERF_COUNTER_STATE_INACTIVE;
596                 counter->oncpu = -1;
597                 return -EAGAIN;
598         }
599
600         counter->tstamp_running += ctx->time - counter->tstamp_stopped;
601
602         if (!is_software_counter(counter))
603                 cpuctx->active_oncpu++;
604         ctx->nr_active++;
605
606         if (counter->attr.exclusive)
607                 cpuctx->exclusive = 1;
608
609         return 0;
610 }
611
612 static int
613 group_sched_in(struct perf_counter *group_counter,
614                struct perf_cpu_context *cpuctx,
615                struct perf_counter_context *ctx,
616                int cpu)
617 {
618         struct perf_counter *counter, *partial_group;
619         int ret;
620
621         if (group_counter->state == PERF_COUNTER_STATE_OFF)
622                 return 0;
623
624         ret = hw_perf_group_sched_in(group_counter, cpuctx, ctx, cpu);
625         if (ret)
626                 return ret < 0 ? ret : 0;
627
628         if (counter_sched_in(group_counter, cpuctx, ctx, cpu))
629                 return -EAGAIN;
630
631         /*
632          * Schedule in siblings as one group (if any):
633          */
634         list_for_each_entry(counter, &group_counter->sibling_list, list_entry) {
635                 if (counter_sched_in(counter, cpuctx, ctx, cpu)) {
636                         partial_group = counter;
637                         goto group_error;
638                 }
639         }
640
641         return 0;
642
643 group_error:
644         /*
645          * Groups can be scheduled in as one unit only, so undo any
646          * partial group before returning:
647          */
648         list_for_each_entry(counter, &group_counter->sibling_list, list_entry) {
649                 if (counter == partial_group)
650                         break;
651                 counter_sched_out(counter, cpuctx, ctx);
652         }
653         counter_sched_out(group_counter, cpuctx, ctx);
654
655         return -EAGAIN;
656 }
657
658 /*
659  * Return 1 for a group consisting entirely of software counters,
660  * 0 if the group contains any hardware counters.
661  */
662 static int is_software_only_group(struct perf_counter *leader)
663 {
664         struct perf_counter *counter;
665
666         if (!is_software_counter(leader))
667                 return 0;
668
669         list_for_each_entry(counter, &leader->sibling_list, list_entry)
670                 if (!is_software_counter(counter))
671                         return 0;
672
673         return 1;
674 }
675
676 /*
677  * Work out whether we can put this counter group on the CPU now.
678  */
679 static int group_can_go_on(struct perf_counter *counter,
680                            struct perf_cpu_context *cpuctx,
681                            int can_add_hw)
682 {
683         /*
684          * Groups consisting entirely of software counters can always go on.
685          */
686         if (is_software_only_group(counter))
687                 return 1;
688         /*
689          * If an exclusive group is already on, no other hardware
690          * counters can go on.
691          */
692         if (cpuctx->exclusive)
693                 return 0;
694         /*
695          * If this group is exclusive and there are already
696          * counters on the CPU, it can't go on.
697          */
698         if (counter->attr.exclusive && cpuctx->active_oncpu)
699                 return 0;
700         /*
701          * Otherwise, try to add it if all previous groups were able
702          * to go on.
703          */
704         return can_add_hw;
705 }
706
707 static void add_counter_to_ctx(struct perf_counter *counter,
708                                struct perf_counter_context *ctx)
709 {
710         list_add_counter(counter, ctx);
711         counter->tstamp_enabled = ctx->time;
712         counter->tstamp_running = ctx->time;
713         counter->tstamp_stopped = ctx->time;
714 }
715
716 /*
717  * Cross CPU call to install and enable a performance counter
718  *
719  * Must be called with ctx->mutex held
720  */
721 static void __perf_install_in_context(void *info)
722 {
723         struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
724         struct perf_counter *counter = info;
725         struct perf_counter_context *ctx = counter->ctx;
726         struct perf_counter *leader = counter->group_leader;
727         int cpu = smp_processor_id();
728         int err;
729
730         /*
731          * If this is a task context, we need to check whether it is
732          * the current task context of this cpu. If not it has been
733          * scheduled out before the smp call arrived.
734          * Or possibly this is the right context but it isn't
735          * on this cpu because it had no counters.
736          */
737         if (ctx->task && cpuctx->task_ctx != ctx) {
738                 if (cpuctx->task_ctx || ctx->task != current)
739                         return;
740                 cpuctx->task_ctx = ctx;
741         }
742
743         spin_lock(&ctx->lock);
744         ctx->is_active = 1;
745         update_context_time(ctx);
746
747         /*
748          * Protect the list operation against NMI by disabling the
749          * counters on a global level. NOP for non NMI based counters.
750          */
751         perf_disable();
752
753         add_counter_to_ctx(counter, ctx);
754
755         /*
756          * Don't put the counter on if it is disabled or if
757          * it is in a group and the group isn't on.
758          */
759         if (counter->state != PERF_COUNTER_STATE_INACTIVE ||
760             (leader != counter && leader->state != PERF_COUNTER_STATE_ACTIVE))
761                 goto unlock;
762
763         /*
764          * An exclusive counter can't go on if there are already active
765          * hardware counters, and no hardware counter can go on if there
766          * is already an exclusive counter on.
767          */
768         if (!group_can_go_on(counter, cpuctx, 1))
769                 err = -EEXIST;
770         else
771                 err = counter_sched_in(counter, cpuctx, ctx, cpu);
772
773         if (err) {
774                 /*
775                  * This counter couldn't go on.  If it is in a group
776                  * then we have to pull the whole group off.
777                  * If the counter group is pinned then put it in error state.
778                  */
779                 if (leader != counter)
780                         group_sched_out(leader, cpuctx, ctx);
781                 if (leader->attr.pinned) {
782                         update_group_times(leader);
783                         leader->state = PERF_COUNTER_STATE_ERROR;
784                 }
785         }
786
787         if (!err && !ctx->task && cpuctx->max_pertask)
788                 cpuctx->max_pertask--;
789
790  unlock:
791         perf_enable();
792
793         spin_unlock(&ctx->lock);
794 }
795
796 /*
797  * Attach a performance counter to a context
798  *
799  * First we add the counter to the list with the hardware enable bit
800  * in counter->hw_config cleared.
801  *
802  * If the counter is attached to a task which is on a CPU we use a smp
803  * call to enable it in the task context. The task might have been
804  * scheduled away, but we check this in the smp call again.
805  *
806  * Must be called with ctx->mutex held.
807  */
808 static void
809 perf_install_in_context(struct perf_counter_context *ctx,
810                         struct perf_counter *counter,
811                         int cpu)
812 {
813         struct task_struct *task = ctx->task;
814
815         if (!task) {
816                 /*
817                  * Per cpu counters are installed via an smp call and
818                  * the install is always sucessful.
819                  */
820                 smp_call_function_single(cpu, __perf_install_in_context,
821                                          counter, 1);
822                 return;
823         }
824
825 retry:
826         task_oncpu_function_call(task, __perf_install_in_context,
827                                  counter);
828
829         spin_lock_irq(&ctx->lock);
830         /*
831          * we need to retry the smp call.
832          */
833         if (ctx->is_active && list_empty(&counter->list_entry)) {
834                 spin_unlock_irq(&ctx->lock);
835                 goto retry;
836         }
837
838         /*
839          * The lock prevents that this context is scheduled in so we
840          * can add the counter safely, if it the call above did not
841          * succeed.
842          */
843         if (list_empty(&counter->list_entry))
844                 add_counter_to_ctx(counter, ctx);
845         spin_unlock_irq(&ctx->lock);
846 }
847
848 /*
849  * Cross CPU call to enable a performance counter
850  */
851 static void __perf_counter_enable(void *info)
852 {
853         struct perf_counter *counter = info;
854         struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
855         struct perf_counter_context *ctx = counter->ctx;
856         struct perf_counter *leader = counter->group_leader;
857         int err;
858
859         /*
860          * If this is a per-task counter, need to check whether this
861          * counter's task is the current task on this cpu.
862          */
863         if (ctx->task && cpuctx->task_ctx != ctx) {
864                 if (cpuctx->task_ctx || ctx->task != current)
865                         return;
866                 cpuctx->task_ctx = ctx;
867         }
868
869         spin_lock(&ctx->lock);
870         ctx->is_active = 1;
871         update_context_time(ctx);
872
873         if (counter->state >= PERF_COUNTER_STATE_INACTIVE)
874                 goto unlock;
875         counter->state = PERF_COUNTER_STATE_INACTIVE;
876         counter->tstamp_enabled = ctx->time - counter->total_time_enabled;
877
878         /*
879          * If the counter is in a group and isn't the group leader,
880          * then don't put it on unless the group is on.
881          */
882         if (leader != counter && leader->state != PERF_COUNTER_STATE_ACTIVE)
883                 goto unlock;
884
885         if (!group_can_go_on(counter, cpuctx, 1)) {
886                 err = -EEXIST;
887         } else {
888                 perf_disable();
889                 if (counter == leader)
890                         err = group_sched_in(counter, cpuctx, ctx,
891                                              smp_processor_id());
892                 else
893                         err = counter_sched_in(counter, cpuctx, ctx,
894                                                smp_processor_id());
895                 perf_enable();
896         }
897
898         if (err) {
899                 /*
900                  * If this counter can't go on and it's part of a
901                  * group, then the whole group has to come off.
902                  */
903                 if (leader != counter)
904                         group_sched_out(leader, cpuctx, ctx);
905                 if (leader->attr.pinned) {
906                         update_group_times(leader);
907                         leader->state = PERF_COUNTER_STATE_ERROR;
908                 }
909         }
910
911  unlock:
912         spin_unlock(&ctx->lock);
913 }
914
915 /*
916  * Enable a counter.
917  *
918  * If counter->ctx is a cloned context, callers must make sure that
919  * every task struct that counter->ctx->task could possibly point to
920  * remains valid.  This condition is satisfied when called through
921  * perf_counter_for_each_child or perf_counter_for_each as described
922  * for perf_counter_disable.
923  */
924 static void perf_counter_enable(struct perf_counter *counter)
925 {
926         struct perf_counter_context *ctx = counter->ctx;
927         struct task_struct *task = ctx->task;
928
929         if (!task) {
930                 /*
931                  * Enable the counter on the cpu that it's on
932                  */
933                 smp_call_function_single(counter->cpu, __perf_counter_enable,
934                                          counter, 1);
935                 return;
936         }
937
938         spin_lock_irq(&ctx->lock);
939         if (counter->state >= PERF_COUNTER_STATE_INACTIVE)
940                 goto out;
941
942         /*
943          * If the counter is in error state, clear that first.
944          * That way, if we see the counter in error state below, we
945          * know that it has gone back into error state, as distinct
946          * from the task having been scheduled away before the
947          * cross-call arrived.
948          */
949         if (counter->state == PERF_COUNTER_STATE_ERROR)
950                 counter->state = PERF_COUNTER_STATE_OFF;
951
952  retry:
953         spin_unlock_irq(&ctx->lock);
954         task_oncpu_function_call(task, __perf_counter_enable, counter);
955
956         spin_lock_irq(&ctx->lock);
957
958         /*
959          * If the context is active and the counter is still off,
960          * we need to retry the cross-call.
961          */
962         if (ctx->is_active && counter->state == PERF_COUNTER_STATE_OFF)
963                 goto retry;
964
965         /*
966          * Since we have the lock this context can't be scheduled
967          * in, so we can change the state safely.
968          */
969         if (counter->state == PERF_COUNTER_STATE_OFF) {
970                 counter->state = PERF_COUNTER_STATE_INACTIVE;
971                 counter->tstamp_enabled =
972                         ctx->time - counter->total_time_enabled;
973         }
974  out:
975         spin_unlock_irq(&ctx->lock);
976 }
977
978 static int perf_counter_refresh(struct perf_counter *counter, int refresh)
979 {
980         /*
981          * not supported on inherited counters
982          */
983         if (counter->attr.inherit)
984                 return -EINVAL;
985
986         atomic_add(refresh, &counter->event_limit);
987         perf_counter_enable(counter);
988
989         return 0;
990 }
991
992 void __perf_counter_sched_out(struct perf_counter_context *ctx,
993                               struct perf_cpu_context *cpuctx)
994 {
995         struct perf_counter *counter;
996
997         spin_lock(&ctx->lock);
998         ctx->is_active = 0;
999         if (likely(!ctx->nr_counters))
1000                 goto out;
1001         update_context_time(ctx);
1002
1003         perf_disable();
1004         if (ctx->nr_active) {
1005                 list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1006                         if (counter != counter->group_leader)
1007                                 counter_sched_out(counter, cpuctx, ctx);
1008                         else
1009                                 group_sched_out(counter, cpuctx, ctx);
1010                 }
1011         }
1012         perf_enable();
1013  out:
1014         spin_unlock(&ctx->lock);
1015 }
1016
1017 /*
1018  * Test whether two contexts are equivalent, i.e. whether they
1019  * have both been cloned from the same version of the same context
1020  * and they both have the same number of enabled counters.
1021  * If the number of enabled counters is the same, then the set
1022  * of enabled counters should be the same, because these are both
1023  * inherited contexts, therefore we can't access individual counters
1024  * in them directly with an fd; we can only enable/disable all
1025  * counters via prctl, or enable/disable all counters in a family
1026  * via ioctl, which will have the same effect on both contexts.
1027  */
1028 static int context_equiv(struct perf_counter_context *ctx1,
1029                          struct perf_counter_context *ctx2)
1030 {
1031         return ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx
1032                 && ctx1->parent_gen == ctx2->parent_gen
1033                 && !ctx1->pin_count && !ctx2->pin_count;
1034 }
1035
1036 static void __perf_counter_read(void *counter);
1037
1038 static void __perf_counter_sync_stat(struct perf_counter *counter,
1039                                      struct perf_counter *next_counter)
1040 {
1041         u64 value;
1042
1043         if (!counter->attr.inherit_stat)
1044                 return;
1045
1046         /*
1047          * Update the counter value, we cannot use perf_counter_read()
1048          * because we're in the middle of a context switch and have IRQs
1049          * disabled, which upsets smp_call_function_single(), however
1050          * we know the counter must be on the current CPU, therefore we
1051          * don't need to use it.
1052          */
1053         switch (counter->state) {
1054         case PERF_COUNTER_STATE_ACTIVE:
1055                 __perf_counter_read(counter);
1056                 break;
1057
1058         case PERF_COUNTER_STATE_INACTIVE:
1059                 update_counter_times(counter);
1060                 break;
1061
1062         default:
1063                 break;
1064         }
1065
1066         /*
1067          * In order to keep per-task stats reliable we need to flip the counter
1068          * values when we flip the contexts.
1069          */
1070         value = atomic64_read(&next_counter->count);
1071         value = atomic64_xchg(&counter->count, value);
1072         atomic64_set(&next_counter->count, value);
1073
1074         swap(counter->total_time_enabled, next_counter->total_time_enabled);
1075         swap(counter->total_time_running, next_counter->total_time_running);
1076
1077         /*
1078          * Since we swizzled the values, update the user visible data too.
1079          */
1080         perf_counter_update_userpage(counter);
1081         perf_counter_update_userpage(next_counter);
1082 }
1083
1084 #define list_next_entry(pos, member) \
1085         list_entry(pos->member.next, typeof(*pos), member)
1086
1087 static void perf_counter_sync_stat(struct perf_counter_context *ctx,
1088                                    struct perf_counter_context *next_ctx)
1089 {
1090         struct perf_counter *counter, *next_counter;
1091
1092         if (!ctx->nr_stat)
1093                 return;
1094
1095         counter = list_first_entry(&ctx->event_list,
1096                                    struct perf_counter, event_entry);
1097
1098         next_counter = list_first_entry(&next_ctx->event_list,
1099                                         struct perf_counter, event_entry);
1100
1101         while (&counter->event_entry != &ctx->event_list &&
1102                &next_counter->event_entry != &next_ctx->event_list) {
1103
1104                 __perf_counter_sync_stat(counter, next_counter);
1105
1106                 counter = list_next_entry(counter, event_entry);
1107                 next_counter = list_next_entry(counter, event_entry);
1108         }
1109 }
1110
1111 /*
1112  * Called from scheduler to remove the counters of the current task,
1113  * with interrupts disabled.
1114  *
1115  * We stop each counter and update the counter value in counter->count.
1116  *
1117  * This does not protect us against NMI, but disable()
1118  * sets the disabled bit in the control field of counter _before_
1119  * accessing the counter control register. If a NMI hits, then it will
1120  * not restart the counter.
1121  */
1122 void perf_counter_task_sched_out(struct task_struct *task,
1123                                  struct task_struct *next, int cpu)
1124 {
1125         struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
1126         struct perf_counter_context *ctx = task->perf_counter_ctxp;
1127         struct perf_counter_context *next_ctx;
1128         struct perf_counter_context *parent;
1129         struct pt_regs *regs;
1130         int do_switch = 1;
1131
1132         regs = task_pt_regs(task);
1133         perf_swcounter_event(PERF_COUNT_SW_CONTEXT_SWITCHES, 1, 1, regs, 0);
1134
1135         if (likely(!ctx || !cpuctx->task_ctx))
1136                 return;
1137
1138         update_context_time(ctx);
1139
1140         rcu_read_lock();
1141         parent = rcu_dereference(ctx->parent_ctx);
1142         next_ctx = next->perf_counter_ctxp;
1143         if (parent && next_ctx &&
1144             rcu_dereference(next_ctx->parent_ctx) == parent) {
1145                 /*
1146                  * Looks like the two contexts are clones, so we might be
1147                  * able to optimize the context switch.  We lock both
1148                  * contexts and check that they are clones under the
1149                  * lock (including re-checking that neither has been
1150                  * uncloned in the meantime).  It doesn't matter which
1151                  * order we take the locks because no other cpu could
1152                  * be trying to lock both of these tasks.
1153                  */
1154                 spin_lock(&ctx->lock);
1155                 spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
1156                 if (context_equiv(ctx, next_ctx)) {
1157                         /*
1158                          * XXX do we need a memory barrier of sorts
1159                          * wrt to rcu_dereference() of perf_counter_ctxp
1160                          */
1161                         task->perf_counter_ctxp = next_ctx;
1162                         next->perf_counter_ctxp = ctx;
1163                         ctx->task = next;
1164                         next_ctx->task = task;
1165                         do_switch = 0;
1166
1167                         perf_counter_sync_stat(ctx, next_ctx);
1168                 }
1169                 spin_unlock(&next_ctx->lock);
1170                 spin_unlock(&ctx->lock);
1171         }
1172         rcu_read_unlock();
1173
1174         if (do_switch) {
1175                 __perf_counter_sched_out(ctx, cpuctx);
1176                 cpuctx->task_ctx = NULL;
1177         }
1178 }
1179
1180 /*
1181  * Called with IRQs disabled
1182  */
1183 static void __perf_counter_task_sched_out(struct perf_counter_context *ctx)
1184 {
1185         struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
1186
1187         if (!cpuctx->task_ctx)
1188                 return;
1189
1190         if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
1191                 return;
1192
1193         __perf_counter_sched_out(ctx, cpuctx);
1194         cpuctx->task_ctx = NULL;
1195 }
1196
1197 /*
1198  * Called with IRQs disabled
1199  */
1200 static void perf_counter_cpu_sched_out(struct perf_cpu_context *cpuctx)
1201 {
1202         __perf_counter_sched_out(&cpuctx->ctx, cpuctx);
1203 }
1204
1205 static void
1206 __perf_counter_sched_in(struct perf_counter_context *ctx,
1207                         struct perf_cpu_context *cpuctx, int cpu)
1208 {
1209         struct perf_counter *counter;
1210         int can_add_hw = 1;
1211
1212         spin_lock(&ctx->lock);
1213         ctx->is_active = 1;
1214         if (likely(!ctx->nr_counters))
1215                 goto out;
1216
1217         ctx->timestamp = perf_clock();
1218
1219         perf_disable();
1220
1221         /*
1222          * First go through the list and put on any pinned groups
1223          * in order to give them the best chance of going on.
1224          */
1225         list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1226                 if (counter->state <= PERF_COUNTER_STATE_OFF ||
1227                     !counter->attr.pinned)
1228                         continue;
1229                 if (counter->cpu != -1 && counter->cpu != cpu)
1230                         continue;
1231
1232                 if (counter != counter->group_leader)
1233                         counter_sched_in(counter, cpuctx, ctx, cpu);
1234                 else {
1235                         if (group_can_go_on(counter, cpuctx, 1))
1236                                 group_sched_in(counter, cpuctx, ctx, cpu);
1237                 }
1238
1239                 /*
1240                  * If this pinned group hasn't been scheduled,
1241                  * put it in error state.
1242                  */
1243                 if (counter->state == PERF_COUNTER_STATE_INACTIVE) {
1244                         update_group_times(counter);
1245                         counter->state = PERF_COUNTER_STATE_ERROR;
1246                 }
1247         }
1248
1249         list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1250                 /*
1251                  * Ignore counters in OFF or ERROR state, and
1252                  * ignore pinned counters since we did them already.
1253                  */
1254                 if (counter->state <= PERF_COUNTER_STATE_OFF ||
1255                     counter->attr.pinned)
1256                         continue;
1257
1258                 /*
1259                  * Listen to the 'cpu' scheduling filter constraint
1260                  * of counters:
1261                  */
1262                 if (counter->cpu != -1 && counter->cpu != cpu)
1263                         continue;
1264
1265                 if (counter != counter->group_leader) {
1266                         if (counter_sched_in(counter, cpuctx, ctx, cpu))
1267                                 can_add_hw = 0;
1268                 } else {
1269                         if (group_can_go_on(counter, cpuctx, can_add_hw)) {
1270                                 if (group_sched_in(counter, cpuctx, ctx, cpu))
1271                                         can_add_hw = 0;
1272                         }
1273                 }
1274         }
1275         perf_enable();
1276  out:
1277         spin_unlock(&ctx->lock);
1278 }
1279
1280 /*
1281  * Called from scheduler to add the counters of the current task
1282  * with interrupts disabled.
1283  *
1284  * We restore the counter value and then enable it.
1285  *
1286  * This does not protect us against NMI, but enable()
1287  * sets the enabled bit in the control field of counter _before_
1288  * accessing the counter control register. If a NMI hits, then it will
1289  * keep the counter running.
1290  */
1291 void perf_counter_task_sched_in(struct task_struct *task, int cpu)
1292 {
1293         struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
1294         struct perf_counter_context *ctx = task->perf_counter_ctxp;
1295
1296         if (likely(!ctx))
1297                 return;
1298         if (cpuctx->task_ctx == ctx)
1299                 return;
1300         __perf_counter_sched_in(ctx, cpuctx, cpu);
1301         cpuctx->task_ctx = ctx;
1302 }
1303
1304 static void perf_counter_cpu_sched_in(struct perf_cpu_context *cpuctx, int cpu)
1305 {
1306         struct perf_counter_context *ctx = &cpuctx->ctx;
1307
1308         __perf_counter_sched_in(ctx, cpuctx, cpu);
1309 }
1310
1311 #define MAX_INTERRUPTS (~0ULL)
1312
1313 static void perf_log_throttle(struct perf_counter *counter, int enable);
1314
1315 static void perf_adjust_period(struct perf_counter *counter, u64 events)
1316 {
1317         struct hw_perf_counter *hwc = &counter->hw;
1318         u64 period, sample_period;
1319         s64 delta;
1320
1321         events *= hwc->sample_period;
1322         period = div64_u64(events, counter->attr.sample_freq);
1323
1324         delta = (s64)(period - hwc->sample_period);
1325         delta = (delta + 7) / 8; /* low pass filter */
1326
1327         sample_period = hwc->sample_period + delta;
1328
1329         if (!sample_period)
1330                 sample_period = 1;
1331
1332         hwc->sample_period = sample_period;
1333 }
1334
1335 static void perf_ctx_adjust_freq(struct perf_counter_context *ctx)
1336 {
1337         struct perf_counter *counter;
1338         struct hw_perf_counter *hwc;
1339         u64 interrupts, freq;
1340
1341         spin_lock(&ctx->lock);
1342         list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1343                 if (counter->state != PERF_COUNTER_STATE_ACTIVE)
1344                         continue;
1345
1346                 hwc = &counter->hw;
1347
1348                 interrupts = hwc->interrupts;
1349                 hwc->interrupts = 0;
1350
1351                 /*
1352                  * unthrottle counters on the tick
1353                  */
1354                 if (interrupts == MAX_INTERRUPTS) {
1355                         perf_log_throttle(counter, 1);
1356                         counter->pmu->unthrottle(counter);
1357                         interrupts = 2*sysctl_perf_counter_sample_rate/HZ;
1358                 }
1359
1360                 if (!counter->attr.freq || !counter->attr.sample_freq)
1361                         continue;
1362
1363                 /*
1364                  * if the specified freq < HZ then we need to skip ticks
1365                  */
1366                 if (counter->attr.sample_freq < HZ) {
1367                         freq = counter->attr.sample_freq;
1368
1369                         hwc->freq_count += freq;
1370                         hwc->freq_interrupts += interrupts;
1371
1372                         if (hwc->freq_count < HZ)
1373                                 continue;
1374
1375                         interrupts = hwc->freq_interrupts;
1376                         hwc->freq_interrupts = 0;
1377                         hwc->freq_count -= HZ;
1378                 } else
1379                         freq = HZ;
1380
1381                 perf_adjust_period(counter, freq * interrupts);
1382
1383                 /*
1384                  * In order to avoid being stalled by an (accidental) huge
1385                  * sample period, force reset the sample period if we didn't
1386                  * get any events in this freq period.
1387                  */
1388                 if (!interrupts) {
1389                         perf_disable();
1390                         counter->pmu->disable(counter);
1391                         atomic64_set(&hwc->period_left, 0);
1392                         counter->pmu->enable(counter);
1393                         perf_enable();
1394                 }
1395         }
1396         spin_unlock(&ctx->lock);
1397 }
1398
1399 /*
1400  * Round-robin a context's counters:
1401  */
1402 static void rotate_ctx(struct perf_counter_context *ctx)
1403 {
1404         struct perf_counter *counter;
1405
1406         if (!ctx->nr_counters)
1407                 return;
1408
1409         spin_lock(&ctx->lock);
1410         /*
1411          * Rotate the first entry last (works just fine for group counters too):
1412          */
1413         perf_disable();
1414         list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1415                 list_move_tail(&counter->list_entry, &ctx->counter_list);
1416                 break;
1417         }
1418         perf_enable();
1419
1420         spin_unlock(&ctx->lock);
1421 }
1422
1423 void perf_counter_task_tick(struct task_struct *curr, int cpu)
1424 {
1425         struct perf_cpu_context *cpuctx;
1426         struct perf_counter_context *ctx;
1427
1428         if (!atomic_read(&nr_counters))
1429                 return;
1430
1431         cpuctx = &per_cpu(perf_cpu_context, cpu);
1432         ctx = curr->perf_counter_ctxp;
1433
1434         perf_ctx_adjust_freq(&cpuctx->ctx);
1435         if (ctx)
1436                 perf_ctx_adjust_freq(ctx);
1437
1438         perf_counter_cpu_sched_out(cpuctx);
1439         if (ctx)
1440                 __perf_counter_task_sched_out(ctx);
1441
1442         rotate_ctx(&cpuctx->ctx);
1443         if (ctx)
1444                 rotate_ctx(ctx);
1445
1446         perf_counter_cpu_sched_in(cpuctx, cpu);
1447         if (ctx)
1448                 perf_counter_task_sched_in(curr, cpu);
1449 }
1450
1451 /*
1452  * Enable all of a task's counters that have been marked enable-on-exec.
1453  * This expects task == current.
1454  */
1455 static void perf_counter_enable_on_exec(struct task_struct *task)
1456 {
1457         struct perf_counter_context *ctx;
1458         struct perf_counter *counter;
1459         unsigned long flags;
1460         int enabled = 0;
1461
1462         local_irq_save(flags);
1463         ctx = task->perf_counter_ctxp;
1464         if (!ctx || !ctx->nr_counters)
1465                 goto out;
1466
1467         __perf_counter_task_sched_out(ctx);
1468
1469         spin_lock(&ctx->lock);
1470
1471         list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1472                 if (!counter->attr.enable_on_exec)
1473                         continue;
1474                 counter->attr.enable_on_exec = 0;
1475                 if (counter->state >= PERF_COUNTER_STATE_INACTIVE)
1476                         continue;
1477                 counter->state = PERF_COUNTER_STATE_INACTIVE;
1478                 counter->tstamp_enabled =
1479                         ctx->time - counter->total_time_enabled;
1480                 enabled = 1;
1481         }
1482
1483         /*
1484          * Unclone this context if we enabled any counter.
1485          */
1486         if (enabled)
1487                 unclone_ctx(ctx);
1488
1489         spin_unlock(&ctx->lock);
1490
1491         perf_counter_task_sched_in(task, smp_processor_id());
1492  out:
1493         local_irq_restore(flags);
1494 }
1495
1496 /*
1497  * Cross CPU call to read the hardware counter
1498  */
1499 static void __perf_counter_read(void *info)
1500 {
1501         struct perf_counter *counter = info;
1502         struct perf_counter_context *ctx = counter->ctx;
1503         unsigned long flags;
1504
1505         local_irq_save(flags);
1506         if (ctx->is_active)
1507                 update_context_time(ctx);
1508         counter->pmu->read(counter);
1509         update_counter_times(counter);
1510         local_irq_restore(flags);
1511 }
1512
1513 static u64 perf_counter_read(struct perf_counter *counter)
1514 {
1515         /*
1516          * If counter is enabled and currently active on a CPU, update the
1517          * value in the counter structure:
1518          */
1519         if (counter->state == PERF_COUNTER_STATE_ACTIVE) {
1520                 smp_call_function_single(counter->oncpu,
1521                                          __perf_counter_read, counter, 1);
1522         } else if (counter->state == PERF_COUNTER_STATE_INACTIVE) {
1523                 update_counter_times(counter);
1524         }
1525
1526         return atomic64_read(&counter->count);
1527 }
1528
1529 /*
1530  * Initialize the perf_counter context in a task_struct:
1531  */
1532 static void
1533 __perf_counter_init_context(struct perf_counter_context *ctx,
1534                             struct task_struct *task)
1535 {
1536         memset(ctx, 0, sizeof(*ctx));
1537         spin_lock_init(&ctx->lock);
1538         mutex_init(&ctx->mutex);
1539         INIT_LIST_HEAD(&ctx->counter_list);
1540         INIT_LIST_HEAD(&ctx->event_list);
1541         atomic_set(&ctx->refcount, 1);
1542         ctx->task = task;
1543 }
1544
1545 static struct perf_counter_context *find_get_context(pid_t pid, int cpu)
1546 {
1547         struct perf_counter_context *ctx;
1548         struct perf_cpu_context *cpuctx;
1549         struct task_struct *task;
1550         unsigned long flags;
1551         int err;
1552
1553         /*
1554          * If cpu is not a wildcard then this is a percpu counter:
1555          */
1556         if (cpu != -1) {
1557                 /* Must be root to operate on a CPU counter: */
1558                 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
1559                         return ERR_PTR(-EACCES);
1560
1561                 if (cpu < 0 || cpu > num_possible_cpus())
1562                         return ERR_PTR(-EINVAL);
1563
1564                 /*
1565                  * We could be clever and allow to attach a counter to an
1566                  * offline CPU and activate it when the CPU comes up, but
1567                  * that's for later.
1568                  */
1569                 if (!cpu_isset(cpu, cpu_online_map))
1570                         return ERR_PTR(-ENODEV);
1571
1572                 cpuctx = &per_cpu(perf_cpu_context, cpu);
1573                 ctx = &cpuctx->ctx;
1574                 get_ctx(ctx);
1575
1576                 return ctx;
1577         }
1578
1579         rcu_read_lock();
1580         if (!pid)
1581                 task = current;
1582         else
1583                 task = find_task_by_vpid(pid);
1584         if (task)
1585                 get_task_struct(task);
1586         rcu_read_unlock();
1587
1588         if (!task)
1589                 return ERR_PTR(-ESRCH);
1590
1591         /*
1592          * Can't attach counters to a dying task.
1593          */
1594         err = -ESRCH;
1595         if (task->flags & PF_EXITING)
1596                 goto errout;
1597
1598         /* Reuse ptrace permission checks for now. */
1599         err = -EACCES;
1600         if (!ptrace_may_access(task, PTRACE_MODE_READ))
1601                 goto errout;
1602
1603  retry:
1604         ctx = perf_lock_task_context(task, &flags);
1605         if (ctx) {
1606                 unclone_ctx(ctx);
1607                 spin_unlock_irqrestore(&ctx->lock, flags);
1608         }
1609
1610         if (!ctx) {
1611                 ctx = kmalloc(sizeof(struct perf_counter_context), GFP_KERNEL);
1612                 err = -ENOMEM;
1613                 if (!ctx)
1614                         goto errout;
1615                 __perf_counter_init_context(ctx, task);
1616                 get_ctx(ctx);
1617                 if (cmpxchg(&task->perf_counter_ctxp, NULL, ctx)) {
1618                         /*
1619                          * We raced with some other task; use
1620                          * the context they set.
1621                          */
1622                         kfree(ctx);
1623                         goto retry;
1624                 }
1625                 get_task_struct(task);
1626         }
1627
1628         put_task_struct(task);
1629         return ctx;
1630
1631  errout:
1632         put_task_struct(task);
1633         return ERR_PTR(err);
1634 }
1635
1636 static void free_counter_rcu(struct rcu_head *head)
1637 {
1638         struct perf_counter *counter;
1639
1640         counter = container_of(head, struct perf_counter, rcu_head);
1641         if (counter->ns)
1642                 put_pid_ns(counter->ns);
1643         kfree(counter);
1644 }
1645
1646 static void perf_pending_sync(struct perf_counter *counter);
1647
1648 static void free_counter(struct perf_counter *counter)
1649 {
1650         perf_pending_sync(counter);
1651
1652         if (!counter->parent) {
1653                 atomic_dec(&nr_counters);
1654                 if (counter->attr.mmap)
1655                         atomic_dec(&nr_mmap_counters);
1656                 if (counter->attr.comm)
1657                         atomic_dec(&nr_comm_counters);
1658                 if (counter->attr.task)
1659                         atomic_dec(&nr_task_counters);
1660         }
1661
1662         if (counter->destroy)
1663                 counter->destroy(counter);
1664
1665         put_ctx(counter->ctx);
1666         call_rcu(&counter->rcu_head, free_counter_rcu);
1667 }
1668
1669 /*
1670  * Called when the last reference to the file is gone.
1671  */
1672 static int perf_release(struct inode *inode, struct file *file)
1673 {
1674         struct perf_counter *counter = file->private_data;
1675         struct perf_counter_context *ctx = counter->ctx;
1676
1677         file->private_data = NULL;
1678
1679         WARN_ON_ONCE(ctx->parent_ctx);
1680         mutex_lock(&ctx->mutex);
1681         perf_counter_remove_from_context(counter);
1682         mutex_unlock(&ctx->mutex);
1683
1684         mutex_lock(&counter->owner->perf_counter_mutex);
1685         list_del_init(&counter->owner_entry);
1686         mutex_unlock(&counter->owner->perf_counter_mutex);
1687         put_task_struct(counter->owner);
1688
1689         free_counter(counter);
1690
1691         return 0;
1692 }
1693
1694 static u64 perf_counter_read_tree(struct perf_counter *counter)
1695 {
1696         struct perf_counter *child;
1697         u64 total = 0;
1698
1699         total += perf_counter_read(counter);
1700         list_for_each_entry(child, &counter->child_list, child_list)
1701                 total += perf_counter_read(child);
1702
1703         return total;
1704 }
1705
1706 /*
1707  * Read the performance counter - simple non blocking version for now
1708  */
1709 static ssize_t
1710 perf_read_hw(struct perf_counter *counter, char __user *buf, size_t count)
1711 {
1712         u64 values[4];
1713         int n;
1714
1715         /*
1716          * Return end-of-file for a read on a counter that is in
1717          * error state (i.e. because it was pinned but it couldn't be
1718          * scheduled on to the CPU at some point).
1719          */
1720         if (counter->state == PERF_COUNTER_STATE_ERROR)
1721                 return 0;
1722
1723         WARN_ON_ONCE(counter->ctx->parent_ctx);
1724         mutex_lock(&counter->child_mutex);
1725         values[0] = perf_counter_read_tree(counter);
1726         n = 1;
1727         if (counter->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1728                 values[n++] = counter->total_time_enabled +
1729                         atomic64_read(&counter->child_total_time_enabled);
1730         if (counter->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1731                 values[n++] = counter->total_time_running +
1732                         atomic64_read(&counter->child_total_time_running);
1733         if (counter->attr.read_format & PERF_FORMAT_ID)
1734                 values[n++] = primary_counter_id(counter);
1735         mutex_unlock(&counter->child_mutex);
1736
1737         if (count < n * sizeof(u64))
1738                 return -EINVAL;
1739         count = n * sizeof(u64);
1740
1741         if (copy_to_user(buf, values, count))
1742                 return -EFAULT;
1743
1744         return count;
1745 }
1746
1747 static ssize_t
1748 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
1749 {
1750         struct perf_counter *counter = file->private_data;
1751
1752         return perf_read_hw(counter, buf, count);
1753 }
1754
1755 static unsigned int perf_poll(struct file *file, poll_table *wait)
1756 {
1757         struct perf_counter *counter = file->private_data;
1758         struct perf_mmap_data *data;
1759         unsigned int events = POLL_HUP;
1760
1761         rcu_read_lock();
1762         data = rcu_dereference(counter->data);
1763         if (data)
1764                 events = atomic_xchg(&data->poll, 0);
1765         rcu_read_unlock();
1766
1767         poll_wait(file, &counter->waitq, wait);
1768
1769         return events;
1770 }
1771
1772 static void perf_counter_reset(struct perf_counter *counter)
1773 {
1774         (void)perf_counter_read(counter);
1775         atomic64_set(&counter->count, 0);
1776         perf_counter_update_userpage(counter);
1777 }
1778
1779 /*
1780  * Holding the top-level counter's child_mutex means that any
1781  * descendant process that has inherited this counter will block
1782  * in sync_child_counter if it goes to exit, thus satisfying the
1783  * task existence requirements of perf_counter_enable/disable.
1784  */
1785 static void perf_counter_for_each_child(struct perf_counter *counter,
1786                                         void (*func)(struct perf_counter *))
1787 {
1788         struct perf_counter *child;
1789
1790         WARN_ON_ONCE(counter->ctx->parent_ctx);
1791         mutex_lock(&counter->child_mutex);
1792         func(counter);
1793         list_for_each_entry(child, &counter->child_list, child_list)
1794                 func(child);
1795         mutex_unlock(&counter->child_mutex);
1796 }
1797
1798 static void perf_counter_for_each(struct perf_counter *counter,
1799                                   void (*func)(struct perf_counter *))
1800 {
1801         struct perf_counter_context *ctx = counter->ctx;
1802         struct perf_counter *sibling;
1803
1804         WARN_ON_ONCE(ctx->parent_ctx);
1805         mutex_lock(&ctx->mutex);
1806         counter = counter->group_leader;
1807
1808         perf_counter_for_each_child(counter, func);
1809         func(counter);
1810         list_for_each_entry(sibling, &counter->sibling_list, list_entry)
1811                 perf_counter_for_each_child(counter, func);
1812         mutex_unlock(&ctx->mutex);
1813 }
1814
1815 static int perf_counter_period(struct perf_counter *counter, u64 __user *arg)
1816 {
1817         struct perf_counter_context *ctx = counter->ctx;
1818         unsigned long size;
1819         int ret = 0;
1820         u64 value;
1821
1822         if (!counter->attr.sample_period)
1823                 return -EINVAL;
1824
1825         size = copy_from_user(&value, arg, sizeof(value));
1826         if (size != sizeof(value))
1827                 return -EFAULT;
1828
1829         if (!value)
1830                 return -EINVAL;
1831
1832         spin_lock_irq(&ctx->lock);
1833         if (counter->attr.freq) {
1834                 if (value > sysctl_perf_counter_sample_rate) {
1835                         ret = -EINVAL;
1836                         goto unlock;
1837                 }
1838
1839                 counter->attr.sample_freq = value;
1840         } else {
1841                 counter->attr.sample_period = value;
1842                 counter->hw.sample_period = value;
1843         }
1844 unlock:
1845         spin_unlock_irq(&ctx->lock);
1846
1847         return ret;
1848 }
1849
1850 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
1851 {
1852         struct perf_counter *counter = file->private_data;
1853         void (*func)(struct perf_counter *);
1854         u32 flags = arg;
1855
1856         switch (cmd) {
1857         case PERF_COUNTER_IOC_ENABLE:
1858                 func = perf_counter_enable;
1859                 break;
1860         case PERF_COUNTER_IOC_DISABLE:
1861                 func = perf_counter_disable;
1862                 break;
1863         case PERF_COUNTER_IOC_RESET:
1864                 func = perf_counter_reset;
1865                 break;
1866
1867         case PERF_COUNTER_IOC_REFRESH:
1868                 return perf_counter_refresh(counter, arg);
1869
1870         case PERF_COUNTER_IOC_PERIOD:
1871                 return perf_counter_period(counter, (u64 __user *)arg);
1872
1873         default:
1874                 return -ENOTTY;
1875         }
1876
1877         if (flags & PERF_IOC_FLAG_GROUP)
1878                 perf_counter_for_each(counter, func);
1879         else
1880                 perf_counter_for_each_child(counter, func);
1881
1882         return 0;
1883 }
1884
1885 int perf_counter_task_enable(void)
1886 {
1887         struct perf_counter *counter;
1888
1889         mutex_lock(&current->perf_counter_mutex);
1890         list_for_each_entry(counter, &current->perf_counter_list, owner_entry)
1891                 perf_counter_for_each_child(counter, perf_counter_enable);
1892         mutex_unlock(&current->perf_counter_mutex);
1893
1894         return 0;
1895 }
1896
1897 int perf_counter_task_disable(void)
1898 {
1899         struct perf_counter *counter;
1900
1901         mutex_lock(&current->perf_counter_mutex);
1902         list_for_each_entry(counter, &current->perf_counter_list, owner_entry)
1903                 perf_counter_for_each_child(counter, perf_counter_disable);
1904         mutex_unlock(&current->perf_counter_mutex);
1905
1906         return 0;
1907 }
1908
1909 static int perf_counter_index(struct perf_counter *counter)
1910 {
1911         if (counter->state != PERF_COUNTER_STATE_ACTIVE)
1912                 return 0;
1913
1914         return counter->hw.idx + 1 - PERF_COUNTER_INDEX_OFFSET;
1915 }
1916
1917 /*
1918  * Callers need to ensure there can be no nesting of this function, otherwise
1919  * the seqlock logic goes bad. We can not serialize this because the arch
1920  * code calls this from NMI context.
1921  */
1922 void perf_counter_update_userpage(struct perf_counter *counter)
1923 {
1924         struct perf_counter_mmap_page *userpg;
1925         struct perf_mmap_data *data;
1926
1927         rcu_read_lock();
1928         data = rcu_dereference(counter->data);
1929         if (!data)
1930                 goto unlock;
1931
1932         userpg = data->user_page;
1933
1934         /*
1935          * Disable preemption so as to not let the corresponding user-space
1936          * spin too long if we get preempted.
1937          */
1938         preempt_disable();
1939         ++userpg->lock;
1940         barrier();
1941         userpg->index = perf_counter_index(counter);
1942         userpg->offset = atomic64_read(&counter->count);
1943         if (counter->state == PERF_COUNTER_STATE_ACTIVE)
1944                 userpg->offset -= atomic64_read(&counter->hw.prev_count);
1945
1946         userpg->time_enabled = counter->total_time_enabled +
1947                         atomic64_read(&counter->child_total_time_enabled);
1948
1949         userpg->time_running = counter->total_time_running +
1950                         atomic64_read(&counter->child_total_time_running);
1951
1952         barrier();
1953         ++userpg->lock;
1954         preempt_enable();
1955 unlock:
1956         rcu_read_unlock();
1957 }
1958
1959 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1960 {
1961         struct perf_counter *counter = vma->vm_file->private_data;
1962         struct perf_mmap_data *data;
1963         int ret = VM_FAULT_SIGBUS;
1964
1965         if (vmf->flags & FAULT_FLAG_MKWRITE) {
1966                 if (vmf->pgoff == 0)
1967                         ret = 0;
1968                 return ret;
1969         }
1970
1971         rcu_read_lock();
1972         data = rcu_dereference(counter->data);
1973         if (!data)
1974                 goto unlock;
1975
1976         if (vmf->pgoff == 0) {
1977                 vmf->page = virt_to_page(data->user_page);
1978         } else {
1979                 int nr = vmf->pgoff - 1;
1980
1981                 if ((unsigned)nr > data->nr_pages)
1982                         goto unlock;
1983
1984                 if (vmf->flags & FAULT_FLAG_WRITE)
1985                         goto unlock;
1986
1987                 vmf->page = virt_to_page(data->data_pages[nr]);
1988         }
1989
1990         get_page(vmf->page);
1991         vmf->page->mapping = vma->vm_file->f_mapping;
1992         vmf->page->index   = vmf->pgoff;
1993
1994         ret = 0;
1995 unlock:
1996         rcu_read_unlock();
1997
1998         return ret;
1999 }
2000
2001 static int perf_mmap_data_alloc(struct perf_counter *counter, int nr_pages)
2002 {
2003         struct perf_mmap_data *data;
2004         unsigned long size;
2005         int i;
2006
2007         WARN_ON(atomic_read(&counter->mmap_count));
2008
2009         size = sizeof(struct perf_mmap_data);
2010         size += nr_pages * sizeof(void *);
2011
2012         data = kzalloc(size, GFP_KERNEL);
2013         if (!data)
2014                 goto fail;
2015
2016         data->user_page = (void *)get_zeroed_page(GFP_KERNEL);
2017         if (!data->user_page)
2018                 goto fail_user_page;
2019
2020         for (i = 0; i < nr_pages; i++) {
2021                 data->data_pages[i] = (void *)get_zeroed_page(GFP_KERNEL);
2022                 if (!data->data_pages[i])
2023                         goto fail_data_pages;
2024         }
2025
2026         data->nr_pages = nr_pages;
2027         atomic_set(&data->lock, -1);
2028
2029         rcu_assign_pointer(counter->data, data);
2030
2031         return 0;
2032
2033 fail_data_pages:
2034         for (i--; i >= 0; i--)
2035                 free_page((unsigned long)data->data_pages[i]);
2036
2037         free_page((unsigned long)data->user_page);
2038
2039 fail_user_page:
2040         kfree(data);
2041
2042 fail:
2043         return -ENOMEM;
2044 }
2045
2046 static void perf_mmap_free_page(unsigned long addr)
2047 {
2048         struct page *page = virt_to_page((void *)addr);
2049
2050         page->mapping = NULL;
2051         __free_page(page);
2052 }
2053
2054 static void __perf_mmap_data_free(struct rcu_head *rcu_head)
2055 {
2056         struct perf_mmap_data *data;
2057         int i;
2058
2059         data = container_of(rcu_head, struct perf_mmap_data, rcu_head);
2060
2061         perf_mmap_free_page((unsigned long)data->user_page);
2062         for (i = 0; i < data->nr_pages; i++)
2063                 perf_mmap_free_page((unsigned long)data->data_pages[i]);
2064
2065         kfree(data);
2066 }
2067
2068 static void perf_mmap_data_free(struct perf_counter *counter)
2069 {
2070         struct perf_mmap_data *data = counter->data;
2071
2072         WARN_ON(atomic_read(&counter->mmap_count));
2073
2074         rcu_assign_pointer(counter->data, NULL);
2075         call_rcu(&data->rcu_head, __perf_mmap_data_free);
2076 }
2077
2078 static void perf_mmap_open(struct vm_area_struct *vma)
2079 {
2080         struct perf_counter *counter = vma->vm_file->private_data;
2081
2082         atomic_inc(&counter->mmap_count);
2083 }
2084
2085 static void perf_mmap_close(struct vm_area_struct *vma)
2086 {
2087         struct perf_counter *counter = vma->vm_file->private_data;
2088
2089         WARN_ON_ONCE(counter->ctx->parent_ctx);
2090         if (atomic_dec_and_mutex_lock(&counter->mmap_count, &counter->mmap_mutex)) {
2091                 struct user_struct *user = current_user();
2092
2093                 atomic_long_sub(counter->data->nr_pages + 1, &user->locked_vm);
2094                 vma->vm_mm->locked_vm -= counter->data->nr_locked;
2095                 perf_mmap_data_free(counter);
2096                 mutex_unlock(&counter->mmap_mutex);
2097         }
2098 }
2099
2100 static struct vm_operations_struct perf_mmap_vmops = {
2101         .open           = perf_mmap_open,
2102         .close          = perf_mmap_close,
2103         .fault          = perf_mmap_fault,
2104         .page_mkwrite   = perf_mmap_fault,
2105 };
2106
2107 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
2108 {
2109         struct perf_counter *counter = file->private_data;
2110         unsigned long user_locked, user_lock_limit;
2111         struct user_struct *user = current_user();
2112         unsigned long locked, lock_limit;
2113         unsigned long vma_size;
2114         unsigned long nr_pages;
2115         long user_extra, extra;
2116         int ret = 0;
2117
2118         if (!(vma->vm_flags & VM_SHARED))
2119                 return -EINVAL;
2120
2121         vma_size = vma->vm_end - vma->vm_start;
2122         nr_pages = (vma_size / PAGE_SIZE) - 1;
2123
2124         /*
2125          * If we have data pages ensure they're a power-of-two number, so we
2126          * can do bitmasks instead of modulo.
2127          */
2128         if (nr_pages != 0 && !is_power_of_2(nr_pages))
2129                 return -EINVAL;
2130
2131         if (vma_size != PAGE_SIZE * (1 + nr_pages))
2132                 return -EINVAL;
2133
2134         if (vma->vm_pgoff != 0)
2135                 return -EINVAL;
2136
2137         WARN_ON_ONCE(counter->ctx->parent_ctx);
2138         mutex_lock(&counter->mmap_mutex);
2139         if (atomic_inc_not_zero(&counter->mmap_count)) {
2140                 if (nr_pages != counter->data->nr_pages)
2141                         ret = -EINVAL;
2142                 goto unlock;
2143         }
2144
2145         user_extra = nr_pages + 1;
2146         user_lock_limit = sysctl_perf_counter_mlock >> (PAGE_SHIFT - 10);
2147
2148         /*
2149          * Increase the limit linearly with more CPUs:
2150          */
2151         user_lock_limit *= num_online_cpus();
2152
2153         user_locked = atomic_long_read(&user->locked_vm) + user_extra;
2154
2155         extra = 0;
2156         if (user_locked > user_lock_limit)
2157                 extra = user_locked - user_lock_limit;
2158
2159         lock_limit = current->signal->rlim[RLIMIT_MEMLOCK].rlim_cur;
2160         lock_limit >>= PAGE_SHIFT;
2161         locked = vma->vm_mm->locked_vm + extra;
2162
2163         if ((locked > lock_limit) && !capable(CAP_IPC_LOCK)) {
2164                 ret = -EPERM;
2165                 goto unlock;
2166         }
2167
2168         WARN_ON(counter->data);
2169         ret = perf_mmap_data_alloc(counter, nr_pages);
2170         if (ret)
2171                 goto unlock;
2172
2173         atomic_set(&counter->mmap_count, 1);
2174         atomic_long_add(user_extra, &user->locked_vm);
2175         vma->vm_mm->locked_vm += extra;
2176         counter->data->nr_locked = extra;
2177         if (vma->vm_flags & VM_WRITE)
2178                 counter->data->writable = 1;
2179
2180 unlock:
2181         mutex_unlock(&counter->mmap_mutex);
2182
2183         vma->vm_flags |= VM_RESERVED;
2184         vma->vm_ops = &perf_mmap_vmops;
2185
2186         return ret;
2187 }
2188
2189 static int perf_fasync(int fd, struct file *filp, int on)
2190 {
2191         struct inode *inode = filp->f_path.dentry->d_inode;
2192         struct perf_counter *counter = filp->private_data;
2193         int retval;
2194
2195         mutex_lock(&inode->i_mutex);
2196         retval = fasync_helper(fd, filp, on, &counter->fasync);
2197         mutex_unlock(&inode->i_mutex);
2198
2199         if (retval < 0)
2200                 return retval;
2201
2202         return 0;
2203 }
2204
2205 static const struct file_operations perf_fops = {
2206         .release                = perf_release,
2207         .read                   = perf_read,
2208         .poll                   = perf_poll,
2209         .unlocked_ioctl         = perf_ioctl,
2210         .compat_ioctl           = perf_ioctl,
2211         .mmap                   = perf_mmap,
2212         .fasync                 = perf_fasync,
2213 };
2214
2215 /*
2216  * Perf counter wakeup
2217  *
2218  * If there's data, ensure we set the poll() state and publish everything
2219  * to user-space before waking everybody up.
2220  */
2221
2222 void perf_counter_wakeup(struct perf_counter *counter)
2223 {
2224         wake_up_all(&counter->waitq);
2225
2226         if (counter->pending_kill) {
2227                 kill_fasync(&counter->fasync, SIGIO, counter->pending_kill);
2228                 counter->pending_kill = 0;
2229         }
2230 }
2231
2232 /*
2233  * Pending wakeups
2234  *
2235  * Handle the case where we need to wakeup up from NMI (or rq->lock) context.
2236  *
2237  * The NMI bit means we cannot possibly take locks. Therefore, maintain a
2238  * single linked list and use cmpxchg() to add entries lockless.
2239  */
2240
2241 static void perf_pending_counter(struct perf_pending_entry *entry)
2242 {
2243         struct perf_counter *counter = container_of(entry,
2244                         struct perf_counter, pending);
2245
2246         if (counter->pending_disable) {
2247                 counter->pending_disable = 0;
2248                 perf_counter_disable(counter);
2249         }
2250
2251         if (counter->pending_wakeup) {
2252                 counter->pending_wakeup = 0;
2253                 perf_counter_wakeup(counter);
2254         }
2255 }
2256
2257 #define PENDING_TAIL ((struct perf_pending_entry *)-1UL)
2258
2259 static DEFINE_PER_CPU(struct perf_pending_entry *, perf_pending_head) = {
2260         PENDING_TAIL,
2261 };
2262
2263 static void perf_pending_queue(struct perf_pending_entry *entry,
2264                                void (*func)(struct perf_pending_entry *))
2265 {
2266         struct perf_pending_entry **head;
2267
2268         if (cmpxchg(&entry->next, NULL, PENDING_TAIL) != NULL)
2269                 return;
2270
2271         entry->func = func;
2272
2273         head = &get_cpu_var(perf_pending_head);
2274
2275         do {
2276                 entry->next = *head;
2277         } while (cmpxchg(head, entry->next, entry) != entry->next);
2278
2279         set_perf_counter_pending();
2280
2281         put_cpu_var(perf_pending_head);
2282 }
2283
2284 static int __perf_pending_run(void)
2285 {
2286         struct perf_pending_entry *list;
2287         int nr = 0;
2288
2289         list = xchg(&__get_cpu_var(perf_pending_head), PENDING_TAIL);
2290         while (list != PENDING_TAIL) {
2291                 void (*func)(struct perf_pending_entry *);
2292                 struct perf_pending_entry *entry = list;
2293
2294                 list = list->next;
2295
2296                 func = entry->func;
2297                 entry->next = NULL;
2298                 /*
2299                  * Ensure we observe the unqueue before we issue the wakeup,
2300                  * so that we won't be waiting forever.
2301                  * -- see perf_not_pending().
2302                  */
2303                 smp_wmb();
2304
2305                 func(entry);
2306                 nr++;
2307         }
2308
2309         return nr;
2310 }
2311
2312 static inline int perf_not_pending(struct perf_counter *counter)
2313 {
2314         /*
2315          * If we flush on whatever cpu we run, there is a chance we don't
2316          * need to wait.
2317          */
2318         get_cpu();
2319         __perf_pending_run();
2320         put_cpu();
2321
2322         /*
2323          * Ensure we see the proper queue state before going to sleep
2324          * so that we do not miss the wakeup. -- see perf_pending_handle()
2325          */
2326         smp_rmb();
2327         return counter->pending.next == NULL;
2328 }
2329
2330 static void perf_pending_sync(struct perf_counter *counter)
2331 {
2332         wait_event(counter->waitq, perf_not_pending(counter));
2333 }
2334
2335 void perf_counter_do_pending(void)
2336 {
2337         __perf_pending_run();
2338 }
2339
2340 /*
2341  * Callchain support -- arch specific
2342  */
2343
2344 __weak struct perf_callchain_entry *perf_callchain(struct pt_regs *regs)
2345 {
2346         return NULL;
2347 }
2348
2349 /*
2350  * Output
2351  */
2352
2353 struct perf_output_handle {
2354         struct perf_counter     *counter;
2355         struct perf_mmap_data   *data;
2356         unsigned long           head;
2357         unsigned long           offset;
2358         int                     nmi;
2359         int                     sample;
2360         int                     locked;
2361         unsigned long           flags;
2362 };
2363
2364 static bool perf_output_space(struct perf_mmap_data *data,
2365                               unsigned int offset, unsigned int head)
2366 {
2367         unsigned long tail;
2368         unsigned long mask;
2369
2370         if (!data->writable)
2371                 return true;
2372
2373         mask = (data->nr_pages << PAGE_SHIFT) - 1;
2374         /*
2375          * Userspace could choose to issue a mb() before updating the tail
2376          * pointer. So that all reads will be completed before the write is
2377          * issued.
2378          */
2379         tail = ACCESS_ONCE(data->user_page->data_tail);
2380         smp_rmb();
2381
2382         offset = (offset - tail) & mask;
2383         head   = (head   - tail) & mask;
2384
2385         if ((int)(head - offset) < 0)
2386                 return false;
2387
2388         return true;
2389 }
2390
2391 static void perf_output_wakeup(struct perf_output_handle *handle)
2392 {
2393         atomic_set(&handle->data->poll, POLL_IN);
2394
2395         if (handle->nmi) {
2396                 handle->counter->pending_wakeup = 1;
2397                 perf_pending_queue(&handle->counter->pending,
2398                                    perf_pending_counter);
2399         } else
2400                 perf_counter_wakeup(handle->counter);
2401 }
2402
2403 /*
2404  * Curious locking construct.
2405  *
2406  * We need to ensure a later event doesn't publish a head when a former
2407  * event isn't done writing. However since we need to deal with NMIs we
2408  * cannot fully serialize things.
2409  *
2410  * What we do is serialize between CPUs so we only have to deal with NMI
2411  * nesting on a single CPU.
2412  *
2413  * We only publish the head (and generate a wakeup) when the outer-most
2414  * event completes.
2415  */
2416 static void perf_output_lock(struct perf_output_handle *handle)
2417 {
2418         struct perf_mmap_data *data = handle->data;
2419         int cpu;
2420
2421         handle->locked = 0;
2422
2423         local_irq_save(handle->flags);
2424         cpu = smp_processor_id();
2425
2426         if (in_nmi() && atomic_read(&data->lock) == cpu)
2427                 return;
2428
2429         while (atomic_cmpxchg(&data->lock, -1, cpu) != -1)
2430                 cpu_relax();
2431
2432         handle->locked = 1;
2433 }
2434
2435 static void perf_output_unlock(struct perf_output_handle *handle)
2436 {
2437         struct perf_mmap_data *data = handle->data;
2438         unsigned long head;
2439         int cpu;
2440
2441         data->done_head = data->head;
2442
2443         if (!handle->locked)
2444                 goto out;
2445
2446 again:
2447         /*
2448          * The xchg implies a full barrier that ensures all writes are done
2449          * before we publish the new head, matched by a rmb() in userspace when
2450          * reading this position.
2451          */
2452         while ((head = atomic_long_xchg(&data->done_head, 0)))
2453                 data->user_page->data_head = head;
2454
2455         /*
2456          * NMI can happen here, which means we can miss a done_head update.
2457          */
2458
2459         cpu = atomic_xchg(&data->lock, -1);
2460         WARN_ON_ONCE(cpu != smp_processor_id());
2461
2462         /*
2463          * Therefore we have to validate we did not indeed do so.
2464          */
2465         if (unlikely(atomic_long_read(&data->done_head))) {
2466                 /*
2467                  * Since we had it locked, we can lock it again.
2468                  */
2469                 while (atomic_cmpxchg(&data->lock, -1, cpu) != -1)
2470                         cpu_relax();
2471
2472                 goto again;
2473         }
2474
2475         if (atomic_xchg(&data->wakeup, 0))
2476                 perf_output_wakeup(handle);
2477 out:
2478         local_irq_restore(handle->flags);
2479 }
2480
2481 static void perf_output_copy(struct perf_output_handle *handle,
2482                              const void *buf, unsigned int len)
2483 {
2484         unsigned int pages_mask;
2485         unsigned int offset;
2486         unsigned int size;
2487         void **pages;
2488
2489         offset          = handle->offset;
2490         pages_mask      = handle->data->nr_pages - 1;
2491         pages           = handle->data->data_pages;
2492
2493         do {
2494                 unsigned int page_offset;
2495                 int nr;
2496
2497                 nr          = (offset >> PAGE_SHIFT) & pages_mask;
2498                 page_offset = offset & (PAGE_SIZE - 1);
2499                 size        = min_t(unsigned int, PAGE_SIZE - page_offset, len);
2500
2501                 memcpy(pages[nr] + page_offset, buf, size);
2502
2503                 len         -= size;
2504                 buf         += size;
2505                 offset      += size;
2506         } while (len);
2507
2508         handle->offset = offset;
2509
2510         /*
2511          * Check we didn't copy past our reservation window, taking the
2512          * possible unsigned int wrap into account.
2513          */
2514         WARN_ON_ONCE(((long)(handle->head - handle->offset)) < 0);
2515 }
2516
2517 #define perf_output_put(handle, x) \
2518         perf_output_copy((handle), &(x), sizeof(x))
2519
2520 static int perf_output_begin(struct perf_output_handle *handle,
2521                              struct perf_counter *counter, unsigned int size,
2522                              int nmi, int sample)
2523 {
2524         struct perf_mmap_data *data;
2525         unsigned int offset, head;
2526         int have_lost;
2527         struct {
2528                 struct perf_event_header header;
2529                 u64                      id;
2530                 u64                      lost;
2531         } lost_event;
2532
2533         /*
2534          * For inherited counters we send all the output towards the parent.
2535          */
2536         if (counter->parent)
2537                 counter = counter->parent;
2538
2539         rcu_read_lock();
2540         data = rcu_dereference(counter->data);
2541         if (!data)
2542                 goto out;
2543
2544         handle->data    = data;
2545         handle->counter = counter;
2546         handle->nmi     = nmi;
2547         handle->sample  = sample;
2548
2549         if (!data->nr_pages)
2550                 goto fail;
2551
2552         have_lost = atomic_read(&data->lost);
2553         if (have_lost)
2554                 size += sizeof(lost_event);
2555
2556         perf_output_lock(handle);
2557
2558         do {
2559                 offset = head = atomic_long_read(&data->head);
2560                 head += size;
2561                 if (unlikely(!perf_output_space(data, offset, head)))
2562                         goto fail;
2563         } while (atomic_long_cmpxchg(&data->head, offset, head) != offset);
2564
2565         handle->offset  = offset;
2566         handle->head    = head;
2567
2568         if ((offset >> PAGE_SHIFT) != (head >> PAGE_SHIFT))
2569                 atomic_set(&data->wakeup, 1);
2570
2571         if (have_lost) {
2572                 lost_event.header.type = PERF_EVENT_LOST;
2573                 lost_event.header.misc = 0;
2574                 lost_event.header.size = sizeof(lost_event);
2575                 lost_event.id          = counter->id;
2576                 lost_event.lost        = atomic_xchg(&data->lost, 0);
2577
2578                 perf_output_put(handle, lost_event);
2579         }
2580
2581         return 0;
2582
2583 fail:
2584         atomic_inc(&data->lost);
2585         perf_output_unlock(handle);
2586 out:
2587         rcu_read_unlock();
2588
2589         return -ENOSPC;
2590 }
2591
2592 static void perf_output_end(struct perf_output_handle *handle)
2593 {
2594         struct perf_counter *counter = handle->counter;
2595         struct perf_mmap_data *data = handle->data;
2596
2597         int wakeup_events = counter->attr.wakeup_events;
2598
2599         if (handle->sample && wakeup_events) {
2600                 int events = atomic_inc_return(&data->events);
2601                 if (events >= wakeup_events) {
2602                         atomic_sub(wakeup_events, &data->events);
2603                         atomic_set(&data->wakeup, 1);
2604                 }
2605         }
2606
2607         perf_output_unlock(handle);
2608         rcu_read_unlock();
2609 }
2610
2611 static u32 perf_counter_pid(struct perf_counter *counter, struct task_struct *p)
2612 {
2613         /*
2614          * only top level counters have the pid namespace they were created in
2615          */
2616         if (counter->parent)
2617                 counter = counter->parent;
2618
2619         return task_tgid_nr_ns(p, counter->ns);
2620 }
2621
2622 static u32 perf_counter_tid(struct perf_counter *counter, struct task_struct *p)
2623 {
2624         /*
2625          * only top level counters have the pid namespace they were created in
2626          */
2627         if (counter->parent)
2628                 counter = counter->parent;
2629
2630         return task_pid_nr_ns(p, counter->ns);
2631 }
2632
2633 static void perf_counter_output(struct perf_counter *counter, int nmi,
2634                                 struct perf_sample_data *data)
2635 {
2636         int ret;
2637         u64 sample_type = counter->attr.sample_type;
2638         struct perf_output_handle handle;
2639         struct perf_event_header header;
2640         u64 ip;
2641         struct {
2642                 u32 pid, tid;
2643         } tid_entry;
2644         struct {
2645                 u64 id;
2646                 u64 counter;
2647         } group_entry;
2648         struct perf_callchain_entry *callchain = NULL;
2649         int callchain_size = 0;
2650         u64 time;
2651         struct {
2652                 u32 cpu, reserved;
2653         } cpu_entry;
2654
2655         header.type = PERF_EVENT_SAMPLE;
2656         header.size = sizeof(header);
2657
2658         header.misc = 0;
2659         header.misc |= perf_misc_flags(data->regs);
2660
2661         if (sample_type & PERF_SAMPLE_IP) {
2662                 ip = perf_instruction_pointer(data->regs);
2663                 header.size += sizeof(ip);
2664         }
2665
2666         if (sample_type & PERF_SAMPLE_TID) {
2667                 /* namespace issues */
2668                 tid_entry.pid = perf_counter_pid(counter, current);
2669                 tid_entry.tid = perf_counter_tid(counter, current);
2670
2671                 header.size += sizeof(tid_entry);
2672         }
2673
2674         if (sample_type & PERF_SAMPLE_TIME) {
2675                 /*
2676                  * Maybe do better on x86 and provide cpu_clock_nmi()
2677                  */
2678                 time = sched_clock();
2679
2680                 header.size += sizeof(u64);
2681         }
2682
2683         if (sample_type & PERF_SAMPLE_ADDR)
2684                 header.size += sizeof(u64);
2685
2686         if (sample_type & PERF_SAMPLE_ID)
2687                 header.size += sizeof(u64);
2688
2689         if (sample_type & PERF_SAMPLE_STREAM_ID)
2690                 header.size += sizeof(u64);
2691
2692         if (sample_type & PERF_SAMPLE_CPU) {
2693                 header.size += sizeof(cpu_entry);
2694
2695                 cpu_entry.cpu = raw_smp_processor_id();
2696                 cpu_entry.reserved = 0;
2697         }
2698
2699         if (sample_type & PERF_SAMPLE_PERIOD)
2700                 header.size += sizeof(u64);
2701
2702         if (sample_type & PERF_SAMPLE_GROUP) {
2703                 header.size += sizeof(u64) +
2704                         counter->nr_siblings * sizeof(group_entry);
2705         }
2706
2707         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
2708                 callchain = perf_callchain(data->regs);
2709
2710                 if (callchain) {
2711                         callchain_size = (1 + callchain->nr) * sizeof(u64);
2712                         header.size += callchain_size;
2713                 } else
2714                         header.size += sizeof(u64);
2715         }
2716
2717         ret = perf_output_begin(&handle, counter, header.size, nmi, 1);
2718         if (ret)
2719                 return;
2720
2721         perf_output_put(&handle, header);
2722
2723         if (sample_type & PERF_SAMPLE_IP)
2724                 perf_output_put(&handle, ip);
2725
2726         if (sample_type & PERF_SAMPLE_TID)
2727                 perf_output_put(&handle, tid_entry);
2728
2729         if (sample_type & PERF_SAMPLE_TIME)
2730                 perf_output_put(&handle, time);
2731
2732         if (sample_type & PERF_SAMPLE_ADDR)
2733                 perf_output_put(&handle, data->addr);
2734
2735         if (sample_type & PERF_SAMPLE_ID) {
2736                 u64 id = primary_counter_id(counter);
2737
2738                 perf_output_put(&handle, id);
2739         }
2740
2741         if (sample_type & PERF_SAMPLE_STREAM_ID)
2742                 perf_output_put(&handle, counter->id);
2743
2744         if (sample_type & PERF_SAMPLE_CPU)
2745                 perf_output_put(&handle, cpu_entry);
2746
2747         if (sample_type & PERF_SAMPLE_PERIOD)
2748                 perf_output_put(&handle, data->period);
2749
2750         /*
2751          * XXX PERF_SAMPLE_GROUP vs inherited counters seems difficult.
2752          */
2753         if (sample_type & PERF_SAMPLE_GROUP) {
2754                 struct perf_counter *leader, *sub;
2755                 u64 nr = counter->nr_siblings;
2756
2757                 perf_output_put(&handle, nr);
2758
2759                 leader = counter->group_leader;
2760                 list_for_each_entry(sub, &leader->sibling_list, list_entry) {
2761                         if (sub != counter)
2762                                 sub->pmu->read(sub);
2763
2764                         group_entry.id = primary_counter_id(sub);
2765                         group_entry.counter = atomic64_read(&sub->count);
2766
2767                         perf_output_put(&handle, group_entry);
2768                 }
2769         }
2770
2771         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
2772                 if (callchain)
2773                         perf_output_copy(&handle, callchain, callchain_size);
2774                 else {
2775                         u64 nr = 0;
2776                         perf_output_put(&handle, nr);
2777                 }
2778         }
2779
2780         perf_output_end(&handle);
2781 }
2782
2783 /*
2784  * read event
2785  */
2786
2787 struct perf_read_event {
2788         struct perf_event_header        header;
2789
2790         u32                             pid;
2791         u32                             tid;
2792         u64                             value;
2793         u64                             format[3];
2794 };
2795
2796 static void
2797 perf_counter_read_event(struct perf_counter *counter,
2798                         struct task_struct *task)
2799 {
2800         struct perf_output_handle handle;
2801         struct perf_read_event event = {
2802                 .header = {
2803                         .type = PERF_EVENT_READ,
2804                         .misc = 0,
2805                         .size = sizeof(event) - sizeof(event.format),
2806                 },
2807                 .pid = perf_counter_pid(counter, task),
2808                 .tid = perf_counter_tid(counter, task),
2809                 .value = atomic64_read(&counter->count),
2810         };
2811         int ret, i = 0;
2812
2813         if (counter->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
2814                 event.header.size += sizeof(u64);
2815                 event.format[i++] = counter->total_time_enabled;
2816         }
2817
2818         if (counter->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
2819                 event.header.size += sizeof(u64);
2820                 event.format[i++] = counter->total_time_running;
2821         }
2822
2823         if (counter->attr.read_format & PERF_FORMAT_ID) {
2824                 event.header.size += sizeof(u64);
2825                 event.format[i++] = primary_counter_id(counter);
2826         }
2827
2828         ret = perf_output_begin(&handle, counter, event.header.size, 0, 0);
2829         if (ret)
2830                 return;
2831
2832         perf_output_copy(&handle, &event, event.header.size);
2833         perf_output_end(&handle);
2834 }
2835
2836 /*
2837  * task tracking -- fork/exit
2838  *
2839  * enabled by: attr.comm | attr.mmap | attr.task
2840  */
2841
2842 struct perf_task_event {
2843         struct task_struct      *task;
2844
2845         struct {
2846                 struct perf_event_header        header;
2847
2848                 u32                             pid;
2849                 u32                             ppid;
2850                 u32                             tid;
2851                 u32                             ptid;
2852         } event;
2853 };
2854
2855 static void perf_counter_task_output(struct perf_counter *counter,
2856                                      struct perf_task_event *task_event)
2857 {
2858         struct perf_output_handle handle;
2859         int size = task_event->event.header.size;
2860         struct task_struct *task = task_event->task;
2861         int ret = perf_output_begin(&handle, counter, size, 0, 0);
2862
2863         if (ret)
2864                 return;
2865
2866         task_event->event.pid = perf_counter_pid(counter, task);
2867         task_event->event.ppid = perf_counter_pid(counter, task->real_parent);
2868
2869         task_event->event.tid = perf_counter_tid(counter, task);
2870         task_event->event.ptid = perf_counter_tid(counter, task->real_parent);
2871
2872         perf_output_put(&handle, task_event->event);
2873         perf_output_end(&handle);
2874 }
2875
2876 static int perf_counter_task_match(struct perf_counter *counter)
2877 {
2878         if (counter->attr.comm || counter->attr.mmap || counter->attr.task)
2879                 return 1;
2880
2881         return 0;
2882 }
2883
2884 static void perf_counter_task_ctx(struct perf_counter_context *ctx,
2885                                   struct perf_task_event *task_event)
2886 {
2887         struct perf_counter *counter;
2888
2889         if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
2890                 return;
2891
2892         rcu_read_lock();
2893         list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
2894                 if (perf_counter_task_match(counter))
2895                         perf_counter_task_output(counter, task_event);
2896         }
2897         rcu_read_unlock();
2898 }
2899
2900 static void perf_counter_task_event(struct perf_task_event *task_event)
2901 {
2902         struct perf_cpu_context *cpuctx;
2903         struct perf_counter_context *ctx;
2904
2905         cpuctx = &get_cpu_var(perf_cpu_context);
2906         perf_counter_task_ctx(&cpuctx->ctx, task_event);
2907         put_cpu_var(perf_cpu_context);
2908
2909         rcu_read_lock();
2910         /*
2911          * doesn't really matter which of the child contexts the
2912          * events ends up in.
2913          */
2914         ctx = rcu_dereference(current->perf_counter_ctxp);
2915         if (ctx)
2916                 perf_counter_task_ctx(ctx, task_event);
2917         rcu_read_unlock();
2918 }
2919
2920 static void perf_counter_task(struct task_struct *task, int new)
2921 {
2922         struct perf_task_event task_event;
2923
2924         if (!atomic_read(&nr_comm_counters) &&
2925             !atomic_read(&nr_mmap_counters) &&
2926             !atomic_read(&nr_task_counters))
2927                 return;
2928
2929         task_event = (struct perf_task_event){
2930                 .task   = task,
2931                 .event  = {
2932                         .header = {
2933                                 .type = new ? PERF_EVENT_FORK : PERF_EVENT_EXIT,
2934                                 .misc = 0,
2935                                 .size = sizeof(task_event.event),
2936                         },
2937                         /* .pid  */
2938                         /* .ppid */
2939                         /* .tid  */
2940                         /* .ptid */
2941                 },
2942         };
2943
2944         perf_counter_task_event(&task_event);
2945 }
2946
2947 void perf_counter_fork(struct task_struct *task)
2948 {
2949         perf_counter_task(task, 1);
2950 }
2951
2952 /*
2953  * comm tracking
2954  */
2955
2956 struct perf_comm_event {
2957         struct task_struct      *task;
2958         char                    *comm;
2959         int                     comm_size;
2960
2961         struct {
2962                 struct perf_event_header        header;
2963
2964                 u32                             pid;
2965                 u32                             tid;
2966         } event;
2967 };
2968
2969 static void perf_counter_comm_output(struct perf_counter *counter,
2970                                      struct perf_comm_event *comm_event)
2971 {
2972         struct perf_output_handle handle;
2973         int size = comm_event->event.header.size;
2974         int ret = perf_output_begin(&handle, counter, size, 0, 0);
2975
2976         if (ret)
2977                 return;
2978
2979         comm_event->event.pid = perf_counter_pid(counter, comm_event->task);
2980         comm_event->event.tid = perf_counter_tid(counter, comm_event->task);
2981
2982         perf_output_put(&handle, comm_event->event);
2983         perf_output_copy(&handle, comm_event->comm,
2984                                    comm_event->comm_size);
2985         perf_output_end(&handle);
2986 }
2987
2988 static int perf_counter_comm_match(struct perf_counter *counter)
2989 {
2990         if (counter->attr.comm)
2991                 return 1;
2992
2993         return 0;
2994 }
2995
2996 static void perf_counter_comm_ctx(struct perf_counter_context *ctx,
2997                                   struct perf_comm_event *comm_event)
2998 {
2999         struct perf_counter *counter;
3000
3001         if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
3002                 return;
3003
3004         rcu_read_lock();
3005         list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
3006                 if (perf_counter_comm_match(counter))
3007                         perf_counter_comm_output(counter, comm_event);
3008         }
3009         rcu_read_unlock();
3010 }
3011
3012 static void perf_counter_comm_event(struct perf_comm_event *comm_event)
3013 {
3014         struct perf_cpu_context *cpuctx;
3015         struct perf_counter_context *ctx;
3016         unsigned int size;
3017         char comm[TASK_COMM_LEN];
3018
3019         memset(comm, 0, sizeof(comm));
3020         strncpy(comm, comm_event->task->comm, sizeof(comm));
3021         size = ALIGN(strlen(comm)+1, sizeof(u64));
3022
3023         comm_event->comm = comm;
3024         comm_event->comm_size = size;
3025
3026         comm_event->event.header.size = sizeof(comm_event->event) + size;
3027
3028         cpuctx = &get_cpu_var(perf_cpu_context);
3029         perf_counter_comm_ctx(&cpuctx->ctx, comm_event);
3030         put_cpu_var(perf_cpu_context);
3031
3032         rcu_read_lock();
3033         /*
3034          * doesn't really matter which of the child contexts the
3035          * events ends up in.
3036          */
3037         ctx = rcu_dereference(current->perf_counter_ctxp);
3038         if (ctx)
3039                 perf_counter_comm_ctx(ctx, comm_event);
3040         rcu_read_unlock();
3041 }
3042
3043 void perf_counter_comm(struct task_struct *task)
3044 {
3045         struct perf_comm_event comm_event;
3046
3047         if (task->perf_counter_ctxp)
3048                 perf_counter_enable_on_exec(task);
3049
3050         if (!atomic_read(&nr_comm_counters))
3051                 return;
3052
3053         comm_event = (struct perf_comm_event){
3054                 .task   = task,
3055                 /* .comm      */
3056                 /* .comm_size */
3057                 .event  = {
3058                         .header = {
3059                                 .type = PERF_EVENT_COMM,
3060                                 .misc = 0,
3061                                 /* .size */
3062                         },
3063                         /* .pid */
3064                         /* .tid */
3065                 },
3066         };
3067
3068         perf_counter_comm_event(&comm_event);
3069 }
3070
3071 /*
3072  * mmap tracking
3073  */
3074
3075 struct perf_mmap_event {
3076         struct vm_area_struct   *vma;
3077
3078         const char              *file_name;
3079         int                     file_size;
3080
3081         struct {
3082                 struct perf_event_header        header;
3083
3084                 u32                             pid;
3085                 u32                             tid;
3086                 u64                             start;
3087                 u64                             len;
3088                 u64                             pgoff;
3089         } event;
3090 };
3091
3092 static void perf_counter_mmap_output(struct perf_counter *counter,
3093                                      struct perf_mmap_event *mmap_event)
3094 {
3095         struct perf_output_handle handle;
3096         int size = mmap_event->event.header.size;
3097         int ret = perf_output_begin(&handle, counter, size, 0, 0);
3098
3099         if (ret)
3100                 return;
3101
3102         mmap_event->event.pid = perf_counter_pid(counter, current);
3103         mmap_event->event.tid = perf_counter_tid(counter, current);
3104
3105         perf_output_put(&handle, mmap_event->event);
3106         perf_output_copy(&handle, mmap_event->file_name,
3107                                    mmap_event->file_size);
3108         perf_output_end(&handle);
3109 }
3110
3111 static int perf_counter_mmap_match(struct perf_counter *counter,
3112                                    struct perf_mmap_event *mmap_event)
3113 {
3114         if (counter->attr.mmap)
3115                 return 1;
3116
3117         return 0;
3118 }
3119
3120 static void perf_counter_mmap_ctx(struct perf_counter_context *ctx,
3121                                   struct perf_mmap_event *mmap_event)
3122 {
3123         struct perf_counter *counter;
3124
3125         if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
3126                 return;
3127
3128         rcu_read_lock();
3129         list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
3130                 if (perf_counter_mmap_match(counter, mmap_event))
3131                         perf_counter_mmap_output(counter, mmap_event);
3132         }
3133         rcu_read_unlock();
3134 }
3135
3136 static void perf_counter_mmap_event(struct perf_mmap_event *mmap_event)
3137 {
3138         struct perf_cpu_context *cpuctx;
3139         struct perf_counter_context *ctx;
3140         struct vm_area_struct *vma = mmap_event->vma;
3141         struct file *file = vma->vm_file;
3142         unsigned int size;
3143         char tmp[16];
3144         char *buf = NULL;
3145         const char *name;
3146
3147         memset(tmp, 0, sizeof(tmp));
3148
3149         if (file) {
3150                 /*
3151                  * d_path works from the end of the buffer backwards, so we
3152                  * need to add enough zero bytes after the string to handle
3153                  * the 64bit alignment we do later.
3154                  */
3155                 buf = kzalloc(PATH_MAX + sizeof(u64), GFP_KERNEL);
3156                 if (!buf) {
3157                         name = strncpy(tmp, "//enomem", sizeof(tmp));
3158                         goto got_name;
3159                 }
3160                 name = d_path(&file->f_path, buf, PATH_MAX);
3161                 if (IS_ERR(name)) {
3162                         name = strncpy(tmp, "//toolong", sizeof(tmp));
3163                         goto got_name;
3164                 }
3165         } else {
3166                 if (arch_vma_name(mmap_event->vma)) {
3167                         name = strncpy(tmp, arch_vma_name(mmap_event->vma),
3168                                        sizeof(tmp));
3169                         goto got_name;
3170                 }
3171
3172                 if (!vma->vm_mm) {
3173                         name = strncpy(tmp, "[vdso]", sizeof(tmp));
3174                         goto got_name;
3175                 }
3176
3177                 name = strncpy(tmp, "//anon", sizeof(tmp));
3178                 goto got_name;
3179         }
3180
3181 got_name:
3182         size = ALIGN(strlen(name)+1, sizeof(u64));
3183
3184         mmap_event->file_name = name;
3185         mmap_event->file_size = size;
3186
3187         mmap_event->event.header.size = sizeof(mmap_event->event) + size;
3188
3189         cpuctx = &get_cpu_var(perf_cpu_context);
3190         perf_counter_mmap_ctx(&cpuctx->ctx, mmap_event);
3191         put_cpu_var(perf_cpu_context);
3192
3193         rcu_read_lock();
3194         /*
3195          * doesn't really matter which of the child contexts the
3196          * events ends up in.
3197          */
3198         ctx = rcu_dereference(current->perf_counter_ctxp);
3199         if (ctx)
3200                 perf_counter_mmap_ctx(ctx, mmap_event);
3201         rcu_read_unlock();
3202
3203         kfree(buf);
3204 }
3205
3206 void __perf_counter_mmap(struct vm_area_struct *vma)
3207 {
3208         struct perf_mmap_event mmap_event;
3209
3210         if (!atomic_read(&nr_mmap_counters))
3211                 return;
3212
3213         mmap_event = (struct perf_mmap_event){
3214                 .vma    = vma,
3215                 /* .file_name */
3216                 /* .file_size */
3217                 .event  = {
3218                         .header = {
3219                                 .type = PERF_EVENT_MMAP,
3220                                 .misc = 0,
3221                                 /* .size */
3222                         },
3223                         /* .pid */
3224                         /* .tid */
3225                         .start  = vma->vm_start,
3226                         .len    = vma->vm_end - vma->vm_start,
3227                         .pgoff  = vma->vm_pgoff,
3228                 },
3229         };
3230
3231         perf_counter_mmap_event(&mmap_event);
3232 }
3233
3234 /*
3235  * IRQ throttle logging
3236  */
3237
3238 static void perf_log_throttle(struct perf_counter *counter, int enable)
3239 {
3240         struct perf_output_handle handle;
3241         int ret;
3242
3243         struct {
3244                 struct perf_event_header        header;
3245                 u64                             time;
3246                 u64                             id;
3247                 u64                             stream_id;
3248         } throttle_event = {
3249                 .header = {
3250                         .type = PERF_EVENT_THROTTLE,
3251                         .misc = 0,
3252                         .size = sizeof(throttle_event),
3253                 },
3254                 .time           = sched_clock(),
3255                 .id             = primary_counter_id(counter),
3256                 .stream_id      = counter->id,
3257         };
3258
3259         if (enable)
3260                 throttle_event.header.type = PERF_EVENT_UNTHROTTLE;
3261
3262         ret = perf_output_begin(&handle, counter, sizeof(throttle_event), 1, 0);
3263         if (ret)
3264                 return;
3265
3266         perf_output_put(&handle, throttle_event);
3267         perf_output_end(&handle);
3268 }
3269
3270 /*
3271  * Generic counter overflow handling, sampling.
3272  */
3273
3274 int perf_counter_overflow(struct perf_counter *counter, int nmi,
3275                           struct perf_sample_data *data)
3276 {
3277         int events = atomic_read(&counter->event_limit);
3278         int throttle = counter->pmu->unthrottle != NULL;
3279         struct hw_perf_counter *hwc = &counter->hw;
3280         int ret = 0;
3281
3282         if (!throttle) {
3283                 hwc->interrupts++;
3284         } else {
3285                 if (hwc->interrupts != MAX_INTERRUPTS) {
3286                         hwc->interrupts++;
3287                         if (HZ * hwc->interrupts >
3288                                         (u64)sysctl_perf_counter_sample_rate) {
3289                                 hwc->interrupts = MAX_INTERRUPTS;
3290                                 perf_log_throttle(counter, 0);
3291                                 ret = 1;
3292                         }
3293                 } else {
3294                         /*
3295                          * Keep re-disabling counters even though on the previous
3296                          * pass we disabled it - just in case we raced with a
3297                          * sched-in and the counter got enabled again:
3298                          */
3299                         ret = 1;
3300                 }
3301         }
3302
3303         if (counter->attr.freq) {
3304                 u64 now = sched_clock();
3305                 s64 delta = now - hwc->freq_stamp;
3306
3307                 hwc->freq_stamp = now;
3308
3309                 if (delta > 0 && delta < TICK_NSEC)
3310                         perf_adjust_period(counter, NSEC_PER_SEC / (int)delta);
3311         }
3312
3313         /*
3314          * XXX event_limit might not quite work as expected on inherited
3315          * counters
3316          */
3317
3318         counter->pending_kill = POLL_IN;
3319         if (events && atomic_dec_and_test(&counter->event_limit)) {
3320                 ret = 1;
3321                 counter->pending_kill = POLL_HUP;
3322                 if (nmi) {
3323                         counter->pending_disable = 1;
3324                         perf_pending_queue(&counter->pending,
3325                                            perf_pending_counter);
3326                 } else
3327                         perf_counter_disable(counter);
3328         }
3329
3330         perf_counter_output(counter, nmi, data);
3331         return ret;
3332 }
3333
3334 /*
3335  * Generic software counter infrastructure
3336  */
3337
3338 static void perf_swcounter_update(struct perf_counter *counter)
3339 {
3340         struct hw_perf_counter *hwc = &counter->hw;
3341         u64 prev, now;
3342         s64 delta;
3343
3344 again:
3345         prev = atomic64_read(&hwc->prev_count);
3346         now = atomic64_read(&hwc->count);
3347         if (atomic64_cmpxchg(&hwc->prev_count, prev, now) != prev)
3348                 goto again;
3349
3350         delta = now - prev;
3351
3352         atomic64_add(delta, &counter->count);
3353         atomic64_sub(delta, &hwc->period_left);
3354 }
3355
3356 static void perf_swcounter_set_period(struct perf_counter *counter)
3357 {
3358         struct hw_perf_counter *hwc = &counter->hw;
3359         s64 left = atomic64_read(&hwc->period_left);
3360         s64 period = hwc->sample_period;
3361
3362         if (unlikely(left <= -period)) {
3363                 left = period;
3364                 atomic64_set(&hwc->period_left, left);
3365                 hwc->last_period = period;
3366         }
3367
3368         if (unlikely(left <= 0)) {
3369                 left += period;
3370                 atomic64_add(period, &hwc->period_left);
3371                 hwc->last_period = period;
3372         }
3373
3374         atomic64_set(&hwc->prev_count, -left);
3375         atomic64_set(&hwc->count, -left);
3376 }
3377
3378 static enum hrtimer_restart perf_swcounter_hrtimer(struct hrtimer *hrtimer)
3379 {
3380         enum hrtimer_restart ret = HRTIMER_RESTART;
3381         struct perf_sample_data data;
3382         struct perf_counter *counter;
3383         u64 period;
3384
3385         counter = container_of(hrtimer, struct perf_counter, hw.hrtimer);
3386         counter->pmu->read(counter);
3387
3388         data.addr = 0;
3389         data.regs = get_irq_regs();
3390         /*
3391          * In case we exclude kernel IPs or are somehow not in interrupt
3392          * context, provide the next best thing, the user IP.
3393          */
3394         if ((counter->attr.exclude_kernel || !data.regs) &&
3395                         !counter->attr.exclude_user)
3396                 data.regs = task_pt_regs(current);
3397
3398         if (data.regs) {
3399                 if (perf_counter_overflow(counter, 0, &data))
3400                         ret = HRTIMER_NORESTART;
3401         }
3402
3403         period = max_t(u64, 10000, counter->hw.sample_period);
3404         hrtimer_forward_now(hrtimer, ns_to_ktime(period));
3405
3406         return ret;
3407 }
3408
3409 static void perf_swcounter_overflow(struct perf_counter *counter,
3410                                     int nmi, struct perf_sample_data *data)
3411 {
3412         data->period = counter->hw.last_period;
3413
3414         perf_swcounter_update(counter);
3415         perf_swcounter_set_period(counter);
3416         if (perf_counter_overflow(counter, nmi, data))
3417                 /* soft-disable the counter */
3418                 ;
3419 }
3420
3421 static int perf_swcounter_is_counting(struct perf_counter *counter)
3422 {
3423         struct perf_counter_context *ctx;
3424         unsigned long flags;
3425         int count;
3426
3427         if (counter->state == PERF_COUNTER_STATE_ACTIVE)
3428                 return 1;
3429
3430         if (counter->state != PERF_COUNTER_STATE_INACTIVE)
3431                 return 0;
3432
3433         /*
3434          * If the counter is inactive, it could be just because
3435          * its task is scheduled out, or because it's in a group
3436          * which could not go on the PMU.  We want to count in
3437          * the first case but not the second.  If the context is
3438          * currently active then an inactive software counter must
3439          * be the second case.  If it's not currently active then
3440          * we need to know whether the counter was active when the
3441          * context was last active, which we can determine by
3442          * comparing counter->tstamp_stopped with ctx->time.
3443          *
3444          * We are within an RCU read-side critical section,
3445          * which protects the existence of *ctx.
3446          */
3447         ctx = counter->ctx;
3448         spin_lock_irqsave(&ctx->lock, flags);
3449         count = 1;
3450         /* Re-check state now we have the lock */
3451         if (counter->state < PERF_COUNTER_STATE_INACTIVE ||
3452             counter->ctx->is_active ||
3453             counter->tstamp_stopped < ctx->time)
3454                 count = 0;
3455         spin_unlock_irqrestore(&ctx->lock, flags);
3456         return count;
3457 }
3458
3459 static int perf_swcounter_match(struct perf_counter *counter,
3460                                 enum perf_type_id type,
3461                                 u32 event, struct pt_regs *regs)
3462 {
3463         if (!perf_swcounter_is_counting(counter))
3464                 return 0;
3465
3466         if (counter->attr.type != type)
3467                 return 0;
3468         if (counter->attr.config != event)
3469                 return 0;
3470
3471         if (regs) {
3472                 if (counter->attr.exclude_user && user_mode(regs))
3473                         return 0;
3474
3475                 if (counter->attr.exclude_kernel && !user_mode(regs))
3476                         return 0;
3477         }
3478
3479         return 1;
3480 }
3481
3482 static void perf_swcounter_add(struct perf_counter *counter, u64 nr,
3483                                int nmi, struct perf_sample_data *data)
3484 {
3485         int neg = atomic64_add_negative(nr, &counter->hw.count);
3486
3487         if (counter->hw.sample_period && !neg && data->regs)
3488                 perf_swcounter_overflow(counter, nmi, data);
3489 }
3490
3491 static void perf_swcounter_ctx_event(struct perf_counter_context *ctx,
3492                                      enum perf_type_id type,
3493                                      u32 event, u64 nr, int nmi,
3494                                      struct perf_sample_data *data)
3495 {
3496         struct perf_counter *counter;
3497
3498         if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
3499                 return;
3500
3501         rcu_read_lock();
3502         list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
3503                 if (perf_swcounter_match(counter, type, event, data->regs))
3504                         perf_swcounter_add(counter, nr, nmi, data);
3505         }
3506         rcu_read_unlock();
3507 }
3508
3509 static int *perf_swcounter_recursion_context(struct perf_cpu_context *cpuctx)
3510 {
3511         if (in_nmi())
3512                 return &cpuctx->recursion[3];
3513
3514         if (in_irq())
3515                 return &cpuctx->recursion[2];
3516
3517         if (in_softirq())
3518                 return &cpuctx->recursion[1];
3519
3520         return &cpuctx->recursion[0];
3521 }
3522
3523 static void do_perf_swcounter_event(enum perf_type_id type, u32 event,
3524                                     u64 nr, int nmi,
3525                                     struct perf_sample_data *data)
3526 {
3527         struct perf_cpu_context *cpuctx = &get_cpu_var(perf_cpu_context);
3528         int *recursion = perf_swcounter_recursion_context(cpuctx);
3529         struct perf_counter_context *ctx;
3530
3531         if (*recursion)
3532                 goto out;
3533
3534         (*recursion)++;
3535         barrier();
3536
3537         perf_swcounter_ctx_event(&cpuctx->ctx, type, event,
3538                                  nr, nmi, data);
3539         rcu_read_lock();
3540         /*
3541          * doesn't really matter which of the child contexts the
3542          * events ends up in.
3543          */
3544         ctx = rcu_dereference(current->perf_counter_ctxp);
3545         if (ctx)
3546                 perf_swcounter_ctx_event(ctx, type, event, nr, nmi, data);
3547         rcu_read_unlock();
3548
3549         barrier();
3550         (*recursion)--;
3551
3552 out:
3553         put_cpu_var(perf_cpu_context);
3554 }
3555
3556 void __perf_swcounter_event(u32 event, u64 nr, int nmi,
3557                             struct pt_regs *regs, u64 addr)
3558 {
3559         struct perf_sample_data data = {
3560                 .regs = regs,
3561                 .addr = addr,
3562         };
3563
3564         do_perf_swcounter_event(PERF_TYPE_SOFTWARE, event, nr, nmi, &data);
3565 }
3566
3567 static void perf_swcounter_read(struct perf_counter *counter)
3568 {
3569         perf_swcounter_update(counter);
3570 }
3571
3572 static int perf_swcounter_enable(struct perf_counter *counter)
3573 {
3574         perf_swcounter_set_period(counter);
3575         return 0;
3576 }
3577
3578 static void perf_swcounter_disable(struct perf_counter *counter)
3579 {
3580         perf_swcounter_update(counter);
3581 }
3582
3583 static const struct pmu perf_ops_generic = {
3584         .enable         = perf_swcounter_enable,
3585         .disable        = perf_swcounter_disable,
3586         .read           = perf_swcounter_read,
3587 };
3588
3589 /*
3590  * Software counter: cpu wall time clock
3591  */
3592
3593 static void cpu_clock_perf_counter_update(struct perf_counter *counter)
3594 {
3595         int cpu = raw_smp_processor_id();
3596         s64 prev;
3597         u64 now;
3598
3599         now = cpu_clock(cpu);
3600         prev = atomic64_read(&counter->hw.prev_count);
3601         atomic64_set(&counter->hw.prev_count, now);
3602         atomic64_add(now - prev, &counter->count);
3603 }
3604
3605 static int cpu_clock_perf_counter_enable(struct perf_counter *counter)
3606 {
3607         struct hw_perf_counter *hwc = &counter->hw;
3608         int cpu = raw_smp_processor_id();
3609
3610         atomic64_set(&hwc->prev_count, cpu_clock(cpu));
3611         hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3612         hwc->hrtimer.function = perf_swcounter_hrtimer;
3613         if (hwc->sample_period) {
3614                 u64 period = max_t(u64, 10000, hwc->sample_period);
3615                 __hrtimer_start_range_ns(&hwc->hrtimer,
3616                                 ns_to_ktime(period), 0,
3617                                 HRTIMER_MODE_REL, 0);
3618         }
3619
3620         return 0;
3621 }
3622
3623 static void cpu_clock_perf_counter_disable(struct perf_counter *counter)
3624 {
3625         if (counter->hw.sample_period)
3626                 hrtimer_cancel(&counter->hw.hrtimer);
3627         cpu_clock_perf_counter_update(counter);
3628 }
3629
3630 static void cpu_clock_perf_counter_read(struct perf_counter *counter)
3631 {
3632         cpu_clock_perf_counter_update(counter);
3633 }
3634
3635 static const struct pmu perf_ops_cpu_clock = {
3636         .enable         = cpu_clock_perf_counter_enable,
3637         .disable        = cpu_clock_perf_counter_disable,
3638         .read           = cpu_clock_perf_counter_read,
3639 };
3640
3641 /*
3642  * Software counter: task time clock
3643  */
3644
3645 static void task_clock_perf_counter_update(struct perf_counter *counter, u64 now)
3646 {
3647         u64 prev;
3648         s64 delta;
3649
3650         prev = atomic64_xchg(&counter->hw.prev_count, now);
3651         delta = now - prev;
3652         atomic64_add(delta, &counter->count);
3653 }
3654
3655 static int task_clock_perf_counter_enable(struct perf_counter *counter)
3656 {
3657         struct hw_perf_counter *hwc = &counter->hw;
3658         u64 now;
3659
3660         now = counter->ctx->time;
3661
3662         atomic64_set(&hwc->prev_count, now);
3663         hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3664         hwc->hrtimer.function = perf_swcounter_hrtimer;
3665         if (hwc->sample_period) {
3666                 u64 period = max_t(u64, 10000, hwc->sample_period);
3667                 __hrtimer_start_range_ns(&hwc->hrtimer,
3668                                 ns_to_ktime(period), 0,
3669                                 HRTIMER_MODE_REL, 0);
3670         }
3671
3672         return 0;
3673 }
3674
3675 static void task_clock_perf_counter_disable(struct perf_counter *counter)
3676 {
3677         if (counter->hw.sample_period)
3678                 hrtimer_cancel(&counter->hw.hrtimer);
3679         task_clock_perf_counter_update(counter, counter->ctx->time);
3680
3681 }
3682
3683 static void task_clock_perf_counter_read(struct perf_counter *counter)
3684 {
3685         u64 time;
3686
3687         if (!in_nmi()) {
3688                 update_context_time(counter->ctx);
3689                 time = counter->ctx->time;
3690         } else {
3691                 u64 now = perf_clock();
3692                 u64 delta = now - counter->ctx->timestamp;
3693                 time = counter->ctx->time + delta;
3694         }
3695
3696         task_clock_perf_counter_update(counter, time);
3697 }
3698
3699 static const struct pmu perf_ops_task_clock = {
3700         .enable         = task_clock_perf_counter_enable,
3701         .disable        = task_clock_perf_counter_disable,
3702         .read           = task_clock_perf_counter_read,
3703 };
3704
3705 #ifdef CONFIG_EVENT_PROFILE
3706 void perf_tpcounter_event(int event_id)
3707 {
3708         struct perf_sample_data data = {
3709                 .regs = get_irq_regs(),
3710                 .addr = 0,
3711         };
3712
3713         if (!data.regs)
3714                 data.regs = task_pt_regs(current);
3715
3716         do_perf_swcounter_event(PERF_TYPE_TRACEPOINT, event_id, 1, 1, &data);
3717 }
3718 EXPORT_SYMBOL_GPL(perf_tpcounter_event);
3719
3720 extern int ftrace_profile_enable(int);
3721 extern void ftrace_profile_disable(int);
3722
3723 static void tp_perf_counter_destroy(struct perf_counter *counter)
3724 {
3725         ftrace_profile_disable(counter->attr.config);
3726 }
3727
3728 static const struct pmu *tp_perf_counter_init(struct perf_counter *counter)
3729 {
3730         if (ftrace_profile_enable(counter->attr.config))
3731                 return NULL;
3732
3733         counter->destroy = tp_perf_counter_destroy;
3734
3735         return &perf_ops_generic;
3736 }
3737 #else
3738 static const struct pmu *tp_perf_counter_init(struct perf_counter *counter)
3739 {
3740         return NULL;
3741 }
3742 #endif
3743
3744 atomic_t perf_swcounter_enabled[PERF_COUNT_SW_MAX];
3745
3746 static void sw_perf_counter_destroy(struct perf_counter *counter)
3747 {
3748         u64 event = counter->attr.config;
3749
3750         WARN_ON(counter->parent);
3751
3752         atomic_dec(&perf_swcounter_enabled[event]);
3753 }
3754
3755 static const struct pmu *sw_perf_counter_init(struct perf_counter *counter)
3756 {
3757         const struct pmu *pmu = NULL;
3758         u64 event = counter->attr.config;
3759
3760         /*
3761          * Software counters (currently) can't in general distinguish
3762          * between user, kernel and hypervisor events.
3763          * However, context switches and cpu migrations are considered
3764          * to be kernel events, and page faults are never hypervisor
3765          * events.
3766          */
3767         switch (event) {
3768         case PERF_COUNT_SW_CPU_CLOCK:
3769                 pmu = &perf_ops_cpu_clock;
3770
3771                 break;
3772         case PERF_COUNT_SW_TASK_CLOCK:
3773                 /*
3774                  * If the user instantiates this as a per-cpu counter,
3775                  * use the cpu_clock counter instead.
3776                  */
3777                 if (counter->ctx->task)
3778                         pmu = &perf_ops_task_clock;
3779                 else
3780                         pmu = &perf_ops_cpu_clock;
3781
3782                 break;
3783         case PERF_COUNT_SW_PAGE_FAULTS:
3784         case PERF_COUNT_SW_PAGE_FAULTS_MIN:
3785         case PERF_COUNT_SW_PAGE_FAULTS_MAJ:
3786         case PERF_COUNT_SW_CONTEXT_SWITCHES:
3787         case PERF_COUNT_SW_CPU_MIGRATIONS:
3788                 if (!counter->parent) {
3789                         atomic_inc(&perf_swcounter_enabled[event]);
3790                         counter->destroy = sw_perf_counter_destroy;
3791                 }
3792                 pmu = &perf_ops_generic;
3793                 break;
3794         }
3795
3796         return pmu;
3797 }
3798
3799 /*
3800  * Allocate and initialize a counter structure
3801  */
3802 static struct perf_counter *
3803 perf_counter_alloc(struct perf_counter_attr *attr,
3804                    int cpu,
3805                    struct perf_counter_context *ctx,
3806                    struct perf_counter *group_leader,
3807                    struct perf_counter *parent_counter,
3808                    gfp_t gfpflags)
3809 {
3810         const struct pmu *pmu;
3811         struct perf_counter *counter;
3812         struct hw_perf_counter *hwc;
3813         long err;
3814
3815         counter = kzalloc(sizeof(*counter), gfpflags);
3816         if (!counter)
3817                 return ERR_PTR(-ENOMEM);
3818
3819         /*
3820          * Single counters are their own group leaders, with an
3821          * empty sibling list:
3822          */
3823         if (!group_leader)
3824                 group_leader = counter;
3825
3826         mutex_init(&counter->child_mutex);
3827         INIT_LIST_HEAD(&counter->child_list);
3828
3829         INIT_LIST_HEAD(&counter->list_entry);
3830         INIT_LIST_HEAD(&counter->event_entry);
3831         INIT_LIST_HEAD(&counter->sibling_list);
3832         init_waitqueue_head(&counter->waitq);
3833
3834         mutex_init(&counter->mmap_mutex);
3835
3836         counter->cpu            = cpu;
3837         counter->attr           = *attr;
3838         counter->group_leader   = group_leader;
3839         counter->pmu            = NULL;
3840         counter->ctx            = ctx;
3841         counter->oncpu          = -1;
3842
3843         counter->parent         = parent_counter;
3844
3845         counter->ns             = get_pid_ns(current->nsproxy->pid_ns);
3846         counter->id             = atomic64_inc_return(&perf_counter_id);
3847
3848         counter->state          = PERF_COUNTER_STATE_INACTIVE;
3849
3850         if (attr->disabled)
3851                 counter->state = PERF_COUNTER_STATE_OFF;
3852
3853         pmu = NULL;
3854
3855         hwc = &counter->hw;
3856         hwc->sample_period = attr->sample_period;
3857         if (attr->freq && attr->sample_freq)
3858                 hwc->sample_period = 1;
3859
3860         atomic64_set(&hwc->period_left, hwc->sample_period);
3861
3862         /*
3863          * we currently do not support PERF_SAMPLE_GROUP on inherited counters
3864          */
3865         if (attr->inherit && (attr->sample_type & PERF_SAMPLE_GROUP))
3866                 goto done;
3867
3868         switch (attr->type) {
3869         case PERF_TYPE_RAW:
3870         case PERF_TYPE_HARDWARE:
3871         case PERF_TYPE_HW_CACHE:
3872                 pmu = hw_perf_counter_init(counter);
3873                 break;
3874
3875         case PERF_TYPE_SOFTWARE:
3876                 pmu = sw_perf_counter_init(counter);
3877                 break;
3878
3879         case PERF_TYPE_TRACEPOINT:
3880                 pmu = tp_perf_counter_init(counter);
3881                 break;
3882
3883         default:
3884                 break;
3885         }
3886 done:
3887         err = 0;
3888         if (!pmu)
3889                 err = -EINVAL;
3890         else if (IS_ERR(pmu))
3891                 err = PTR_ERR(pmu);
3892
3893         if (err) {
3894                 if (counter->ns)
3895                         put_pid_ns(counter->ns);
3896                 kfree(counter);
3897                 return ERR_PTR(err);
3898         }
3899
3900         counter->pmu = pmu;
3901
3902         if (!counter->parent) {
3903                 atomic_inc(&nr_counters);
3904                 if (counter->attr.mmap)
3905                         atomic_inc(&nr_mmap_counters);
3906                 if (counter->attr.comm)
3907                         atomic_inc(&nr_comm_counters);
3908                 if (counter->attr.task)
3909                         atomic_inc(&nr_task_counters);
3910         }
3911
3912         return counter;
3913 }
3914
3915 static int perf_copy_attr(struct perf_counter_attr __user *uattr,
3916                           struct perf_counter_attr *attr)
3917 {
3918         int ret;
3919         u32 size;
3920
3921         if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
3922                 return -EFAULT;
3923
3924         /*
3925          * zero the full structure, so that a short copy will be nice.
3926          */
3927         memset(attr, 0, sizeof(*attr));
3928
3929         ret = get_user(size, &uattr->size);
3930         if (ret)
3931                 return ret;
3932
3933         if (size > PAGE_SIZE)   /* silly large */
3934                 goto err_size;
3935
3936         if (!size)              /* abi compat */
3937                 size = PERF_ATTR_SIZE_VER0;
3938
3939         if (size < PERF_ATTR_SIZE_VER0)
3940                 goto err_size;
3941
3942         /*
3943          * If we're handed a bigger struct than we know of,
3944          * ensure all the unknown bits are 0.
3945          */
3946         if (size > sizeof(*attr)) {
3947                 unsigned long val;
3948                 unsigned long __user *addr;
3949                 unsigned long __user *end;
3950
3951                 addr = PTR_ALIGN((void __user *)uattr + sizeof(*attr),
3952                                 sizeof(unsigned long));
3953                 end  = PTR_ALIGN((void __user *)uattr + size,
3954                                 sizeof(unsigned long));
3955
3956                 for (; addr < end; addr += sizeof(unsigned long)) {
3957                         ret = get_user(val, addr);
3958                         if (ret)
3959                                 return ret;
3960                         if (val)
3961                                 goto err_size;
3962                 }
3963         }
3964
3965         ret = copy_from_user(attr, uattr, size);
3966         if (ret)
3967                 return -EFAULT;
3968
3969         /*
3970          * If the type exists, the corresponding creation will verify
3971          * the attr->config.
3972          */
3973         if (attr->type >= PERF_TYPE_MAX)
3974                 return -EINVAL;
3975
3976         if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
3977                 return -EINVAL;
3978
3979         if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
3980                 return -EINVAL;
3981
3982         if (attr->read_format & ~(PERF_FORMAT_MAX-1))
3983                 return -EINVAL;
3984
3985 out:
3986         return ret;
3987
3988 err_size:
3989         put_user(sizeof(*attr), &uattr->size);
3990         ret = -E2BIG;
3991         goto out;
3992 }
3993
3994 /**
3995  * sys_perf_counter_open - open a performance counter, associate it to a task/cpu
3996  *
3997  * @attr_uptr:  event type attributes for monitoring/sampling
3998  * @pid:                target pid
3999  * @cpu:                target cpu
4000  * @group_fd:           group leader counter fd
4001  */
4002 SYSCALL_DEFINE5(perf_counter_open,
4003                 struct perf_counter_attr __user *, attr_uptr,
4004                 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
4005 {
4006         struct perf_counter *counter, *group_leader;
4007         struct perf_counter_attr attr;
4008         struct perf_counter_context *ctx;
4009         struct file *counter_file = NULL;
4010         struct file *group_file = NULL;
4011         int fput_needed = 0;
4012         int fput_needed2 = 0;
4013         int ret;
4014
4015         /* for future expandability... */
4016         if (flags)
4017                 return -EINVAL;
4018
4019         ret = perf_copy_attr(attr_uptr, &attr);
4020         if (ret)
4021                 return ret;
4022
4023         if (!attr.exclude_kernel) {
4024                 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
4025                         return -EACCES;
4026         }
4027
4028         if (attr.freq) {
4029                 if (attr.sample_freq > sysctl_perf_counter_sample_rate)
4030                         return -EINVAL;
4031         }
4032
4033         /*
4034          * Get the target context (task or percpu):
4035          */
4036         ctx = find_get_context(pid, cpu);
4037         if (IS_ERR(ctx))
4038                 return PTR_ERR(ctx);
4039
4040         /*
4041          * Look up the group leader (we will attach this counter to it):
4042          */
4043         group_leader = NULL;
4044         if (group_fd != -1) {
4045                 ret = -EINVAL;
4046                 group_file = fget_light(group_fd, &fput_needed);
4047                 if (!group_file)
4048                         goto err_put_context;
4049                 if (group_file->f_op != &perf_fops)
4050                         goto err_put_context;
4051
4052                 group_leader = group_file->private_data;
4053                 /*
4054                  * Do not allow a recursive hierarchy (this new sibling
4055                  * becoming part of another group-sibling):
4056                  */
4057                 if (group_leader->group_leader != group_leader)
4058                         goto err_put_context;
4059                 /*
4060                  * Do not allow to attach to a group in a different
4061                  * task or CPU context:
4062                  */
4063                 if (group_leader->ctx != ctx)
4064                         goto err_put_context;
4065                 /*
4066                  * Only a group leader can be exclusive or pinned
4067                  */
4068                 if (attr.exclusive || attr.pinned)
4069                         goto err_put_context;
4070         }
4071
4072         counter = perf_counter_alloc(&attr, cpu, ctx, group_leader,
4073                                      NULL, GFP_KERNEL);
4074         ret = PTR_ERR(counter);
4075         if (IS_ERR(counter))
4076                 goto err_put_context;
4077
4078         ret = anon_inode_getfd("[perf_counter]", &perf_fops, counter, 0);
4079         if (ret < 0)
4080                 goto err_free_put_context;
4081
4082         counter_file = fget_light(ret, &fput_needed2);
4083         if (!counter_file)
4084                 goto err_free_put_context;
4085
4086         counter->filp = counter_file;
4087         WARN_ON_ONCE(ctx->parent_ctx);
4088         mutex_lock(&ctx->mutex);
4089         perf_install_in_context(ctx, counter, cpu);
4090         ++ctx->generation;
4091         mutex_unlock(&ctx->mutex);
4092
4093         counter->owner = current;
4094         get_task_struct(current);
4095         mutex_lock(&current->perf_counter_mutex);
4096         list_add_tail(&counter->owner_entry, &current->perf_counter_list);
4097         mutex_unlock(&current->perf_counter_mutex);
4098
4099         fput_light(counter_file, fput_needed2);
4100
4101 out_fput:
4102         fput_light(group_file, fput_needed);
4103
4104         return ret;
4105
4106 err_free_put_context:
4107         kfree(counter);
4108
4109 err_put_context:
4110         put_ctx(ctx);
4111
4112         goto out_fput;
4113 }
4114
4115 /*
4116  * inherit a counter from parent task to child task:
4117  */
4118 static struct perf_counter *
4119 inherit_counter(struct perf_counter *parent_counter,
4120               struct task_struct *parent,
4121               struct perf_counter_context *parent_ctx,
4122               struct task_struct *child,
4123               struct perf_counter *group_leader,
4124               struct perf_counter_context *child_ctx)
4125 {
4126         struct perf_counter *child_counter;
4127
4128         /*
4129          * Instead of creating recursive hierarchies of counters,
4130          * we link inherited counters back to the original parent,
4131          * which has a filp for sure, which we use as the reference
4132          * count:
4133          */
4134         if (parent_counter->parent)
4135                 parent_counter = parent_counter->parent;
4136
4137         child_counter = perf_counter_alloc(&parent_counter->attr,
4138                                            parent_counter->cpu, child_ctx,
4139                                            group_leader, parent_counter,
4140                                            GFP_KERNEL);
4141         if (IS_ERR(child_counter))
4142                 return child_counter;
4143         get_ctx(child_ctx);
4144
4145         /*
4146          * Make the child state follow the state of the parent counter,
4147          * not its attr.disabled bit.  We hold the parent's mutex,
4148          * so we won't race with perf_counter_{en, dis}able_family.
4149          */
4150         if (parent_counter->state >= PERF_COUNTER_STATE_INACTIVE)
4151                 child_counter->state = PERF_COUNTER_STATE_INACTIVE;
4152         else
4153                 child_counter->state = PERF_COUNTER_STATE_OFF;
4154
4155         if (parent_counter->attr.freq)
4156                 child_counter->hw.sample_period = parent_counter->hw.sample_period;
4157
4158         /*
4159          * Link it up in the child's context:
4160          */
4161         add_counter_to_ctx(child_counter, child_ctx);
4162
4163         /*
4164          * Get a reference to the parent filp - we will fput it
4165          * when the child counter exits. This is safe to do because
4166          * we are in the parent and we know that the filp still
4167          * exists and has a nonzero count:
4168          */
4169         atomic_long_inc(&parent_counter->filp->f_count);
4170
4171         /*
4172          * Link this into the parent counter's child list
4173          */
4174         WARN_ON_ONCE(parent_counter->ctx->parent_ctx);
4175         mutex_lock(&parent_counter->child_mutex);
4176         list_add_tail(&child_counter->child_list, &parent_counter->child_list);
4177         mutex_unlock(&parent_counter->child_mutex);
4178
4179         return child_counter;
4180 }
4181
4182 static int inherit_group(struct perf_counter *parent_counter,
4183               struct task_struct *parent,
4184               struct perf_counter_context *parent_ctx,
4185               struct task_struct *child,
4186               struct perf_counter_context *child_ctx)
4187 {
4188         struct perf_counter *leader;
4189         struct perf_counter *sub;
4190         struct perf_counter *child_ctr;
4191
4192         leader = inherit_counter(parent_counter, parent, parent_ctx,
4193                                  child, NULL, child_ctx);
4194         if (IS_ERR(leader))
4195                 return PTR_ERR(leader);
4196         list_for_each_entry(sub, &parent_counter->sibling_list, list_entry) {
4197                 child_ctr = inherit_counter(sub, parent, parent_ctx,
4198                                             child, leader, child_ctx);
4199                 if (IS_ERR(child_ctr))
4200                         return PTR_ERR(child_ctr);
4201         }
4202         return 0;
4203 }
4204
4205 static void sync_child_counter(struct perf_counter *child_counter,
4206                                struct task_struct *child)
4207 {
4208         struct perf_counter *parent_counter = child_counter->parent;
4209         u64 child_val;
4210
4211         if (child_counter->attr.inherit_stat)
4212                 perf_counter_read_event(child_counter, child);
4213
4214         child_val = atomic64_read(&child_counter->count);
4215
4216         /*
4217          * Add back the child's count to the parent's count:
4218          */
4219         atomic64_add(child_val, &parent_counter->count);
4220         atomic64_add(child_counter->total_time_enabled,
4221                      &parent_counter->child_total_time_enabled);
4222         atomic64_add(child_counter->total_time_running,
4223                      &parent_counter->child_total_time_running);
4224
4225         /*
4226          * Remove this counter from the parent's list
4227          */
4228         WARN_ON_ONCE(parent_counter->ctx->parent_ctx);
4229         mutex_lock(&parent_counter->child_mutex);
4230         list_del_init(&child_counter->child_list);
4231         mutex_unlock(&parent_counter->child_mutex);
4232
4233         /*
4234          * Release the parent counter, if this was the last
4235          * reference to it.
4236          */
4237         fput(parent_counter->filp);
4238 }
4239
4240 static void
4241 __perf_counter_exit_task(struct perf_counter *child_counter,
4242                          struct perf_counter_context *child_ctx,
4243                          struct task_struct *child)
4244 {
4245         struct perf_counter *parent_counter;
4246
4247         update_counter_times(child_counter);
4248         perf_counter_remove_from_context(child_counter);
4249
4250         parent_counter = child_counter->parent;
4251         /*
4252          * It can happen that parent exits first, and has counters
4253          * that are still around due to the child reference. These
4254          * counters need to be zapped - but otherwise linger.
4255          */
4256         if (parent_counter) {
4257                 sync_child_counter(child_counter, child);
4258                 free_counter(child_counter);
4259         }
4260 }
4261
4262 /*
4263  * When a child task exits, feed back counter values to parent counters.
4264  */
4265 void perf_counter_exit_task(struct task_struct *child)
4266 {
4267         struct perf_counter *child_counter, *tmp;
4268         struct perf_counter_context *child_ctx;
4269         unsigned long flags;
4270
4271         if (likely(!child->perf_counter_ctxp)) {
4272                 perf_counter_task(child, 0);
4273                 return;
4274         }
4275
4276         local_irq_save(flags);
4277         /*
4278          * We can't reschedule here because interrupts are disabled,
4279          * and either child is current or it is a task that can't be
4280          * scheduled, so we are now safe from rescheduling changing
4281          * our context.
4282          */
4283         child_ctx = child->perf_counter_ctxp;
4284         __perf_counter_task_sched_out(child_ctx);
4285
4286         /*
4287          * Take the context lock here so that if find_get_context is
4288          * reading child->perf_counter_ctxp, we wait until it has
4289          * incremented the context's refcount before we do put_ctx below.
4290          */
4291         spin_lock(&child_ctx->lock);
4292         /*
4293          * If this context is a clone; unclone it so it can't get
4294          * swapped to another process while we're removing all
4295          * the counters from it.
4296          */
4297         unclone_ctx(child_ctx);
4298         spin_unlock_irqrestore(&child_ctx->lock, flags);
4299
4300         /*
4301          * Report the task dead after unscheduling the counters so that we
4302          * won't get any samples after PERF_EVENT_EXIT. We can however still
4303          * get a few PERF_EVENT_READ events.
4304          */
4305         perf_counter_task(child, 0);
4306
4307         child->perf_counter_ctxp = NULL;
4308
4309         /*
4310          * We can recurse on the same lock type through:
4311          *
4312          *   __perf_counter_exit_task()
4313          *     sync_child_counter()
4314          *       fput(parent_counter->filp)
4315          *         perf_release()
4316          *           mutex_lock(&ctx->mutex)
4317          *
4318          * But since its the parent context it won't be the same instance.
4319          */
4320         mutex_lock_nested(&child_ctx->mutex, SINGLE_DEPTH_NESTING);
4321
4322 again:
4323         list_for_each_entry_safe(child_counter, tmp, &child_ctx->counter_list,
4324                                  list_entry)
4325                 __perf_counter_exit_task(child_counter, child_ctx, child);
4326
4327         /*
4328          * If the last counter was a group counter, it will have appended all
4329          * its siblings to the list, but we obtained 'tmp' before that which
4330          * will still point to the list head terminating the iteration.
4331          */
4332         if (!list_empty(&child_ctx->counter_list))
4333                 goto again;
4334
4335         mutex_unlock(&child_ctx->mutex);
4336
4337         put_ctx(child_ctx);
4338 }
4339
4340 /*
4341  * free an unexposed, unused context as created by inheritance by
4342  * init_task below, used by fork() in case of fail.
4343  */
4344 void perf_counter_free_task(struct task_struct *task)
4345 {
4346         struct perf_counter_context *ctx = task->perf_counter_ctxp;
4347         struct perf_counter *counter, *tmp;
4348
4349         if (!ctx)
4350                 return;
4351
4352         mutex_lock(&ctx->mutex);
4353 again:
4354         list_for_each_entry_safe(counter, tmp, &ctx->counter_list, list_entry) {
4355                 struct perf_counter *parent = counter->parent;
4356
4357                 if (WARN_ON_ONCE(!parent))
4358                         continue;
4359
4360                 mutex_lock(&parent->child_mutex);
4361                 list_del_init(&counter->child_list);
4362                 mutex_unlock(&parent->child_mutex);
4363
4364                 fput(parent->filp);
4365
4366                 list_del_counter(counter, ctx);
4367                 free_counter(counter);
4368         }
4369
4370         if (!list_empty(&ctx->counter_list))
4371                 goto again;
4372
4373         mutex_unlock(&ctx->mutex);
4374
4375         put_ctx(ctx);
4376 }
4377
4378 /*
4379  * Initialize the perf_counter context in task_struct
4380  */
4381 int perf_counter_init_task(struct task_struct *child)
4382 {
4383         struct perf_counter_context *child_ctx, *parent_ctx;
4384         struct perf_counter_context *cloned_ctx;
4385         struct perf_counter *counter;
4386         struct task_struct *parent = current;
4387         int inherited_all = 1;
4388         int ret = 0;
4389
4390         child->perf_counter_ctxp = NULL;
4391
4392         mutex_init(&child->perf_counter_mutex);
4393         INIT_LIST_HEAD(&child->perf_counter_list);
4394
4395         if (likely(!parent->perf_counter_ctxp))
4396                 return 0;
4397
4398         /*
4399          * This is executed from the parent task context, so inherit
4400          * counters that have been marked for cloning.
4401          * First allocate and initialize a context for the child.
4402          */
4403
4404         child_ctx = kmalloc(sizeof(struct perf_counter_context), GFP_KERNEL);
4405         if (!child_ctx)
4406                 return -ENOMEM;
4407
4408         __perf_counter_init_context(child_ctx, child);
4409         child->perf_counter_ctxp = child_ctx;
4410         get_task_struct(child);
4411
4412         /*
4413          * If the parent's context is a clone, pin it so it won't get
4414          * swapped under us.
4415          */
4416         parent_ctx = perf_pin_task_context(parent);
4417
4418         /*
4419          * No need to check if parent_ctx != NULL here; since we saw
4420          * it non-NULL earlier, the only reason for it to become NULL
4421          * is if we exit, and since we're currently in the middle of
4422          * a fork we can't be exiting at the same time.
4423          */
4424
4425         /*
4426          * Lock the parent list. No need to lock the child - not PID
4427          * hashed yet and not running, so nobody can access it.
4428          */
4429         mutex_lock(&parent_ctx->mutex);
4430
4431         /*
4432          * We dont have to disable NMIs - we are only looking at
4433          * the list, not manipulating it:
4434          */
4435         list_for_each_entry_rcu(counter, &parent_ctx->event_list, event_entry) {
4436                 if (counter != counter->group_leader)
4437                         continue;
4438
4439                 if (!counter->attr.inherit) {
4440                         inherited_all = 0;
4441                         continue;
4442                 }
4443
4444                 ret = inherit_group(counter, parent, parent_ctx,
4445                                              child, child_ctx);
4446                 if (ret) {
4447                         inherited_all = 0;
4448                         break;
4449                 }
4450         }
4451
4452         if (inherited_all) {
4453                 /*
4454                  * Mark the child context as a clone of the parent
4455                  * context, or of whatever the parent is a clone of.
4456                  * Note that if the parent is a clone, it could get
4457                  * uncloned at any point, but that doesn't matter
4458                  * because the list of counters and the generation
4459                  * count can't have changed since we took the mutex.
4460                  */
4461                 cloned_ctx = rcu_dereference(parent_ctx->parent_ctx);
4462                 if (cloned_ctx) {
4463                         child_ctx->parent_ctx = cloned_ctx;
4464                         child_ctx->parent_gen = parent_ctx->parent_gen;
4465                 } else {
4466                         child_ctx->parent_ctx = parent_ctx;
4467                         child_ctx->parent_gen = parent_ctx->generation;
4468                 }
4469                 get_ctx(child_ctx->parent_ctx);
4470         }
4471
4472         mutex_unlock(&parent_ctx->mutex);
4473
4474         perf_unpin_context(parent_ctx);
4475
4476         return ret;
4477 }
4478
4479 static void __cpuinit perf_counter_init_cpu(int cpu)
4480 {
4481         struct perf_cpu_context *cpuctx;
4482
4483         cpuctx = &per_cpu(perf_cpu_context, cpu);
4484         __perf_counter_init_context(&cpuctx->ctx, NULL);
4485
4486         spin_lock(&perf_resource_lock);
4487         cpuctx->max_pertask = perf_max_counters - perf_reserved_percpu;
4488         spin_unlock(&perf_resource_lock);
4489
4490         hw_perf_counter_setup(cpu);
4491 }
4492
4493 #ifdef CONFIG_HOTPLUG_CPU
4494 static void __perf_counter_exit_cpu(void *info)
4495 {
4496         struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
4497         struct perf_counter_context *ctx = &cpuctx->ctx;
4498         struct perf_counter *counter, *tmp;
4499
4500         list_for_each_entry_safe(counter, tmp, &ctx->counter_list, list_entry)
4501                 __perf_counter_remove_from_context(counter);
4502 }
4503 static void perf_counter_exit_cpu(int cpu)
4504 {
4505         struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
4506         struct perf_counter_context *ctx = &cpuctx->ctx;
4507
4508         mutex_lock(&ctx->mutex);
4509         smp_call_function_single(cpu, __perf_counter_exit_cpu, NULL, 1);
4510         mutex_unlock(&ctx->mutex);
4511 }
4512 #else
4513 static inline void perf_counter_exit_cpu(int cpu) { }
4514 #endif
4515
4516 static int __cpuinit
4517 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
4518 {
4519         unsigned int cpu = (long)hcpu;
4520
4521         switch (action) {
4522
4523         case CPU_UP_PREPARE:
4524         case CPU_UP_PREPARE_FROZEN:
4525                 perf_counter_init_cpu(cpu);
4526                 break;
4527
4528         case CPU_DOWN_PREPARE:
4529         case CPU_DOWN_PREPARE_FROZEN:
4530                 perf_counter_exit_cpu(cpu);
4531                 break;
4532
4533         default:
4534                 break;
4535         }
4536
4537         return NOTIFY_OK;
4538 }
4539
4540 /*
4541  * This has to have a higher priority than migration_notifier in sched.c.
4542  */
4543 static struct notifier_block __cpuinitdata perf_cpu_nb = {
4544         .notifier_call          = perf_cpu_notify,
4545         .priority               = 20,
4546 };
4547
4548 void __init perf_counter_init(void)
4549 {
4550         perf_cpu_notify(&perf_cpu_nb, (unsigned long)CPU_UP_PREPARE,
4551                         (void *)(long)smp_processor_id());
4552         register_cpu_notifier(&perf_cpu_nb);
4553 }
4554
4555 static ssize_t perf_show_reserve_percpu(struct sysdev_class *class, char *buf)
4556 {
4557         return sprintf(buf, "%d\n", perf_reserved_percpu);
4558 }
4559
4560 static ssize_t
4561 perf_set_reserve_percpu(struct sysdev_class *class,
4562                         const char *buf,
4563                         size_t count)
4564 {
4565         struct perf_cpu_context *cpuctx;
4566         unsigned long val;
4567         int err, cpu, mpt;
4568
4569         err = strict_strtoul(buf, 10, &val);
4570         if (err)
4571                 return err;
4572         if (val > perf_max_counters)
4573                 return -EINVAL;
4574
4575         spin_lock(&perf_resource_lock);
4576         perf_reserved_percpu = val;
4577         for_each_online_cpu(cpu) {
4578                 cpuctx = &per_cpu(perf_cpu_context, cpu);
4579                 spin_lock_irq(&cpuctx->ctx.lock);
4580                 mpt = min(perf_max_counters - cpuctx->ctx.nr_counters,
4581                           perf_max_counters - perf_reserved_percpu);
4582                 cpuctx->max_pertask = mpt;
4583                 spin_unlock_irq(&cpuctx->ctx.lock);
4584         }
4585         spin_unlock(&perf_resource_lock);
4586
4587         return count;
4588 }
4589
4590 static ssize_t perf_show_overcommit(struct sysdev_class *class, char *buf)
4591 {
4592         return sprintf(buf, "%d\n", perf_overcommit);
4593 }
4594
4595 static ssize_t
4596 perf_set_overcommit(struct sysdev_class *class, const char *buf, size_t count)
4597 {
4598         unsigned long val;
4599         int err;
4600
4601         err = strict_strtoul(buf, 10, &val);
4602         if (err)
4603                 return err;
4604         if (val > 1)
4605                 return -EINVAL;
4606
4607         spin_lock(&perf_resource_lock);
4608         perf_overcommit = val;
4609         spin_unlock(&perf_resource_lock);
4610
4611         return count;
4612 }
4613
4614 static SYSDEV_CLASS_ATTR(
4615                                 reserve_percpu,
4616                                 0644,
4617                                 perf_show_reserve_percpu,
4618                                 perf_set_reserve_percpu
4619                         );
4620
4621 static SYSDEV_CLASS_ATTR(
4622                                 overcommit,
4623                                 0644,
4624                                 perf_show_overcommit,
4625                                 perf_set_overcommit
4626                         );
4627
4628 static struct attribute *perfclass_attrs[] = {
4629         &attr_reserve_percpu.attr,
4630         &attr_overcommit.attr,
4631         NULL
4632 };
4633
4634 static struct attribute_group perfclass_attr_group = {
4635         .attrs                  = perfclass_attrs,
4636         .name                   = "perf_counters",
4637 };
4638
4639 static int __init perf_counter_sysfs_init(void)
4640 {
4641         return sysfs_create_group(&cpu_sysdev_class.kset.kobj,
4642                                   &perfclass_attr_group);
4643 }
4644 device_initcall(perf_counter_sysfs_init);