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