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