]> git.karo-electronics.de Git - karo-tx-linux.git/blob - kernel/perf_counter.c
perf_counter: optimize perf_counter_task_tick()
[karo-tx-linux.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/ptrace.h>
20 #include <linux/percpu.h>
21 #include <linux/vmstat.h>
22 #include <linux/hardirq.h>
23 #include <linux/rculist.h>
24 #include <linux/uaccess.h>
25 #include <linux/syscalls.h>
26 #include <linux/anon_inodes.h>
27 #include <linux/kernel_stat.h>
28 #include <linux/perf_counter.h>
29 #include <linux/dcache.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_tracking __read_mostly;
44 static atomic_t nr_munmap_tracking __read_mostly;
45 static atomic_t nr_comm_tracking __read_mostly;
46
47 int sysctl_perf_counter_priv __read_mostly; /* do we need to be privileged */
48 int sysctl_perf_counter_mlock __read_mostly = 128; /* 'free' kb per counter */
49
50 /*
51  * Lock for (sysadmin-configurable) counter reservations:
52  */
53 static DEFINE_SPINLOCK(perf_resource_lock);
54
55 /*
56  * Architecture provided APIs - weak aliases:
57  */
58 extern __weak const struct pmu *hw_perf_counter_init(struct perf_counter *counter)
59 {
60         return NULL;
61 }
62
63 u64 __weak hw_perf_save_disable(void)           { return 0; }
64 void __weak hw_perf_restore(u64 ctrl)           { barrier(); }
65 void __weak hw_perf_counter_setup(int cpu)      { barrier(); }
66 int __weak hw_perf_group_sched_in(struct perf_counter *group_leader,
67                struct perf_cpu_context *cpuctx,
68                struct perf_counter_context *ctx, int cpu)
69 {
70         return 0;
71 }
72
73 void __weak perf_counter_print_debug(void)      { }
74
75 static void
76 list_add_counter(struct perf_counter *counter, struct perf_counter_context *ctx)
77 {
78         struct perf_counter *group_leader = counter->group_leader;
79
80         /*
81          * Depending on whether it is a standalone or sibling counter,
82          * add it straight to the context's counter list, or to the group
83          * leader's sibling list:
84          */
85         if (counter->group_leader == counter)
86                 list_add_tail(&counter->list_entry, &ctx->counter_list);
87         else {
88                 list_add_tail(&counter->list_entry, &group_leader->sibling_list);
89                 group_leader->nr_siblings++;
90         }
91
92         list_add_rcu(&counter->event_entry, &ctx->event_list);
93 }
94
95 static void
96 list_del_counter(struct perf_counter *counter, struct perf_counter_context *ctx)
97 {
98         struct perf_counter *sibling, *tmp;
99
100         list_del_init(&counter->list_entry);
101         list_del_rcu(&counter->event_entry);
102
103         if (counter->group_leader != counter)
104                 counter->group_leader->nr_siblings--;
105
106         /*
107          * If this was a group counter with sibling counters then
108          * upgrade the siblings to singleton counters by adding them
109          * to the context list directly:
110          */
111         list_for_each_entry_safe(sibling, tmp,
112                                  &counter->sibling_list, list_entry) {
113
114                 list_move_tail(&sibling->list_entry, &ctx->counter_list);
115                 sibling->group_leader = sibling;
116         }
117 }
118
119 static void
120 counter_sched_out(struct perf_counter *counter,
121                   struct perf_cpu_context *cpuctx,
122                   struct perf_counter_context *ctx)
123 {
124         if (counter->state != PERF_COUNTER_STATE_ACTIVE)
125                 return;
126
127         counter->state = PERF_COUNTER_STATE_INACTIVE;
128         counter->tstamp_stopped = ctx->time;
129         counter->pmu->disable(counter);
130         counter->oncpu = -1;
131
132         if (!is_software_counter(counter))
133                 cpuctx->active_oncpu--;
134         ctx->nr_active--;
135         if (counter->hw_event.exclusive || !cpuctx->active_oncpu)
136                 cpuctx->exclusive = 0;
137 }
138
139 static void
140 group_sched_out(struct perf_counter *group_counter,
141                 struct perf_cpu_context *cpuctx,
142                 struct perf_counter_context *ctx)
143 {
144         struct perf_counter *counter;
145
146         if (group_counter->state != PERF_COUNTER_STATE_ACTIVE)
147                 return;
148
149         counter_sched_out(group_counter, cpuctx, ctx);
150
151         /*
152          * Schedule out siblings (if any):
153          */
154         list_for_each_entry(counter, &group_counter->sibling_list, list_entry)
155                 counter_sched_out(counter, cpuctx, ctx);
156
157         if (group_counter->hw_event.exclusive)
158                 cpuctx->exclusive = 0;
159 }
160
161 /*
162  * Cross CPU call to remove a performance counter
163  *
164  * We disable the counter on the hardware level first. After that we
165  * remove it from the context list.
166  */
167 static void __perf_counter_remove_from_context(void *info)
168 {
169         struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
170         struct perf_counter *counter = info;
171         struct perf_counter_context *ctx = counter->ctx;
172         unsigned long flags;
173         u64 perf_flags;
174
175         /*
176          * If this is a task context, we need to check whether it is
177          * the current task context of this cpu. If not it has been
178          * scheduled out before the smp call arrived.
179          */
180         if (ctx->task && cpuctx->task_ctx != ctx)
181                 return;
182
183         spin_lock_irqsave(&ctx->lock, flags);
184
185         counter_sched_out(counter, cpuctx, ctx);
186
187         counter->task = NULL;
188         ctx->nr_counters--;
189
190         /*
191          * Protect the list operation against NMI by disabling the
192          * counters on a global level. NOP for non NMI based counters.
193          */
194         perf_flags = hw_perf_save_disable();
195         list_del_counter(counter, ctx);
196         hw_perf_restore(perf_flags);
197
198         if (!ctx->task) {
199                 /*
200                  * Allow more per task counters with respect to the
201                  * reservation:
202                  */
203                 cpuctx->max_pertask =
204                         min(perf_max_counters - ctx->nr_counters,
205                             perf_max_counters - perf_reserved_percpu);
206         }
207
208         spin_unlock_irqrestore(&ctx->lock, flags);
209 }
210
211
212 /*
213  * Remove the counter from a task's (or a CPU's) list of counters.
214  *
215  * Must be called with counter->mutex and ctx->mutex held.
216  *
217  * CPU counters are removed with a smp call. For task counters we only
218  * call when the task is on a CPU.
219  */
220 static void perf_counter_remove_from_context(struct perf_counter *counter)
221 {
222         struct perf_counter_context *ctx = counter->ctx;
223         struct task_struct *task = ctx->task;
224
225         if (!task) {
226                 /*
227                  * Per cpu counters are removed via an smp call and
228                  * the removal is always sucessful.
229                  */
230                 smp_call_function_single(counter->cpu,
231                                          __perf_counter_remove_from_context,
232                                          counter, 1);
233                 return;
234         }
235
236 retry:
237         task_oncpu_function_call(task, __perf_counter_remove_from_context,
238                                  counter);
239
240         spin_lock_irq(&ctx->lock);
241         /*
242          * If the context is active we need to retry the smp call.
243          */
244         if (ctx->nr_active && !list_empty(&counter->list_entry)) {
245                 spin_unlock_irq(&ctx->lock);
246                 goto retry;
247         }
248
249         /*
250          * The lock prevents that this context is scheduled in so we
251          * can remove the counter safely, if the call above did not
252          * succeed.
253          */
254         if (!list_empty(&counter->list_entry)) {
255                 ctx->nr_counters--;
256                 list_del_counter(counter, ctx);
257                 counter->task = NULL;
258         }
259         spin_unlock_irq(&ctx->lock);
260 }
261
262 static inline u64 perf_clock(void)
263 {
264         return cpu_clock(smp_processor_id());
265 }
266
267 /*
268  * Update the record of the current time in a context.
269  */
270 static void update_context_time(struct perf_counter_context *ctx)
271 {
272         u64 now = perf_clock();
273
274         ctx->time += now - ctx->timestamp;
275         ctx->timestamp = now;
276 }
277
278 /*
279  * Update the total_time_enabled and total_time_running fields for a counter.
280  */
281 static void update_counter_times(struct perf_counter *counter)
282 {
283         struct perf_counter_context *ctx = counter->ctx;
284         u64 run_end;
285
286         if (counter->state < PERF_COUNTER_STATE_INACTIVE)
287                 return;
288
289         counter->total_time_enabled = ctx->time - counter->tstamp_enabled;
290
291         if (counter->state == PERF_COUNTER_STATE_INACTIVE)
292                 run_end = counter->tstamp_stopped;
293         else
294                 run_end = ctx->time;
295
296         counter->total_time_running = run_end - counter->tstamp_running;
297 }
298
299 /*
300  * Update total_time_enabled and total_time_running for all counters in a group.
301  */
302 static void update_group_times(struct perf_counter *leader)
303 {
304         struct perf_counter *counter;
305
306         update_counter_times(leader);
307         list_for_each_entry(counter, &leader->sibling_list, list_entry)
308                 update_counter_times(counter);
309 }
310
311 /*
312  * Cross CPU call to disable a performance counter
313  */
314 static void __perf_counter_disable(void *info)
315 {
316         struct perf_counter *counter = info;
317         struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
318         struct perf_counter_context *ctx = counter->ctx;
319         unsigned long flags;
320
321         /*
322          * If this is a per-task counter, need to check whether this
323          * counter's task is the current task on this cpu.
324          */
325         if (ctx->task && cpuctx->task_ctx != ctx)
326                 return;
327
328         spin_lock_irqsave(&ctx->lock, flags);
329
330         /*
331          * If the counter is on, turn it off.
332          * If it is in error state, leave it in error state.
333          */
334         if (counter->state >= PERF_COUNTER_STATE_INACTIVE) {
335                 update_context_time(ctx);
336                 update_counter_times(counter);
337                 if (counter == counter->group_leader)
338                         group_sched_out(counter, cpuctx, ctx);
339                 else
340                         counter_sched_out(counter, cpuctx, ctx);
341                 counter->state = PERF_COUNTER_STATE_OFF;
342         }
343
344         spin_unlock_irqrestore(&ctx->lock, flags);
345 }
346
347 /*
348  * Disable a counter.
349  */
350 static void perf_counter_disable(struct perf_counter *counter)
351 {
352         struct perf_counter_context *ctx = counter->ctx;
353         struct task_struct *task = ctx->task;
354
355         if (!task) {
356                 /*
357                  * Disable the counter on the cpu that it's on
358                  */
359                 smp_call_function_single(counter->cpu, __perf_counter_disable,
360                                          counter, 1);
361                 return;
362         }
363
364  retry:
365         task_oncpu_function_call(task, __perf_counter_disable, counter);
366
367         spin_lock_irq(&ctx->lock);
368         /*
369          * If the counter is still active, we need to retry the cross-call.
370          */
371         if (counter->state == PERF_COUNTER_STATE_ACTIVE) {
372                 spin_unlock_irq(&ctx->lock);
373                 goto retry;
374         }
375
376         /*
377          * Since we have the lock this context can't be scheduled
378          * in, so we can change the state safely.
379          */
380         if (counter->state == PERF_COUNTER_STATE_INACTIVE) {
381                 update_counter_times(counter);
382                 counter->state = PERF_COUNTER_STATE_OFF;
383         }
384
385         spin_unlock_irq(&ctx->lock);
386 }
387
388 /*
389  * Disable a counter and all its children.
390  */
391 static void perf_counter_disable_family(struct perf_counter *counter)
392 {
393         struct perf_counter *child;
394
395         perf_counter_disable(counter);
396
397         /*
398          * Lock the mutex to protect the list of children
399          */
400         mutex_lock(&counter->mutex);
401         list_for_each_entry(child, &counter->child_list, child_list)
402                 perf_counter_disable(child);
403         mutex_unlock(&counter->mutex);
404 }
405
406 static int
407 counter_sched_in(struct perf_counter *counter,
408                  struct perf_cpu_context *cpuctx,
409                  struct perf_counter_context *ctx,
410                  int cpu)
411 {
412         if (counter->state <= PERF_COUNTER_STATE_OFF)
413                 return 0;
414
415         counter->state = PERF_COUNTER_STATE_ACTIVE;
416         counter->oncpu = cpu;   /* TODO: put 'cpu' into cpuctx->cpu */
417         /*
418          * The new state must be visible before we turn it on in the hardware:
419          */
420         smp_wmb();
421
422         if (counter->pmu->enable(counter)) {
423                 counter->state = PERF_COUNTER_STATE_INACTIVE;
424                 counter->oncpu = -1;
425                 return -EAGAIN;
426         }
427
428         counter->tstamp_running += ctx->time - counter->tstamp_stopped;
429
430         if (!is_software_counter(counter))
431                 cpuctx->active_oncpu++;
432         ctx->nr_active++;
433
434         if (counter->hw_event.exclusive)
435                 cpuctx->exclusive = 1;
436
437         return 0;
438 }
439
440 /*
441  * Return 1 for a group consisting entirely of software counters,
442  * 0 if the group contains any hardware counters.
443  */
444 static int is_software_only_group(struct perf_counter *leader)
445 {
446         struct perf_counter *counter;
447
448         if (!is_software_counter(leader))
449                 return 0;
450
451         list_for_each_entry(counter, &leader->sibling_list, list_entry)
452                 if (!is_software_counter(counter))
453                         return 0;
454
455         return 1;
456 }
457
458 /*
459  * Work out whether we can put this counter group on the CPU now.
460  */
461 static int group_can_go_on(struct perf_counter *counter,
462                            struct perf_cpu_context *cpuctx,
463                            int can_add_hw)
464 {
465         /*
466          * Groups consisting entirely of software counters can always go on.
467          */
468         if (is_software_only_group(counter))
469                 return 1;
470         /*
471          * If an exclusive group is already on, no other hardware
472          * counters can go on.
473          */
474         if (cpuctx->exclusive)
475                 return 0;
476         /*
477          * If this group is exclusive and there are already
478          * counters on the CPU, it can't go on.
479          */
480         if (counter->hw_event.exclusive && cpuctx->active_oncpu)
481                 return 0;
482         /*
483          * Otherwise, try to add it if all previous groups were able
484          * to go on.
485          */
486         return can_add_hw;
487 }
488
489 static void add_counter_to_ctx(struct perf_counter *counter,
490                                struct perf_counter_context *ctx)
491 {
492         list_add_counter(counter, ctx);
493         ctx->nr_counters++;
494         counter->prev_state = PERF_COUNTER_STATE_OFF;
495         counter->tstamp_enabled = ctx->time;
496         counter->tstamp_running = ctx->time;
497         counter->tstamp_stopped = ctx->time;
498 }
499
500 /*
501  * Cross CPU call to install and enable a performance counter
502  */
503 static void __perf_install_in_context(void *info)
504 {
505         struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
506         struct perf_counter *counter = info;
507         struct perf_counter_context *ctx = counter->ctx;
508         struct perf_counter *leader = counter->group_leader;
509         int cpu = smp_processor_id();
510         unsigned long flags;
511         u64 perf_flags;
512         int err;
513
514         /*
515          * If this is a task context, we need to check whether it is
516          * the current task context of this cpu. If not it has been
517          * scheduled out before the smp call arrived.
518          */
519         if (ctx->task && cpuctx->task_ctx != ctx)
520                 return;
521
522         spin_lock_irqsave(&ctx->lock, flags);
523         update_context_time(ctx);
524
525         /*
526          * Protect the list operation against NMI by disabling the
527          * counters on a global level. NOP for non NMI based counters.
528          */
529         perf_flags = hw_perf_save_disable();
530
531         add_counter_to_ctx(counter, ctx);
532
533         /*
534          * Don't put the counter on if it is disabled or if
535          * it is in a group and the group isn't on.
536          */
537         if (counter->state != PERF_COUNTER_STATE_INACTIVE ||
538             (leader != counter && leader->state != PERF_COUNTER_STATE_ACTIVE))
539                 goto unlock;
540
541         /*
542          * An exclusive counter can't go on if there are already active
543          * hardware counters, and no hardware counter can go on if there
544          * is already an exclusive counter on.
545          */
546         if (!group_can_go_on(counter, cpuctx, 1))
547                 err = -EEXIST;
548         else
549                 err = counter_sched_in(counter, cpuctx, ctx, cpu);
550
551         if (err) {
552                 /*
553                  * This counter couldn't go on.  If it is in a group
554                  * then we have to pull the whole group off.
555                  * If the counter group is pinned then put it in error state.
556                  */
557                 if (leader != counter)
558                         group_sched_out(leader, cpuctx, ctx);
559                 if (leader->hw_event.pinned) {
560                         update_group_times(leader);
561                         leader->state = PERF_COUNTER_STATE_ERROR;
562                 }
563         }
564
565         if (!err && !ctx->task && cpuctx->max_pertask)
566                 cpuctx->max_pertask--;
567
568  unlock:
569         hw_perf_restore(perf_flags);
570
571         spin_unlock_irqrestore(&ctx->lock, flags);
572 }
573
574 /*
575  * Attach a performance counter to a context
576  *
577  * First we add the counter to the list with the hardware enable bit
578  * in counter->hw_config cleared.
579  *
580  * If the counter is attached to a task which is on a CPU we use a smp
581  * call to enable it in the task context. The task might have been
582  * scheduled away, but we check this in the smp call again.
583  *
584  * Must be called with ctx->mutex held.
585  */
586 static void
587 perf_install_in_context(struct perf_counter_context *ctx,
588                         struct perf_counter *counter,
589                         int cpu)
590 {
591         struct task_struct *task = ctx->task;
592
593         if (!task) {
594                 /*
595                  * Per cpu counters are installed via an smp call and
596                  * the install is always sucessful.
597                  */
598                 smp_call_function_single(cpu, __perf_install_in_context,
599                                          counter, 1);
600                 return;
601         }
602
603         counter->task = task;
604 retry:
605         task_oncpu_function_call(task, __perf_install_in_context,
606                                  counter);
607
608         spin_lock_irq(&ctx->lock);
609         /*
610          * we need to retry the smp call.
611          */
612         if (ctx->is_active && list_empty(&counter->list_entry)) {
613                 spin_unlock_irq(&ctx->lock);
614                 goto retry;
615         }
616
617         /*
618          * The lock prevents that this context is scheduled in so we
619          * can add the counter safely, if it the call above did not
620          * succeed.
621          */
622         if (list_empty(&counter->list_entry))
623                 add_counter_to_ctx(counter, ctx);
624         spin_unlock_irq(&ctx->lock);
625 }
626
627 /*
628  * Cross CPU call to enable a performance counter
629  */
630 static void __perf_counter_enable(void *info)
631 {
632         struct perf_counter *counter = info;
633         struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
634         struct perf_counter_context *ctx = counter->ctx;
635         struct perf_counter *leader = counter->group_leader;
636         unsigned long flags;
637         int err;
638
639         /*
640          * If this is a per-task counter, need to check whether this
641          * counter's task is the current task on this cpu.
642          */
643         if (ctx->task && cpuctx->task_ctx != ctx)
644                 return;
645
646         spin_lock_irqsave(&ctx->lock, flags);
647         update_context_time(ctx);
648
649         counter->prev_state = counter->state;
650         if (counter->state >= PERF_COUNTER_STATE_INACTIVE)
651                 goto unlock;
652         counter->state = PERF_COUNTER_STATE_INACTIVE;
653         counter->tstamp_enabled = ctx->time - counter->total_time_enabled;
654
655         /*
656          * If the counter is in a group and isn't the group leader,
657          * then don't put it on unless the group is on.
658          */
659         if (leader != counter && leader->state != PERF_COUNTER_STATE_ACTIVE)
660                 goto unlock;
661
662         if (!group_can_go_on(counter, cpuctx, 1))
663                 err = -EEXIST;
664         else
665                 err = counter_sched_in(counter, cpuctx, ctx,
666                                        smp_processor_id());
667
668         if (err) {
669                 /*
670                  * If this counter can't go on and it's part of a
671                  * group, then the whole group has to come off.
672                  */
673                 if (leader != counter)
674                         group_sched_out(leader, cpuctx, ctx);
675                 if (leader->hw_event.pinned) {
676                         update_group_times(leader);
677                         leader->state = PERF_COUNTER_STATE_ERROR;
678                 }
679         }
680
681  unlock:
682         spin_unlock_irqrestore(&ctx->lock, flags);
683 }
684
685 /*
686  * Enable a counter.
687  */
688 static void perf_counter_enable(struct perf_counter *counter)
689 {
690         struct perf_counter_context *ctx = counter->ctx;
691         struct task_struct *task = ctx->task;
692
693         if (!task) {
694                 /*
695                  * Enable the counter on the cpu that it's on
696                  */
697                 smp_call_function_single(counter->cpu, __perf_counter_enable,
698                                          counter, 1);
699                 return;
700         }
701
702         spin_lock_irq(&ctx->lock);
703         if (counter->state >= PERF_COUNTER_STATE_INACTIVE)
704                 goto out;
705
706         /*
707          * If the counter is in error state, clear that first.
708          * That way, if we see the counter in error state below, we
709          * know that it has gone back into error state, as distinct
710          * from the task having been scheduled away before the
711          * cross-call arrived.
712          */
713         if (counter->state == PERF_COUNTER_STATE_ERROR)
714                 counter->state = PERF_COUNTER_STATE_OFF;
715
716  retry:
717         spin_unlock_irq(&ctx->lock);
718         task_oncpu_function_call(task, __perf_counter_enable, counter);
719
720         spin_lock_irq(&ctx->lock);
721
722         /*
723          * If the context is active and the counter is still off,
724          * we need to retry the cross-call.
725          */
726         if (ctx->is_active && counter->state == PERF_COUNTER_STATE_OFF)
727                 goto retry;
728
729         /*
730          * Since we have the lock this context can't be scheduled
731          * in, so we can change the state safely.
732          */
733         if (counter->state == PERF_COUNTER_STATE_OFF) {
734                 counter->state = PERF_COUNTER_STATE_INACTIVE;
735                 counter->tstamp_enabled =
736                         ctx->time - counter->total_time_enabled;
737         }
738  out:
739         spin_unlock_irq(&ctx->lock);
740 }
741
742 static int perf_counter_refresh(struct perf_counter *counter, int refresh)
743 {
744         /*
745          * not supported on inherited counters
746          */
747         if (counter->hw_event.inherit)
748                 return -EINVAL;
749
750         atomic_add(refresh, &counter->event_limit);
751         perf_counter_enable(counter);
752
753         return 0;
754 }
755
756 /*
757  * Enable a counter and all its children.
758  */
759 static void perf_counter_enable_family(struct perf_counter *counter)
760 {
761         struct perf_counter *child;
762
763         perf_counter_enable(counter);
764
765         /*
766          * Lock the mutex to protect the list of children
767          */
768         mutex_lock(&counter->mutex);
769         list_for_each_entry(child, &counter->child_list, child_list)
770                 perf_counter_enable(child);
771         mutex_unlock(&counter->mutex);
772 }
773
774 void __perf_counter_sched_out(struct perf_counter_context *ctx,
775                               struct perf_cpu_context *cpuctx)
776 {
777         struct perf_counter *counter;
778         u64 flags;
779
780         spin_lock(&ctx->lock);
781         ctx->is_active = 0;
782         if (likely(!ctx->nr_counters))
783                 goto out;
784         update_context_time(ctx);
785
786         flags = hw_perf_save_disable();
787         if (ctx->nr_active) {
788                 list_for_each_entry(counter, &ctx->counter_list, list_entry)
789                         group_sched_out(counter, cpuctx, ctx);
790         }
791         hw_perf_restore(flags);
792  out:
793         spin_unlock(&ctx->lock);
794 }
795
796 /*
797  * Called from scheduler to remove the counters of the current task,
798  * with interrupts disabled.
799  *
800  * We stop each counter and update the counter value in counter->count.
801  *
802  * This does not protect us against NMI, but disable()
803  * sets the disabled bit in the control field of counter _before_
804  * accessing the counter control register. If a NMI hits, then it will
805  * not restart the counter.
806  */
807 void perf_counter_task_sched_out(struct task_struct *task, int cpu)
808 {
809         struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
810         struct perf_counter_context *ctx = &task->perf_counter_ctx;
811         struct pt_regs *regs;
812
813         if (likely(!cpuctx->task_ctx))
814                 return;
815
816         update_context_time(ctx);
817
818         regs = task_pt_regs(task);
819         perf_swcounter_event(PERF_COUNT_CONTEXT_SWITCHES, 1, 1, regs, 0);
820         __perf_counter_sched_out(ctx, cpuctx);
821
822         cpuctx->task_ctx = NULL;
823 }
824
825 static void perf_counter_cpu_sched_out(struct perf_cpu_context *cpuctx)
826 {
827         __perf_counter_sched_out(&cpuctx->ctx, cpuctx);
828 }
829
830 static int
831 group_sched_in(struct perf_counter *group_counter,
832                struct perf_cpu_context *cpuctx,
833                struct perf_counter_context *ctx,
834                int cpu)
835 {
836         struct perf_counter *counter, *partial_group;
837         int ret;
838
839         if (group_counter->state == PERF_COUNTER_STATE_OFF)
840                 return 0;
841
842         ret = hw_perf_group_sched_in(group_counter, cpuctx, ctx, cpu);
843         if (ret)
844                 return ret < 0 ? ret : 0;
845
846         group_counter->prev_state = group_counter->state;
847         if (counter_sched_in(group_counter, cpuctx, ctx, cpu))
848                 return -EAGAIN;
849
850         /*
851          * Schedule in siblings as one group (if any):
852          */
853         list_for_each_entry(counter, &group_counter->sibling_list, list_entry) {
854                 counter->prev_state = counter->state;
855                 if (counter_sched_in(counter, cpuctx, ctx, cpu)) {
856                         partial_group = counter;
857                         goto group_error;
858                 }
859         }
860
861         return 0;
862
863 group_error:
864         /*
865          * Groups can be scheduled in as one unit only, so undo any
866          * partial group before returning:
867          */
868         list_for_each_entry(counter, &group_counter->sibling_list, list_entry) {
869                 if (counter == partial_group)
870                         break;
871                 counter_sched_out(counter, cpuctx, ctx);
872         }
873         counter_sched_out(group_counter, cpuctx, ctx);
874
875         return -EAGAIN;
876 }
877
878 static void
879 __perf_counter_sched_in(struct perf_counter_context *ctx,
880                         struct perf_cpu_context *cpuctx, int cpu)
881 {
882         struct perf_counter *counter;
883         u64 flags;
884         int can_add_hw = 1;
885
886         spin_lock(&ctx->lock);
887         ctx->is_active = 1;
888         if (likely(!ctx->nr_counters))
889                 goto out;
890
891         ctx->timestamp = perf_clock();
892
893         flags = hw_perf_save_disable();
894
895         /*
896          * First go through the list and put on any pinned groups
897          * in order to give them the best chance of going on.
898          */
899         list_for_each_entry(counter, &ctx->counter_list, list_entry) {
900                 if (counter->state <= PERF_COUNTER_STATE_OFF ||
901                     !counter->hw_event.pinned)
902                         continue;
903                 if (counter->cpu != -1 && counter->cpu != cpu)
904                         continue;
905
906                 if (group_can_go_on(counter, cpuctx, 1))
907                         group_sched_in(counter, cpuctx, ctx, cpu);
908
909                 /*
910                  * If this pinned group hasn't been scheduled,
911                  * put it in error state.
912                  */
913                 if (counter->state == PERF_COUNTER_STATE_INACTIVE) {
914                         update_group_times(counter);
915                         counter->state = PERF_COUNTER_STATE_ERROR;
916                 }
917         }
918
919         list_for_each_entry(counter, &ctx->counter_list, list_entry) {
920                 /*
921                  * Ignore counters in OFF or ERROR state, and
922                  * ignore pinned counters since we did them already.
923                  */
924                 if (counter->state <= PERF_COUNTER_STATE_OFF ||
925                     counter->hw_event.pinned)
926                         continue;
927
928                 /*
929                  * Listen to the 'cpu' scheduling filter constraint
930                  * of counters:
931                  */
932                 if (counter->cpu != -1 && counter->cpu != cpu)
933                         continue;
934
935                 if (group_can_go_on(counter, cpuctx, can_add_hw)) {
936                         if (group_sched_in(counter, cpuctx, ctx, cpu))
937                                 can_add_hw = 0;
938                 }
939         }
940         hw_perf_restore(flags);
941  out:
942         spin_unlock(&ctx->lock);
943 }
944
945 /*
946  * Called from scheduler to add the counters of the current task
947  * with interrupts disabled.
948  *
949  * We restore the counter value and then enable it.
950  *
951  * This does not protect us against NMI, but enable()
952  * sets the enabled bit in the control field of counter _before_
953  * accessing the counter control register. If a NMI hits, then it will
954  * keep the counter running.
955  */
956 void perf_counter_task_sched_in(struct task_struct *task, int cpu)
957 {
958         struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
959         struct perf_counter_context *ctx = &task->perf_counter_ctx;
960
961         __perf_counter_sched_in(ctx, cpuctx, cpu);
962         cpuctx->task_ctx = ctx;
963 }
964
965 static void perf_counter_cpu_sched_in(struct perf_cpu_context *cpuctx, int cpu)
966 {
967         struct perf_counter_context *ctx = &cpuctx->ctx;
968
969         __perf_counter_sched_in(ctx, cpuctx, cpu);
970 }
971
972 int perf_counter_task_disable(void)
973 {
974         struct task_struct *curr = current;
975         struct perf_counter_context *ctx = &curr->perf_counter_ctx;
976         struct perf_counter *counter;
977         unsigned long flags;
978         u64 perf_flags;
979         int cpu;
980
981         if (likely(!ctx->nr_counters))
982                 return 0;
983
984         local_irq_save(flags);
985         cpu = smp_processor_id();
986
987         perf_counter_task_sched_out(curr, cpu);
988
989         spin_lock(&ctx->lock);
990
991         /*
992          * Disable all the counters:
993          */
994         perf_flags = hw_perf_save_disable();
995
996         list_for_each_entry(counter, &ctx->counter_list, list_entry) {
997                 if (counter->state != PERF_COUNTER_STATE_ERROR) {
998                         update_group_times(counter);
999                         counter->state = PERF_COUNTER_STATE_OFF;
1000                 }
1001         }
1002
1003         hw_perf_restore(perf_flags);
1004
1005         spin_unlock_irqrestore(&ctx->lock, flags);
1006
1007         return 0;
1008 }
1009
1010 int perf_counter_task_enable(void)
1011 {
1012         struct task_struct *curr = current;
1013         struct perf_counter_context *ctx = &curr->perf_counter_ctx;
1014         struct perf_counter *counter;
1015         unsigned long flags;
1016         u64 perf_flags;
1017         int cpu;
1018
1019         if (likely(!ctx->nr_counters))
1020                 return 0;
1021
1022         local_irq_save(flags);
1023         cpu = smp_processor_id();
1024
1025         perf_counter_task_sched_out(curr, cpu);
1026
1027         spin_lock(&ctx->lock);
1028
1029         /*
1030          * Disable all the counters:
1031          */
1032         perf_flags = hw_perf_save_disable();
1033
1034         list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1035                 if (counter->state > PERF_COUNTER_STATE_OFF)
1036                         continue;
1037                 counter->state = PERF_COUNTER_STATE_INACTIVE;
1038                 counter->tstamp_enabled =
1039                         ctx->time - counter->total_time_enabled;
1040                 counter->hw_event.disabled = 0;
1041         }
1042         hw_perf_restore(perf_flags);
1043
1044         spin_unlock(&ctx->lock);
1045
1046         perf_counter_task_sched_in(curr, cpu);
1047
1048         local_irq_restore(flags);
1049
1050         return 0;
1051 }
1052
1053 /*
1054  * Round-robin a context's counters:
1055  */
1056 static void rotate_ctx(struct perf_counter_context *ctx)
1057 {
1058         struct perf_counter *counter;
1059         u64 perf_flags;
1060
1061         if (!ctx->nr_counters)
1062                 return;
1063
1064         spin_lock(&ctx->lock);
1065         /*
1066          * Rotate the first entry last (works just fine for group counters too):
1067          */
1068         perf_flags = hw_perf_save_disable();
1069         list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1070                 list_move_tail(&counter->list_entry, &ctx->counter_list);
1071                 break;
1072         }
1073         hw_perf_restore(perf_flags);
1074
1075         spin_unlock(&ctx->lock);
1076 }
1077
1078 void perf_counter_task_tick(struct task_struct *curr, int cpu)
1079 {
1080         struct perf_cpu_context *cpuctx;
1081         struct perf_counter_context *ctx;
1082
1083         if (!atomic_read(&nr_counters))
1084                 return;
1085
1086         cpuctx = &per_cpu(perf_cpu_context, cpu);
1087         ctx = &curr->perf_counter_ctx;
1088
1089         perf_counter_cpu_sched_out(cpuctx);
1090         perf_counter_task_sched_out(curr, cpu);
1091
1092         rotate_ctx(&cpuctx->ctx);
1093         rotate_ctx(ctx);
1094
1095         perf_counter_cpu_sched_in(cpuctx, cpu);
1096         perf_counter_task_sched_in(curr, cpu);
1097 }
1098
1099 /*
1100  * Cross CPU call to read the hardware counter
1101  */
1102 static void __read(void *info)
1103 {
1104         struct perf_counter *counter = info;
1105         struct perf_counter_context *ctx = counter->ctx;
1106         unsigned long flags;
1107
1108         local_irq_save(flags);
1109         if (ctx->is_active)
1110                 update_context_time(ctx);
1111         counter->pmu->read(counter);
1112         update_counter_times(counter);
1113         local_irq_restore(flags);
1114 }
1115
1116 static u64 perf_counter_read(struct perf_counter *counter)
1117 {
1118         /*
1119          * If counter is enabled and currently active on a CPU, update the
1120          * value in the counter structure:
1121          */
1122         if (counter->state == PERF_COUNTER_STATE_ACTIVE) {
1123                 smp_call_function_single(counter->oncpu,
1124                                          __read, counter, 1);
1125         } else if (counter->state == PERF_COUNTER_STATE_INACTIVE) {
1126                 update_counter_times(counter);
1127         }
1128
1129         return atomic64_read(&counter->count);
1130 }
1131
1132 static void put_context(struct perf_counter_context *ctx)
1133 {
1134         if (ctx->task)
1135                 put_task_struct(ctx->task);
1136 }
1137
1138 static struct perf_counter_context *find_get_context(pid_t pid, int cpu)
1139 {
1140         struct perf_cpu_context *cpuctx;
1141         struct perf_counter_context *ctx;
1142         struct task_struct *task;
1143
1144         /*
1145          * If cpu is not a wildcard then this is a percpu counter:
1146          */
1147         if (cpu != -1) {
1148                 /* Must be root to operate on a CPU counter: */
1149                 if (sysctl_perf_counter_priv && !capable(CAP_SYS_ADMIN))
1150                         return ERR_PTR(-EACCES);
1151
1152                 if (cpu < 0 || cpu > num_possible_cpus())
1153                         return ERR_PTR(-EINVAL);
1154
1155                 /*
1156                  * We could be clever and allow to attach a counter to an
1157                  * offline CPU and activate it when the CPU comes up, but
1158                  * that's for later.
1159                  */
1160                 if (!cpu_isset(cpu, cpu_online_map))
1161                         return ERR_PTR(-ENODEV);
1162
1163                 cpuctx = &per_cpu(perf_cpu_context, cpu);
1164                 ctx = &cpuctx->ctx;
1165
1166                 return ctx;
1167         }
1168
1169         rcu_read_lock();
1170         if (!pid)
1171                 task = current;
1172         else
1173                 task = find_task_by_vpid(pid);
1174         if (task)
1175                 get_task_struct(task);
1176         rcu_read_unlock();
1177
1178         if (!task)
1179                 return ERR_PTR(-ESRCH);
1180
1181         ctx = &task->perf_counter_ctx;
1182         ctx->task = task;
1183
1184         /* Reuse ptrace permission checks for now. */
1185         if (!ptrace_may_access(task, PTRACE_MODE_READ)) {
1186                 put_context(ctx);
1187                 return ERR_PTR(-EACCES);
1188         }
1189
1190         return ctx;
1191 }
1192
1193 static void free_counter_rcu(struct rcu_head *head)
1194 {
1195         struct perf_counter *counter;
1196
1197         counter = container_of(head, struct perf_counter, rcu_head);
1198         kfree(counter);
1199 }
1200
1201 static void perf_pending_sync(struct perf_counter *counter);
1202
1203 static void free_counter(struct perf_counter *counter)
1204 {
1205         perf_pending_sync(counter);
1206
1207         atomic_dec(&nr_counters);
1208         if (counter->hw_event.mmap)
1209                 atomic_dec(&nr_mmap_tracking);
1210         if (counter->hw_event.munmap)
1211                 atomic_dec(&nr_munmap_tracking);
1212         if (counter->hw_event.comm)
1213                 atomic_dec(&nr_comm_tracking);
1214
1215         if (counter->destroy)
1216                 counter->destroy(counter);
1217
1218         call_rcu(&counter->rcu_head, free_counter_rcu);
1219 }
1220
1221 /*
1222  * Called when the last reference to the file is gone.
1223  */
1224 static int perf_release(struct inode *inode, struct file *file)
1225 {
1226         struct perf_counter *counter = file->private_data;
1227         struct perf_counter_context *ctx = counter->ctx;
1228
1229         file->private_data = NULL;
1230
1231         mutex_lock(&ctx->mutex);
1232         mutex_lock(&counter->mutex);
1233
1234         perf_counter_remove_from_context(counter);
1235
1236         mutex_unlock(&counter->mutex);
1237         mutex_unlock(&ctx->mutex);
1238
1239         free_counter(counter);
1240         put_context(ctx);
1241
1242         return 0;
1243 }
1244
1245 /*
1246  * Read the performance counter - simple non blocking version for now
1247  */
1248 static ssize_t
1249 perf_read_hw(struct perf_counter *counter, char __user *buf, size_t count)
1250 {
1251         u64 values[3];
1252         int n;
1253
1254         /*
1255          * Return end-of-file for a read on a counter that is in
1256          * error state (i.e. because it was pinned but it couldn't be
1257          * scheduled on to the CPU at some point).
1258          */
1259         if (counter->state == PERF_COUNTER_STATE_ERROR)
1260                 return 0;
1261
1262         mutex_lock(&counter->mutex);
1263         values[0] = perf_counter_read(counter);
1264         n = 1;
1265         if (counter->hw_event.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1266                 values[n++] = counter->total_time_enabled +
1267                         atomic64_read(&counter->child_total_time_enabled);
1268         if (counter->hw_event.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1269                 values[n++] = counter->total_time_running +
1270                         atomic64_read(&counter->child_total_time_running);
1271         mutex_unlock(&counter->mutex);
1272
1273         if (count < n * sizeof(u64))
1274                 return -EINVAL;
1275         count = n * sizeof(u64);
1276
1277         if (copy_to_user(buf, values, count))
1278                 return -EFAULT;
1279
1280         return count;
1281 }
1282
1283 static ssize_t
1284 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
1285 {
1286         struct perf_counter *counter = file->private_data;
1287
1288         return perf_read_hw(counter, buf, count);
1289 }
1290
1291 static unsigned int perf_poll(struct file *file, poll_table *wait)
1292 {
1293         struct perf_counter *counter = file->private_data;
1294         struct perf_mmap_data *data;
1295         unsigned int events = POLL_HUP;
1296
1297         rcu_read_lock();
1298         data = rcu_dereference(counter->data);
1299         if (data)
1300                 events = atomic_xchg(&data->poll, 0);
1301         rcu_read_unlock();
1302
1303         poll_wait(file, &counter->waitq, wait);
1304
1305         return events;
1306 }
1307
1308 static void perf_counter_reset(struct perf_counter *counter)
1309 {
1310         atomic_set(&counter->count, 0);
1311 }
1312
1313 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
1314 {
1315         struct perf_counter *counter = file->private_data;
1316         int err = 0;
1317
1318         switch (cmd) {
1319         case PERF_COUNTER_IOC_ENABLE:
1320                 perf_counter_enable_family(counter);
1321                 break;
1322         case PERF_COUNTER_IOC_DISABLE:
1323                 perf_counter_disable_family(counter);
1324                 break;
1325         case PERF_COUNTER_IOC_REFRESH:
1326                 err = perf_counter_refresh(counter, arg);
1327                 break;
1328         case PERF_COUNTER_IOC_RESET:
1329                 perf_counter_reset(counter);
1330                 break;
1331         default:
1332                 err = -ENOTTY;
1333         }
1334         return err;
1335 }
1336
1337 /*
1338  * Callers need to ensure there can be no nesting of this function, otherwise
1339  * the seqlock logic goes bad. We can not serialize this because the arch
1340  * code calls this from NMI context.
1341  */
1342 void perf_counter_update_userpage(struct perf_counter *counter)
1343 {
1344         struct perf_mmap_data *data;
1345         struct perf_counter_mmap_page *userpg;
1346
1347         rcu_read_lock();
1348         data = rcu_dereference(counter->data);
1349         if (!data)
1350                 goto unlock;
1351
1352         userpg = data->user_page;
1353
1354         /*
1355          * Disable preemption so as to not let the corresponding user-space
1356          * spin too long if we get preempted.
1357          */
1358         preempt_disable();
1359         ++userpg->lock;
1360         barrier();
1361         userpg->index = counter->hw.idx;
1362         userpg->offset = atomic64_read(&counter->count);
1363         if (counter->state == PERF_COUNTER_STATE_ACTIVE)
1364                 userpg->offset -= atomic64_read(&counter->hw.prev_count);
1365
1366         barrier();
1367         ++userpg->lock;
1368         preempt_enable();
1369 unlock:
1370         rcu_read_unlock();
1371 }
1372
1373 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1374 {
1375         struct perf_counter *counter = vma->vm_file->private_data;
1376         struct perf_mmap_data *data;
1377         int ret = VM_FAULT_SIGBUS;
1378
1379         rcu_read_lock();
1380         data = rcu_dereference(counter->data);
1381         if (!data)
1382                 goto unlock;
1383
1384         if (vmf->pgoff == 0) {
1385                 vmf->page = virt_to_page(data->user_page);
1386         } else {
1387                 int nr = vmf->pgoff - 1;
1388
1389                 if ((unsigned)nr > data->nr_pages)
1390                         goto unlock;
1391
1392                 vmf->page = virt_to_page(data->data_pages[nr]);
1393         }
1394         get_page(vmf->page);
1395         ret = 0;
1396 unlock:
1397         rcu_read_unlock();
1398
1399         return ret;
1400 }
1401
1402 static int perf_mmap_data_alloc(struct perf_counter *counter, int nr_pages)
1403 {
1404         struct perf_mmap_data *data;
1405         unsigned long size;
1406         int i;
1407
1408         WARN_ON(atomic_read(&counter->mmap_count));
1409
1410         size = sizeof(struct perf_mmap_data);
1411         size += nr_pages * sizeof(void *);
1412
1413         data = kzalloc(size, GFP_KERNEL);
1414         if (!data)
1415                 goto fail;
1416
1417         data->user_page = (void *)get_zeroed_page(GFP_KERNEL);
1418         if (!data->user_page)
1419                 goto fail_user_page;
1420
1421         for (i = 0; i < nr_pages; i++) {
1422                 data->data_pages[i] = (void *)get_zeroed_page(GFP_KERNEL);
1423                 if (!data->data_pages[i])
1424                         goto fail_data_pages;
1425         }
1426
1427         data->nr_pages = nr_pages;
1428         atomic_set(&data->lock, -1);
1429
1430         rcu_assign_pointer(counter->data, data);
1431
1432         return 0;
1433
1434 fail_data_pages:
1435         for (i--; i >= 0; i--)
1436                 free_page((unsigned long)data->data_pages[i]);
1437
1438         free_page((unsigned long)data->user_page);
1439
1440 fail_user_page:
1441         kfree(data);
1442
1443 fail:
1444         return -ENOMEM;
1445 }
1446
1447 static void __perf_mmap_data_free(struct rcu_head *rcu_head)
1448 {
1449         struct perf_mmap_data *data = container_of(rcu_head,
1450                         struct perf_mmap_data, rcu_head);
1451         int i;
1452
1453         free_page((unsigned long)data->user_page);
1454         for (i = 0; i < data->nr_pages; i++)
1455                 free_page((unsigned long)data->data_pages[i]);
1456         kfree(data);
1457 }
1458
1459 static void perf_mmap_data_free(struct perf_counter *counter)
1460 {
1461         struct perf_mmap_data *data = counter->data;
1462
1463         WARN_ON(atomic_read(&counter->mmap_count));
1464
1465         rcu_assign_pointer(counter->data, NULL);
1466         call_rcu(&data->rcu_head, __perf_mmap_data_free);
1467 }
1468
1469 static void perf_mmap_open(struct vm_area_struct *vma)
1470 {
1471         struct perf_counter *counter = vma->vm_file->private_data;
1472
1473         atomic_inc(&counter->mmap_count);
1474 }
1475
1476 static void perf_mmap_close(struct vm_area_struct *vma)
1477 {
1478         struct perf_counter *counter = vma->vm_file->private_data;
1479
1480         if (atomic_dec_and_mutex_lock(&counter->mmap_count,
1481                                       &counter->mmap_mutex)) {
1482                 vma->vm_mm->locked_vm -= counter->data->nr_locked;
1483                 perf_mmap_data_free(counter);
1484                 mutex_unlock(&counter->mmap_mutex);
1485         }
1486 }
1487
1488 static struct vm_operations_struct perf_mmap_vmops = {
1489         .open  = perf_mmap_open,
1490         .close = perf_mmap_close,
1491         .fault = perf_mmap_fault,
1492 };
1493
1494 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
1495 {
1496         struct perf_counter *counter = file->private_data;
1497         unsigned long vma_size;
1498         unsigned long nr_pages;
1499         unsigned long locked, lock_limit;
1500         int ret = 0;
1501         long extra;
1502
1503         if (!(vma->vm_flags & VM_SHARED) || (vma->vm_flags & VM_WRITE))
1504                 return -EINVAL;
1505
1506         vma_size = vma->vm_end - vma->vm_start;
1507         nr_pages = (vma_size / PAGE_SIZE) - 1;
1508
1509         /*
1510          * If we have data pages ensure they're a power-of-two number, so we
1511          * can do bitmasks instead of modulo.
1512          */
1513         if (nr_pages != 0 && !is_power_of_2(nr_pages))
1514                 return -EINVAL;
1515
1516         if (vma_size != PAGE_SIZE * (1 + nr_pages))
1517                 return -EINVAL;
1518
1519         if (vma->vm_pgoff != 0)
1520                 return -EINVAL;
1521
1522         mutex_lock(&counter->mmap_mutex);
1523         if (atomic_inc_not_zero(&counter->mmap_count)) {
1524                 if (nr_pages != counter->data->nr_pages)
1525                         ret = -EINVAL;
1526                 goto unlock;
1527         }
1528
1529         extra = nr_pages /* + 1 only account the data pages */;
1530         extra -= sysctl_perf_counter_mlock >> (PAGE_SHIFT - 10);
1531         if (extra < 0)
1532                 extra = 0;
1533
1534         locked = vma->vm_mm->locked_vm + extra;
1535
1536         lock_limit = current->signal->rlim[RLIMIT_MEMLOCK].rlim_cur;
1537         lock_limit >>= PAGE_SHIFT;
1538
1539         if ((locked > lock_limit) && !capable(CAP_IPC_LOCK)) {
1540                 ret = -EPERM;
1541                 goto unlock;
1542         }
1543
1544         WARN_ON(counter->data);
1545         ret = perf_mmap_data_alloc(counter, nr_pages);
1546         if (ret)
1547                 goto unlock;
1548
1549         atomic_set(&counter->mmap_count, 1);
1550         vma->vm_mm->locked_vm += extra;
1551         counter->data->nr_locked = extra;
1552 unlock:
1553         mutex_unlock(&counter->mmap_mutex);
1554
1555         vma->vm_flags &= ~VM_MAYWRITE;
1556         vma->vm_flags |= VM_RESERVED;
1557         vma->vm_ops = &perf_mmap_vmops;
1558
1559         return ret;
1560 }
1561
1562 static int perf_fasync(int fd, struct file *filp, int on)
1563 {
1564         struct perf_counter *counter = filp->private_data;
1565         struct inode *inode = filp->f_path.dentry->d_inode;
1566         int retval;
1567
1568         mutex_lock(&inode->i_mutex);
1569         retval = fasync_helper(fd, filp, on, &counter->fasync);
1570         mutex_unlock(&inode->i_mutex);
1571
1572         if (retval < 0)
1573                 return retval;
1574
1575         return 0;
1576 }
1577
1578 static const struct file_operations perf_fops = {
1579         .release                = perf_release,
1580         .read                   = perf_read,
1581         .poll                   = perf_poll,
1582         .unlocked_ioctl         = perf_ioctl,
1583         .compat_ioctl           = perf_ioctl,
1584         .mmap                   = perf_mmap,
1585         .fasync                 = perf_fasync,
1586 };
1587
1588 /*
1589  * Perf counter wakeup
1590  *
1591  * If there's data, ensure we set the poll() state and publish everything
1592  * to user-space before waking everybody up.
1593  */
1594
1595 void perf_counter_wakeup(struct perf_counter *counter)
1596 {
1597         wake_up_all(&counter->waitq);
1598
1599         if (counter->pending_kill) {
1600                 kill_fasync(&counter->fasync, SIGIO, counter->pending_kill);
1601                 counter->pending_kill = 0;
1602         }
1603 }
1604
1605 /*
1606  * Pending wakeups
1607  *
1608  * Handle the case where we need to wakeup up from NMI (or rq->lock) context.
1609  *
1610  * The NMI bit means we cannot possibly take locks. Therefore, maintain a
1611  * single linked list and use cmpxchg() to add entries lockless.
1612  */
1613
1614 static void perf_pending_counter(struct perf_pending_entry *entry)
1615 {
1616         struct perf_counter *counter = container_of(entry,
1617                         struct perf_counter, pending);
1618
1619         if (counter->pending_disable) {
1620                 counter->pending_disable = 0;
1621                 perf_counter_disable(counter);
1622         }
1623
1624         if (counter->pending_wakeup) {
1625                 counter->pending_wakeup = 0;
1626                 perf_counter_wakeup(counter);
1627         }
1628 }
1629
1630 #define PENDING_TAIL ((struct perf_pending_entry *)-1UL)
1631
1632 static DEFINE_PER_CPU(struct perf_pending_entry *, perf_pending_head) = {
1633         PENDING_TAIL,
1634 };
1635
1636 static void perf_pending_queue(struct perf_pending_entry *entry,
1637                                void (*func)(struct perf_pending_entry *))
1638 {
1639         struct perf_pending_entry **head;
1640
1641         if (cmpxchg(&entry->next, NULL, PENDING_TAIL) != NULL)
1642                 return;
1643
1644         entry->func = func;
1645
1646         head = &get_cpu_var(perf_pending_head);
1647
1648         do {
1649                 entry->next = *head;
1650         } while (cmpxchg(head, entry->next, entry) != entry->next);
1651
1652         set_perf_counter_pending();
1653
1654         put_cpu_var(perf_pending_head);
1655 }
1656
1657 static int __perf_pending_run(void)
1658 {
1659         struct perf_pending_entry *list;
1660         int nr = 0;
1661
1662         list = xchg(&__get_cpu_var(perf_pending_head), PENDING_TAIL);
1663         while (list != PENDING_TAIL) {
1664                 void (*func)(struct perf_pending_entry *);
1665                 struct perf_pending_entry *entry = list;
1666
1667                 list = list->next;
1668
1669                 func = entry->func;
1670                 entry->next = NULL;
1671                 /*
1672                  * Ensure we observe the unqueue before we issue the wakeup,
1673                  * so that we won't be waiting forever.
1674                  * -- see perf_not_pending().
1675                  */
1676                 smp_wmb();
1677
1678                 func(entry);
1679                 nr++;
1680         }
1681
1682         return nr;
1683 }
1684
1685 static inline int perf_not_pending(struct perf_counter *counter)
1686 {
1687         /*
1688          * If we flush on whatever cpu we run, there is a chance we don't
1689          * need to wait.
1690          */
1691         get_cpu();
1692         __perf_pending_run();
1693         put_cpu();
1694
1695         /*
1696          * Ensure we see the proper queue state before going to sleep
1697          * so that we do not miss the wakeup. -- see perf_pending_handle()
1698          */
1699         smp_rmb();
1700         return counter->pending.next == NULL;
1701 }
1702
1703 static void perf_pending_sync(struct perf_counter *counter)
1704 {
1705         wait_event(counter->waitq, perf_not_pending(counter));
1706 }
1707
1708 void perf_counter_do_pending(void)
1709 {
1710         __perf_pending_run();
1711 }
1712
1713 /*
1714  * Callchain support -- arch specific
1715  */
1716
1717 __weak struct perf_callchain_entry *perf_callchain(struct pt_regs *regs)
1718 {
1719         return NULL;
1720 }
1721
1722 /*
1723  * Output
1724  */
1725
1726 struct perf_output_handle {
1727         struct perf_counter     *counter;
1728         struct perf_mmap_data   *data;
1729         unsigned int            offset;
1730         unsigned int            head;
1731         int                     nmi;
1732         int                     overflow;
1733         int                     locked;
1734         unsigned long           flags;
1735 };
1736
1737 static void perf_output_wakeup(struct perf_output_handle *handle)
1738 {
1739         atomic_set(&handle->data->poll, POLL_IN);
1740
1741         if (handle->nmi) {
1742                 handle->counter->pending_wakeup = 1;
1743                 perf_pending_queue(&handle->counter->pending,
1744                                    perf_pending_counter);
1745         } else
1746                 perf_counter_wakeup(handle->counter);
1747 }
1748
1749 /*
1750  * Curious locking construct.
1751  *
1752  * We need to ensure a later event doesn't publish a head when a former
1753  * event isn't done writing. However since we need to deal with NMIs we
1754  * cannot fully serialize things.
1755  *
1756  * What we do is serialize between CPUs so we only have to deal with NMI
1757  * nesting on a single CPU.
1758  *
1759  * We only publish the head (and generate a wakeup) when the outer-most
1760  * event completes.
1761  */
1762 static void perf_output_lock(struct perf_output_handle *handle)
1763 {
1764         struct perf_mmap_data *data = handle->data;
1765         int cpu;
1766
1767         handle->locked = 0;
1768
1769         local_irq_save(handle->flags);
1770         cpu = smp_processor_id();
1771
1772         if (in_nmi() && atomic_read(&data->lock) == cpu)
1773                 return;
1774
1775         while (atomic_cmpxchg(&data->lock, -1, cpu) != -1)
1776                 cpu_relax();
1777
1778         handle->locked = 1;
1779 }
1780
1781 static void perf_output_unlock(struct perf_output_handle *handle)
1782 {
1783         struct perf_mmap_data *data = handle->data;
1784         int head, cpu;
1785
1786         data->done_head = data->head;
1787
1788         if (!handle->locked)
1789                 goto out;
1790
1791 again:
1792         /*
1793          * The xchg implies a full barrier that ensures all writes are done
1794          * before we publish the new head, matched by a rmb() in userspace when
1795          * reading this position.
1796          */
1797         while ((head = atomic_xchg(&data->done_head, 0)))
1798                 data->user_page->data_head = head;
1799
1800         /*
1801          * NMI can happen here, which means we can miss a done_head update.
1802          */
1803
1804         cpu = atomic_xchg(&data->lock, -1);
1805         WARN_ON_ONCE(cpu != smp_processor_id());
1806
1807         /*
1808          * Therefore we have to validate we did not indeed do so.
1809          */
1810         if (unlikely(atomic_read(&data->done_head))) {
1811                 /*
1812                  * Since we had it locked, we can lock it again.
1813                  */
1814                 while (atomic_cmpxchg(&data->lock, -1, cpu) != -1)
1815                         cpu_relax();
1816
1817                 goto again;
1818         }
1819
1820         if (atomic_xchg(&data->wakeup, 0))
1821                 perf_output_wakeup(handle);
1822 out:
1823         local_irq_restore(handle->flags);
1824 }
1825
1826 static int perf_output_begin(struct perf_output_handle *handle,
1827                              struct perf_counter *counter, unsigned int size,
1828                              int nmi, int overflow)
1829 {
1830         struct perf_mmap_data *data;
1831         unsigned int offset, head;
1832
1833         /*
1834          * For inherited counters we send all the output towards the parent.
1835          */
1836         if (counter->parent)
1837                 counter = counter->parent;
1838
1839         rcu_read_lock();
1840         data = rcu_dereference(counter->data);
1841         if (!data)
1842                 goto out;
1843
1844         handle->data     = data;
1845         handle->counter  = counter;
1846         handle->nmi      = nmi;
1847         handle->overflow = overflow;
1848
1849         if (!data->nr_pages)
1850                 goto fail;
1851
1852         perf_output_lock(handle);
1853
1854         do {
1855                 offset = head = atomic_read(&data->head);
1856                 head += size;
1857         } while (atomic_cmpxchg(&data->head, offset, head) != offset);
1858
1859         handle->offset  = offset;
1860         handle->head    = head;
1861
1862         if ((offset >> PAGE_SHIFT) != (head >> PAGE_SHIFT))
1863                 atomic_set(&data->wakeup, 1);
1864
1865         return 0;
1866
1867 fail:
1868         perf_output_wakeup(handle);
1869 out:
1870         rcu_read_unlock();
1871
1872         return -ENOSPC;
1873 }
1874
1875 static void perf_output_copy(struct perf_output_handle *handle,
1876                              void *buf, unsigned int len)
1877 {
1878         unsigned int pages_mask;
1879         unsigned int offset;
1880         unsigned int size;
1881         void **pages;
1882
1883         offset          = handle->offset;
1884         pages_mask      = handle->data->nr_pages - 1;
1885         pages           = handle->data->data_pages;
1886
1887         do {
1888                 unsigned int page_offset;
1889                 int nr;
1890
1891                 nr          = (offset >> PAGE_SHIFT) & pages_mask;
1892                 page_offset = offset & (PAGE_SIZE - 1);
1893                 size        = min_t(unsigned int, PAGE_SIZE - page_offset, len);
1894
1895                 memcpy(pages[nr] + page_offset, buf, size);
1896
1897                 len         -= size;
1898                 buf         += size;
1899                 offset      += size;
1900         } while (len);
1901
1902         handle->offset = offset;
1903
1904         WARN_ON_ONCE(handle->offset > handle->head);
1905 }
1906
1907 #define perf_output_put(handle, x) \
1908         perf_output_copy((handle), &(x), sizeof(x))
1909
1910 static void perf_output_end(struct perf_output_handle *handle)
1911 {
1912         struct perf_counter *counter = handle->counter;
1913         struct perf_mmap_data *data = handle->data;
1914
1915         int wakeup_events = counter->hw_event.wakeup_events;
1916
1917         if (handle->overflow && wakeup_events) {
1918                 int events = atomic_inc_return(&data->events);
1919                 if (events >= wakeup_events) {
1920                         atomic_sub(wakeup_events, &data->events);
1921                         atomic_set(&data->wakeup, 1);
1922                 }
1923         }
1924
1925         perf_output_unlock(handle);
1926         rcu_read_unlock();
1927 }
1928
1929 static void perf_counter_output(struct perf_counter *counter,
1930                                 int nmi, struct pt_regs *regs, u64 addr)
1931 {
1932         int ret;
1933         u64 record_type = counter->hw_event.record_type;
1934         struct perf_output_handle handle;
1935         struct perf_event_header header;
1936         u64 ip;
1937         struct {
1938                 u32 pid, tid;
1939         } tid_entry;
1940         struct {
1941                 u64 event;
1942                 u64 counter;
1943         } group_entry;
1944         struct perf_callchain_entry *callchain = NULL;
1945         int callchain_size = 0;
1946         u64 time;
1947
1948         header.type = 0;
1949         header.size = sizeof(header);
1950
1951         header.misc = PERF_EVENT_MISC_OVERFLOW;
1952         header.misc |= user_mode(regs) ?
1953                 PERF_EVENT_MISC_USER : PERF_EVENT_MISC_KERNEL;
1954
1955         if (record_type & PERF_RECORD_IP) {
1956                 ip = instruction_pointer(regs);
1957                 header.type |= PERF_RECORD_IP;
1958                 header.size += sizeof(ip);
1959         }
1960
1961         if (record_type & PERF_RECORD_TID) {
1962                 /* namespace issues */
1963                 tid_entry.pid = current->group_leader->pid;
1964                 tid_entry.tid = current->pid;
1965
1966                 header.type |= PERF_RECORD_TID;
1967                 header.size += sizeof(tid_entry);
1968         }
1969
1970         if (record_type & PERF_RECORD_TIME) {
1971                 /*
1972                  * Maybe do better on x86 and provide cpu_clock_nmi()
1973                  */
1974                 time = sched_clock();
1975
1976                 header.type |= PERF_RECORD_TIME;
1977                 header.size += sizeof(u64);
1978         }
1979
1980         if (record_type & PERF_RECORD_ADDR) {
1981                 header.type |= PERF_RECORD_ADDR;
1982                 header.size += sizeof(u64);
1983         }
1984
1985         if (record_type & PERF_RECORD_GROUP) {
1986                 header.type |= PERF_RECORD_GROUP;
1987                 header.size += sizeof(u64) +
1988                         counter->nr_siblings * sizeof(group_entry);
1989         }
1990
1991         if (record_type & PERF_RECORD_CALLCHAIN) {
1992                 callchain = perf_callchain(regs);
1993
1994                 if (callchain) {
1995                         callchain_size = (1 + callchain->nr) * sizeof(u64);
1996
1997                         header.type |= PERF_RECORD_CALLCHAIN;
1998                         header.size += callchain_size;
1999                 }
2000         }
2001
2002         ret = perf_output_begin(&handle, counter, header.size, nmi, 1);
2003         if (ret)
2004                 return;
2005
2006         perf_output_put(&handle, header);
2007
2008         if (record_type & PERF_RECORD_IP)
2009                 perf_output_put(&handle, ip);
2010
2011         if (record_type & PERF_RECORD_TID)
2012                 perf_output_put(&handle, tid_entry);
2013
2014         if (record_type & PERF_RECORD_TIME)
2015                 perf_output_put(&handle, time);
2016
2017         if (record_type & PERF_RECORD_ADDR)
2018                 perf_output_put(&handle, addr);
2019
2020         /*
2021          * XXX PERF_RECORD_GROUP vs inherited counters seems difficult.
2022          */
2023         if (record_type & PERF_RECORD_GROUP) {
2024                 struct perf_counter *leader, *sub;
2025                 u64 nr = counter->nr_siblings;
2026
2027                 perf_output_put(&handle, nr);
2028
2029                 leader = counter->group_leader;
2030                 list_for_each_entry(sub, &leader->sibling_list, list_entry) {
2031                         if (sub != counter)
2032                                 sub->pmu->read(sub);
2033
2034                         group_entry.event = sub->hw_event.config;
2035                         group_entry.counter = atomic64_read(&sub->count);
2036
2037                         perf_output_put(&handle, group_entry);
2038                 }
2039         }
2040
2041         if (callchain)
2042                 perf_output_copy(&handle, callchain, callchain_size);
2043
2044         perf_output_end(&handle);
2045 }
2046
2047 /*
2048  * comm tracking
2049  */
2050
2051 struct perf_comm_event {
2052         struct task_struct      *task;
2053         char                    *comm;
2054         int                     comm_size;
2055
2056         struct {
2057                 struct perf_event_header        header;
2058
2059                 u32                             pid;
2060                 u32                             tid;
2061         } event;
2062 };
2063
2064 static void perf_counter_comm_output(struct perf_counter *counter,
2065                                      struct perf_comm_event *comm_event)
2066 {
2067         struct perf_output_handle handle;
2068         int size = comm_event->event.header.size;
2069         int ret = perf_output_begin(&handle, counter, size, 0, 0);
2070
2071         if (ret)
2072                 return;
2073
2074         perf_output_put(&handle, comm_event->event);
2075         perf_output_copy(&handle, comm_event->comm,
2076                                    comm_event->comm_size);
2077         perf_output_end(&handle);
2078 }
2079
2080 static int perf_counter_comm_match(struct perf_counter *counter,
2081                                    struct perf_comm_event *comm_event)
2082 {
2083         if (counter->hw_event.comm &&
2084             comm_event->event.header.type == PERF_EVENT_COMM)
2085                 return 1;
2086
2087         return 0;
2088 }
2089
2090 static void perf_counter_comm_ctx(struct perf_counter_context *ctx,
2091                                   struct perf_comm_event *comm_event)
2092 {
2093         struct perf_counter *counter;
2094
2095         if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
2096                 return;
2097
2098         rcu_read_lock();
2099         list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
2100                 if (perf_counter_comm_match(counter, comm_event))
2101                         perf_counter_comm_output(counter, comm_event);
2102         }
2103         rcu_read_unlock();
2104 }
2105
2106 static void perf_counter_comm_event(struct perf_comm_event *comm_event)
2107 {
2108         struct perf_cpu_context *cpuctx;
2109         unsigned int size;
2110         char *comm = comm_event->task->comm;
2111
2112         size = ALIGN(strlen(comm)+1, sizeof(u64));
2113
2114         comm_event->comm = comm;
2115         comm_event->comm_size = size;
2116
2117         comm_event->event.header.size = sizeof(comm_event->event) + size;
2118
2119         cpuctx = &get_cpu_var(perf_cpu_context);
2120         perf_counter_comm_ctx(&cpuctx->ctx, comm_event);
2121         put_cpu_var(perf_cpu_context);
2122
2123         perf_counter_comm_ctx(&current->perf_counter_ctx, comm_event);
2124 }
2125
2126 void perf_counter_comm(struct task_struct *task)
2127 {
2128         struct perf_comm_event comm_event;
2129
2130         if (!atomic_read(&nr_comm_tracking))
2131                 return;
2132        
2133         comm_event = (struct perf_comm_event){
2134                 .task   = task,
2135                 .event  = {
2136                         .header = { .type = PERF_EVENT_COMM, },
2137                         .pid    = task->group_leader->pid,
2138                         .tid    = task->pid,
2139                 },
2140         };
2141
2142         perf_counter_comm_event(&comm_event);
2143 }
2144
2145 /*
2146  * mmap tracking
2147  */
2148
2149 struct perf_mmap_event {
2150         struct file     *file;
2151         char            *file_name;
2152         int             file_size;
2153
2154         struct {
2155                 struct perf_event_header        header;
2156
2157                 u32                             pid;
2158                 u32                             tid;
2159                 u64                             start;
2160                 u64                             len;
2161                 u64                             pgoff;
2162         } event;
2163 };
2164
2165 static void perf_counter_mmap_output(struct perf_counter *counter,
2166                                      struct perf_mmap_event *mmap_event)
2167 {
2168         struct perf_output_handle handle;
2169         int size = mmap_event->event.header.size;
2170         int ret = perf_output_begin(&handle, counter, size, 0, 0);
2171
2172         if (ret)
2173                 return;
2174
2175         perf_output_put(&handle, mmap_event->event);
2176         perf_output_copy(&handle, mmap_event->file_name,
2177                                    mmap_event->file_size);
2178         perf_output_end(&handle);
2179 }
2180
2181 static int perf_counter_mmap_match(struct perf_counter *counter,
2182                                    struct perf_mmap_event *mmap_event)
2183 {
2184         if (counter->hw_event.mmap &&
2185             mmap_event->event.header.type == PERF_EVENT_MMAP)
2186                 return 1;
2187
2188         if (counter->hw_event.munmap &&
2189             mmap_event->event.header.type == PERF_EVENT_MUNMAP)
2190                 return 1;
2191
2192         return 0;
2193 }
2194
2195 static void perf_counter_mmap_ctx(struct perf_counter_context *ctx,
2196                                   struct perf_mmap_event *mmap_event)
2197 {
2198         struct perf_counter *counter;
2199
2200         if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
2201                 return;
2202
2203         rcu_read_lock();
2204         list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
2205                 if (perf_counter_mmap_match(counter, mmap_event))
2206                         perf_counter_mmap_output(counter, mmap_event);
2207         }
2208         rcu_read_unlock();
2209 }
2210
2211 static void perf_counter_mmap_event(struct perf_mmap_event *mmap_event)
2212 {
2213         struct perf_cpu_context *cpuctx;
2214         struct file *file = mmap_event->file;
2215         unsigned int size;
2216         char tmp[16];
2217         char *buf = NULL;
2218         char *name;
2219
2220         if (file) {
2221                 buf = kzalloc(PATH_MAX, GFP_KERNEL);
2222                 if (!buf) {
2223                         name = strncpy(tmp, "//enomem", sizeof(tmp));
2224                         goto got_name;
2225                 }
2226                 name = d_path(&file->f_path, buf, PATH_MAX);
2227                 if (IS_ERR(name)) {
2228                         name = strncpy(tmp, "//toolong", sizeof(tmp));
2229                         goto got_name;
2230                 }
2231         } else {
2232                 name = strncpy(tmp, "//anon", sizeof(tmp));
2233                 goto got_name;
2234         }
2235
2236 got_name:
2237         size = ALIGN(strlen(name)+1, sizeof(u64));
2238
2239         mmap_event->file_name = name;
2240         mmap_event->file_size = size;
2241
2242         mmap_event->event.header.size = sizeof(mmap_event->event) + size;
2243
2244         cpuctx = &get_cpu_var(perf_cpu_context);
2245         perf_counter_mmap_ctx(&cpuctx->ctx, mmap_event);
2246         put_cpu_var(perf_cpu_context);
2247
2248         perf_counter_mmap_ctx(&current->perf_counter_ctx, mmap_event);
2249
2250         kfree(buf);
2251 }
2252
2253 void perf_counter_mmap(unsigned long addr, unsigned long len,
2254                        unsigned long pgoff, struct file *file)
2255 {
2256         struct perf_mmap_event mmap_event;
2257
2258         if (!atomic_read(&nr_mmap_tracking))
2259                 return;
2260
2261         mmap_event = (struct perf_mmap_event){
2262                 .file   = file,
2263                 .event  = {
2264                         .header = { .type = PERF_EVENT_MMAP, },
2265                         .pid    = current->group_leader->pid,
2266                         .tid    = current->pid,
2267                         .start  = addr,
2268                         .len    = len,
2269                         .pgoff  = pgoff,
2270                 },
2271         };
2272
2273         perf_counter_mmap_event(&mmap_event);
2274 }
2275
2276 void perf_counter_munmap(unsigned long addr, unsigned long len,
2277                          unsigned long pgoff, struct file *file)
2278 {
2279         struct perf_mmap_event mmap_event;
2280
2281         if (!atomic_read(&nr_munmap_tracking))
2282                 return;
2283
2284         mmap_event = (struct perf_mmap_event){
2285                 .file   = file,
2286                 .event  = {
2287                         .header = { .type = PERF_EVENT_MUNMAP, },
2288                         .pid    = current->group_leader->pid,
2289                         .tid    = current->pid,
2290                         .start  = addr,
2291                         .len    = len,
2292                         .pgoff  = pgoff,
2293                 },
2294         };
2295
2296         perf_counter_mmap_event(&mmap_event);
2297 }
2298
2299 /*
2300  * Generic counter overflow handling.
2301  */
2302
2303 int perf_counter_overflow(struct perf_counter *counter,
2304                           int nmi, struct pt_regs *regs, u64 addr)
2305 {
2306         int events = atomic_read(&counter->event_limit);
2307         int ret = 0;
2308
2309         /*
2310          * XXX event_limit might not quite work as expected on inherited
2311          * counters
2312          */
2313
2314         counter->pending_kill = POLL_IN;
2315         if (events && atomic_dec_and_test(&counter->event_limit)) {
2316                 ret = 1;
2317                 counter->pending_kill = POLL_HUP;
2318                 if (nmi) {
2319                         counter->pending_disable = 1;
2320                         perf_pending_queue(&counter->pending,
2321                                            perf_pending_counter);
2322                 } else
2323                         perf_counter_disable(counter);
2324         }
2325
2326         perf_counter_output(counter, nmi, regs, addr);
2327         return ret;
2328 }
2329
2330 /*
2331  * Generic software counter infrastructure
2332  */
2333
2334 static void perf_swcounter_update(struct perf_counter *counter)
2335 {
2336         struct hw_perf_counter *hwc = &counter->hw;
2337         u64 prev, now;
2338         s64 delta;
2339
2340 again:
2341         prev = atomic64_read(&hwc->prev_count);
2342         now = atomic64_read(&hwc->count);
2343         if (atomic64_cmpxchg(&hwc->prev_count, prev, now) != prev)
2344                 goto again;
2345
2346         delta = now - prev;
2347
2348         atomic64_add(delta, &counter->count);
2349         atomic64_sub(delta, &hwc->period_left);
2350 }
2351
2352 static void perf_swcounter_set_period(struct perf_counter *counter)
2353 {
2354         struct hw_perf_counter *hwc = &counter->hw;
2355         s64 left = atomic64_read(&hwc->period_left);
2356         s64 period = hwc->irq_period;
2357
2358         if (unlikely(left <= -period)) {
2359                 left = period;
2360                 atomic64_set(&hwc->period_left, left);
2361         }
2362
2363         if (unlikely(left <= 0)) {
2364                 left += period;
2365                 atomic64_add(period, &hwc->period_left);
2366         }
2367
2368         atomic64_set(&hwc->prev_count, -left);
2369         atomic64_set(&hwc->count, -left);
2370 }
2371
2372 static enum hrtimer_restart perf_swcounter_hrtimer(struct hrtimer *hrtimer)
2373 {
2374         enum hrtimer_restart ret = HRTIMER_RESTART;
2375         struct perf_counter *counter;
2376         struct pt_regs *regs;
2377
2378         counter = container_of(hrtimer, struct perf_counter, hw.hrtimer);
2379         counter->pmu->read(counter);
2380
2381         regs = get_irq_regs();
2382         /*
2383          * In case we exclude kernel IPs or are somehow not in interrupt
2384          * context, provide the next best thing, the user IP.
2385          */
2386         if ((counter->hw_event.exclude_kernel || !regs) &&
2387                         !counter->hw_event.exclude_user)
2388                 regs = task_pt_regs(current);
2389
2390         if (regs) {
2391                 if (perf_counter_overflow(counter, 0, regs, 0))
2392                         ret = HRTIMER_NORESTART;
2393         }
2394
2395         hrtimer_forward_now(hrtimer, ns_to_ktime(counter->hw.irq_period));
2396
2397         return ret;
2398 }
2399
2400 static void perf_swcounter_overflow(struct perf_counter *counter,
2401                                     int nmi, struct pt_regs *regs, u64 addr)
2402 {
2403         perf_swcounter_update(counter);
2404         perf_swcounter_set_period(counter);
2405         if (perf_counter_overflow(counter, nmi, regs, addr))
2406                 /* soft-disable the counter */
2407                 ;
2408
2409 }
2410
2411 static int perf_swcounter_match(struct perf_counter *counter,
2412                                 enum perf_event_types type,
2413                                 u32 event, struct pt_regs *regs)
2414 {
2415         if (counter->state != PERF_COUNTER_STATE_ACTIVE)
2416                 return 0;
2417
2418         if (perf_event_raw(&counter->hw_event))
2419                 return 0;
2420
2421         if (perf_event_type(&counter->hw_event) != type)
2422                 return 0;
2423
2424         if (perf_event_id(&counter->hw_event) != event)
2425                 return 0;
2426
2427         if (counter->hw_event.exclude_user && user_mode(regs))
2428                 return 0;
2429
2430         if (counter->hw_event.exclude_kernel && !user_mode(regs))
2431                 return 0;
2432
2433         return 1;
2434 }
2435
2436 static void perf_swcounter_add(struct perf_counter *counter, u64 nr,
2437                                int nmi, struct pt_regs *regs, u64 addr)
2438 {
2439         int neg = atomic64_add_negative(nr, &counter->hw.count);
2440         if (counter->hw.irq_period && !neg)
2441                 perf_swcounter_overflow(counter, nmi, regs, addr);
2442 }
2443
2444 static void perf_swcounter_ctx_event(struct perf_counter_context *ctx,
2445                                      enum perf_event_types type, u32 event,
2446                                      u64 nr, int nmi, struct pt_regs *regs,
2447                                      u64 addr)
2448 {
2449         struct perf_counter *counter;
2450
2451         if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
2452                 return;
2453
2454         rcu_read_lock();
2455         list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
2456                 if (perf_swcounter_match(counter, type, event, regs))
2457                         perf_swcounter_add(counter, nr, nmi, regs, addr);
2458         }
2459         rcu_read_unlock();
2460 }
2461
2462 static int *perf_swcounter_recursion_context(struct perf_cpu_context *cpuctx)
2463 {
2464         if (in_nmi())
2465                 return &cpuctx->recursion[3];
2466
2467         if (in_irq())
2468                 return &cpuctx->recursion[2];
2469
2470         if (in_softirq())
2471                 return &cpuctx->recursion[1];
2472
2473         return &cpuctx->recursion[0];
2474 }
2475
2476 static void __perf_swcounter_event(enum perf_event_types type, u32 event,
2477                                    u64 nr, int nmi, struct pt_regs *regs,
2478                                    u64 addr)
2479 {
2480         struct perf_cpu_context *cpuctx = &get_cpu_var(perf_cpu_context);
2481         int *recursion = perf_swcounter_recursion_context(cpuctx);
2482
2483         if (*recursion)
2484                 goto out;
2485
2486         (*recursion)++;
2487         barrier();
2488
2489         perf_swcounter_ctx_event(&cpuctx->ctx, type, event,
2490                                  nr, nmi, regs, addr);
2491         if (cpuctx->task_ctx) {
2492                 perf_swcounter_ctx_event(cpuctx->task_ctx, type, event,
2493                                          nr, nmi, regs, addr);
2494         }
2495
2496         barrier();
2497         (*recursion)--;
2498
2499 out:
2500         put_cpu_var(perf_cpu_context);
2501 }
2502
2503 void
2504 perf_swcounter_event(u32 event, u64 nr, int nmi, struct pt_regs *regs, u64 addr)
2505 {
2506         __perf_swcounter_event(PERF_TYPE_SOFTWARE, event, nr, nmi, regs, addr);
2507 }
2508
2509 static void perf_swcounter_read(struct perf_counter *counter)
2510 {
2511         perf_swcounter_update(counter);
2512 }
2513
2514 static int perf_swcounter_enable(struct perf_counter *counter)
2515 {
2516         perf_swcounter_set_period(counter);
2517         return 0;
2518 }
2519
2520 static void perf_swcounter_disable(struct perf_counter *counter)
2521 {
2522         perf_swcounter_update(counter);
2523 }
2524
2525 static const struct pmu perf_ops_generic = {
2526         .enable         = perf_swcounter_enable,
2527         .disable        = perf_swcounter_disable,
2528         .read           = perf_swcounter_read,
2529 };
2530
2531 /*
2532  * Software counter: cpu wall time clock
2533  */
2534
2535 static void cpu_clock_perf_counter_update(struct perf_counter *counter)
2536 {
2537         int cpu = raw_smp_processor_id();
2538         s64 prev;
2539         u64 now;
2540
2541         now = cpu_clock(cpu);
2542         prev = atomic64_read(&counter->hw.prev_count);
2543         atomic64_set(&counter->hw.prev_count, now);
2544         atomic64_add(now - prev, &counter->count);
2545 }
2546
2547 static int cpu_clock_perf_counter_enable(struct perf_counter *counter)
2548 {
2549         struct hw_perf_counter *hwc = &counter->hw;
2550         int cpu = raw_smp_processor_id();
2551
2552         atomic64_set(&hwc->prev_count, cpu_clock(cpu));
2553         hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2554         hwc->hrtimer.function = perf_swcounter_hrtimer;
2555         if (hwc->irq_period) {
2556                 __hrtimer_start_range_ns(&hwc->hrtimer,
2557                                 ns_to_ktime(hwc->irq_period), 0,
2558                                 HRTIMER_MODE_REL, 0);
2559         }
2560
2561         return 0;
2562 }
2563
2564 static void cpu_clock_perf_counter_disable(struct perf_counter *counter)
2565 {
2566         hrtimer_cancel(&counter->hw.hrtimer);
2567         cpu_clock_perf_counter_update(counter);
2568 }
2569
2570 static void cpu_clock_perf_counter_read(struct perf_counter *counter)
2571 {
2572         cpu_clock_perf_counter_update(counter);
2573 }
2574
2575 static const struct pmu perf_ops_cpu_clock = {
2576         .enable         = cpu_clock_perf_counter_enable,
2577         .disable        = cpu_clock_perf_counter_disable,
2578         .read           = cpu_clock_perf_counter_read,
2579 };
2580
2581 /*
2582  * Software counter: task time clock
2583  */
2584
2585 static void task_clock_perf_counter_update(struct perf_counter *counter, u64 now)
2586 {
2587         u64 prev;
2588         s64 delta;
2589
2590         prev = atomic64_xchg(&counter->hw.prev_count, now);
2591         delta = now - prev;
2592         atomic64_add(delta, &counter->count);
2593 }
2594
2595 static int task_clock_perf_counter_enable(struct perf_counter *counter)
2596 {
2597         struct hw_perf_counter *hwc = &counter->hw;
2598         u64 now;
2599
2600         now = counter->ctx->time;
2601
2602         atomic64_set(&hwc->prev_count, now);
2603         hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2604         hwc->hrtimer.function = perf_swcounter_hrtimer;
2605         if (hwc->irq_period) {
2606                 __hrtimer_start_range_ns(&hwc->hrtimer,
2607                                 ns_to_ktime(hwc->irq_period), 0,
2608                                 HRTIMER_MODE_REL, 0);
2609         }
2610
2611         return 0;
2612 }
2613
2614 static void task_clock_perf_counter_disable(struct perf_counter *counter)
2615 {
2616         hrtimer_cancel(&counter->hw.hrtimer);
2617         task_clock_perf_counter_update(counter, counter->ctx->time);
2618
2619 }
2620
2621 static void task_clock_perf_counter_read(struct perf_counter *counter)
2622 {
2623         u64 time;
2624
2625         if (!in_nmi()) {
2626                 update_context_time(counter->ctx);
2627                 time = counter->ctx->time;
2628         } else {
2629                 u64 now = perf_clock();
2630                 u64 delta = now - counter->ctx->timestamp;
2631                 time = counter->ctx->time + delta;
2632         }
2633
2634         task_clock_perf_counter_update(counter, time);
2635 }
2636
2637 static const struct pmu perf_ops_task_clock = {
2638         .enable         = task_clock_perf_counter_enable,
2639         .disable        = task_clock_perf_counter_disable,
2640         .read           = task_clock_perf_counter_read,
2641 };
2642
2643 /*
2644  * Software counter: cpu migrations
2645  */
2646
2647 static inline u64 get_cpu_migrations(struct perf_counter *counter)
2648 {
2649         struct task_struct *curr = counter->ctx->task;
2650
2651         if (curr)
2652                 return curr->se.nr_migrations;
2653         return cpu_nr_migrations(smp_processor_id());
2654 }
2655
2656 static void cpu_migrations_perf_counter_update(struct perf_counter *counter)
2657 {
2658         u64 prev, now;
2659         s64 delta;
2660
2661         prev = atomic64_read(&counter->hw.prev_count);
2662         now = get_cpu_migrations(counter);
2663
2664         atomic64_set(&counter->hw.prev_count, now);
2665
2666         delta = now - prev;
2667
2668         atomic64_add(delta, &counter->count);
2669 }
2670
2671 static void cpu_migrations_perf_counter_read(struct perf_counter *counter)
2672 {
2673         cpu_migrations_perf_counter_update(counter);
2674 }
2675
2676 static int cpu_migrations_perf_counter_enable(struct perf_counter *counter)
2677 {
2678         if (counter->prev_state <= PERF_COUNTER_STATE_OFF)
2679                 atomic64_set(&counter->hw.prev_count,
2680                              get_cpu_migrations(counter));
2681         return 0;
2682 }
2683
2684 static void cpu_migrations_perf_counter_disable(struct perf_counter *counter)
2685 {
2686         cpu_migrations_perf_counter_update(counter);
2687 }
2688
2689 static const struct pmu perf_ops_cpu_migrations = {
2690         .enable         = cpu_migrations_perf_counter_enable,
2691         .disable        = cpu_migrations_perf_counter_disable,
2692         .read           = cpu_migrations_perf_counter_read,
2693 };
2694
2695 #ifdef CONFIG_EVENT_PROFILE
2696 void perf_tpcounter_event(int event_id)
2697 {
2698         struct pt_regs *regs = get_irq_regs();
2699
2700         if (!regs)
2701                 regs = task_pt_regs(current);
2702
2703         __perf_swcounter_event(PERF_TYPE_TRACEPOINT, event_id, 1, 1, regs, 0);
2704 }
2705 EXPORT_SYMBOL_GPL(perf_tpcounter_event);
2706
2707 extern int ftrace_profile_enable(int);
2708 extern void ftrace_profile_disable(int);
2709
2710 static void tp_perf_counter_destroy(struct perf_counter *counter)
2711 {
2712         ftrace_profile_disable(perf_event_id(&counter->hw_event));
2713 }
2714
2715 static const struct pmu *tp_perf_counter_init(struct perf_counter *counter)
2716 {
2717         int event_id = perf_event_id(&counter->hw_event);
2718         int ret;
2719
2720         ret = ftrace_profile_enable(event_id);
2721         if (ret)
2722                 return NULL;
2723
2724         counter->destroy = tp_perf_counter_destroy;
2725         counter->hw.irq_period = counter->hw_event.irq_period;
2726
2727         return &perf_ops_generic;
2728 }
2729 #else
2730 static const struct pmu *tp_perf_counter_init(struct perf_counter *counter)
2731 {
2732         return NULL;
2733 }
2734 #endif
2735
2736 static const struct pmu *sw_perf_counter_init(struct perf_counter *counter)
2737 {
2738         struct perf_counter_hw_event *hw_event = &counter->hw_event;
2739         const struct pmu *pmu = NULL;
2740         struct hw_perf_counter *hwc = &counter->hw;
2741
2742         /*
2743          * Software counters (currently) can't in general distinguish
2744          * between user, kernel and hypervisor events.
2745          * However, context switches and cpu migrations are considered
2746          * to be kernel events, and page faults are never hypervisor
2747          * events.
2748          */
2749         switch (perf_event_id(&counter->hw_event)) {
2750         case PERF_COUNT_CPU_CLOCK:
2751                 pmu = &perf_ops_cpu_clock;
2752
2753                 if (hw_event->irq_period && hw_event->irq_period < 10000)
2754                         hw_event->irq_period = 10000;
2755                 break;
2756         case PERF_COUNT_TASK_CLOCK:
2757                 /*
2758                  * If the user instantiates this as a per-cpu counter,
2759                  * use the cpu_clock counter instead.
2760                  */
2761                 if (counter->ctx->task)
2762                         pmu = &perf_ops_task_clock;
2763                 else
2764                         pmu = &perf_ops_cpu_clock;
2765
2766                 if (hw_event->irq_period && hw_event->irq_period < 10000)
2767                         hw_event->irq_period = 10000;
2768                 break;
2769         case PERF_COUNT_PAGE_FAULTS:
2770         case PERF_COUNT_PAGE_FAULTS_MIN:
2771         case PERF_COUNT_PAGE_FAULTS_MAJ:
2772         case PERF_COUNT_CONTEXT_SWITCHES:
2773                 pmu = &perf_ops_generic;
2774                 break;
2775         case PERF_COUNT_CPU_MIGRATIONS:
2776                 if (!counter->hw_event.exclude_kernel)
2777                         pmu = &perf_ops_cpu_migrations;
2778                 break;
2779         }
2780
2781         if (pmu)
2782                 hwc->irq_period = hw_event->irq_period;
2783
2784         return pmu;
2785 }
2786
2787 /*
2788  * Allocate and initialize a counter structure
2789  */
2790 static struct perf_counter *
2791 perf_counter_alloc(struct perf_counter_hw_event *hw_event,
2792                    int cpu,
2793                    struct perf_counter_context *ctx,
2794                    struct perf_counter *group_leader,
2795                    gfp_t gfpflags)
2796 {
2797         const struct pmu *pmu;
2798         struct perf_counter *counter;
2799         long err;
2800
2801         counter = kzalloc(sizeof(*counter), gfpflags);
2802         if (!counter)
2803                 return ERR_PTR(-ENOMEM);
2804
2805         /*
2806          * Single counters are their own group leaders, with an
2807          * empty sibling list:
2808          */
2809         if (!group_leader)
2810                 group_leader = counter;
2811
2812         mutex_init(&counter->mutex);
2813         INIT_LIST_HEAD(&counter->list_entry);
2814         INIT_LIST_HEAD(&counter->event_entry);
2815         INIT_LIST_HEAD(&counter->sibling_list);
2816         init_waitqueue_head(&counter->waitq);
2817
2818         mutex_init(&counter->mmap_mutex);
2819
2820         INIT_LIST_HEAD(&counter->child_list);
2821
2822         counter->cpu                    = cpu;
2823         counter->hw_event               = *hw_event;
2824         counter->group_leader           = group_leader;
2825         counter->pmu                    = NULL;
2826         counter->ctx                    = ctx;
2827
2828         counter->state = PERF_COUNTER_STATE_INACTIVE;
2829         if (hw_event->disabled)
2830                 counter->state = PERF_COUNTER_STATE_OFF;
2831
2832         pmu = NULL;
2833
2834         /*
2835          * we currently do not support PERF_RECORD_GROUP on inherited counters
2836          */
2837         if (hw_event->inherit && (hw_event->record_type & PERF_RECORD_GROUP))
2838                 goto done;
2839
2840         if (perf_event_raw(hw_event)) {
2841                 pmu = hw_perf_counter_init(counter);
2842                 goto done;
2843         }
2844
2845         switch (perf_event_type(hw_event)) {
2846         case PERF_TYPE_HARDWARE:
2847                 pmu = hw_perf_counter_init(counter);
2848                 break;
2849
2850         case PERF_TYPE_SOFTWARE:
2851                 pmu = sw_perf_counter_init(counter);
2852                 break;
2853
2854         case PERF_TYPE_TRACEPOINT:
2855                 pmu = tp_perf_counter_init(counter);
2856                 break;
2857         }
2858 done:
2859         err = 0;
2860         if (!pmu)
2861                 err = -EINVAL;
2862         else if (IS_ERR(pmu))
2863                 err = PTR_ERR(pmu);
2864
2865         if (err) {
2866                 kfree(counter);
2867                 return ERR_PTR(err);
2868         }
2869
2870         counter->pmu = pmu;
2871
2872         atomic_inc(&nr_counters);
2873         if (counter->hw_event.mmap)
2874                 atomic_inc(&nr_mmap_tracking);
2875         if (counter->hw_event.munmap)
2876                 atomic_inc(&nr_munmap_tracking);
2877         if (counter->hw_event.comm)
2878                 atomic_inc(&nr_comm_tracking);
2879
2880         return counter;
2881 }
2882
2883 /**
2884  * sys_perf_counter_open - open a performance counter, associate it to a task/cpu
2885  *
2886  * @hw_event_uptr:      event type attributes for monitoring/sampling
2887  * @pid:                target pid
2888  * @cpu:                target cpu
2889  * @group_fd:           group leader counter fd
2890  */
2891 SYSCALL_DEFINE5(perf_counter_open,
2892                 const struct perf_counter_hw_event __user *, hw_event_uptr,
2893                 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
2894 {
2895         struct perf_counter *counter, *group_leader;
2896         struct perf_counter_hw_event hw_event;
2897         struct perf_counter_context *ctx;
2898         struct file *counter_file = NULL;
2899         struct file *group_file = NULL;
2900         int fput_needed = 0;
2901         int fput_needed2 = 0;
2902         int ret;
2903
2904         /* for future expandability... */
2905         if (flags)
2906                 return -EINVAL;
2907
2908         if (copy_from_user(&hw_event, hw_event_uptr, sizeof(hw_event)) != 0)
2909                 return -EFAULT;
2910
2911         /*
2912          * Get the target context (task or percpu):
2913          */
2914         ctx = find_get_context(pid, cpu);
2915         if (IS_ERR(ctx))
2916                 return PTR_ERR(ctx);
2917
2918         /*
2919          * Look up the group leader (we will attach this counter to it):
2920          */
2921         group_leader = NULL;
2922         if (group_fd != -1) {
2923                 ret = -EINVAL;
2924                 group_file = fget_light(group_fd, &fput_needed);
2925                 if (!group_file)
2926                         goto err_put_context;
2927                 if (group_file->f_op != &perf_fops)
2928                         goto err_put_context;
2929
2930                 group_leader = group_file->private_data;
2931                 /*
2932                  * Do not allow a recursive hierarchy (this new sibling
2933                  * becoming part of another group-sibling):
2934                  */
2935                 if (group_leader->group_leader != group_leader)
2936                         goto err_put_context;
2937                 /*
2938                  * Do not allow to attach to a group in a different
2939                  * task or CPU context:
2940                  */
2941                 if (group_leader->ctx != ctx)
2942                         goto err_put_context;
2943                 /*
2944                  * Only a group leader can be exclusive or pinned
2945                  */
2946                 if (hw_event.exclusive || hw_event.pinned)
2947                         goto err_put_context;
2948         }
2949
2950         counter = perf_counter_alloc(&hw_event, cpu, ctx, group_leader,
2951                                      GFP_KERNEL);
2952         ret = PTR_ERR(counter);
2953         if (IS_ERR(counter))
2954                 goto err_put_context;
2955
2956         ret = anon_inode_getfd("[perf_counter]", &perf_fops, counter, 0);
2957         if (ret < 0)
2958                 goto err_free_put_context;
2959
2960         counter_file = fget_light(ret, &fput_needed2);
2961         if (!counter_file)
2962                 goto err_free_put_context;
2963
2964         counter->filp = counter_file;
2965         mutex_lock(&ctx->mutex);
2966         perf_install_in_context(ctx, counter, cpu);
2967         mutex_unlock(&ctx->mutex);
2968
2969         fput_light(counter_file, fput_needed2);
2970
2971 out_fput:
2972         fput_light(group_file, fput_needed);
2973
2974         return ret;
2975
2976 err_free_put_context:
2977         kfree(counter);
2978
2979 err_put_context:
2980         put_context(ctx);
2981
2982         goto out_fput;
2983 }
2984
2985 /*
2986  * Initialize the perf_counter context in a task_struct:
2987  */
2988 static void
2989 __perf_counter_init_context(struct perf_counter_context *ctx,
2990                             struct task_struct *task)
2991 {
2992         memset(ctx, 0, sizeof(*ctx));
2993         spin_lock_init(&ctx->lock);
2994         mutex_init(&ctx->mutex);
2995         INIT_LIST_HEAD(&ctx->counter_list);
2996         INIT_LIST_HEAD(&ctx->event_list);
2997         ctx->task = task;
2998 }
2999
3000 /*
3001  * inherit a counter from parent task to child task:
3002  */
3003 static struct perf_counter *
3004 inherit_counter(struct perf_counter *parent_counter,
3005               struct task_struct *parent,
3006               struct perf_counter_context *parent_ctx,
3007               struct task_struct *child,
3008               struct perf_counter *group_leader,
3009               struct perf_counter_context *child_ctx)
3010 {
3011         struct perf_counter *child_counter;
3012
3013         /*
3014          * Instead of creating recursive hierarchies of counters,
3015          * we link inherited counters back to the original parent,
3016          * which has a filp for sure, which we use as the reference
3017          * count:
3018          */
3019         if (parent_counter->parent)
3020                 parent_counter = parent_counter->parent;
3021
3022         child_counter = perf_counter_alloc(&parent_counter->hw_event,
3023                                            parent_counter->cpu, child_ctx,
3024                                            group_leader, GFP_KERNEL);
3025         if (IS_ERR(child_counter))
3026                 return child_counter;
3027
3028         /*
3029          * Link it up in the child's context:
3030          */
3031         child_counter->task = child;
3032         add_counter_to_ctx(child_counter, child_ctx);
3033
3034         child_counter->parent = parent_counter;
3035         /*
3036          * inherit into child's child as well:
3037          */
3038         child_counter->hw_event.inherit = 1;
3039
3040         /*
3041          * Get a reference to the parent filp - we will fput it
3042          * when the child counter exits. This is safe to do because
3043          * we are in the parent and we know that the filp still
3044          * exists and has a nonzero count:
3045          */
3046         atomic_long_inc(&parent_counter->filp->f_count);
3047
3048         /*
3049          * Link this into the parent counter's child list
3050          */
3051         mutex_lock(&parent_counter->mutex);
3052         list_add_tail(&child_counter->child_list, &parent_counter->child_list);
3053
3054         /*
3055          * Make the child state follow the state of the parent counter,
3056          * not its hw_event.disabled bit.  We hold the parent's mutex,
3057          * so we won't race with perf_counter_{en,dis}able_family.
3058          */
3059         if (parent_counter->state >= PERF_COUNTER_STATE_INACTIVE)
3060                 child_counter->state = PERF_COUNTER_STATE_INACTIVE;
3061         else
3062                 child_counter->state = PERF_COUNTER_STATE_OFF;
3063
3064         mutex_unlock(&parent_counter->mutex);
3065
3066         return child_counter;
3067 }
3068
3069 static int inherit_group(struct perf_counter *parent_counter,
3070               struct task_struct *parent,
3071               struct perf_counter_context *parent_ctx,
3072               struct task_struct *child,
3073               struct perf_counter_context *child_ctx)
3074 {
3075         struct perf_counter *leader;
3076         struct perf_counter *sub;
3077         struct perf_counter *child_ctr;
3078
3079         leader = inherit_counter(parent_counter, parent, parent_ctx,
3080                                  child, NULL, child_ctx);
3081         if (IS_ERR(leader))
3082                 return PTR_ERR(leader);
3083         list_for_each_entry(sub, &parent_counter->sibling_list, list_entry) {
3084                 child_ctr = inherit_counter(sub, parent, parent_ctx,
3085                                             child, leader, child_ctx);
3086                 if (IS_ERR(child_ctr))
3087                         return PTR_ERR(child_ctr);
3088         }
3089         return 0;
3090 }
3091
3092 static void sync_child_counter(struct perf_counter *child_counter,
3093                                struct perf_counter *parent_counter)
3094 {
3095         u64 parent_val, child_val;
3096
3097         parent_val = atomic64_read(&parent_counter->count);
3098         child_val = atomic64_read(&child_counter->count);
3099
3100         /*
3101          * Add back the child's count to the parent's count:
3102          */
3103         atomic64_add(child_val, &parent_counter->count);
3104         atomic64_add(child_counter->total_time_enabled,
3105                      &parent_counter->child_total_time_enabled);
3106         atomic64_add(child_counter->total_time_running,
3107                      &parent_counter->child_total_time_running);
3108
3109         /*
3110          * Remove this counter from the parent's list
3111          */
3112         mutex_lock(&parent_counter->mutex);
3113         list_del_init(&child_counter->child_list);
3114         mutex_unlock(&parent_counter->mutex);
3115
3116         /*
3117          * Release the parent counter, if this was the last
3118          * reference to it.
3119          */
3120         fput(parent_counter->filp);
3121 }
3122
3123 static void
3124 __perf_counter_exit_task(struct task_struct *child,
3125                          struct perf_counter *child_counter,
3126                          struct perf_counter_context *child_ctx)
3127 {
3128         struct perf_counter *parent_counter;
3129         struct perf_counter *sub, *tmp;
3130
3131         /*
3132          * If we do not self-reap then we have to wait for the
3133          * child task to unschedule (it will happen for sure),
3134          * so that its counter is at its final count. (This
3135          * condition triggers rarely - child tasks usually get
3136          * off their CPU before the parent has a chance to
3137          * get this far into the reaping action)
3138          */
3139         if (child != current) {
3140                 wait_task_inactive(child, 0);
3141                 list_del_init(&child_counter->list_entry);
3142                 update_counter_times(child_counter);
3143         } else {
3144                 struct perf_cpu_context *cpuctx;
3145                 unsigned long flags;
3146                 u64 perf_flags;
3147
3148                 /*
3149                  * Disable and unlink this counter.
3150                  *
3151                  * Be careful about zapping the list - IRQ/NMI context
3152                  * could still be processing it:
3153                  */
3154                 local_irq_save(flags);
3155                 perf_flags = hw_perf_save_disable();
3156
3157                 cpuctx = &__get_cpu_var(perf_cpu_context);
3158
3159                 group_sched_out(child_counter, cpuctx, child_ctx);
3160                 update_counter_times(child_counter);
3161
3162                 list_del_init(&child_counter->list_entry);
3163
3164                 child_ctx->nr_counters--;
3165
3166                 hw_perf_restore(perf_flags);
3167                 local_irq_restore(flags);
3168         }
3169
3170         parent_counter = child_counter->parent;
3171         /*
3172          * It can happen that parent exits first, and has counters
3173          * that are still around due to the child reference. These
3174          * counters need to be zapped - but otherwise linger.
3175          */
3176         if (parent_counter) {
3177                 sync_child_counter(child_counter, parent_counter);
3178                 list_for_each_entry_safe(sub, tmp, &child_counter->sibling_list,
3179                                          list_entry) {
3180                         if (sub->parent) {
3181                                 sync_child_counter(sub, sub->parent);
3182                                 free_counter(sub);
3183                         }
3184                 }
3185                 free_counter(child_counter);
3186         }
3187 }
3188
3189 /*
3190  * When a child task exits, feed back counter values to parent counters.
3191  *
3192  * Note: we may be running in child context, but the PID is not hashed
3193  * anymore so new counters will not be added.
3194  */
3195 void perf_counter_exit_task(struct task_struct *child)
3196 {
3197         struct perf_counter *child_counter, *tmp;
3198         struct perf_counter_context *child_ctx;
3199
3200         child_ctx = &child->perf_counter_ctx;
3201
3202         if (likely(!child_ctx->nr_counters))
3203                 return;
3204
3205         list_for_each_entry_safe(child_counter, tmp, &child_ctx->counter_list,
3206                                  list_entry)
3207                 __perf_counter_exit_task(child, child_counter, child_ctx);
3208 }
3209
3210 /*
3211  * Initialize the perf_counter context in task_struct
3212  */
3213 void perf_counter_init_task(struct task_struct *child)
3214 {
3215         struct perf_counter_context *child_ctx, *parent_ctx;
3216         struct perf_counter *counter;
3217         struct task_struct *parent = current;
3218
3219         child_ctx  =  &child->perf_counter_ctx;
3220         parent_ctx = &parent->perf_counter_ctx;
3221
3222         __perf_counter_init_context(child_ctx, child);
3223
3224         /*
3225          * This is executed from the parent task context, so inherit
3226          * counters that have been marked for cloning:
3227          */
3228
3229         if (likely(!parent_ctx->nr_counters))
3230                 return;
3231
3232         /*
3233          * Lock the parent list. No need to lock the child - not PID
3234          * hashed yet and not running, so nobody can access it.
3235          */
3236         mutex_lock(&parent_ctx->mutex);
3237
3238         /*
3239          * We dont have to disable NMIs - we are only looking at
3240          * the list, not manipulating it:
3241          */
3242         list_for_each_entry(counter, &parent_ctx->counter_list, list_entry) {
3243                 if (!counter->hw_event.inherit)
3244                         continue;
3245
3246                 if (inherit_group(counter, parent,
3247                                   parent_ctx, child, child_ctx))
3248                         break;
3249         }
3250
3251         mutex_unlock(&parent_ctx->mutex);
3252 }
3253
3254 static void __cpuinit perf_counter_init_cpu(int cpu)
3255 {
3256         struct perf_cpu_context *cpuctx;
3257
3258         cpuctx = &per_cpu(perf_cpu_context, cpu);
3259         __perf_counter_init_context(&cpuctx->ctx, NULL);
3260
3261         spin_lock(&perf_resource_lock);
3262         cpuctx->max_pertask = perf_max_counters - perf_reserved_percpu;
3263         spin_unlock(&perf_resource_lock);
3264
3265         hw_perf_counter_setup(cpu);
3266 }
3267
3268 #ifdef CONFIG_HOTPLUG_CPU
3269 static void __perf_counter_exit_cpu(void *info)
3270 {
3271         struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
3272         struct perf_counter_context *ctx = &cpuctx->ctx;
3273         struct perf_counter *counter, *tmp;
3274
3275         list_for_each_entry_safe(counter, tmp, &ctx->counter_list, list_entry)
3276                 __perf_counter_remove_from_context(counter);
3277 }
3278 static void perf_counter_exit_cpu(int cpu)
3279 {
3280         struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
3281         struct perf_counter_context *ctx = &cpuctx->ctx;
3282
3283         mutex_lock(&ctx->mutex);
3284         smp_call_function_single(cpu, __perf_counter_exit_cpu, NULL, 1);
3285         mutex_unlock(&ctx->mutex);
3286 }
3287 #else
3288 static inline void perf_counter_exit_cpu(int cpu) { }
3289 #endif
3290
3291 static int __cpuinit
3292 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
3293 {
3294         unsigned int cpu = (long)hcpu;
3295
3296         switch (action) {
3297
3298         case CPU_UP_PREPARE:
3299         case CPU_UP_PREPARE_FROZEN:
3300                 perf_counter_init_cpu(cpu);
3301                 break;
3302
3303         case CPU_DOWN_PREPARE:
3304         case CPU_DOWN_PREPARE_FROZEN:
3305                 perf_counter_exit_cpu(cpu);
3306                 break;
3307
3308         default:
3309                 break;
3310         }
3311
3312         return NOTIFY_OK;
3313 }
3314
3315 static struct notifier_block __cpuinitdata perf_cpu_nb = {
3316         .notifier_call          = perf_cpu_notify,
3317 };
3318
3319 void __init perf_counter_init(void)
3320 {
3321         perf_cpu_notify(&perf_cpu_nb, (unsigned long)CPU_UP_PREPARE,
3322                         (void *)(long)smp_processor_id());
3323         register_cpu_notifier(&perf_cpu_nb);
3324 }
3325
3326 static ssize_t perf_show_reserve_percpu(struct sysdev_class *class, char *buf)
3327 {
3328         return sprintf(buf, "%d\n", perf_reserved_percpu);
3329 }
3330
3331 static ssize_t
3332 perf_set_reserve_percpu(struct sysdev_class *class,
3333                         const char *buf,
3334                         size_t count)
3335 {
3336         struct perf_cpu_context *cpuctx;
3337         unsigned long val;
3338         int err, cpu, mpt;
3339
3340         err = strict_strtoul(buf, 10, &val);
3341         if (err)
3342                 return err;
3343         if (val > perf_max_counters)
3344                 return -EINVAL;
3345
3346         spin_lock(&perf_resource_lock);
3347         perf_reserved_percpu = val;
3348         for_each_online_cpu(cpu) {
3349                 cpuctx = &per_cpu(perf_cpu_context, cpu);
3350                 spin_lock_irq(&cpuctx->ctx.lock);
3351                 mpt = min(perf_max_counters - cpuctx->ctx.nr_counters,
3352                           perf_max_counters - perf_reserved_percpu);
3353                 cpuctx->max_pertask = mpt;
3354                 spin_unlock_irq(&cpuctx->ctx.lock);
3355         }
3356         spin_unlock(&perf_resource_lock);
3357
3358         return count;
3359 }
3360
3361 static ssize_t perf_show_overcommit(struct sysdev_class *class, char *buf)
3362 {
3363         return sprintf(buf, "%d\n", perf_overcommit);
3364 }
3365
3366 static ssize_t
3367 perf_set_overcommit(struct sysdev_class *class, const char *buf, size_t count)
3368 {
3369         unsigned long val;
3370         int err;
3371
3372         err = strict_strtoul(buf, 10, &val);
3373         if (err)
3374                 return err;
3375         if (val > 1)
3376                 return -EINVAL;
3377
3378         spin_lock(&perf_resource_lock);
3379         perf_overcommit = val;
3380         spin_unlock(&perf_resource_lock);
3381
3382         return count;
3383 }
3384
3385 static SYSDEV_CLASS_ATTR(
3386                                 reserve_percpu,
3387                                 0644,
3388                                 perf_show_reserve_percpu,
3389                                 perf_set_reserve_percpu
3390                         );
3391
3392 static SYSDEV_CLASS_ATTR(
3393                                 overcommit,
3394                                 0644,
3395                                 perf_show_overcommit,
3396                                 perf_set_overcommit
3397                         );
3398
3399 static struct attribute *perfclass_attrs[] = {
3400         &attr_reserve_percpu.attr,
3401         &attr_overcommit.attr,
3402         NULL
3403 };
3404
3405 static struct attribute_group perfclass_attr_group = {
3406         .attrs                  = perfclass_attrs,
3407         .name                   = "perf_counters",
3408 };
3409
3410 static int __init perf_counter_sysfs_init(void)
3411 {
3412         return sysfs_create_group(&cpu_sysdev_class.kset.kobj,
3413                                   &perfclass_attr_group);
3414 }
3415 device_initcall(perf_counter_sysfs_init);