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