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