perf_counter: Provide hw_perf_counter_setup_online() APIs
[pandora-kernel.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/dcache.h>
20 #include <linux/percpu.h>
21 #include <linux/ptrace.h>
22 #include <linux/vmstat.h>
23 #include <linux/hardirq.h>
24 #include <linux/rculist.h>
25 #include <linux/uaccess.h>
26 #include <linux/syscalls.h>
27 #include <linux/anon_inodes.h>
28 #include <linux/kernel_stat.h>
29 #include <linux/perf_counter.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_counters __read_mostly;
44 static atomic_t nr_comm_counters __read_mostly;
45 static atomic_t nr_task_counters __read_mostly;
46
47 /*
48  * perf counter paranoia level:
49  *  0 - not paranoid
50  *  1 - disallow cpu counters to unpriv
51  *  2 - disallow kernel profiling to unpriv
52  */
53 int sysctl_perf_counter_paranoid __read_mostly;
54
55 static inline bool perf_paranoid_cpu(void)
56 {
57         return sysctl_perf_counter_paranoid > 0;
58 }
59
60 static inline bool perf_paranoid_kernel(void)
61 {
62         return sysctl_perf_counter_paranoid > 1;
63 }
64
65 int sysctl_perf_counter_mlock __read_mostly = 512; /* 'free' kb per user */
66
67 /*
68  * max perf counter sample rate
69  */
70 int sysctl_perf_counter_sample_rate __read_mostly = 100000;
71
72 static atomic64_t perf_counter_id;
73
74 /*
75  * Lock for (sysadmin-configurable) counter reservations:
76  */
77 static DEFINE_SPINLOCK(perf_resource_lock);
78
79 /*
80  * Architecture provided APIs - weak aliases:
81  */
82 extern __weak const struct pmu *hw_perf_counter_init(struct perf_counter *counter)
83 {
84         return NULL;
85 }
86
87 void __weak hw_perf_disable(void)               { barrier(); }
88 void __weak hw_perf_enable(void)                { barrier(); }
89
90 void __weak hw_perf_counter_setup(int cpu)      { barrier(); }
91 void __weak hw_perf_counter_setup_online(int cpu)       { barrier(); }
92
93 int __weak
94 hw_perf_group_sched_in(struct perf_counter *group_leader,
95                struct perf_cpu_context *cpuctx,
96                struct perf_counter_context *ctx, int cpu)
97 {
98         return 0;
99 }
100
101 void __weak perf_counter_print_debug(void)      { }
102
103 static DEFINE_PER_CPU(int, disable_count);
104
105 void __perf_disable(void)
106 {
107         __get_cpu_var(disable_count)++;
108 }
109
110 bool __perf_enable(void)
111 {
112         return !--__get_cpu_var(disable_count);
113 }
114
115 void perf_disable(void)
116 {
117         __perf_disable();
118         hw_perf_disable();
119 }
120
121 void perf_enable(void)
122 {
123         if (__perf_enable())
124                 hw_perf_enable();
125 }
126
127 static void get_ctx(struct perf_counter_context *ctx)
128 {
129         WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
130 }
131
132 static void free_ctx(struct rcu_head *head)
133 {
134         struct perf_counter_context *ctx;
135
136         ctx = container_of(head, struct perf_counter_context, rcu_head);
137         kfree(ctx);
138 }
139
140 static void put_ctx(struct perf_counter_context *ctx)
141 {
142         if (atomic_dec_and_test(&ctx->refcount)) {
143                 if (ctx->parent_ctx)
144                         put_ctx(ctx->parent_ctx);
145                 if (ctx->task)
146                         put_task_struct(ctx->task);
147                 call_rcu(&ctx->rcu_head, free_ctx);
148         }
149 }
150
151 static void unclone_ctx(struct perf_counter_context *ctx)
152 {
153         if (ctx->parent_ctx) {
154                 put_ctx(ctx->parent_ctx);
155                 ctx->parent_ctx = NULL;
156         }
157 }
158
159 /*
160  * If we inherit counters we want to return the parent counter id
161  * to userspace.
162  */
163 static u64 primary_counter_id(struct perf_counter *counter)
164 {
165         u64 id = counter->id;
166
167         if (counter->parent)
168                 id = counter->parent->id;
169
170         return id;
171 }
172
173 /*
174  * Get the perf_counter_context for a task and lock it.
175  * This has to cope with with the fact that until it is locked,
176  * the context could get moved to another task.
177  */
178 static struct perf_counter_context *
179 perf_lock_task_context(struct task_struct *task, unsigned long *flags)
180 {
181         struct perf_counter_context *ctx;
182
183         rcu_read_lock();
184  retry:
185         ctx = rcu_dereference(task->perf_counter_ctxp);
186         if (ctx) {
187                 /*
188                  * If this context is a clone of another, it might
189                  * get swapped for another underneath us by
190                  * perf_counter_task_sched_out, though the
191                  * rcu_read_lock() protects us from any context
192                  * getting freed.  Lock the context and check if it
193                  * got swapped before we could get the lock, and retry
194                  * if so.  If we locked the right context, then it
195                  * can't get swapped on us any more.
196                  */
197                 spin_lock_irqsave(&ctx->lock, *flags);
198                 if (ctx != rcu_dereference(task->perf_counter_ctxp)) {
199                         spin_unlock_irqrestore(&ctx->lock, *flags);
200                         goto retry;
201                 }
202
203                 if (!atomic_inc_not_zero(&ctx->refcount)) {
204                         spin_unlock_irqrestore(&ctx->lock, *flags);
205                         ctx = NULL;
206                 }
207         }
208         rcu_read_unlock();
209         return ctx;
210 }
211
212 /*
213  * Get the context for a task and increment its pin_count so it
214  * can't get swapped to another task.  This also increments its
215  * reference count so that the context can't get freed.
216  */
217 static struct perf_counter_context *perf_pin_task_context(struct task_struct *task)
218 {
219         struct perf_counter_context *ctx;
220         unsigned long flags;
221
222         ctx = perf_lock_task_context(task, &flags);
223         if (ctx) {
224                 ++ctx->pin_count;
225                 spin_unlock_irqrestore(&ctx->lock, flags);
226         }
227         return ctx;
228 }
229
230 static void perf_unpin_context(struct perf_counter_context *ctx)
231 {
232         unsigned long flags;
233
234         spin_lock_irqsave(&ctx->lock, flags);
235         --ctx->pin_count;
236         spin_unlock_irqrestore(&ctx->lock, flags);
237         put_ctx(ctx);
238 }
239
240 /*
241  * Add a counter from the lists for its context.
242  * Must be called with ctx->mutex and ctx->lock held.
243  */
244 static void
245 list_add_counter(struct perf_counter *counter, struct perf_counter_context *ctx)
246 {
247         struct perf_counter *group_leader = counter->group_leader;
248
249         /*
250          * Depending on whether it is a standalone or sibling counter,
251          * add it straight to the context's counter list, or to the group
252          * leader's sibling list:
253          */
254         if (group_leader == counter)
255                 list_add_tail(&counter->list_entry, &ctx->counter_list);
256         else {
257                 list_add_tail(&counter->list_entry, &group_leader->sibling_list);
258                 group_leader->nr_siblings++;
259         }
260
261         list_add_rcu(&counter->event_entry, &ctx->event_list);
262         ctx->nr_counters++;
263         if (counter->attr.inherit_stat)
264                 ctx->nr_stat++;
265 }
266
267 /*
268  * Remove a counter from the lists for its context.
269  * Must be called with ctx->mutex and ctx->lock held.
270  */
271 static void
272 list_del_counter(struct perf_counter *counter, struct perf_counter_context *ctx)
273 {
274         struct perf_counter *sibling, *tmp;
275
276         if (list_empty(&counter->list_entry))
277                 return;
278         ctx->nr_counters--;
279         if (counter->attr.inherit_stat)
280                 ctx->nr_stat--;
281
282         list_del_init(&counter->list_entry);
283         list_del_rcu(&counter->event_entry);
284
285         if (counter->group_leader != counter)
286                 counter->group_leader->nr_siblings--;
287
288         /*
289          * If this was a group counter with sibling counters then
290          * upgrade the siblings to singleton counters by adding them
291          * to the context list directly:
292          */
293         list_for_each_entry_safe(sibling, tmp,
294                                  &counter->sibling_list, list_entry) {
295
296                 list_move_tail(&sibling->list_entry, &ctx->counter_list);
297                 sibling->group_leader = sibling;
298         }
299 }
300
301 static void
302 counter_sched_out(struct perf_counter *counter,
303                   struct perf_cpu_context *cpuctx,
304                   struct perf_counter_context *ctx)
305 {
306         if (counter->state != PERF_COUNTER_STATE_ACTIVE)
307                 return;
308
309         counter->state = PERF_COUNTER_STATE_INACTIVE;
310         counter->tstamp_stopped = ctx->time;
311         counter->pmu->disable(counter);
312         counter->oncpu = -1;
313
314         if (!is_software_counter(counter))
315                 cpuctx->active_oncpu--;
316         ctx->nr_active--;
317         if (counter->attr.exclusive || !cpuctx->active_oncpu)
318                 cpuctx->exclusive = 0;
319 }
320
321 static void
322 group_sched_out(struct perf_counter *group_counter,
323                 struct perf_cpu_context *cpuctx,
324                 struct perf_counter_context *ctx)
325 {
326         struct perf_counter *counter;
327
328         if (group_counter->state != PERF_COUNTER_STATE_ACTIVE)
329                 return;
330
331         counter_sched_out(group_counter, cpuctx, ctx);
332
333         /*
334          * Schedule out siblings (if any):
335          */
336         list_for_each_entry(counter, &group_counter->sibling_list, list_entry)
337                 counter_sched_out(counter, cpuctx, ctx);
338
339         if (group_counter->attr.exclusive)
340                 cpuctx->exclusive = 0;
341 }
342
343 /*
344  * Cross CPU call to remove a performance counter
345  *
346  * We disable the counter on the hardware level first. After that we
347  * remove it from the context list.
348  */
349 static void __perf_counter_remove_from_context(void *info)
350 {
351         struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
352         struct perf_counter *counter = info;
353         struct perf_counter_context *ctx = counter->ctx;
354
355         /*
356          * If this is a task context, we need to check whether it is
357          * the current task context of this cpu. If not it has been
358          * scheduled out before the smp call arrived.
359          */
360         if (ctx->task && cpuctx->task_ctx != ctx)
361                 return;
362
363         spin_lock(&ctx->lock);
364         /*
365          * Protect the list operation against NMI by disabling the
366          * counters on a global level.
367          */
368         perf_disable();
369
370         counter_sched_out(counter, cpuctx, ctx);
371
372         list_del_counter(counter, ctx);
373
374         if (!ctx->task) {
375                 /*
376                  * Allow more per task counters with respect to the
377                  * reservation:
378                  */
379                 cpuctx->max_pertask =
380                         min(perf_max_counters - ctx->nr_counters,
381                             perf_max_counters - perf_reserved_percpu);
382         }
383
384         perf_enable();
385         spin_unlock(&ctx->lock);
386 }
387
388
389 /*
390  * Remove the counter from a task's (or a CPU's) list of counters.
391  *
392  * Must be called with ctx->mutex held.
393  *
394  * CPU counters are removed with a smp call. For task counters we only
395  * call when the task is on a CPU.
396  *
397  * If counter->ctx is a cloned context, callers must make sure that
398  * every task struct that counter->ctx->task could possibly point to
399  * remains valid.  This is OK when called from perf_release since
400  * that only calls us on the top-level context, which can't be a clone.
401  * When called from perf_counter_exit_task, it's OK because the
402  * context has been detached from its task.
403  */
404 static void perf_counter_remove_from_context(struct perf_counter *counter)
405 {
406         struct perf_counter_context *ctx = counter->ctx;
407         struct task_struct *task = ctx->task;
408
409         if (!task) {
410                 /*
411                  * Per cpu counters are removed via an smp call and
412                  * the removal is always sucessful.
413                  */
414                 smp_call_function_single(counter->cpu,
415                                          __perf_counter_remove_from_context,
416                                          counter, 1);
417                 return;
418         }
419
420 retry:
421         task_oncpu_function_call(task, __perf_counter_remove_from_context,
422                                  counter);
423
424         spin_lock_irq(&ctx->lock);
425         /*
426          * If the context is active we need to retry the smp call.
427          */
428         if (ctx->nr_active && !list_empty(&counter->list_entry)) {
429                 spin_unlock_irq(&ctx->lock);
430                 goto retry;
431         }
432
433         /*
434          * The lock prevents that this context is scheduled in so we
435          * can remove the counter safely, if the call above did not
436          * succeed.
437          */
438         if (!list_empty(&counter->list_entry)) {
439                 list_del_counter(counter, ctx);
440         }
441         spin_unlock_irq(&ctx->lock);
442 }
443
444 static inline u64 perf_clock(void)
445 {
446         return cpu_clock(smp_processor_id());
447 }
448
449 /*
450  * Update the record of the current time in a context.
451  */
452 static void update_context_time(struct perf_counter_context *ctx)
453 {
454         u64 now = perf_clock();
455
456         ctx->time += now - ctx->timestamp;
457         ctx->timestamp = now;
458 }
459
460 /*
461  * Update the total_time_enabled and total_time_running fields for a counter.
462  */
463 static void update_counter_times(struct perf_counter *counter)
464 {
465         struct perf_counter_context *ctx = counter->ctx;
466         u64 run_end;
467
468         if (counter->state < PERF_COUNTER_STATE_INACTIVE)
469                 return;
470
471         counter->total_time_enabled = ctx->time - counter->tstamp_enabled;
472
473         if (counter->state == PERF_COUNTER_STATE_INACTIVE)
474                 run_end = counter->tstamp_stopped;
475         else
476                 run_end = ctx->time;
477
478         counter->total_time_running = run_end - counter->tstamp_running;
479 }
480
481 /*
482  * Update total_time_enabled and total_time_running for all counters in a group.
483  */
484 static void update_group_times(struct perf_counter *leader)
485 {
486         struct perf_counter *counter;
487
488         update_counter_times(leader);
489         list_for_each_entry(counter, &leader->sibling_list, list_entry)
490                 update_counter_times(counter);
491 }
492
493 /*
494  * Cross CPU call to disable a performance counter
495  */
496 static void __perf_counter_disable(void *info)
497 {
498         struct perf_counter *counter = info;
499         struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
500         struct perf_counter_context *ctx = counter->ctx;
501
502         /*
503          * If this is a per-task counter, need to check whether this
504          * counter's task is the current task on this cpu.
505          */
506         if (ctx->task && cpuctx->task_ctx != ctx)
507                 return;
508
509         spin_lock(&ctx->lock);
510
511         /*
512          * If the counter is on, turn it off.
513          * If it is in error state, leave it in error state.
514          */
515         if (counter->state >= PERF_COUNTER_STATE_INACTIVE) {
516                 update_context_time(ctx);
517                 update_counter_times(counter);
518                 if (counter == counter->group_leader)
519                         group_sched_out(counter, cpuctx, ctx);
520                 else
521                         counter_sched_out(counter, cpuctx, ctx);
522                 counter->state = PERF_COUNTER_STATE_OFF;
523         }
524
525         spin_unlock(&ctx->lock);
526 }
527
528 /*
529  * Disable a counter.
530  *
531  * If counter->ctx is a cloned context, callers must make sure that
532  * every task struct that counter->ctx->task could possibly point to
533  * remains valid.  This condition is satisifed when called through
534  * perf_counter_for_each_child or perf_counter_for_each because they
535  * hold the top-level counter's child_mutex, so any descendant that
536  * goes to exit will block in sync_child_counter.
537  * When called from perf_pending_counter it's OK because counter->ctx
538  * is the current context on this CPU and preemption is disabled,
539  * hence we can't get into perf_counter_task_sched_out for this context.
540  */
541 static void perf_counter_disable(struct perf_counter *counter)
542 {
543         struct perf_counter_context *ctx = counter->ctx;
544         struct task_struct *task = ctx->task;
545
546         if (!task) {
547                 /*
548                  * Disable the counter on the cpu that it's on
549                  */
550                 smp_call_function_single(counter->cpu, __perf_counter_disable,
551                                          counter, 1);
552                 return;
553         }
554
555  retry:
556         task_oncpu_function_call(task, __perf_counter_disable, counter);
557
558         spin_lock_irq(&ctx->lock);
559         /*
560          * If the counter is still active, we need to retry the cross-call.
561          */
562         if (counter->state == PERF_COUNTER_STATE_ACTIVE) {
563                 spin_unlock_irq(&ctx->lock);
564                 goto retry;
565         }
566
567         /*
568          * Since we have the lock this context can't be scheduled
569          * in, so we can change the state safely.
570          */
571         if (counter->state == PERF_COUNTER_STATE_INACTIVE) {
572                 update_counter_times(counter);
573                 counter->state = PERF_COUNTER_STATE_OFF;
574         }
575
576         spin_unlock_irq(&ctx->lock);
577 }
578
579 static int
580 counter_sched_in(struct perf_counter *counter,
581                  struct perf_cpu_context *cpuctx,
582                  struct perf_counter_context *ctx,
583                  int cpu)
584 {
585         if (counter->state <= PERF_COUNTER_STATE_OFF)
586                 return 0;
587
588         counter->state = PERF_COUNTER_STATE_ACTIVE;
589         counter->oncpu = cpu;   /* TODO: put 'cpu' into cpuctx->cpu */
590         /*
591          * The new state must be visible before we turn it on in the hardware:
592          */
593         smp_wmb();
594
595         if (counter->pmu->enable(counter)) {
596                 counter->state = PERF_COUNTER_STATE_INACTIVE;
597                 counter->oncpu = -1;
598                 return -EAGAIN;
599         }
600
601         counter->tstamp_running += ctx->time - counter->tstamp_stopped;
602
603         if (!is_software_counter(counter))
604                 cpuctx->active_oncpu++;
605         ctx->nr_active++;
606
607         if (counter->attr.exclusive)
608                 cpuctx->exclusive = 1;
609
610         return 0;
611 }
612
613 static int
614 group_sched_in(struct perf_counter *group_counter,
615                struct perf_cpu_context *cpuctx,
616                struct perf_counter_context *ctx,
617                int cpu)
618 {
619         struct perf_counter *counter, *partial_group;
620         int ret;
621
622         if (group_counter->state == PERF_COUNTER_STATE_OFF)
623                 return 0;
624
625         ret = hw_perf_group_sched_in(group_counter, cpuctx, ctx, cpu);
626         if (ret)
627                 return ret < 0 ? ret : 0;
628
629         if (counter_sched_in(group_counter, cpuctx, ctx, cpu))
630                 return -EAGAIN;
631
632         /*
633          * Schedule in siblings as one group (if any):
634          */
635         list_for_each_entry(counter, &group_counter->sibling_list, list_entry) {
636                 if (counter_sched_in(counter, cpuctx, ctx, cpu)) {
637                         partial_group = counter;
638                         goto group_error;
639                 }
640         }
641
642         return 0;
643
644 group_error:
645         /*
646          * Groups can be scheduled in as one unit only, so undo any
647          * partial group before returning:
648          */
649         list_for_each_entry(counter, &group_counter->sibling_list, list_entry) {
650                 if (counter == partial_group)
651                         break;
652                 counter_sched_out(counter, cpuctx, ctx);
653         }
654         counter_sched_out(group_counter, cpuctx, ctx);
655
656         return -EAGAIN;
657 }
658
659 /*
660  * Return 1 for a group consisting entirely of software counters,
661  * 0 if the group contains any hardware counters.
662  */
663 static int is_software_only_group(struct perf_counter *leader)
664 {
665         struct perf_counter *counter;
666
667         if (!is_software_counter(leader))
668                 return 0;
669
670         list_for_each_entry(counter, &leader->sibling_list, list_entry)
671                 if (!is_software_counter(counter))
672                         return 0;
673
674         return 1;
675 }
676
677 /*
678  * Work out whether we can put this counter group on the CPU now.
679  */
680 static int group_can_go_on(struct perf_counter *counter,
681                            struct perf_cpu_context *cpuctx,
682                            int can_add_hw)
683 {
684         /*
685          * Groups consisting entirely of software counters can always go on.
686          */
687         if (is_software_only_group(counter))
688                 return 1;
689         /*
690          * If an exclusive group is already on, no other hardware
691          * counters can go on.
692          */
693         if (cpuctx->exclusive)
694                 return 0;
695         /*
696          * If this group is exclusive and there are already
697          * counters on the CPU, it can't go on.
698          */
699         if (counter->attr.exclusive && cpuctx->active_oncpu)
700                 return 0;
701         /*
702          * Otherwise, try to add it if all previous groups were able
703          * to go on.
704          */
705         return can_add_hw;
706 }
707
708 static void add_counter_to_ctx(struct perf_counter *counter,
709                                struct perf_counter_context *ctx)
710 {
711         list_add_counter(counter, ctx);
712         counter->tstamp_enabled = ctx->time;
713         counter->tstamp_running = ctx->time;
714         counter->tstamp_stopped = ctx->time;
715 }
716
717 /*
718  * Cross CPU call to install and enable a performance counter
719  *
720  * Must be called with ctx->mutex held
721  */
722 static void __perf_install_in_context(void *info)
723 {
724         struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
725         struct perf_counter *counter = info;
726         struct perf_counter_context *ctx = counter->ctx;
727         struct perf_counter *leader = counter->group_leader;
728         int cpu = smp_processor_id();
729         int err;
730
731         /*
732          * If this is a task context, we need to check whether it is
733          * the current task context of this cpu. If not it has been
734          * scheduled out before the smp call arrived.
735          * Or possibly this is the right context but it isn't
736          * on this cpu because it had no counters.
737          */
738         if (ctx->task && cpuctx->task_ctx != ctx) {
739                 if (cpuctx->task_ctx || ctx->task != current)
740                         return;
741                 cpuctx->task_ctx = ctx;
742         }
743
744         spin_lock(&ctx->lock);
745         ctx->is_active = 1;
746         update_context_time(ctx);
747
748         /*
749          * Protect the list operation against NMI by disabling the
750          * counters on a global level. NOP for non NMI based counters.
751          */
752         perf_disable();
753
754         add_counter_to_ctx(counter, ctx);
755
756         /*
757          * Don't put the counter on if it is disabled or if
758          * it is in a group and the group isn't on.
759          */
760         if (counter->state != PERF_COUNTER_STATE_INACTIVE ||
761             (leader != counter && leader->state != PERF_COUNTER_STATE_ACTIVE))
762                 goto unlock;
763
764         /*
765          * An exclusive counter can't go on if there are already active
766          * hardware counters, and no hardware counter can go on if there
767          * is already an exclusive counter on.
768          */
769         if (!group_can_go_on(counter, cpuctx, 1))
770                 err = -EEXIST;
771         else
772                 err = counter_sched_in(counter, cpuctx, ctx, cpu);
773
774         if (err) {
775                 /*
776                  * This counter couldn't go on.  If it is in a group
777                  * then we have to pull the whole group off.
778                  * If the counter group is pinned then put it in error state.
779                  */
780                 if (leader != counter)
781                         group_sched_out(leader, cpuctx, ctx);
782                 if (leader->attr.pinned) {
783                         update_group_times(leader);
784                         leader->state = PERF_COUNTER_STATE_ERROR;
785                 }
786         }
787
788         if (!err && !ctx->task && cpuctx->max_pertask)
789                 cpuctx->max_pertask--;
790
791  unlock:
792         perf_enable();
793
794         spin_unlock(&ctx->lock);
795 }
796
797 /*
798  * Attach a performance counter to a context
799  *
800  * First we add the counter to the list with the hardware enable bit
801  * in counter->hw_config cleared.
802  *
803  * If the counter is attached to a task which is on a CPU we use a smp
804  * call to enable it in the task context. The task might have been
805  * scheduled away, but we check this in the smp call again.
806  *
807  * Must be called with ctx->mutex held.
808  */
809 static void
810 perf_install_in_context(struct perf_counter_context *ctx,
811                         struct perf_counter *counter,
812                         int cpu)
813 {
814         struct task_struct *task = ctx->task;
815
816         if (!task) {
817                 /*
818                  * Per cpu counters are installed via an smp call and
819                  * the install is always sucessful.
820                  */
821                 smp_call_function_single(cpu, __perf_install_in_context,
822                                          counter, 1);
823                 return;
824         }
825
826 retry:
827         task_oncpu_function_call(task, __perf_install_in_context,
828                                  counter);
829
830         spin_lock_irq(&ctx->lock);
831         /*
832          * we need to retry the smp call.
833          */
834         if (ctx->is_active && list_empty(&counter->list_entry)) {
835                 spin_unlock_irq(&ctx->lock);
836                 goto retry;
837         }
838
839         /*
840          * The lock prevents that this context is scheduled in so we
841          * can add the counter safely, if it the call above did not
842          * succeed.
843          */
844         if (list_empty(&counter->list_entry))
845                 add_counter_to_ctx(counter, ctx);
846         spin_unlock_irq(&ctx->lock);
847 }
848
849 /*
850  * Cross CPU call to enable a performance counter
851  */
852 static void __perf_counter_enable(void *info)
853 {
854         struct perf_counter *counter = info;
855         struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
856         struct perf_counter_context *ctx = counter->ctx;
857         struct perf_counter *leader = counter->group_leader;
858         int err;
859
860         /*
861          * If this is a per-task counter, need to check whether this
862          * counter's task is the current task on this cpu.
863          */
864         if (ctx->task && cpuctx->task_ctx != ctx) {
865                 if (cpuctx->task_ctx || ctx->task != current)
866                         return;
867                 cpuctx->task_ctx = ctx;
868         }
869
870         spin_lock(&ctx->lock);
871         ctx->is_active = 1;
872         update_context_time(ctx);
873
874         if (counter->state >= PERF_COUNTER_STATE_INACTIVE)
875                 goto unlock;
876         counter->state = PERF_COUNTER_STATE_INACTIVE;
877         counter->tstamp_enabled = ctx->time - counter->total_time_enabled;
878
879         /*
880          * If the counter is in a group and isn't the group leader,
881          * then don't put it on unless the group is on.
882          */
883         if (leader != counter && leader->state != PERF_COUNTER_STATE_ACTIVE)
884                 goto unlock;
885
886         if (!group_can_go_on(counter, cpuctx, 1)) {
887                 err = -EEXIST;
888         } else {
889                 perf_disable();
890                 if (counter == leader)
891                         err = group_sched_in(counter, cpuctx, ctx,
892                                              smp_processor_id());
893                 else
894                         err = counter_sched_in(counter, cpuctx, ctx,
895                                                smp_processor_id());
896                 perf_enable();
897         }
898
899         if (err) {
900                 /*
901                  * If this counter can't go on and it's part of a
902                  * group, then the whole group has to come off.
903                  */
904                 if (leader != counter)
905                         group_sched_out(leader, cpuctx, ctx);
906                 if (leader->attr.pinned) {
907                         update_group_times(leader);
908                         leader->state = PERF_COUNTER_STATE_ERROR;
909                 }
910         }
911
912  unlock:
913         spin_unlock(&ctx->lock);
914 }
915
916 /*
917  * Enable a counter.
918  *
919  * If counter->ctx is a cloned context, callers must make sure that
920  * every task struct that counter->ctx->task could possibly point to
921  * remains valid.  This condition is satisfied when called through
922  * perf_counter_for_each_child or perf_counter_for_each as described
923  * for perf_counter_disable.
924  */
925 static void perf_counter_enable(struct perf_counter *counter)
926 {
927         struct perf_counter_context *ctx = counter->ctx;
928         struct task_struct *task = ctx->task;
929
930         if (!task) {
931                 /*
932                  * Enable the counter on the cpu that it's on
933                  */
934                 smp_call_function_single(counter->cpu, __perf_counter_enable,
935                                          counter, 1);
936                 return;
937         }
938
939         spin_lock_irq(&ctx->lock);
940         if (counter->state >= PERF_COUNTER_STATE_INACTIVE)
941                 goto out;
942
943         /*
944          * If the counter is in error state, clear that first.
945          * That way, if we see the counter in error state below, we
946          * know that it has gone back into error state, as distinct
947          * from the task having been scheduled away before the
948          * cross-call arrived.
949          */
950         if (counter->state == PERF_COUNTER_STATE_ERROR)
951                 counter->state = PERF_COUNTER_STATE_OFF;
952
953  retry:
954         spin_unlock_irq(&ctx->lock);
955         task_oncpu_function_call(task, __perf_counter_enable, counter);
956
957         spin_lock_irq(&ctx->lock);
958
959         /*
960          * If the context is active and the counter is still off,
961          * we need to retry the cross-call.
962          */
963         if (ctx->is_active && counter->state == PERF_COUNTER_STATE_OFF)
964                 goto retry;
965
966         /*
967          * Since we have the lock this context can't be scheduled
968          * in, so we can change the state safely.
969          */
970         if (counter->state == PERF_COUNTER_STATE_OFF) {
971                 counter->state = PERF_COUNTER_STATE_INACTIVE;
972                 counter->tstamp_enabled =
973                         ctx->time - counter->total_time_enabled;
974         }
975  out:
976         spin_unlock_irq(&ctx->lock);
977 }
978
979 static int perf_counter_refresh(struct perf_counter *counter, int refresh)
980 {
981         /*
982          * not supported on inherited counters
983          */
984         if (counter->attr.inherit)
985                 return -EINVAL;
986
987         atomic_add(refresh, &counter->event_limit);
988         perf_counter_enable(counter);
989
990         return 0;
991 }
992
993 void __perf_counter_sched_out(struct perf_counter_context *ctx,
994                               struct perf_cpu_context *cpuctx)
995 {
996         struct perf_counter *counter;
997
998         spin_lock(&ctx->lock);
999         ctx->is_active = 0;
1000         if (likely(!ctx->nr_counters))
1001                 goto out;
1002         update_context_time(ctx);
1003
1004         perf_disable();
1005         if (ctx->nr_active) {
1006                 list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1007                         if (counter != counter->group_leader)
1008                                 counter_sched_out(counter, cpuctx, ctx);
1009                         else
1010                                 group_sched_out(counter, cpuctx, ctx);
1011                 }
1012         }
1013         perf_enable();
1014  out:
1015         spin_unlock(&ctx->lock);
1016 }
1017
1018 /*
1019  * Test whether two contexts are equivalent, i.e. whether they
1020  * have both been cloned from the same version of the same context
1021  * and they both have the same number of enabled counters.
1022  * If the number of enabled counters is the same, then the set
1023  * of enabled counters should be the same, because these are both
1024  * inherited contexts, therefore we can't access individual counters
1025  * in them directly with an fd; we can only enable/disable all
1026  * counters via prctl, or enable/disable all counters in a family
1027  * via ioctl, which will have the same effect on both contexts.
1028  */
1029 static int context_equiv(struct perf_counter_context *ctx1,
1030                          struct perf_counter_context *ctx2)
1031 {
1032         return ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx
1033                 && ctx1->parent_gen == ctx2->parent_gen
1034                 && !ctx1->pin_count && !ctx2->pin_count;
1035 }
1036
1037 static void __perf_counter_read(void *counter);
1038
1039 static void __perf_counter_sync_stat(struct perf_counter *counter,
1040                                      struct perf_counter *next_counter)
1041 {
1042         u64 value;
1043
1044         if (!counter->attr.inherit_stat)
1045                 return;
1046
1047         /*
1048          * Update the counter value, we cannot use perf_counter_read()
1049          * because we're in the middle of a context switch and have IRQs
1050          * disabled, which upsets smp_call_function_single(), however
1051          * we know the counter must be on the current CPU, therefore we
1052          * don't need to use it.
1053          */
1054         switch (counter->state) {
1055         case PERF_COUNTER_STATE_ACTIVE:
1056                 __perf_counter_read(counter);
1057                 break;
1058
1059         case PERF_COUNTER_STATE_INACTIVE:
1060                 update_counter_times(counter);
1061                 break;
1062
1063         default:
1064                 break;
1065         }
1066
1067         /*
1068          * In order to keep per-task stats reliable we need to flip the counter
1069          * values when we flip the contexts.
1070          */
1071         value = atomic64_read(&next_counter->count);
1072         value = atomic64_xchg(&counter->count, value);
1073         atomic64_set(&next_counter->count, value);
1074
1075         swap(counter->total_time_enabled, next_counter->total_time_enabled);
1076         swap(counter->total_time_running, next_counter->total_time_running);
1077
1078         /*
1079          * Since we swizzled the values, update the user visible data too.
1080          */
1081         perf_counter_update_userpage(counter);
1082         perf_counter_update_userpage(next_counter);
1083 }
1084
1085 #define list_next_entry(pos, member) \
1086         list_entry(pos->member.next, typeof(*pos), member)
1087
1088 static void perf_counter_sync_stat(struct perf_counter_context *ctx,
1089                                    struct perf_counter_context *next_ctx)
1090 {
1091         struct perf_counter *counter, *next_counter;
1092
1093         if (!ctx->nr_stat)
1094                 return;
1095
1096         counter = list_first_entry(&ctx->event_list,
1097                                    struct perf_counter, event_entry);
1098
1099         next_counter = list_first_entry(&next_ctx->event_list,
1100                                         struct perf_counter, event_entry);
1101
1102         while (&counter->event_entry != &ctx->event_list &&
1103                &next_counter->event_entry != &next_ctx->event_list) {
1104
1105                 __perf_counter_sync_stat(counter, next_counter);
1106
1107                 counter = list_next_entry(counter, event_entry);
1108                 next_counter = list_next_entry(next_counter, event_entry);
1109         }
1110 }
1111
1112 /*
1113  * Called from scheduler to remove the counters of the current task,
1114  * with interrupts disabled.
1115  *
1116  * We stop each counter and update the counter value in counter->count.
1117  *
1118  * This does not protect us against NMI, but disable()
1119  * sets the disabled bit in the control field of counter _before_
1120  * accessing the counter control register. If a NMI hits, then it will
1121  * not restart the counter.
1122  */
1123 void perf_counter_task_sched_out(struct task_struct *task,
1124                                  struct task_struct *next, int cpu)
1125 {
1126         struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
1127         struct perf_counter_context *ctx = task->perf_counter_ctxp;
1128         struct perf_counter_context *next_ctx;
1129         struct perf_counter_context *parent;
1130         struct pt_regs *regs;
1131         int do_switch = 1;
1132
1133         regs = task_pt_regs(task);
1134         perf_swcounter_event(PERF_COUNT_SW_CONTEXT_SWITCHES, 1, 1, regs, 0);
1135
1136         if (likely(!ctx || !cpuctx->task_ctx))
1137                 return;
1138
1139         update_context_time(ctx);
1140
1141         rcu_read_lock();
1142         parent = rcu_dereference(ctx->parent_ctx);
1143         next_ctx = next->perf_counter_ctxp;
1144         if (parent && next_ctx &&
1145             rcu_dereference(next_ctx->parent_ctx) == parent) {
1146                 /*
1147                  * Looks like the two contexts are clones, so we might be
1148                  * able to optimize the context switch.  We lock both
1149                  * contexts and check that they are clones under the
1150                  * lock (including re-checking that neither has been
1151                  * uncloned in the meantime).  It doesn't matter which
1152                  * order we take the locks because no other cpu could
1153                  * be trying to lock both of these tasks.
1154                  */
1155                 spin_lock(&ctx->lock);
1156                 spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
1157                 if (context_equiv(ctx, next_ctx)) {
1158                         /*
1159                          * XXX do we need a memory barrier of sorts
1160                          * wrt to rcu_dereference() of perf_counter_ctxp
1161                          */
1162                         task->perf_counter_ctxp = next_ctx;
1163                         next->perf_counter_ctxp = ctx;
1164                         ctx->task = next;
1165                         next_ctx->task = task;
1166                         do_switch = 0;
1167
1168                         perf_counter_sync_stat(ctx, next_ctx);
1169                 }
1170                 spin_unlock(&next_ctx->lock);
1171                 spin_unlock(&ctx->lock);
1172         }
1173         rcu_read_unlock();
1174
1175         if (do_switch) {
1176                 __perf_counter_sched_out(ctx, cpuctx);
1177                 cpuctx->task_ctx = NULL;
1178         }
1179 }
1180
1181 /*
1182  * Called with IRQs disabled
1183  */
1184 static void __perf_counter_task_sched_out(struct perf_counter_context *ctx)
1185 {
1186         struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
1187
1188         if (!cpuctx->task_ctx)
1189                 return;
1190
1191         if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
1192                 return;
1193
1194         __perf_counter_sched_out(ctx, cpuctx);
1195         cpuctx->task_ctx = NULL;
1196 }
1197
1198 /*
1199  * Called with IRQs disabled
1200  */
1201 static void perf_counter_cpu_sched_out(struct perf_cpu_context *cpuctx)
1202 {
1203         __perf_counter_sched_out(&cpuctx->ctx, cpuctx);
1204 }
1205
1206 static void
1207 __perf_counter_sched_in(struct perf_counter_context *ctx,
1208                         struct perf_cpu_context *cpuctx, int cpu)
1209 {
1210         struct perf_counter *counter;
1211         int can_add_hw = 1;
1212
1213         spin_lock(&ctx->lock);
1214         ctx->is_active = 1;
1215         if (likely(!ctx->nr_counters))
1216                 goto out;
1217
1218         ctx->timestamp = perf_clock();
1219
1220         perf_disable();
1221
1222         /*
1223          * First go through the list and put on any pinned groups
1224          * in order to give them the best chance of going on.
1225          */
1226         list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1227                 if (counter->state <= PERF_COUNTER_STATE_OFF ||
1228                     !counter->attr.pinned)
1229                         continue;
1230                 if (counter->cpu != -1 && counter->cpu != cpu)
1231                         continue;
1232
1233                 if (counter != counter->group_leader)
1234                         counter_sched_in(counter, cpuctx, ctx, cpu);
1235                 else {
1236                         if (group_can_go_on(counter, cpuctx, 1))
1237                                 group_sched_in(counter, cpuctx, ctx, cpu);
1238                 }
1239
1240                 /*
1241                  * If this pinned group hasn't been scheduled,
1242                  * put it in error state.
1243                  */
1244                 if (counter->state == PERF_COUNTER_STATE_INACTIVE) {
1245                         update_group_times(counter);
1246                         counter->state = PERF_COUNTER_STATE_ERROR;
1247                 }
1248         }
1249
1250         list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1251                 /*
1252                  * Ignore counters in OFF or ERROR state, and
1253                  * ignore pinned counters since we did them already.
1254                  */
1255                 if (counter->state <= PERF_COUNTER_STATE_OFF ||
1256                     counter->attr.pinned)
1257                         continue;
1258
1259                 /*
1260                  * Listen to the 'cpu' scheduling filter constraint
1261                  * of counters:
1262                  */
1263                 if (counter->cpu != -1 && counter->cpu != cpu)
1264                         continue;
1265
1266                 if (counter != counter->group_leader) {
1267                         if (counter_sched_in(counter, cpuctx, ctx, cpu))
1268                                 can_add_hw = 0;
1269                 } else {
1270                         if (group_can_go_on(counter, cpuctx, can_add_hw)) {
1271                                 if (group_sched_in(counter, cpuctx, ctx, cpu))
1272                                         can_add_hw = 0;
1273                         }
1274                 }
1275         }
1276         perf_enable();
1277  out:
1278         spin_unlock(&ctx->lock);
1279 }
1280
1281 /*
1282  * Called from scheduler to add the counters of the current task
1283  * with interrupts disabled.
1284  *
1285  * We restore the counter value and then enable it.
1286  *
1287  * This does not protect us against NMI, but enable()
1288  * sets the enabled bit in the control field of counter _before_
1289  * accessing the counter control register. If a NMI hits, then it will
1290  * keep the counter running.
1291  */
1292 void perf_counter_task_sched_in(struct task_struct *task, int cpu)
1293 {
1294         struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
1295         struct perf_counter_context *ctx = task->perf_counter_ctxp;
1296
1297         if (likely(!ctx))
1298                 return;
1299         if (cpuctx->task_ctx == ctx)
1300                 return;
1301         __perf_counter_sched_in(ctx, cpuctx, cpu);
1302         cpuctx->task_ctx = ctx;
1303 }
1304
1305 static void perf_counter_cpu_sched_in(struct perf_cpu_context *cpuctx, int cpu)
1306 {
1307         struct perf_counter_context *ctx = &cpuctx->ctx;
1308
1309         __perf_counter_sched_in(ctx, cpuctx, cpu);
1310 }
1311
1312 #define MAX_INTERRUPTS (~0ULL)
1313
1314 static void perf_log_throttle(struct perf_counter *counter, int enable);
1315
1316 static void perf_adjust_period(struct perf_counter *counter, u64 events)
1317 {
1318         struct hw_perf_counter *hwc = &counter->hw;
1319         u64 period, sample_period;
1320         s64 delta;
1321
1322         events *= hwc->sample_period;
1323         period = div64_u64(events, counter->attr.sample_freq);
1324
1325         delta = (s64)(period - hwc->sample_period);
1326         delta = (delta + 7) / 8; /* low pass filter */
1327
1328         sample_period = hwc->sample_period + delta;
1329
1330         if (!sample_period)
1331                 sample_period = 1;
1332
1333         hwc->sample_period = sample_period;
1334 }
1335
1336 static void perf_ctx_adjust_freq(struct perf_counter_context *ctx)
1337 {
1338         struct perf_counter *counter;
1339         struct hw_perf_counter *hwc;
1340         u64 interrupts, freq;
1341
1342         spin_lock(&ctx->lock);
1343         list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1344                 if (counter->state != PERF_COUNTER_STATE_ACTIVE)
1345                         continue;
1346
1347                 hwc = &counter->hw;
1348
1349                 interrupts = hwc->interrupts;
1350                 hwc->interrupts = 0;
1351
1352                 /*
1353                  * unthrottle counters on the tick
1354                  */
1355                 if (interrupts == MAX_INTERRUPTS) {
1356                         perf_log_throttle(counter, 1);
1357                         counter->pmu->unthrottle(counter);
1358                         interrupts = 2*sysctl_perf_counter_sample_rate/HZ;
1359                 }
1360
1361                 if (!counter->attr.freq || !counter->attr.sample_freq)
1362                         continue;
1363
1364                 /*
1365                  * if the specified freq < HZ then we need to skip ticks
1366                  */
1367                 if (counter->attr.sample_freq < HZ) {
1368                         freq = counter->attr.sample_freq;
1369
1370                         hwc->freq_count += freq;
1371                         hwc->freq_interrupts += interrupts;
1372
1373                         if (hwc->freq_count < HZ)
1374                                 continue;
1375
1376                         interrupts = hwc->freq_interrupts;
1377                         hwc->freq_interrupts = 0;
1378                         hwc->freq_count -= HZ;
1379                 } else
1380                         freq = HZ;
1381
1382                 perf_adjust_period(counter, freq * interrupts);
1383
1384                 /*
1385                  * In order to avoid being stalled by an (accidental) huge
1386                  * sample period, force reset the sample period if we didn't
1387                  * get any events in this freq period.
1388                  */
1389                 if (!interrupts) {
1390                         perf_disable();
1391                         counter->pmu->disable(counter);
1392                         atomic64_set(&hwc->period_left, 0);
1393                         counter->pmu->enable(counter);
1394                         perf_enable();
1395                 }
1396         }
1397         spin_unlock(&ctx->lock);
1398 }
1399
1400 /*
1401  * Round-robin a context's counters:
1402  */
1403 static void rotate_ctx(struct perf_counter_context *ctx)
1404 {
1405         struct perf_counter *counter;
1406
1407         if (!ctx->nr_counters)
1408                 return;
1409
1410         spin_lock(&ctx->lock);
1411         /*
1412          * Rotate the first entry last (works just fine for group counters too):
1413          */
1414         perf_disable();
1415         list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1416                 list_move_tail(&counter->list_entry, &ctx->counter_list);
1417                 break;
1418         }
1419         perf_enable();
1420
1421         spin_unlock(&ctx->lock);
1422 }
1423
1424 void perf_counter_task_tick(struct task_struct *curr, int cpu)
1425 {
1426         struct perf_cpu_context *cpuctx;
1427         struct perf_counter_context *ctx;
1428
1429         if (!atomic_read(&nr_counters))
1430                 return;
1431
1432         cpuctx = &per_cpu(perf_cpu_context, cpu);
1433         ctx = curr->perf_counter_ctxp;
1434
1435         perf_ctx_adjust_freq(&cpuctx->ctx);
1436         if (ctx)
1437                 perf_ctx_adjust_freq(ctx);
1438
1439         perf_counter_cpu_sched_out(cpuctx);
1440         if (ctx)
1441                 __perf_counter_task_sched_out(ctx);
1442
1443         rotate_ctx(&cpuctx->ctx);
1444         if (ctx)
1445                 rotate_ctx(ctx);
1446
1447         perf_counter_cpu_sched_in(cpuctx, cpu);
1448         if (ctx)
1449                 perf_counter_task_sched_in(curr, cpu);
1450 }
1451
1452 /*
1453  * Enable all of a task's counters that have been marked enable-on-exec.
1454  * This expects task == current.
1455  */
1456 static void perf_counter_enable_on_exec(struct task_struct *task)
1457 {
1458         struct perf_counter_context *ctx;
1459         struct perf_counter *counter;
1460         unsigned long flags;
1461         int enabled = 0;
1462
1463         local_irq_save(flags);
1464         ctx = task->perf_counter_ctxp;
1465         if (!ctx || !ctx->nr_counters)
1466                 goto out;
1467
1468         __perf_counter_task_sched_out(ctx);
1469
1470         spin_lock(&ctx->lock);
1471
1472         list_for_each_entry(counter, &ctx->counter_list, list_entry) {
1473                 if (!counter->attr.enable_on_exec)
1474                         continue;
1475                 counter->attr.enable_on_exec = 0;
1476                 if (counter->state >= PERF_COUNTER_STATE_INACTIVE)
1477                         continue;
1478                 counter->state = PERF_COUNTER_STATE_INACTIVE;
1479                 counter->tstamp_enabled =
1480                         ctx->time - counter->total_time_enabled;
1481                 enabled = 1;
1482         }
1483
1484         /*
1485          * Unclone this context if we enabled any counter.
1486          */
1487         if (enabled)
1488                 unclone_ctx(ctx);
1489
1490         spin_unlock(&ctx->lock);
1491
1492         perf_counter_task_sched_in(task, smp_processor_id());
1493  out:
1494         local_irq_restore(flags);
1495 }
1496
1497 /*
1498  * Cross CPU call to read the hardware counter
1499  */
1500 static void __perf_counter_read(void *info)
1501 {
1502         struct perf_counter *counter = info;
1503         struct perf_counter_context *ctx = counter->ctx;
1504         unsigned long flags;
1505
1506         local_irq_save(flags);
1507         if (ctx->is_active)
1508                 update_context_time(ctx);
1509         counter->pmu->read(counter);
1510         update_counter_times(counter);
1511         local_irq_restore(flags);
1512 }
1513
1514 static u64 perf_counter_read(struct perf_counter *counter)
1515 {
1516         /*
1517          * If counter is enabled and currently active on a CPU, update the
1518          * value in the counter structure:
1519          */
1520         if (counter->state == PERF_COUNTER_STATE_ACTIVE) {
1521                 smp_call_function_single(counter->oncpu,
1522                                          __perf_counter_read, counter, 1);
1523         } else if (counter->state == PERF_COUNTER_STATE_INACTIVE) {
1524                 update_counter_times(counter);
1525         }
1526
1527         return atomic64_read(&counter->count);
1528 }
1529
1530 /*
1531  * Initialize the perf_counter context in a task_struct:
1532  */
1533 static void
1534 __perf_counter_init_context(struct perf_counter_context *ctx,
1535                             struct task_struct *task)
1536 {
1537         memset(ctx, 0, sizeof(*ctx));
1538         spin_lock_init(&ctx->lock);
1539         mutex_init(&ctx->mutex);
1540         INIT_LIST_HEAD(&ctx->counter_list);
1541         INIT_LIST_HEAD(&ctx->event_list);
1542         atomic_set(&ctx->refcount, 1);
1543         ctx->task = task;
1544 }
1545
1546 static struct perf_counter_context *find_get_context(pid_t pid, int cpu)
1547 {
1548         struct perf_counter_context *ctx;
1549         struct perf_cpu_context *cpuctx;
1550         struct task_struct *task;
1551         unsigned long flags;
1552         int err;
1553
1554         /*
1555          * If cpu is not a wildcard then this is a percpu counter:
1556          */
1557         if (cpu != -1) {
1558                 /* Must be root to operate on a CPU counter: */
1559                 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
1560                         return ERR_PTR(-EACCES);
1561
1562                 if (cpu < 0 || cpu > num_possible_cpus())
1563                         return ERR_PTR(-EINVAL);
1564
1565                 /*
1566                  * We could be clever and allow to attach a counter to an
1567                  * offline CPU and activate it when the CPU comes up, but
1568                  * that's for later.
1569                  */
1570                 if (!cpu_isset(cpu, cpu_online_map))
1571                         return ERR_PTR(-ENODEV);
1572
1573                 cpuctx = &per_cpu(perf_cpu_context, cpu);
1574                 ctx = &cpuctx->ctx;
1575                 get_ctx(ctx);
1576
1577                 return ctx;
1578         }
1579
1580         rcu_read_lock();
1581         if (!pid)
1582                 task = current;
1583         else
1584                 task = find_task_by_vpid(pid);
1585         if (task)
1586                 get_task_struct(task);
1587         rcu_read_unlock();
1588
1589         if (!task)
1590                 return ERR_PTR(-ESRCH);
1591
1592         /*
1593          * Can't attach counters to a dying task.
1594          */
1595         err = -ESRCH;
1596         if (task->flags & PF_EXITING)
1597                 goto errout;
1598
1599         /* Reuse ptrace permission checks for now. */
1600         err = -EACCES;
1601         if (!ptrace_may_access(task, PTRACE_MODE_READ))
1602                 goto errout;
1603
1604  retry:
1605         ctx = perf_lock_task_context(task, &flags);
1606         if (ctx) {
1607                 unclone_ctx(ctx);
1608                 spin_unlock_irqrestore(&ctx->lock, flags);
1609         }
1610
1611         if (!ctx) {
1612                 ctx = kmalloc(sizeof(struct perf_counter_context), GFP_KERNEL);
1613                 err = -ENOMEM;
1614                 if (!ctx)
1615                         goto errout;
1616                 __perf_counter_init_context(ctx, task);
1617                 get_ctx(ctx);
1618                 if (cmpxchg(&task->perf_counter_ctxp, NULL, ctx)) {
1619                         /*
1620                          * We raced with some other task; use
1621                          * the context they set.
1622                          */
1623                         kfree(ctx);
1624                         goto retry;
1625                 }
1626                 get_task_struct(task);
1627         }
1628
1629         put_task_struct(task);
1630         return ctx;
1631
1632  errout:
1633         put_task_struct(task);
1634         return ERR_PTR(err);
1635 }
1636
1637 static void free_counter_rcu(struct rcu_head *head)
1638 {
1639         struct perf_counter *counter;
1640
1641         counter = container_of(head, struct perf_counter, rcu_head);
1642         if (counter->ns)
1643                 put_pid_ns(counter->ns);
1644         kfree(counter);
1645 }
1646
1647 static void perf_pending_sync(struct perf_counter *counter);
1648
1649 static void free_counter(struct perf_counter *counter)
1650 {
1651         perf_pending_sync(counter);
1652
1653         if (!counter->parent) {
1654                 atomic_dec(&nr_counters);
1655                 if (counter->attr.mmap)
1656                         atomic_dec(&nr_mmap_counters);
1657                 if (counter->attr.comm)
1658                         atomic_dec(&nr_comm_counters);
1659                 if (counter->attr.task)
1660                         atomic_dec(&nr_task_counters);
1661         }
1662
1663         if (counter->destroy)
1664                 counter->destroy(counter);
1665
1666         put_ctx(counter->ctx);
1667         call_rcu(&counter->rcu_head, free_counter_rcu);
1668 }
1669
1670 /*
1671  * Called when the last reference to the file is gone.
1672  */
1673 static int perf_release(struct inode *inode, struct file *file)
1674 {
1675         struct perf_counter *counter = file->private_data;
1676         struct perf_counter_context *ctx = counter->ctx;
1677
1678         file->private_data = NULL;
1679
1680         WARN_ON_ONCE(ctx->parent_ctx);
1681         mutex_lock(&ctx->mutex);
1682         perf_counter_remove_from_context(counter);
1683         mutex_unlock(&ctx->mutex);
1684
1685         mutex_lock(&counter->owner->perf_counter_mutex);
1686         list_del_init(&counter->owner_entry);
1687         mutex_unlock(&counter->owner->perf_counter_mutex);
1688         put_task_struct(counter->owner);
1689
1690         free_counter(counter);
1691
1692         return 0;
1693 }
1694
1695 static u64 perf_counter_read_tree(struct perf_counter *counter)
1696 {
1697         struct perf_counter *child;
1698         u64 total = 0;
1699
1700         total += perf_counter_read(counter);
1701         list_for_each_entry(child, &counter->child_list, child_list)
1702                 total += perf_counter_read(child);
1703
1704         return total;
1705 }
1706
1707 /*
1708  * Read the performance counter - simple non blocking version for now
1709  */
1710 static ssize_t
1711 perf_read_hw(struct perf_counter *counter, char __user *buf, size_t count)
1712 {
1713         u64 values[4];
1714         int n;
1715
1716         /*
1717          * Return end-of-file for a read on a counter that is in
1718          * error state (i.e. because it was pinned but it couldn't be
1719          * scheduled on to the CPU at some point).
1720          */
1721         if (counter->state == PERF_COUNTER_STATE_ERROR)
1722                 return 0;
1723
1724         WARN_ON_ONCE(counter->ctx->parent_ctx);
1725         mutex_lock(&counter->child_mutex);
1726         values[0] = perf_counter_read_tree(counter);
1727         n = 1;
1728         if (counter->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1729                 values[n++] = counter->total_time_enabled +
1730                         atomic64_read(&counter->child_total_time_enabled);
1731         if (counter->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1732                 values[n++] = counter->total_time_running +
1733                         atomic64_read(&counter->child_total_time_running);
1734         if (counter->attr.read_format & PERF_FORMAT_ID)
1735                 values[n++] = primary_counter_id(counter);
1736         mutex_unlock(&counter->child_mutex);
1737
1738         if (count < n * sizeof(u64))
1739                 return -EINVAL;
1740         count = n * sizeof(u64);
1741
1742         if (copy_to_user(buf, values, count))
1743                 return -EFAULT;
1744
1745         return count;
1746 }
1747
1748 static ssize_t
1749 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
1750 {
1751         struct perf_counter *counter = file->private_data;
1752
1753         return perf_read_hw(counter, buf, count);
1754 }
1755
1756 static unsigned int perf_poll(struct file *file, poll_table *wait)
1757 {
1758         struct perf_counter *counter = file->private_data;
1759         struct perf_mmap_data *data;
1760         unsigned int events = POLL_HUP;
1761
1762         rcu_read_lock();
1763         data = rcu_dereference(counter->data);
1764         if (data)
1765                 events = atomic_xchg(&data->poll, 0);
1766         rcu_read_unlock();
1767
1768         poll_wait(file, &counter->waitq, wait);
1769
1770         return events;
1771 }
1772
1773 static void perf_counter_reset(struct perf_counter *counter)
1774 {
1775         (void)perf_counter_read(counter);
1776         atomic64_set(&counter->count, 0);
1777         perf_counter_update_userpage(counter);
1778 }
1779
1780 /*
1781  * Holding the top-level counter's child_mutex means that any
1782  * descendant process that has inherited this counter will block
1783  * in sync_child_counter if it goes to exit, thus satisfying the
1784  * task existence requirements of perf_counter_enable/disable.
1785  */
1786 static void perf_counter_for_each_child(struct perf_counter *counter,
1787                                         void (*func)(struct perf_counter *))
1788 {
1789         struct perf_counter *child;
1790
1791         WARN_ON_ONCE(counter->ctx->parent_ctx);
1792         mutex_lock(&counter->child_mutex);
1793         func(counter);
1794         list_for_each_entry(child, &counter->child_list, child_list)
1795                 func(child);
1796         mutex_unlock(&counter->child_mutex);
1797 }
1798
1799 static void perf_counter_for_each(struct perf_counter *counter,
1800                                   void (*func)(struct perf_counter *))
1801 {
1802         struct perf_counter_context *ctx = counter->ctx;
1803         struct perf_counter *sibling;
1804
1805         WARN_ON_ONCE(ctx->parent_ctx);
1806         mutex_lock(&ctx->mutex);
1807         counter = counter->group_leader;
1808
1809         perf_counter_for_each_child(counter, func);
1810         func(counter);
1811         list_for_each_entry(sibling, &counter->sibling_list, list_entry)
1812                 perf_counter_for_each_child(counter, func);
1813         mutex_unlock(&ctx->mutex);
1814 }
1815
1816 static int perf_counter_period(struct perf_counter *counter, u64 __user *arg)
1817 {
1818         struct perf_counter_context *ctx = counter->ctx;
1819         unsigned long size;
1820         int ret = 0;
1821         u64 value;
1822
1823         if (!counter->attr.sample_period)
1824                 return -EINVAL;
1825
1826         size = copy_from_user(&value, arg, sizeof(value));
1827         if (size != sizeof(value))
1828                 return -EFAULT;
1829
1830         if (!value)
1831                 return -EINVAL;
1832
1833         spin_lock_irq(&ctx->lock);
1834         if (counter->attr.freq) {
1835                 if (value > sysctl_perf_counter_sample_rate) {
1836                         ret = -EINVAL;
1837                         goto unlock;
1838                 }
1839
1840                 counter->attr.sample_freq = value;
1841         } else {
1842                 counter->attr.sample_period = value;
1843                 counter->hw.sample_period = value;
1844         }
1845 unlock:
1846         spin_unlock_irq(&ctx->lock);
1847
1848         return ret;
1849 }
1850
1851 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
1852 {
1853         struct perf_counter *counter = file->private_data;
1854         void (*func)(struct perf_counter *);
1855         u32 flags = arg;
1856
1857         switch (cmd) {
1858         case PERF_COUNTER_IOC_ENABLE:
1859                 func = perf_counter_enable;
1860                 break;
1861         case PERF_COUNTER_IOC_DISABLE:
1862                 func = perf_counter_disable;
1863                 break;
1864         case PERF_COUNTER_IOC_RESET:
1865                 func = perf_counter_reset;
1866                 break;
1867
1868         case PERF_COUNTER_IOC_REFRESH:
1869                 return perf_counter_refresh(counter, arg);
1870
1871         case PERF_COUNTER_IOC_PERIOD:
1872                 return perf_counter_period(counter, (u64 __user *)arg);
1873
1874         default:
1875                 return -ENOTTY;
1876         }
1877
1878         if (flags & PERF_IOC_FLAG_GROUP)
1879                 perf_counter_for_each(counter, func);
1880         else
1881                 perf_counter_for_each_child(counter, func);
1882
1883         return 0;
1884 }
1885
1886 int perf_counter_task_enable(void)
1887 {
1888         struct perf_counter *counter;
1889
1890         mutex_lock(&current->perf_counter_mutex);
1891         list_for_each_entry(counter, &current->perf_counter_list, owner_entry)
1892                 perf_counter_for_each_child(counter, perf_counter_enable);
1893         mutex_unlock(&current->perf_counter_mutex);
1894
1895         return 0;
1896 }
1897
1898 int perf_counter_task_disable(void)
1899 {
1900         struct perf_counter *counter;
1901
1902         mutex_lock(&current->perf_counter_mutex);
1903         list_for_each_entry(counter, &current->perf_counter_list, owner_entry)
1904                 perf_counter_for_each_child(counter, perf_counter_disable);
1905         mutex_unlock(&current->perf_counter_mutex);
1906
1907         return 0;
1908 }
1909
1910 static int perf_counter_index(struct perf_counter *counter)
1911 {
1912         if (counter->state != PERF_COUNTER_STATE_ACTIVE)
1913                 return 0;
1914
1915         return counter->hw.idx + 1 - PERF_COUNTER_INDEX_OFFSET;
1916 }
1917
1918 /*
1919  * Callers need to ensure there can be no nesting of this function, otherwise
1920  * the seqlock logic goes bad. We can not serialize this because the arch
1921  * code calls this from NMI context.
1922  */
1923 void perf_counter_update_userpage(struct perf_counter *counter)
1924 {
1925         struct perf_counter_mmap_page *userpg;
1926         struct perf_mmap_data *data;
1927
1928         rcu_read_lock();
1929         data = rcu_dereference(counter->data);
1930         if (!data)
1931                 goto unlock;
1932
1933         userpg = data->user_page;
1934
1935         /*
1936          * Disable preemption so as to not let the corresponding user-space
1937          * spin too long if we get preempted.
1938          */
1939         preempt_disable();
1940         ++userpg->lock;
1941         barrier();
1942         userpg->index = perf_counter_index(counter);
1943         userpg->offset = atomic64_read(&counter->count);
1944         if (counter->state == PERF_COUNTER_STATE_ACTIVE)
1945                 userpg->offset -= atomic64_read(&counter->hw.prev_count);
1946
1947         userpg->time_enabled = counter->total_time_enabled +
1948                         atomic64_read(&counter->child_total_time_enabled);
1949
1950         userpg->time_running = counter->total_time_running +
1951                         atomic64_read(&counter->child_total_time_running);
1952
1953         barrier();
1954         ++userpg->lock;
1955         preempt_enable();
1956 unlock:
1957         rcu_read_unlock();
1958 }
1959
1960 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1961 {
1962         struct perf_counter *counter = vma->vm_file->private_data;
1963         struct perf_mmap_data *data;
1964         int ret = VM_FAULT_SIGBUS;
1965
1966         if (vmf->flags & FAULT_FLAG_MKWRITE) {
1967                 if (vmf->pgoff == 0)
1968                         ret = 0;
1969                 return ret;
1970         }
1971
1972         rcu_read_lock();
1973         data = rcu_dereference(counter->data);
1974         if (!data)
1975                 goto unlock;
1976
1977         if (vmf->pgoff == 0) {
1978                 vmf->page = virt_to_page(data->user_page);
1979         } else {
1980                 int nr = vmf->pgoff - 1;
1981
1982                 if ((unsigned)nr > data->nr_pages)
1983                         goto unlock;
1984
1985                 if (vmf->flags & FAULT_FLAG_WRITE)
1986                         goto unlock;
1987
1988                 vmf->page = virt_to_page(data->data_pages[nr]);
1989         }
1990
1991         get_page(vmf->page);
1992         vmf->page->mapping = vma->vm_file->f_mapping;
1993         vmf->page->index   = vmf->pgoff;
1994
1995         ret = 0;
1996 unlock:
1997         rcu_read_unlock();
1998
1999         return ret;
2000 }
2001
2002 static int perf_mmap_data_alloc(struct perf_counter *counter, int nr_pages)
2003 {
2004         struct perf_mmap_data *data;
2005         unsigned long size;
2006         int i;
2007
2008         WARN_ON(atomic_read(&counter->mmap_count));
2009
2010         size = sizeof(struct perf_mmap_data);
2011         size += nr_pages * sizeof(void *);
2012
2013         data = kzalloc(size, GFP_KERNEL);
2014         if (!data)
2015                 goto fail;
2016
2017         data->user_page = (void *)get_zeroed_page(GFP_KERNEL);
2018         if (!data->user_page)
2019                 goto fail_user_page;
2020
2021         for (i = 0; i < nr_pages; i++) {
2022                 data->data_pages[i] = (void *)get_zeroed_page(GFP_KERNEL);
2023                 if (!data->data_pages[i])
2024                         goto fail_data_pages;
2025         }
2026
2027         data->nr_pages = nr_pages;
2028         atomic_set(&data->lock, -1);
2029
2030         rcu_assign_pointer(counter->data, data);
2031
2032         return 0;
2033
2034 fail_data_pages:
2035         for (i--; i >= 0; i--)
2036                 free_page((unsigned long)data->data_pages[i]);
2037
2038         free_page((unsigned long)data->user_page);
2039
2040 fail_user_page:
2041         kfree(data);
2042
2043 fail:
2044         return -ENOMEM;
2045 }
2046
2047 static void perf_mmap_free_page(unsigned long addr)
2048 {
2049         struct page *page = virt_to_page((void *)addr);
2050
2051         page->mapping = NULL;
2052         __free_page(page);
2053 }
2054
2055 static void __perf_mmap_data_free(struct rcu_head *rcu_head)
2056 {
2057         struct perf_mmap_data *data;
2058         int i;
2059
2060         data = container_of(rcu_head, struct perf_mmap_data, rcu_head);
2061
2062         perf_mmap_free_page((unsigned long)data->user_page);
2063         for (i = 0; i < data->nr_pages; i++)
2064                 perf_mmap_free_page((unsigned long)data->data_pages[i]);
2065
2066         kfree(data);
2067 }
2068
2069 static void perf_mmap_data_free(struct perf_counter *counter)
2070 {
2071         struct perf_mmap_data *data = counter->data;
2072
2073         WARN_ON(atomic_read(&counter->mmap_count));
2074
2075         rcu_assign_pointer(counter->data, NULL);
2076         call_rcu(&data->rcu_head, __perf_mmap_data_free);
2077 }
2078
2079 static void perf_mmap_open(struct vm_area_struct *vma)
2080 {
2081         struct perf_counter *counter = vma->vm_file->private_data;
2082
2083         atomic_inc(&counter->mmap_count);
2084 }
2085
2086 static void perf_mmap_close(struct vm_area_struct *vma)
2087 {
2088         struct perf_counter *counter = vma->vm_file->private_data;
2089
2090         WARN_ON_ONCE(counter->ctx->parent_ctx);
2091         if (atomic_dec_and_mutex_lock(&counter->mmap_count, &counter->mmap_mutex)) {
2092                 struct user_struct *user = current_user();
2093
2094                 atomic_long_sub(counter->data->nr_pages + 1, &user->locked_vm);
2095                 vma->vm_mm->locked_vm -= counter->data->nr_locked;
2096                 perf_mmap_data_free(counter);
2097                 mutex_unlock(&counter->mmap_mutex);
2098         }
2099 }
2100
2101 static struct vm_operations_struct perf_mmap_vmops = {
2102         .open           = perf_mmap_open,
2103         .close          = perf_mmap_close,
2104         .fault          = perf_mmap_fault,
2105         .page_mkwrite   = perf_mmap_fault,
2106 };
2107
2108 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
2109 {
2110         struct perf_counter *counter = file->private_data;
2111         unsigned long user_locked, user_lock_limit;
2112         struct user_struct *user = current_user();
2113         unsigned long locked, lock_limit;
2114         unsigned long vma_size;
2115         unsigned long nr_pages;
2116         long user_extra, extra;
2117         int ret = 0;
2118
2119         if (!(vma->vm_flags & VM_SHARED))
2120                 return -EINVAL;
2121
2122         vma_size = vma->vm_end - vma->vm_start;
2123         nr_pages = (vma_size / PAGE_SIZE) - 1;
2124
2125         /*
2126          * If we have data pages ensure they're a power-of-two number, so we
2127          * can do bitmasks instead of modulo.
2128          */
2129         if (nr_pages != 0 && !is_power_of_2(nr_pages))
2130                 return -EINVAL;
2131
2132         if (vma_size != PAGE_SIZE * (1 + nr_pages))
2133                 return -EINVAL;
2134
2135         if (vma->vm_pgoff != 0)
2136                 return -EINVAL;
2137
2138         WARN_ON_ONCE(counter->ctx->parent_ctx);
2139         mutex_lock(&counter->mmap_mutex);
2140         if (atomic_inc_not_zero(&counter->mmap_count)) {
2141                 if (nr_pages != counter->data->nr_pages)
2142                         ret = -EINVAL;
2143                 goto unlock;
2144         }
2145
2146         user_extra = nr_pages + 1;
2147         user_lock_limit = sysctl_perf_counter_mlock >> (PAGE_SHIFT - 10);
2148
2149         /*
2150          * Increase the limit linearly with more CPUs:
2151          */
2152         user_lock_limit *= num_online_cpus();
2153
2154         user_locked = atomic_long_read(&user->locked_vm) + user_extra;
2155
2156         extra = 0;
2157         if (user_locked > user_lock_limit)
2158                 extra = user_locked - user_lock_limit;
2159
2160         lock_limit = current->signal->rlim[RLIMIT_MEMLOCK].rlim_cur;
2161         lock_limit >>= PAGE_SHIFT;
2162         locked = vma->vm_mm->locked_vm + extra;
2163
2164         if ((locked > lock_limit) && !capable(CAP_IPC_LOCK)) {
2165                 ret = -EPERM;
2166                 goto unlock;
2167         }
2168
2169         WARN_ON(counter->data);
2170         ret = perf_mmap_data_alloc(counter, nr_pages);
2171         if (ret)
2172                 goto unlock;
2173
2174         atomic_set(&counter->mmap_count, 1);
2175         atomic_long_add(user_extra, &user->locked_vm);
2176         vma->vm_mm->locked_vm += extra;
2177         counter->data->nr_locked = extra;
2178         if (vma->vm_flags & VM_WRITE)
2179                 counter->data->writable = 1;
2180
2181 unlock:
2182         mutex_unlock(&counter->mmap_mutex);
2183
2184         vma->vm_flags |= VM_RESERVED;
2185         vma->vm_ops = &perf_mmap_vmops;
2186
2187         return ret;
2188 }
2189
2190 static int perf_fasync(int fd, struct file *filp, int on)
2191 {
2192         struct inode *inode = filp->f_path.dentry->d_inode;
2193         struct perf_counter *counter = filp->private_data;
2194         int retval;
2195
2196         mutex_lock(&inode->i_mutex);
2197         retval = fasync_helper(fd, filp, on, &counter->fasync);
2198         mutex_unlock(&inode->i_mutex);
2199
2200         if (retval < 0)
2201                 return retval;
2202
2203         return 0;
2204 }
2205
2206 static const struct file_operations perf_fops = {
2207         .release                = perf_release,
2208         .read                   = perf_read,
2209         .poll                   = perf_poll,
2210         .unlocked_ioctl         = perf_ioctl,
2211         .compat_ioctl           = perf_ioctl,
2212         .mmap                   = perf_mmap,
2213         .fasync                 = perf_fasync,
2214 };
2215
2216 /*
2217  * Perf counter wakeup
2218  *
2219  * If there's data, ensure we set the poll() state and publish everything
2220  * to user-space before waking everybody up.
2221  */
2222
2223 void perf_counter_wakeup(struct perf_counter *counter)
2224 {
2225         wake_up_all(&counter->waitq);
2226
2227         if (counter->pending_kill) {
2228                 kill_fasync(&counter->fasync, SIGIO, counter->pending_kill);
2229                 counter->pending_kill = 0;
2230         }
2231 }
2232
2233 /*
2234  * Pending wakeups
2235  *
2236  * Handle the case where we need to wakeup up from NMI (or rq->lock) context.
2237  *
2238  * The NMI bit means we cannot possibly take locks. Therefore, maintain a
2239  * single linked list and use cmpxchg() to add entries lockless.
2240  */
2241
2242 static void perf_pending_counter(struct perf_pending_entry *entry)
2243 {
2244         struct perf_counter *counter = container_of(entry,
2245                         struct perf_counter, pending);
2246
2247         if (counter->pending_disable) {
2248                 counter->pending_disable = 0;
2249                 perf_counter_disable(counter);
2250         }
2251
2252         if (counter->pending_wakeup) {
2253                 counter->pending_wakeup = 0;
2254                 perf_counter_wakeup(counter);
2255         }
2256 }
2257
2258 #define PENDING_TAIL ((struct perf_pending_entry *)-1UL)
2259
2260 static DEFINE_PER_CPU(struct perf_pending_entry *, perf_pending_head) = {
2261         PENDING_TAIL,
2262 };
2263
2264 static void perf_pending_queue(struct perf_pending_entry *entry,
2265                                void (*func)(struct perf_pending_entry *))
2266 {
2267         struct perf_pending_entry **head;
2268
2269         if (cmpxchg(&entry->next, NULL, PENDING_TAIL) != NULL)
2270                 return;
2271
2272         entry->func = func;
2273
2274         head = &get_cpu_var(perf_pending_head);
2275
2276         do {
2277                 entry->next = *head;
2278         } while (cmpxchg(head, entry->next, entry) != entry->next);
2279
2280         set_perf_counter_pending();
2281
2282         put_cpu_var(perf_pending_head);
2283 }
2284
2285 static int __perf_pending_run(void)
2286 {
2287         struct perf_pending_entry *list;
2288         int nr = 0;
2289
2290         list = xchg(&__get_cpu_var(perf_pending_head), PENDING_TAIL);
2291         while (list != PENDING_TAIL) {
2292                 void (*func)(struct perf_pending_entry *);
2293                 struct perf_pending_entry *entry = list;
2294
2295                 list = list->next;
2296
2297                 func = entry->func;
2298                 entry->next = NULL;
2299                 /*
2300                  * Ensure we observe the unqueue before we issue the wakeup,
2301                  * so that we won't be waiting forever.
2302                  * -- see perf_not_pending().
2303                  */
2304                 smp_wmb();
2305
2306                 func(entry);
2307                 nr++;
2308         }
2309
2310         return nr;
2311 }
2312
2313 static inline int perf_not_pending(struct perf_counter *counter)
2314 {
2315         /*
2316          * If we flush on whatever cpu we run, there is a chance we don't
2317          * need to wait.
2318          */
2319         get_cpu();
2320         __perf_pending_run();
2321         put_cpu();
2322
2323         /*
2324          * Ensure we see the proper queue state before going to sleep
2325          * so that we do not miss the wakeup. -- see perf_pending_handle()
2326          */
2327         smp_rmb();
2328         return counter->pending.next == NULL;
2329 }
2330
2331 static void perf_pending_sync(struct perf_counter *counter)
2332 {
2333         wait_event(counter->waitq, perf_not_pending(counter));
2334 }
2335
2336 void perf_counter_do_pending(void)
2337 {
2338         __perf_pending_run();
2339 }
2340
2341 /*
2342  * Callchain support -- arch specific
2343  */
2344
2345 __weak struct perf_callchain_entry *perf_callchain(struct pt_regs *regs)
2346 {
2347         return NULL;
2348 }
2349
2350 /*
2351  * Output
2352  */
2353
2354 struct perf_output_handle {
2355         struct perf_counter     *counter;
2356         struct perf_mmap_data   *data;
2357         unsigned long           head;
2358         unsigned long           offset;
2359         int                     nmi;
2360         int                     sample;
2361         int                     locked;
2362         unsigned long           flags;
2363 };
2364
2365 static bool perf_output_space(struct perf_mmap_data *data,
2366                               unsigned int offset, unsigned int head)
2367 {
2368         unsigned long tail;
2369         unsigned long mask;
2370
2371         if (!data->writable)
2372                 return true;
2373
2374         mask = (data->nr_pages << PAGE_SHIFT) - 1;
2375         /*
2376          * Userspace could choose to issue a mb() before updating the tail
2377          * pointer. So that all reads will be completed before the write is
2378          * issued.
2379          */
2380         tail = ACCESS_ONCE(data->user_page->data_tail);
2381         smp_rmb();
2382
2383         offset = (offset - tail) & mask;
2384         head   = (head   - tail) & mask;
2385
2386         if ((int)(head - offset) < 0)
2387                 return false;
2388
2389         return true;
2390 }
2391
2392 static void perf_output_wakeup(struct perf_output_handle *handle)
2393 {
2394         atomic_set(&handle->data->poll, POLL_IN);
2395
2396         if (handle->nmi) {
2397                 handle->counter->pending_wakeup = 1;
2398                 perf_pending_queue(&handle->counter->pending,
2399                                    perf_pending_counter);
2400         } else
2401                 perf_counter_wakeup(handle->counter);
2402 }
2403
2404 /*
2405  * Curious locking construct.
2406  *
2407  * We need to ensure a later event doesn't publish a head when a former
2408  * event isn't done writing. However since we need to deal with NMIs we
2409  * cannot fully serialize things.
2410  *
2411  * What we do is serialize between CPUs so we only have to deal with NMI
2412  * nesting on a single CPU.
2413  *
2414  * We only publish the head (and generate a wakeup) when the outer-most
2415  * event completes.
2416  */
2417 static void perf_output_lock(struct perf_output_handle *handle)
2418 {
2419         struct perf_mmap_data *data = handle->data;
2420         int cpu;
2421
2422         handle->locked = 0;
2423
2424         local_irq_save(handle->flags);
2425         cpu = smp_processor_id();
2426
2427         if (in_nmi() && atomic_read(&data->lock) == cpu)
2428                 return;
2429
2430         while (atomic_cmpxchg(&data->lock, -1, cpu) != -1)
2431                 cpu_relax();
2432
2433         handle->locked = 1;
2434 }
2435
2436 static void perf_output_unlock(struct perf_output_handle *handle)
2437 {
2438         struct perf_mmap_data *data = handle->data;
2439         unsigned long head;
2440         int cpu;
2441
2442         data->done_head = data->head;
2443
2444         if (!handle->locked)
2445                 goto out;
2446
2447 again:
2448         /*
2449          * The xchg implies a full barrier that ensures all writes are done
2450          * before we publish the new head, matched by a rmb() in userspace when
2451          * reading this position.
2452          */
2453         while ((head = atomic_long_xchg(&data->done_head, 0)))
2454                 data->user_page->data_head = head;
2455
2456         /*
2457          * NMI can happen here, which means we can miss a done_head update.
2458          */
2459
2460         cpu = atomic_xchg(&data->lock, -1);
2461         WARN_ON_ONCE(cpu != smp_processor_id());
2462
2463         /*
2464          * Therefore we have to validate we did not indeed do so.
2465          */
2466         if (unlikely(atomic_long_read(&data->done_head))) {
2467                 /*
2468                  * Since we had it locked, we can lock it again.
2469                  */
2470                 while (atomic_cmpxchg(&data->lock, -1, cpu) != -1)
2471                         cpu_relax();
2472
2473                 goto again;
2474         }
2475
2476         if (atomic_xchg(&data->wakeup, 0))
2477                 perf_output_wakeup(handle);
2478 out:
2479         local_irq_restore(handle->flags);
2480 }
2481
2482 static void perf_output_copy(struct perf_output_handle *handle,
2483                              const void *buf, unsigned int len)
2484 {
2485         unsigned int pages_mask;
2486         unsigned int offset;
2487         unsigned int size;
2488         void **pages;
2489
2490         offset          = handle->offset;
2491         pages_mask      = handle->data->nr_pages - 1;
2492         pages           = handle->data->data_pages;
2493
2494         do {
2495                 unsigned int page_offset;
2496                 int nr;
2497
2498                 nr          = (offset >> PAGE_SHIFT) & pages_mask;
2499                 page_offset = offset & (PAGE_SIZE - 1);
2500                 size        = min_t(unsigned int, PAGE_SIZE - page_offset, len);
2501
2502                 memcpy(pages[nr] + page_offset, buf, size);
2503
2504                 len         -= size;
2505                 buf         += size;
2506                 offset      += size;
2507         } while (len);
2508
2509         handle->offset = offset;
2510
2511         /*
2512          * Check we didn't copy past our reservation window, taking the
2513          * possible unsigned int wrap into account.
2514          */
2515         WARN_ON_ONCE(((long)(handle->head - handle->offset)) < 0);
2516 }
2517
2518 #define perf_output_put(handle, x) \
2519         perf_output_copy((handle), &(x), sizeof(x))
2520
2521 static int perf_output_begin(struct perf_output_handle *handle,
2522                              struct perf_counter *counter, unsigned int size,
2523                              int nmi, int sample)
2524 {
2525         struct perf_mmap_data *data;
2526         unsigned int offset, head;
2527         int have_lost;
2528         struct {
2529                 struct perf_event_header header;
2530                 u64                      id;
2531                 u64                      lost;
2532         } lost_event;
2533
2534         /*
2535          * For inherited counters we send all the output towards the parent.
2536          */
2537         if (counter->parent)
2538                 counter = counter->parent;
2539
2540         rcu_read_lock();
2541         data = rcu_dereference(counter->data);
2542         if (!data)
2543                 goto out;
2544
2545         handle->data    = data;
2546         handle->counter = counter;
2547         handle->nmi     = nmi;
2548         handle->sample  = sample;
2549
2550         if (!data->nr_pages)
2551                 goto fail;
2552
2553         have_lost = atomic_read(&data->lost);
2554         if (have_lost)
2555                 size += sizeof(lost_event);
2556
2557         perf_output_lock(handle);
2558
2559         do {
2560                 offset = head = atomic_long_read(&data->head);
2561                 head += size;
2562                 if (unlikely(!perf_output_space(data, offset, head)))
2563                         goto fail;
2564         } while (atomic_long_cmpxchg(&data->head, offset, head) != offset);
2565
2566         handle->offset  = offset;
2567         handle->head    = head;
2568
2569         if ((offset >> PAGE_SHIFT) != (head >> PAGE_SHIFT))
2570                 atomic_set(&data->wakeup, 1);
2571
2572         if (have_lost) {
2573                 lost_event.header.type = PERF_EVENT_LOST;
2574                 lost_event.header.misc = 0;
2575                 lost_event.header.size = sizeof(lost_event);
2576                 lost_event.id          = counter->id;
2577                 lost_event.lost        = atomic_xchg(&data->lost, 0);
2578
2579                 perf_output_put(handle, lost_event);
2580         }
2581
2582         return 0;
2583
2584 fail:
2585         atomic_inc(&data->lost);
2586         perf_output_unlock(handle);
2587 out:
2588         rcu_read_unlock();
2589
2590         return -ENOSPC;
2591 }
2592
2593 static void perf_output_end(struct perf_output_handle *handle)
2594 {
2595         struct perf_counter *counter = handle->counter;
2596         struct perf_mmap_data *data = handle->data;
2597
2598         int wakeup_events = counter->attr.wakeup_events;
2599
2600         if (handle->sample && wakeup_events) {
2601                 int events = atomic_inc_return(&data->events);
2602                 if (events >= wakeup_events) {
2603                         atomic_sub(wakeup_events, &data->events);
2604                         atomic_set(&data->wakeup, 1);
2605                 }
2606         }
2607
2608         perf_output_unlock(handle);
2609         rcu_read_unlock();
2610 }
2611
2612 static u32 perf_counter_pid(struct perf_counter *counter, struct task_struct *p)
2613 {
2614         /*
2615          * only top level counters have the pid namespace they were created in
2616          */
2617         if (counter->parent)
2618                 counter = counter->parent;
2619
2620         return task_tgid_nr_ns(p, counter->ns);
2621 }
2622
2623 static u32 perf_counter_tid(struct perf_counter *counter, struct task_struct *p)
2624 {
2625         /*
2626          * only top level counters have the pid namespace they were created in
2627          */
2628         if (counter->parent)
2629                 counter = counter->parent;
2630
2631         return task_pid_nr_ns(p, counter->ns);
2632 }
2633
2634 void perf_counter_output(struct perf_counter *counter, int nmi,
2635                                 struct perf_sample_data *data)
2636 {
2637         int ret;
2638         u64 sample_type = counter->attr.sample_type;
2639         struct perf_output_handle handle;
2640         struct perf_event_header header;
2641         u64 ip;
2642         struct {
2643                 u32 pid, tid;
2644         } tid_entry;
2645         struct {
2646                 u64 id;
2647                 u64 counter;
2648         } group_entry;
2649         struct perf_callchain_entry *callchain = NULL;
2650         int callchain_size = 0;
2651         u64 time;
2652         struct {
2653                 u32 cpu, reserved;
2654         } cpu_entry;
2655
2656         header.type = PERF_EVENT_SAMPLE;
2657         header.size = sizeof(header);
2658
2659         header.misc = 0;
2660         header.misc |= perf_misc_flags(data->regs);
2661
2662         if (sample_type & PERF_SAMPLE_IP) {
2663                 ip = perf_instruction_pointer(data->regs);
2664                 header.size += sizeof(ip);
2665         }
2666
2667         if (sample_type & PERF_SAMPLE_TID) {
2668                 /* namespace issues */
2669                 tid_entry.pid = perf_counter_pid(counter, current);
2670                 tid_entry.tid = perf_counter_tid(counter, current);
2671
2672                 header.size += sizeof(tid_entry);
2673         }
2674
2675         if (sample_type & PERF_SAMPLE_TIME) {
2676                 /*
2677                  * Maybe do better on x86 and provide cpu_clock_nmi()
2678                  */
2679                 time = sched_clock();
2680
2681                 header.size += sizeof(u64);
2682         }
2683
2684         if (sample_type & PERF_SAMPLE_ADDR)
2685                 header.size += sizeof(u64);
2686
2687         if (sample_type & PERF_SAMPLE_ID)
2688                 header.size += sizeof(u64);
2689
2690         if (sample_type & PERF_SAMPLE_STREAM_ID)
2691                 header.size += sizeof(u64);
2692
2693         if (sample_type & PERF_SAMPLE_CPU) {
2694                 header.size += sizeof(cpu_entry);
2695
2696                 cpu_entry.cpu = raw_smp_processor_id();
2697                 cpu_entry.reserved = 0;
2698         }
2699
2700         if (sample_type & PERF_SAMPLE_PERIOD)
2701                 header.size += sizeof(u64);
2702
2703         if (sample_type & PERF_SAMPLE_GROUP) {
2704                 header.size += sizeof(u64) +
2705                         counter->nr_siblings * sizeof(group_entry);
2706         }
2707
2708         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
2709                 callchain = perf_callchain(data->regs);
2710
2711                 if (callchain) {
2712                         callchain_size = (1 + callchain->nr) * sizeof(u64);
2713                         header.size += callchain_size;
2714                 } else
2715                         header.size += sizeof(u64);
2716         }
2717
2718         if (sample_type & PERF_SAMPLE_RAW) {
2719                 int size = sizeof(u32);
2720
2721                 if (data->raw)
2722                         size += data->raw->size;
2723                 else
2724                         size += sizeof(u32);
2725
2726                 WARN_ON_ONCE(size & (sizeof(u64)-1));
2727                 header.size += size;
2728         }
2729
2730         ret = perf_output_begin(&handle, counter, header.size, nmi, 1);
2731         if (ret)
2732                 return;
2733
2734         perf_output_put(&handle, header);
2735
2736         if (sample_type & PERF_SAMPLE_IP)
2737                 perf_output_put(&handle, ip);
2738
2739         if (sample_type & PERF_SAMPLE_TID)
2740                 perf_output_put(&handle, tid_entry);
2741
2742         if (sample_type & PERF_SAMPLE_TIME)
2743                 perf_output_put(&handle, time);
2744
2745         if (sample_type & PERF_SAMPLE_ADDR)
2746                 perf_output_put(&handle, data->addr);
2747
2748         if (sample_type & PERF_SAMPLE_ID) {
2749                 u64 id = primary_counter_id(counter);
2750
2751                 perf_output_put(&handle, id);
2752         }
2753
2754         if (sample_type & PERF_SAMPLE_STREAM_ID)
2755                 perf_output_put(&handle, counter->id);
2756
2757         if (sample_type & PERF_SAMPLE_CPU)
2758                 perf_output_put(&handle, cpu_entry);
2759
2760         if (sample_type & PERF_SAMPLE_PERIOD)
2761                 perf_output_put(&handle, data->period);
2762
2763         /*
2764          * XXX PERF_SAMPLE_GROUP vs inherited counters seems difficult.
2765          */
2766         if (sample_type & PERF_SAMPLE_GROUP) {
2767                 struct perf_counter *leader, *sub;
2768                 u64 nr = counter->nr_siblings;
2769
2770                 perf_output_put(&handle, nr);
2771
2772                 leader = counter->group_leader;
2773                 list_for_each_entry(sub, &leader->sibling_list, list_entry) {
2774                         if (sub != counter)
2775                                 sub->pmu->read(sub);
2776
2777                         group_entry.id = primary_counter_id(sub);
2778                         group_entry.counter = atomic64_read(&sub->count);
2779
2780                         perf_output_put(&handle, group_entry);
2781                 }
2782         }
2783
2784         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
2785                 if (callchain)
2786                         perf_output_copy(&handle, callchain, callchain_size);
2787                 else {
2788                         u64 nr = 0;
2789                         perf_output_put(&handle, nr);
2790                 }
2791         }
2792
2793         if (sample_type & PERF_SAMPLE_RAW) {
2794                 if (data->raw) {
2795                         perf_output_put(&handle, data->raw->size);
2796                         perf_output_copy(&handle, data->raw->data, data->raw->size);
2797                 } else {
2798                         struct {
2799                                 u32     size;
2800                                 u32     data;
2801                         } raw = {
2802                                 .size = sizeof(u32),
2803                                 .data = 0,
2804                         };
2805                         perf_output_put(&handle, raw);
2806                 }
2807         }
2808
2809         perf_output_end(&handle);
2810 }
2811
2812 /*
2813  * read event
2814  */
2815
2816 struct perf_read_event {
2817         struct perf_event_header        header;
2818
2819         u32                             pid;
2820         u32                             tid;
2821         u64                             value;
2822         u64                             format[3];
2823 };
2824
2825 static void
2826 perf_counter_read_event(struct perf_counter *counter,
2827                         struct task_struct *task)
2828 {
2829         struct perf_output_handle handle;
2830         struct perf_read_event event = {
2831                 .header = {
2832                         .type = PERF_EVENT_READ,
2833                         .misc = 0,
2834                         .size = sizeof(event) - sizeof(event.format),
2835                 },
2836                 .pid = perf_counter_pid(counter, task),
2837                 .tid = perf_counter_tid(counter, task),
2838                 .value = atomic64_read(&counter->count),
2839         };
2840         int ret, i = 0;
2841
2842         if (counter->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
2843                 event.header.size += sizeof(u64);
2844                 event.format[i++] = counter->total_time_enabled;
2845         }
2846
2847         if (counter->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
2848                 event.header.size += sizeof(u64);
2849                 event.format[i++] = counter->total_time_running;
2850         }
2851
2852         if (counter->attr.read_format & PERF_FORMAT_ID) {
2853                 event.header.size += sizeof(u64);
2854                 event.format[i++] = primary_counter_id(counter);
2855         }
2856
2857         ret = perf_output_begin(&handle, counter, event.header.size, 0, 0);
2858         if (ret)
2859                 return;
2860
2861         perf_output_copy(&handle, &event, event.header.size);
2862         perf_output_end(&handle);
2863 }
2864
2865 /*
2866  * task tracking -- fork/exit
2867  *
2868  * enabled by: attr.comm | attr.mmap | attr.task
2869  */
2870
2871 struct perf_task_event {
2872         struct task_struct              *task;
2873         struct perf_counter_context     *task_ctx;
2874
2875         struct {
2876                 struct perf_event_header        header;
2877
2878                 u32                             pid;
2879                 u32                             ppid;
2880                 u32                             tid;
2881                 u32                             ptid;
2882         } event;
2883 };
2884
2885 static void perf_counter_task_output(struct perf_counter *counter,
2886                                      struct perf_task_event *task_event)
2887 {
2888         struct perf_output_handle handle;
2889         int size = task_event->event.header.size;
2890         struct task_struct *task = task_event->task;
2891         int ret = perf_output_begin(&handle, counter, size, 0, 0);
2892
2893         if (ret)
2894                 return;
2895
2896         task_event->event.pid = perf_counter_pid(counter, task);
2897         task_event->event.ppid = perf_counter_pid(counter, task->real_parent);
2898
2899         task_event->event.tid = perf_counter_tid(counter, task);
2900         task_event->event.ptid = perf_counter_tid(counter, task->real_parent);
2901
2902         perf_output_put(&handle, task_event->event);
2903         perf_output_end(&handle);
2904 }
2905
2906 static int perf_counter_task_match(struct perf_counter *counter)
2907 {
2908         if (counter->attr.comm || counter->attr.mmap || counter->attr.task)
2909                 return 1;
2910
2911         return 0;
2912 }
2913
2914 static void perf_counter_task_ctx(struct perf_counter_context *ctx,
2915                                   struct perf_task_event *task_event)
2916 {
2917         struct perf_counter *counter;
2918
2919         if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
2920                 return;
2921
2922         rcu_read_lock();
2923         list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
2924                 if (perf_counter_task_match(counter))
2925                         perf_counter_task_output(counter, task_event);
2926         }
2927         rcu_read_unlock();
2928 }
2929
2930 static void perf_counter_task_event(struct perf_task_event *task_event)
2931 {
2932         struct perf_cpu_context *cpuctx;
2933         struct perf_counter_context *ctx = task_event->task_ctx;
2934
2935         cpuctx = &get_cpu_var(perf_cpu_context);
2936         perf_counter_task_ctx(&cpuctx->ctx, task_event);
2937         put_cpu_var(perf_cpu_context);
2938
2939         rcu_read_lock();
2940         if (!ctx)
2941                 ctx = rcu_dereference(task_event->task->perf_counter_ctxp);
2942         if (ctx)
2943                 perf_counter_task_ctx(ctx, task_event);
2944         rcu_read_unlock();
2945 }
2946
2947 static void perf_counter_task(struct task_struct *task,
2948                               struct perf_counter_context *task_ctx,
2949                               int new)
2950 {
2951         struct perf_task_event task_event;
2952
2953         if (!atomic_read(&nr_comm_counters) &&
2954             !atomic_read(&nr_mmap_counters) &&
2955             !atomic_read(&nr_task_counters))
2956                 return;
2957
2958         task_event = (struct perf_task_event){
2959                 .task     = task,
2960                 .task_ctx = task_ctx,
2961                 .event    = {
2962                         .header = {
2963                                 .type = new ? PERF_EVENT_FORK : PERF_EVENT_EXIT,
2964                                 .misc = 0,
2965                                 .size = sizeof(task_event.event),
2966                         },
2967                         /* .pid  */
2968                         /* .ppid */
2969                         /* .tid  */
2970                         /* .ptid */
2971                 },
2972         };
2973
2974         perf_counter_task_event(&task_event);
2975 }
2976
2977 void perf_counter_fork(struct task_struct *task)
2978 {
2979         perf_counter_task(task, NULL, 1);
2980 }
2981
2982 /*
2983  * comm tracking
2984  */
2985
2986 struct perf_comm_event {
2987         struct task_struct      *task;
2988         char                    *comm;
2989         int                     comm_size;
2990
2991         struct {
2992                 struct perf_event_header        header;
2993
2994                 u32                             pid;
2995                 u32                             tid;
2996         } event;
2997 };
2998
2999 static void perf_counter_comm_output(struct perf_counter *counter,
3000                                      struct perf_comm_event *comm_event)
3001 {
3002         struct perf_output_handle handle;
3003         int size = comm_event->event.header.size;
3004         int ret = perf_output_begin(&handle, counter, size, 0, 0);
3005
3006         if (ret)
3007                 return;
3008
3009         comm_event->event.pid = perf_counter_pid(counter, comm_event->task);
3010         comm_event->event.tid = perf_counter_tid(counter, comm_event->task);
3011
3012         perf_output_put(&handle, comm_event->event);
3013         perf_output_copy(&handle, comm_event->comm,
3014                                    comm_event->comm_size);
3015         perf_output_end(&handle);
3016 }
3017
3018 static int perf_counter_comm_match(struct perf_counter *counter)
3019 {
3020         if (counter->attr.comm)
3021                 return 1;
3022
3023         return 0;
3024 }
3025
3026 static void perf_counter_comm_ctx(struct perf_counter_context *ctx,
3027                                   struct perf_comm_event *comm_event)
3028 {
3029         struct perf_counter *counter;
3030
3031         if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
3032                 return;
3033
3034         rcu_read_lock();
3035         list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
3036                 if (perf_counter_comm_match(counter))
3037                         perf_counter_comm_output(counter, comm_event);
3038         }
3039         rcu_read_unlock();
3040 }
3041
3042 static void perf_counter_comm_event(struct perf_comm_event *comm_event)
3043 {
3044         struct perf_cpu_context *cpuctx;
3045         struct perf_counter_context *ctx;
3046         unsigned int size;
3047         char comm[TASK_COMM_LEN];
3048
3049         memset(comm, 0, sizeof(comm));
3050         strncpy(comm, comm_event->task->comm, sizeof(comm));
3051         size = ALIGN(strlen(comm)+1, sizeof(u64));
3052
3053         comm_event->comm = comm;
3054         comm_event->comm_size = size;
3055
3056         comm_event->event.header.size = sizeof(comm_event->event) + size;
3057
3058         cpuctx = &get_cpu_var(perf_cpu_context);
3059         perf_counter_comm_ctx(&cpuctx->ctx, comm_event);
3060         put_cpu_var(perf_cpu_context);
3061
3062         rcu_read_lock();
3063         /*
3064          * doesn't really matter which of the child contexts the
3065          * events ends up in.
3066          */
3067         ctx = rcu_dereference(current->perf_counter_ctxp);
3068         if (ctx)
3069                 perf_counter_comm_ctx(ctx, comm_event);
3070         rcu_read_unlock();
3071 }
3072
3073 void perf_counter_comm(struct task_struct *task)
3074 {
3075         struct perf_comm_event comm_event;
3076
3077         if (task->perf_counter_ctxp)
3078                 perf_counter_enable_on_exec(task);
3079
3080         if (!atomic_read(&nr_comm_counters))
3081                 return;
3082
3083         comm_event = (struct perf_comm_event){
3084                 .task   = task,
3085                 /* .comm      */
3086                 /* .comm_size */
3087                 .event  = {
3088                         .header = {
3089                                 .type = PERF_EVENT_COMM,
3090                                 .misc = 0,
3091                                 /* .size */
3092                         },
3093                         /* .pid */
3094                         /* .tid */
3095                 },
3096         };
3097
3098         perf_counter_comm_event(&comm_event);
3099 }
3100
3101 /*
3102  * mmap tracking
3103  */
3104
3105 struct perf_mmap_event {
3106         struct vm_area_struct   *vma;
3107
3108         const char              *file_name;
3109         int                     file_size;
3110
3111         struct {
3112                 struct perf_event_header        header;
3113
3114                 u32                             pid;
3115                 u32                             tid;
3116                 u64                             start;
3117                 u64                             len;
3118                 u64                             pgoff;
3119         } event;
3120 };
3121
3122 static void perf_counter_mmap_output(struct perf_counter *counter,
3123                                      struct perf_mmap_event *mmap_event)
3124 {
3125         struct perf_output_handle handle;
3126         int size = mmap_event->event.header.size;
3127         int ret = perf_output_begin(&handle, counter, size, 0, 0);
3128
3129         if (ret)
3130                 return;
3131
3132         mmap_event->event.pid = perf_counter_pid(counter, current);
3133         mmap_event->event.tid = perf_counter_tid(counter, current);
3134
3135         perf_output_put(&handle, mmap_event->event);
3136         perf_output_copy(&handle, mmap_event->file_name,
3137                                    mmap_event->file_size);
3138         perf_output_end(&handle);
3139 }
3140
3141 static int perf_counter_mmap_match(struct perf_counter *counter,
3142                                    struct perf_mmap_event *mmap_event)
3143 {
3144         if (counter->attr.mmap)
3145                 return 1;
3146
3147         return 0;
3148 }
3149
3150 static void perf_counter_mmap_ctx(struct perf_counter_context *ctx,
3151                                   struct perf_mmap_event *mmap_event)
3152 {
3153         struct perf_counter *counter;
3154
3155         if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
3156                 return;
3157
3158         rcu_read_lock();
3159         list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
3160                 if (perf_counter_mmap_match(counter, mmap_event))
3161                         perf_counter_mmap_output(counter, mmap_event);
3162         }
3163         rcu_read_unlock();
3164 }
3165
3166 static void perf_counter_mmap_event(struct perf_mmap_event *mmap_event)
3167 {
3168         struct perf_cpu_context *cpuctx;
3169         struct perf_counter_context *ctx;
3170         struct vm_area_struct *vma = mmap_event->vma;
3171         struct file *file = vma->vm_file;
3172         unsigned int size;
3173         char tmp[16];
3174         char *buf = NULL;
3175         const char *name;
3176
3177         memset(tmp, 0, sizeof(tmp));
3178
3179         if (file) {
3180                 /*
3181                  * d_path works from the end of the buffer backwards, so we
3182                  * need to add enough zero bytes after the string to handle
3183                  * the 64bit alignment we do later.
3184                  */
3185                 buf = kzalloc(PATH_MAX + sizeof(u64), GFP_KERNEL);
3186                 if (!buf) {
3187                         name = strncpy(tmp, "//enomem", sizeof(tmp));
3188                         goto got_name;
3189                 }
3190                 name = d_path(&file->f_path, buf, PATH_MAX);
3191                 if (IS_ERR(name)) {
3192                         name = strncpy(tmp, "//toolong", sizeof(tmp));
3193                         goto got_name;
3194                 }
3195         } else {
3196                 if (arch_vma_name(mmap_event->vma)) {
3197                         name = strncpy(tmp, arch_vma_name(mmap_event->vma),
3198                                        sizeof(tmp));
3199                         goto got_name;
3200                 }
3201
3202                 if (!vma->vm_mm) {
3203                         name = strncpy(tmp, "[vdso]", sizeof(tmp));
3204                         goto got_name;
3205                 }
3206
3207                 name = strncpy(tmp, "//anon", sizeof(tmp));
3208                 goto got_name;
3209         }
3210
3211 got_name:
3212         size = ALIGN(strlen(name)+1, sizeof(u64));
3213
3214         mmap_event->file_name = name;
3215         mmap_event->file_size = size;
3216
3217         mmap_event->event.header.size = sizeof(mmap_event->event) + size;
3218
3219         cpuctx = &get_cpu_var(perf_cpu_context);
3220         perf_counter_mmap_ctx(&cpuctx->ctx, mmap_event);
3221         put_cpu_var(perf_cpu_context);
3222
3223         rcu_read_lock();
3224         /*
3225          * doesn't really matter which of the child contexts the
3226          * events ends up in.
3227          */
3228         ctx = rcu_dereference(current->perf_counter_ctxp);
3229         if (ctx)
3230                 perf_counter_mmap_ctx(ctx, mmap_event);
3231         rcu_read_unlock();
3232
3233         kfree(buf);
3234 }
3235
3236 void __perf_counter_mmap(struct vm_area_struct *vma)
3237 {
3238         struct perf_mmap_event mmap_event;
3239
3240         if (!atomic_read(&nr_mmap_counters))
3241                 return;
3242
3243         mmap_event = (struct perf_mmap_event){
3244                 .vma    = vma,
3245                 /* .file_name */
3246                 /* .file_size */
3247                 .event  = {
3248                         .header = {
3249                                 .type = PERF_EVENT_MMAP,
3250                                 .misc = 0,
3251                                 /* .size */
3252                         },
3253                         /* .pid */
3254                         /* .tid */
3255                         .start  = vma->vm_start,
3256                         .len    = vma->vm_end - vma->vm_start,
3257                         .pgoff  = vma->vm_pgoff,
3258                 },
3259         };
3260
3261         perf_counter_mmap_event(&mmap_event);
3262 }
3263
3264 /*
3265  * IRQ throttle logging
3266  */
3267
3268 static void perf_log_throttle(struct perf_counter *counter, int enable)
3269 {
3270         struct perf_output_handle handle;
3271         int ret;
3272
3273         struct {
3274                 struct perf_event_header        header;
3275                 u64                             time;
3276                 u64                             id;
3277                 u64                             stream_id;
3278         } throttle_event = {
3279                 .header = {
3280                         .type = PERF_EVENT_THROTTLE,
3281                         .misc = 0,
3282                         .size = sizeof(throttle_event),
3283                 },
3284                 .time           = sched_clock(),
3285                 .id             = primary_counter_id(counter),
3286                 .stream_id      = counter->id,
3287         };
3288
3289         if (enable)
3290                 throttle_event.header.type = PERF_EVENT_UNTHROTTLE;
3291
3292         ret = perf_output_begin(&handle, counter, sizeof(throttle_event), 1, 0);
3293         if (ret)
3294                 return;
3295
3296         perf_output_put(&handle, throttle_event);
3297         perf_output_end(&handle);
3298 }
3299
3300 /*
3301  * Generic counter overflow handling, sampling.
3302  */
3303
3304 int perf_counter_overflow(struct perf_counter *counter, int nmi,
3305                           struct perf_sample_data *data)
3306 {
3307         int events = atomic_read(&counter->event_limit);
3308         int throttle = counter->pmu->unthrottle != NULL;
3309         struct hw_perf_counter *hwc = &counter->hw;
3310         int ret = 0;
3311
3312         if (!throttle) {
3313                 hwc->interrupts++;
3314         } else {
3315                 if (hwc->interrupts != MAX_INTERRUPTS) {
3316                         hwc->interrupts++;
3317                         if (HZ * hwc->interrupts >
3318                                         (u64)sysctl_perf_counter_sample_rate) {
3319                                 hwc->interrupts = MAX_INTERRUPTS;
3320                                 perf_log_throttle(counter, 0);
3321                                 ret = 1;
3322                         }
3323                 } else {
3324                         /*
3325                          * Keep re-disabling counters even though on the previous
3326                          * pass we disabled it - just in case we raced with a
3327                          * sched-in and the counter got enabled again:
3328                          */
3329                         ret = 1;
3330                 }
3331         }
3332
3333         if (counter->attr.freq) {
3334                 u64 now = sched_clock();
3335                 s64 delta = now - hwc->freq_stamp;
3336
3337                 hwc->freq_stamp = now;
3338
3339                 if (delta > 0 && delta < TICK_NSEC)
3340                         perf_adjust_period(counter, NSEC_PER_SEC / (int)delta);
3341         }
3342
3343         /*
3344          * XXX event_limit might not quite work as expected on inherited
3345          * counters
3346          */
3347
3348         counter->pending_kill = POLL_IN;
3349         if (events && atomic_dec_and_test(&counter->event_limit)) {
3350                 ret = 1;
3351                 counter->pending_kill = POLL_HUP;
3352                 if (nmi) {
3353                         counter->pending_disable = 1;
3354                         perf_pending_queue(&counter->pending,
3355                                            perf_pending_counter);
3356                 } else
3357                         perf_counter_disable(counter);
3358         }
3359
3360         perf_counter_output(counter, nmi, data);
3361         return ret;
3362 }
3363
3364 /*
3365  * Generic software counter infrastructure
3366  */
3367
3368 /*
3369  * We directly increment counter->count and keep a second value in
3370  * counter->hw.period_left to count intervals. This period counter
3371  * is kept in the range [-sample_period, 0] so that we can use the
3372  * sign as trigger.
3373  */
3374
3375 static u64 perf_swcounter_set_period(struct perf_counter *counter)
3376 {
3377         struct hw_perf_counter *hwc = &counter->hw;
3378         u64 period = hwc->last_period;
3379         u64 nr, offset;
3380         s64 old, val;
3381
3382         hwc->last_period = hwc->sample_period;
3383
3384 again:
3385         old = val = atomic64_read(&hwc->period_left);
3386         if (val < 0)
3387                 return 0;
3388
3389         nr = div64_u64(period + val, period);
3390         offset = nr * period;
3391         val -= offset;
3392         if (atomic64_cmpxchg(&hwc->period_left, old, val) != old)
3393                 goto again;
3394
3395         return nr;
3396 }
3397
3398 static void perf_swcounter_overflow(struct perf_counter *counter,
3399                                     int nmi, struct perf_sample_data *data)
3400 {
3401         struct hw_perf_counter *hwc = &counter->hw;
3402         u64 overflow;
3403
3404         data->period = counter->hw.last_period;
3405         overflow = perf_swcounter_set_period(counter);
3406
3407         if (hwc->interrupts == MAX_INTERRUPTS)
3408                 return;
3409
3410         for (; overflow; overflow--) {
3411                 if (perf_counter_overflow(counter, nmi, data)) {
3412                         /*
3413                          * We inhibit the overflow from happening when
3414                          * hwc->interrupts == MAX_INTERRUPTS.
3415                          */
3416                         break;
3417                 }
3418         }
3419 }
3420
3421 static void perf_swcounter_unthrottle(struct perf_counter *counter)
3422 {
3423         /*
3424          * Nothing to do, we already reset hwc->interrupts.
3425          */
3426 }
3427
3428 static void perf_swcounter_add(struct perf_counter *counter, u64 nr,
3429                                int nmi, struct perf_sample_data *data)
3430 {
3431         struct hw_perf_counter *hwc = &counter->hw;
3432
3433         atomic64_add(nr, &counter->count);
3434
3435         if (!hwc->sample_period)
3436                 return;
3437
3438         if (!data->regs)
3439                 return;
3440
3441         if (!atomic64_add_negative(nr, &hwc->period_left))
3442                 perf_swcounter_overflow(counter, nmi, data);
3443 }
3444
3445 static int perf_swcounter_is_counting(struct perf_counter *counter)
3446 {
3447         struct perf_counter_context *ctx;
3448         unsigned long flags;
3449         int count;
3450
3451         if (counter->state == PERF_COUNTER_STATE_ACTIVE)
3452                 return 1;
3453
3454         if (counter->state != PERF_COUNTER_STATE_INACTIVE)
3455                 return 0;
3456
3457         /*
3458          * If the counter is inactive, it could be just because
3459          * its task is scheduled out, or because it's in a group
3460          * which could not go on the PMU.  We want to count in
3461          * the first case but not the second.  If the context is
3462          * currently active then an inactive software counter must
3463          * be the second case.  If it's not currently active then
3464          * we need to know whether the counter was active when the
3465          * context was last active, which we can determine by
3466          * comparing counter->tstamp_stopped with ctx->time.
3467          *
3468          * We are within an RCU read-side critical section,
3469          * which protects the existence of *ctx.
3470          */
3471         ctx = counter->ctx;
3472         spin_lock_irqsave(&ctx->lock, flags);
3473         count = 1;
3474         /* Re-check state now we have the lock */
3475         if (counter->state < PERF_COUNTER_STATE_INACTIVE ||
3476             counter->ctx->is_active ||
3477             counter->tstamp_stopped < ctx->time)
3478                 count = 0;
3479         spin_unlock_irqrestore(&ctx->lock, flags);
3480         return count;
3481 }
3482
3483 static int perf_swcounter_match(struct perf_counter *counter,
3484                                 enum perf_type_id type,
3485                                 u32 event, struct pt_regs *regs)
3486 {
3487         if (!perf_swcounter_is_counting(counter))
3488                 return 0;
3489
3490         if (counter->attr.type != type)
3491                 return 0;
3492         if (counter->attr.config != event)
3493                 return 0;
3494
3495         if (regs) {
3496                 if (counter->attr.exclude_user && user_mode(regs))
3497                         return 0;
3498
3499                 if (counter->attr.exclude_kernel && !user_mode(regs))
3500                         return 0;
3501         }
3502
3503         return 1;
3504 }
3505
3506 static void perf_swcounter_ctx_event(struct perf_counter_context *ctx,
3507                                      enum perf_type_id type,
3508                                      u32 event, u64 nr, int nmi,
3509                                      struct perf_sample_data *data)
3510 {
3511         struct perf_counter *counter;
3512
3513         if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
3514                 return;
3515
3516         rcu_read_lock();
3517         list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
3518                 if (perf_swcounter_match(counter, type, event, data->regs))
3519                         perf_swcounter_add(counter, nr, nmi, data);
3520         }
3521         rcu_read_unlock();
3522 }
3523
3524 static int *perf_swcounter_recursion_context(struct perf_cpu_context *cpuctx)
3525 {
3526         if (in_nmi())
3527                 return &cpuctx->recursion[3];
3528
3529         if (in_irq())
3530                 return &cpuctx->recursion[2];
3531
3532         if (in_softirq())
3533                 return &cpuctx->recursion[1];
3534
3535         return &cpuctx->recursion[0];
3536 }
3537
3538 static void do_perf_swcounter_event(enum perf_type_id type, u32 event,
3539                                     u64 nr, int nmi,
3540                                     struct perf_sample_data *data)
3541 {
3542         struct perf_cpu_context *cpuctx = &get_cpu_var(perf_cpu_context);
3543         int *recursion = perf_swcounter_recursion_context(cpuctx);
3544         struct perf_counter_context *ctx;
3545
3546         if (*recursion)
3547                 goto out;
3548
3549         (*recursion)++;
3550         barrier();
3551
3552         perf_swcounter_ctx_event(&cpuctx->ctx, type, event,
3553                                  nr, nmi, data);
3554         rcu_read_lock();
3555         /*
3556          * doesn't really matter which of the child contexts the
3557          * events ends up in.
3558          */
3559         ctx = rcu_dereference(current->perf_counter_ctxp);
3560         if (ctx)
3561                 perf_swcounter_ctx_event(ctx, type, event, nr, nmi, data);
3562         rcu_read_unlock();
3563
3564         barrier();
3565         (*recursion)--;
3566
3567 out:
3568         put_cpu_var(perf_cpu_context);
3569 }
3570
3571 void __perf_swcounter_event(u32 event, u64 nr, int nmi,
3572                             struct pt_regs *regs, u64 addr)
3573 {
3574         struct perf_sample_data data = {
3575                 .regs = regs,
3576                 .addr = addr,
3577         };
3578
3579         do_perf_swcounter_event(PERF_TYPE_SOFTWARE, event, nr, nmi, &data);
3580 }
3581
3582 static void perf_swcounter_read(struct perf_counter *counter)
3583 {
3584 }
3585
3586 static int perf_swcounter_enable(struct perf_counter *counter)
3587 {
3588         struct hw_perf_counter *hwc = &counter->hw;
3589
3590         if (hwc->sample_period) {
3591                 hwc->last_period = hwc->sample_period;
3592                 perf_swcounter_set_period(counter);
3593         }
3594         return 0;
3595 }
3596
3597 static void perf_swcounter_disable(struct perf_counter *counter)
3598 {
3599 }
3600
3601 static const struct pmu perf_ops_generic = {
3602         .enable         = perf_swcounter_enable,
3603         .disable        = perf_swcounter_disable,
3604         .read           = perf_swcounter_read,
3605         .unthrottle     = perf_swcounter_unthrottle,
3606 };
3607
3608 /*
3609  * hrtimer based swcounter callback
3610  */
3611
3612 static enum hrtimer_restart perf_swcounter_hrtimer(struct hrtimer *hrtimer)
3613 {
3614         enum hrtimer_restart ret = HRTIMER_RESTART;
3615         struct perf_sample_data data;
3616         struct perf_counter *counter;
3617         u64 period;
3618
3619         counter = container_of(hrtimer, struct perf_counter, hw.hrtimer);
3620         counter->pmu->read(counter);
3621
3622         data.addr = 0;
3623         data.regs = get_irq_regs();
3624         /*
3625          * In case we exclude kernel IPs or are somehow not in interrupt
3626          * context, provide the next best thing, the user IP.
3627          */
3628         if ((counter->attr.exclude_kernel || !data.regs) &&
3629                         !counter->attr.exclude_user)
3630                 data.regs = task_pt_regs(current);
3631
3632         if (data.regs) {
3633                 if (perf_counter_overflow(counter, 0, &data))
3634                         ret = HRTIMER_NORESTART;
3635         }
3636
3637         period = max_t(u64, 10000, counter->hw.sample_period);
3638         hrtimer_forward_now(hrtimer, ns_to_ktime(period));
3639
3640         return ret;
3641 }
3642
3643 /*
3644  * Software counter: cpu wall time clock
3645  */
3646
3647 static void cpu_clock_perf_counter_update(struct perf_counter *counter)
3648 {
3649         int cpu = raw_smp_processor_id();
3650         s64 prev;
3651         u64 now;
3652
3653         now = cpu_clock(cpu);
3654         prev = atomic64_read(&counter->hw.prev_count);
3655         atomic64_set(&counter->hw.prev_count, now);
3656         atomic64_add(now - prev, &counter->count);
3657 }
3658
3659 static int cpu_clock_perf_counter_enable(struct perf_counter *counter)
3660 {
3661         struct hw_perf_counter *hwc = &counter->hw;
3662         int cpu = raw_smp_processor_id();
3663
3664         atomic64_set(&hwc->prev_count, cpu_clock(cpu));
3665         hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3666         hwc->hrtimer.function = perf_swcounter_hrtimer;
3667         if (hwc->sample_period) {
3668                 u64 period = max_t(u64, 10000, hwc->sample_period);
3669                 __hrtimer_start_range_ns(&hwc->hrtimer,
3670                                 ns_to_ktime(period), 0,
3671                                 HRTIMER_MODE_REL, 0);
3672         }
3673
3674         return 0;
3675 }
3676
3677 static void cpu_clock_perf_counter_disable(struct perf_counter *counter)
3678 {
3679         if (counter->hw.sample_period)
3680                 hrtimer_cancel(&counter->hw.hrtimer);
3681         cpu_clock_perf_counter_update(counter);
3682 }
3683
3684 static void cpu_clock_perf_counter_read(struct perf_counter *counter)
3685 {
3686         cpu_clock_perf_counter_update(counter);
3687 }
3688
3689 static const struct pmu perf_ops_cpu_clock = {
3690         .enable         = cpu_clock_perf_counter_enable,
3691         .disable        = cpu_clock_perf_counter_disable,
3692         .read           = cpu_clock_perf_counter_read,
3693 };
3694
3695 /*
3696  * Software counter: task time clock
3697  */
3698
3699 static void task_clock_perf_counter_update(struct perf_counter *counter, u64 now)
3700 {
3701         u64 prev;
3702         s64 delta;
3703
3704         prev = atomic64_xchg(&counter->hw.prev_count, now);
3705         delta = now - prev;
3706         atomic64_add(delta, &counter->count);
3707 }
3708
3709 static int task_clock_perf_counter_enable(struct perf_counter *counter)
3710 {
3711         struct hw_perf_counter *hwc = &counter->hw;
3712         u64 now;
3713
3714         now = counter->ctx->time;
3715
3716         atomic64_set(&hwc->prev_count, now);
3717         hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3718         hwc->hrtimer.function = perf_swcounter_hrtimer;
3719         if (hwc->sample_period) {
3720                 u64 period = max_t(u64, 10000, hwc->sample_period);
3721                 __hrtimer_start_range_ns(&hwc->hrtimer,
3722                                 ns_to_ktime(period), 0,
3723                                 HRTIMER_MODE_REL, 0);
3724         }
3725
3726         return 0;
3727 }
3728
3729 static void task_clock_perf_counter_disable(struct perf_counter *counter)
3730 {
3731         if (counter->hw.sample_period)
3732                 hrtimer_cancel(&counter->hw.hrtimer);
3733         task_clock_perf_counter_update(counter, counter->ctx->time);
3734
3735 }
3736
3737 static void task_clock_perf_counter_read(struct perf_counter *counter)
3738 {
3739         u64 time;
3740
3741         if (!in_nmi()) {
3742                 update_context_time(counter->ctx);
3743                 time = counter->ctx->time;
3744         } else {
3745                 u64 now = perf_clock();
3746                 u64 delta = now - counter->ctx->timestamp;
3747                 time = counter->ctx->time + delta;
3748         }
3749
3750         task_clock_perf_counter_update(counter, time);
3751 }
3752
3753 static const struct pmu perf_ops_task_clock = {
3754         .enable         = task_clock_perf_counter_enable,
3755         .disable        = task_clock_perf_counter_disable,
3756         .read           = task_clock_perf_counter_read,
3757 };
3758
3759 #ifdef CONFIG_EVENT_PROFILE
3760 void perf_tpcounter_event(int event_id, u64 addr, u64 count, void *record,
3761                           int entry_size)
3762 {
3763         struct perf_raw_record raw = {
3764                 .size = entry_size,
3765                 .data = record,
3766         };
3767
3768         struct perf_sample_data data = {
3769                 .regs = get_irq_regs(),
3770                 .addr = addr,
3771                 .raw = &raw,
3772         };
3773
3774         if (!data.regs)
3775                 data.regs = task_pt_regs(current);
3776
3777         do_perf_swcounter_event(PERF_TYPE_TRACEPOINT, event_id, count, 1, &data);
3778 }
3779 EXPORT_SYMBOL_GPL(perf_tpcounter_event);
3780
3781 extern int ftrace_profile_enable(int);
3782 extern void ftrace_profile_disable(int);
3783
3784 static void tp_perf_counter_destroy(struct perf_counter *counter)
3785 {
3786         ftrace_profile_disable(counter->attr.config);
3787 }
3788
3789 static const struct pmu *tp_perf_counter_init(struct perf_counter *counter)
3790 {
3791         /*
3792          * Raw tracepoint data is a severe data leak, only allow root to
3793          * have these.
3794          */
3795         if ((counter->attr.sample_type & PERF_SAMPLE_RAW) &&
3796                         !capable(CAP_SYS_ADMIN))
3797                 return ERR_PTR(-EPERM);
3798
3799         if (ftrace_profile_enable(counter->attr.config))
3800                 return NULL;
3801
3802         counter->destroy = tp_perf_counter_destroy;
3803
3804         return &perf_ops_generic;
3805 }
3806 #else
3807 static const struct pmu *tp_perf_counter_init(struct perf_counter *counter)
3808 {
3809         return NULL;
3810 }
3811 #endif
3812
3813 atomic_t perf_swcounter_enabled[PERF_COUNT_SW_MAX];
3814
3815 static void sw_perf_counter_destroy(struct perf_counter *counter)
3816 {
3817         u64 event = counter->attr.config;
3818
3819         WARN_ON(counter->parent);
3820
3821         atomic_dec(&perf_swcounter_enabled[event]);
3822 }
3823
3824 static const struct pmu *sw_perf_counter_init(struct perf_counter *counter)
3825 {
3826         const struct pmu *pmu = NULL;
3827         u64 event = counter->attr.config;
3828
3829         /*
3830          * Software counters (currently) can't in general distinguish
3831          * between user, kernel and hypervisor events.
3832          * However, context switches and cpu migrations are considered
3833          * to be kernel events, and page faults are never hypervisor
3834          * events.
3835          */
3836         switch (event) {
3837         case PERF_COUNT_SW_CPU_CLOCK:
3838                 pmu = &perf_ops_cpu_clock;
3839
3840                 break;
3841         case PERF_COUNT_SW_TASK_CLOCK:
3842                 /*
3843                  * If the user instantiates this as a per-cpu counter,
3844                  * use the cpu_clock counter instead.
3845                  */
3846                 if (counter->ctx->task)
3847                         pmu = &perf_ops_task_clock;
3848                 else
3849                         pmu = &perf_ops_cpu_clock;
3850
3851                 break;
3852         case PERF_COUNT_SW_PAGE_FAULTS:
3853         case PERF_COUNT_SW_PAGE_FAULTS_MIN:
3854         case PERF_COUNT_SW_PAGE_FAULTS_MAJ:
3855         case PERF_COUNT_SW_CONTEXT_SWITCHES:
3856         case PERF_COUNT_SW_CPU_MIGRATIONS:
3857                 if (!counter->parent) {
3858                         atomic_inc(&perf_swcounter_enabled[event]);
3859                         counter->destroy = sw_perf_counter_destroy;
3860                 }
3861                 pmu = &perf_ops_generic;
3862                 break;
3863         }
3864
3865         return pmu;
3866 }
3867
3868 /*
3869  * Allocate and initialize a counter structure
3870  */
3871 static struct perf_counter *
3872 perf_counter_alloc(struct perf_counter_attr *attr,
3873                    int cpu,
3874                    struct perf_counter_context *ctx,
3875                    struct perf_counter *group_leader,
3876                    struct perf_counter *parent_counter,
3877                    gfp_t gfpflags)
3878 {
3879         const struct pmu *pmu;
3880         struct perf_counter *counter;
3881         struct hw_perf_counter *hwc;
3882         long err;
3883
3884         counter = kzalloc(sizeof(*counter), gfpflags);
3885         if (!counter)
3886                 return ERR_PTR(-ENOMEM);
3887
3888         /*
3889          * Single counters are their own group leaders, with an
3890          * empty sibling list:
3891          */
3892         if (!group_leader)
3893                 group_leader = counter;
3894
3895         mutex_init(&counter->child_mutex);
3896         INIT_LIST_HEAD(&counter->child_list);
3897
3898         INIT_LIST_HEAD(&counter->list_entry);
3899         INIT_LIST_HEAD(&counter->event_entry);
3900         INIT_LIST_HEAD(&counter->sibling_list);
3901         init_waitqueue_head(&counter->waitq);
3902
3903         mutex_init(&counter->mmap_mutex);
3904
3905         counter->cpu            = cpu;
3906         counter->attr           = *attr;
3907         counter->group_leader   = group_leader;
3908         counter->pmu            = NULL;
3909         counter->ctx            = ctx;
3910         counter->oncpu          = -1;
3911
3912         counter->parent         = parent_counter;
3913
3914         counter->ns             = get_pid_ns(current->nsproxy->pid_ns);
3915         counter->id             = atomic64_inc_return(&perf_counter_id);
3916
3917         counter->state          = PERF_COUNTER_STATE_INACTIVE;
3918
3919         if (attr->disabled)
3920                 counter->state = PERF_COUNTER_STATE_OFF;
3921
3922         pmu = NULL;
3923
3924         hwc = &counter->hw;
3925         hwc->sample_period = attr->sample_period;
3926         if (attr->freq && attr->sample_freq)
3927                 hwc->sample_period = 1;
3928
3929         atomic64_set(&hwc->period_left, hwc->sample_period);
3930
3931         /*
3932          * we currently do not support PERF_SAMPLE_GROUP on inherited counters
3933          */
3934         if (attr->inherit && (attr->sample_type & PERF_SAMPLE_GROUP))
3935                 goto done;
3936
3937         switch (attr->type) {
3938         case PERF_TYPE_RAW:
3939         case PERF_TYPE_HARDWARE:
3940         case PERF_TYPE_HW_CACHE:
3941                 pmu = hw_perf_counter_init(counter);
3942                 break;
3943
3944         case PERF_TYPE_SOFTWARE:
3945                 pmu = sw_perf_counter_init(counter);
3946                 break;
3947
3948         case PERF_TYPE_TRACEPOINT:
3949                 pmu = tp_perf_counter_init(counter);
3950                 break;
3951
3952         default:
3953                 break;
3954         }
3955 done:
3956         err = 0;
3957         if (!pmu)
3958                 err = -EINVAL;
3959         else if (IS_ERR(pmu))
3960                 err = PTR_ERR(pmu);
3961
3962         if (err) {
3963                 if (counter->ns)
3964                         put_pid_ns(counter->ns);
3965                 kfree(counter);
3966                 return ERR_PTR(err);
3967         }
3968
3969         counter->pmu = pmu;
3970
3971         if (!counter->parent) {
3972                 atomic_inc(&nr_counters);
3973                 if (counter->attr.mmap)
3974                         atomic_inc(&nr_mmap_counters);
3975                 if (counter->attr.comm)
3976                         atomic_inc(&nr_comm_counters);
3977                 if (counter->attr.task)
3978                         atomic_inc(&nr_task_counters);
3979         }
3980
3981         return counter;
3982 }
3983
3984 static int perf_copy_attr(struct perf_counter_attr __user *uattr,
3985                           struct perf_counter_attr *attr)
3986 {
3987         int ret;
3988         u32 size;
3989
3990         if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
3991                 return -EFAULT;
3992
3993         /*
3994          * zero the full structure, so that a short copy will be nice.
3995          */
3996         memset(attr, 0, sizeof(*attr));
3997
3998         ret = get_user(size, &uattr->size);
3999         if (ret)
4000                 return ret;
4001
4002         if (size > PAGE_SIZE)   /* silly large */
4003                 goto err_size;
4004
4005         if (!size)              /* abi compat */
4006                 size = PERF_ATTR_SIZE_VER0;
4007
4008         if (size < PERF_ATTR_SIZE_VER0)
4009                 goto err_size;
4010
4011         /*
4012          * If we're handed a bigger struct than we know of,
4013          * ensure all the unknown bits are 0.
4014          */
4015         if (size > sizeof(*attr)) {
4016                 unsigned long val;
4017                 unsigned long __user *addr;
4018                 unsigned long __user *end;
4019
4020                 addr = PTR_ALIGN((void __user *)uattr + sizeof(*attr),
4021                                 sizeof(unsigned long));
4022                 end  = PTR_ALIGN((void __user *)uattr + size,
4023                                 sizeof(unsigned long));
4024
4025                 for (; addr < end; addr += sizeof(unsigned long)) {
4026                         ret = get_user(val, addr);
4027                         if (ret)
4028                                 return ret;
4029                         if (val)
4030                                 goto err_size;
4031                 }
4032         }
4033
4034         ret = copy_from_user(attr, uattr, size);
4035         if (ret)
4036                 return -EFAULT;
4037
4038         /*
4039          * If the type exists, the corresponding creation will verify
4040          * the attr->config.
4041          */
4042         if (attr->type >= PERF_TYPE_MAX)
4043                 return -EINVAL;
4044
4045         if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
4046                 return -EINVAL;
4047
4048         if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
4049                 return -EINVAL;
4050
4051         if (attr->read_format & ~(PERF_FORMAT_MAX-1))
4052                 return -EINVAL;
4053
4054 out:
4055         return ret;
4056
4057 err_size:
4058         put_user(sizeof(*attr), &uattr->size);
4059         ret = -E2BIG;
4060         goto out;
4061 }
4062
4063 /**
4064  * sys_perf_counter_open - open a performance counter, associate it to a task/cpu
4065  *
4066  * @attr_uptr:  event type attributes for monitoring/sampling
4067  * @pid:                target pid
4068  * @cpu:                target cpu
4069  * @group_fd:           group leader counter fd
4070  */
4071 SYSCALL_DEFINE5(perf_counter_open,
4072                 struct perf_counter_attr __user *, attr_uptr,
4073                 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
4074 {
4075         struct perf_counter *counter, *group_leader;
4076         struct perf_counter_attr attr;
4077         struct perf_counter_context *ctx;
4078         struct file *counter_file = NULL;
4079         struct file *group_file = NULL;
4080         int fput_needed = 0;
4081         int fput_needed2 = 0;
4082         int ret;
4083
4084         /* for future expandability... */
4085         if (flags)
4086                 return -EINVAL;
4087
4088         ret = perf_copy_attr(attr_uptr, &attr);
4089         if (ret)
4090                 return ret;
4091
4092         if (!attr.exclude_kernel) {
4093                 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
4094                         return -EACCES;
4095         }
4096
4097         if (attr.freq) {
4098                 if (attr.sample_freq > sysctl_perf_counter_sample_rate)
4099                         return -EINVAL;
4100         }
4101
4102         /*
4103          * Get the target context (task or percpu):
4104          */
4105         ctx = find_get_context(pid, cpu);
4106         if (IS_ERR(ctx))
4107                 return PTR_ERR(ctx);
4108
4109         /*
4110          * Look up the group leader (we will attach this counter to it):
4111          */
4112         group_leader = NULL;
4113         if (group_fd != -1) {
4114                 ret = -EINVAL;
4115                 group_file = fget_light(group_fd, &fput_needed);
4116                 if (!group_file)
4117                         goto err_put_context;
4118                 if (group_file->f_op != &perf_fops)
4119                         goto err_put_context;
4120
4121                 group_leader = group_file->private_data;
4122                 /*
4123                  * Do not allow a recursive hierarchy (this new sibling
4124                  * becoming part of another group-sibling):
4125                  */
4126                 if (group_leader->group_leader != group_leader)
4127                         goto err_put_context;
4128                 /*
4129                  * Do not allow to attach to a group in a different
4130                  * task or CPU context:
4131                  */
4132                 if (group_leader->ctx != ctx)
4133                         goto err_put_context;
4134                 /*
4135                  * Only a group leader can be exclusive or pinned
4136                  */
4137                 if (attr.exclusive || attr.pinned)
4138                         goto err_put_context;
4139         }
4140
4141         counter = perf_counter_alloc(&attr, cpu, ctx, group_leader,
4142                                      NULL, GFP_KERNEL);
4143         ret = PTR_ERR(counter);
4144         if (IS_ERR(counter))
4145                 goto err_put_context;
4146
4147         ret = anon_inode_getfd("[perf_counter]", &perf_fops, counter, 0);
4148         if (ret < 0)
4149                 goto err_free_put_context;
4150
4151         counter_file = fget_light(ret, &fput_needed2);
4152         if (!counter_file)
4153                 goto err_free_put_context;
4154
4155         counter->filp = counter_file;
4156         WARN_ON_ONCE(ctx->parent_ctx);
4157         mutex_lock(&ctx->mutex);
4158         perf_install_in_context(ctx, counter, cpu);
4159         ++ctx->generation;
4160         mutex_unlock(&ctx->mutex);
4161
4162         counter->owner = current;
4163         get_task_struct(current);
4164         mutex_lock(&current->perf_counter_mutex);
4165         list_add_tail(&counter->owner_entry, &current->perf_counter_list);
4166         mutex_unlock(&current->perf_counter_mutex);
4167
4168         fput_light(counter_file, fput_needed2);
4169
4170 out_fput:
4171         fput_light(group_file, fput_needed);
4172
4173         return ret;
4174
4175 err_free_put_context:
4176         kfree(counter);
4177
4178 err_put_context:
4179         put_ctx(ctx);
4180
4181         goto out_fput;
4182 }
4183
4184 /*
4185  * inherit a counter from parent task to child task:
4186  */
4187 static struct perf_counter *
4188 inherit_counter(struct perf_counter *parent_counter,
4189               struct task_struct *parent,
4190               struct perf_counter_context *parent_ctx,
4191               struct task_struct *child,
4192               struct perf_counter *group_leader,
4193               struct perf_counter_context *child_ctx)
4194 {
4195         struct perf_counter *child_counter;
4196
4197         /*
4198          * Instead of creating recursive hierarchies of counters,
4199          * we link inherited counters back to the original parent,
4200          * which has a filp for sure, which we use as the reference
4201          * count:
4202          */
4203         if (parent_counter->parent)
4204                 parent_counter = parent_counter->parent;
4205
4206         child_counter = perf_counter_alloc(&parent_counter->attr,
4207                                            parent_counter->cpu, child_ctx,
4208                                            group_leader, parent_counter,
4209                                            GFP_KERNEL);
4210         if (IS_ERR(child_counter))
4211                 return child_counter;
4212         get_ctx(child_ctx);
4213
4214         /*
4215          * Make the child state follow the state of the parent counter,
4216          * not its attr.disabled bit.  We hold the parent's mutex,
4217          * so we won't race with perf_counter_{en, dis}able_family.
4218          */
4219         if (parent_counter->state >= PERF_COUNTER_STATE_INACTIVE)
4220                 child_counter->state = PERF_COUNTER_STATE_INACTIVE;
4221         else
4222                 child_counter->state = PERF_COUNTER_STATE_OFF;
4223
4224         if (parent_counter->attr.freq)
4225                 child_counter->hw.sample_period = parent_counter->hw.sample_period;
4226
4227         /*
4228          * Link it up in the child's context:
4229          */
4230         add_counter_to_ctx(child_counter, child_ctx);
4231
4232         /*
4233          * Get a reference to the parent filp - we will fput it
4234          * when the child counter exits. This is safe to do because
4235          * we are in the parent and we know that the filp still
4236          * exists and has a nonzero count:
4237          */
4238         atomic_long_inc(&parent_counter->filp->f_count);
4239
4240         /*
4241          * Link this into the parent counter's child list
4242          */
4243         WARN_ON_ONCE(parent_counter->ctx->parent_ctx);
4244         mutex_lock(&parent_counter->child_mutex);
4245         list_add_tail(&child_counter->child_list, &parent_counter->child_list);
4246         mutex_unlock(&parent_counter->child_mutex);
4247
4248         return child_counter;
4249 }
4250
4251 static int inherit_group(struct perf_counter *parent_counter,
4252               struct task_struct *parent,
4253               struct perf_counter_context *parent_ctx,
4254               struct task_struct *child,
4255               struct perf_counter_context *child_ctx)
4256 {
4257         struct perf_counter *leader;
4258         struct perf_counter *sub;
4259         struct perf_counter *child_ctr;
4260
4261         leader = inherit_counter(parent_counter, parent, parent_ctx,
4262                                  child, NULL, child_ctx);
4263         if (IS_ERR(leader))
4264                 return PTR_ERR(leader);
4265         list_for_each_entry(sub, &parent_counter->sibling_list, list_entry) {
4266                 child_ctr = inherit_counter(sub, parent, parent_ctx,
4267                                             child, leader, child_ctx);
4268                 if (IS_ERR(child_ctr))
4269                         return PTR_ERR(child_ctr);
4270         }
4271         return 0;
4272 }
4273
4274 static void sync_child_counter(struct perf_counter *child_counter,
4275                                struct task_struct *child)
4276 {
4277         struct perf_counter *parent_counter = child_counter->parent;
4278         u64 child_val;
4279
4280         if (child_counter->attr.inherit_stat)
4281                 perf_counter_read_event(child_counter, child);
4282
4283         child_val = atomic64_read(&child_counter->count);
4284
4285         /*
4286          * Add back the child's count to the parent's count:
4287          */
4288         atomic64_add(child_val, &parent_counter->count);
4289         atomic64_add(child_counter->total_time_enabled,
4290                      &parent_counter->child_total_time_enabled);
4291         atomic64_add(child_counter->total_time_running,
4292                      &parent_counter->child_total_time_running);
4293
4294         /*
4295          * Remove this counter from the parent's list
4296          */
4297         WARN_ON_ONCE(parent_counter->ctx->parent_ctx);
4298         mutex_lock(&parent_counter->child_mutex);
4299         list_del_init(&child_counter->child_list);
4300         mutex_unlock(&parent_counter->child_mutex);
4301
4302         /*
4303          * Release the parent counter, if this was the last
4304          * reference to it.
4305          */
4306         fput(parent_counter->filp);
4307 }
4308
4309 static void
4310 __perf_counter_exit_task(struct perf_counter *child_counter,
4311                          struct perf_counter_context *child_ctx,
4312                          struct task_struct *child)
4313 {
4314         struct perf_counter *parent_counter;
4315
4316         update_counter_times(child_counter);
4317         perf_counter_remove_from_context(child_counter);
4318
4319         parent_counter = child_counter->parent;
4320         /*
4321          * It can happen that parent exits first, and has counters
4322          * that are still around due to the child reference. These
4323          * counters need to be zapped - but otherwise linger.
4324          */
4325         if (parent_counter) {
4326                 sync_child_counter(child_counter, child);
4327                 free_counter(child_counter);
4328         }
4329 }
4330
4331 /*
4332  * When a child task exits, feed back counter values to parent counters.
4333  */
4334 void perf_counter_exit_task(struct task_struct *child)
4335 {
4336         struct perf_counter *child_counter, *tmp;
4337         struct perf_counter_context *child_ctx;
4338         unsigned long flags;
4339
4340         if (likely(!child->perf_counter_ctxp)) {
4341                 perf_counter_task(child, NULL, 0);
4342                 return;
4343         }
4344
4345         local_irq_save(flags);
4346         /*
4347          * We can't reschedule here because interrupts are disabled,
4348          * and either child is current or it is a task that can't be
4349          * scheduled, so we are now safe from rescheduling changing
4350          * our context.
4351          */
4352         child_ctx = child->perf_counter_ctxp;
4353         __perf_counter_task_sched_out(child_ctx);
4354
4355         /*
4356          * Take the context lock here so that if find_get_context is
4357          * reading child->perf_counter_ctxp, we wait until it has
4358          * incremented the context's refcount before we do put_ctx below.
4359          */
4360         spin_lock(&child_ctx->lock);
4361         child->perf_counter_ctxp = NULL;
4362         /*
4363          * If this context is a clone; unclone it so it can't get
4364          * swapped to another process while we're removing all
4365          * the counters from it.
4366          */
4367         unclone_ctx(child_ctx);
4368         spin_unlock_irqrestore(&child_ctx->lock, flags);
4369
4370         /*
4371          * Report the task dead after unscheduling the counters so that we
4372          * won't get any samples after PERF_EVENT_EXIT. We can however still
4373          * get a few PERF_EVENT_READ events.
4374          */
4375         perf_counter_task(child, child_ctx, 0);
4376
4377         /*
4378          * We can recurse on the same lock type through:
4379          *
4380          *   __perf_counter_exit_task()
4381          *     sync_child_counter()
4382          *       fput(parent_counter->filp)
4383          *         perf_release()
4384          *           mutex_lock(&ctx->mutex)
4385          *
4386          * But since its the parent context it won't be the same instance.
4387          */
4388         mutex_lock_nested(&child_ctx->mutex, SINGLE_DEPTH_NESTING);
4389
4390 again:
4391         list_for_each_entry_safe(child_counter, tmp, &child_ctx->counter_list,
4392                                  list_entry)
4393                 __perf_counter_exit_task(child_counter, child_ctx, child);
4394
4395         /*
4396          * If the last counter was a group counter, it will have appended all
4397          * its siblings to the list, but we obtained 'tmp' before that which
4398          * will still point to the list head terminating the iteration.
4399          */
4400         if (!list_empty(&child_ctx->counter_list))
4401                 goto again;
4402
4403         mutex_unlock(&child_ctx->mutex);
4404
4405         put_ctx(child_ctx);
4406 }
4407
4408 /*
4409  * free an unexposed, unused context as created by inheritance by
4410  * init_task below, used by fork() in case of fail.
4411  */
4412 void perf_counter_free_task(struct task_struct *task)
4413 {
4414         struct perf_counter_context *ctx = task->perf_counter_ctxp;
4415         struct perf_counter *counter, *tmp;
4416
4417         if (!ctx)
4418                 return;
4419
4420         mutex_lock(&ctx->mutex);
4421 again:
4422         list_for_each_entry_safe(counter, tmp, &ctx->counter_list, list_entry) {
4423                 struct perf_counter *parent = counter->parent;
4424
4425                 if (WARN_ON_ONCE(!parent))
4426                         continue;
4427
4428                 mutex_lock(&parent->child_mutex);
4429                 list_del_init(&counter->child_list);
4430                 mutex_unlock(&parent->child_mutex);
4431
4432                 fput(parent->filp);
4433
4434                 list_del_counter(counter, ctx);
4435                 free_counter(counter);
4436         }
4437
4438         if (!list_empty(&ctx->counter_list))
4439                 goto again;
4440
4441         mutex_unlock(&ctx->mutex);
4442
4443         put_ctx(ctx);
4444 }
4445
4446 /*
4447  * Initialize the perf_counter context in task_struct
4448  */
4449 int perf_counter_init_task(struct task_struct *child)
4450 {
4451         struct perf_counter_context *child_ctx, *parent_ctx;
4452         struct perf_counter_context *cloned_ctx;
4453         struct perf_counter *counter;
4454         struct task_struct *parent = current;
4455         int inherited_all = 1;
4456         int ret = 0;
4457
4458         child->perf_counter_ctxp = NULL;
4459
4460         mutex_init(&child->perf_counter_mutex);
4461         INIT_LIST_HEAD(&child->perf_counter_list);
4462
4463         if (likely(!parent->perf_counter_ctxp))
4464                 return 0;
4465
4466         /*
4467          * This is executed from the parent task context, so inherit
4468          * counters that have been marked for cloning.
4469          * First allocate and initialize a context for the child.
4470          */
4471
4472         child_ctx = kmalloc(sizeof(struct perf_counter_context), GFP_KERNEL);
4473         if (!child_ctx)
4474                 return -ENOMEM;
4475
4476         __perf_counter_init_context(child_ctx, child);
4477         child->perf_counter_ctxp = child_ctx;
4478         get_task_struct(child);
4479
4480         /*
4481          * If the parent's context is a clone, pin it so it won't get
4482          * swapped under us.
4483          */
4484         parent_ctx = perf_pin_task_context(parent);
4485
4486         /*
4487          * No need to check if parent_ctx != NULL here; since we saw
4488          * it non-NULL earlier, the only reason for it to become NULL
4489          * is if we exit, and since we're currently in the middle of
4490          * a fork we can't be exiting at the same time.
4491          */
4492
4493         /*
4494          * Lock the parent list. No need to lock the child - not PID
4495          * hashed yet and not running, so nobody can access it.
4496          */
4497         mutex_lock(&parent_ctx->mutex);
4498
4499         /*
4500          * We dont have to disable NMIs - we are only looking at
4501          * the list, not manipulating it:
4502          */
4503         list_for_each_entry_rcu(counter, &parent_ctx->event_list, event_entry) {
4504                 if (counter != counter->group_leader)
4505                         continue;
4506
4507                 if (!counter->attr.inherit) {
4508                         inherited_all = 0;
4509                         continue;
4510                 }
4511
4512                 ret = inherit_group(counter, parent, parent_ctx,
4513                                              child, child_ctx);
4514                 if (ret) {
4515                         inherited_all = 0;
4516                         break;
4517                 }
4518         }
4519
4520         if (inherited_all) {
4521                 /*
4522                  * Mark the child context as a clone of the parent
4523                  * context, or of whatever the parent is a clone of.
4524                  * Note that if the parent is a clone, it could get
4525                  * uncloned at any point, but that doesn't matter
4526                  * because the list of counters and the generation
4527                  * count can't have changed since we took the mutex.
4528                  */
4529                 cloned_ctx = rcu_dereference(parent_ctx->parent_ctx);
4530                 if (cloned_ctx) {
4531                         child_ctx->parent_ctx = cloned_ctx;
4532                         child_ctx->parent_gen = parent_ctx->parent_gen;
4533                 } else {
4534                         child_ctx->parent_ctx = parent_ctx;
4535                         child_ctx->parent_gen = parent_ctx->generation;
4536                 }
4537                 get_ctx(child_ctx->parent_ctx);
4538         }
4539
4540         mutex_unlock(&parent_ctx->mutex);
4541
4542         perf_unpin_context(parent_ctx);
4543
4544         return ret;
4545 }
4546
4547 static void __cpuinit perf_counter_init_cpu(int cpu)
4548 {
4549         struct perf_cpu_context *cpuctx;
4550
4551         cpuctx = &per_cpu(perf_cpu_context, cpu);
4552         __perf_counter_init_context(&cpuctx->ctx, NULL);
4553
4554         spin_lock(&perf_resource_lock);
4555         cpuctx->max_pertask = perf_max_counters - perf_reserved_percpu;
4556         spin_unlock(&perf_resource_lock);
4557
4558         hw_perf_counter_setup(cpu);
4559 }
4560
4561 #ifdef CONFIG_HOTPLUG_CPU
4562 static void __perf_counter_exit_cpu(void *info)
4563 {
4564         struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
4565         struct perf_counter_context *ctx = &cpuctx->ctx;
4566         struct perf_counter *counter, *tmp;
4567
4568         list_for_each_entry_safe(counter, tmp, &ctx->counter_list, list_entry)
4569                 __perf_counter_remove_from_context(counter);
4570 }
4571 static void perf_counter_exit_cpu(int cpu)
4572 {
4573         struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
4574         struct perf_counter_context *ctx = &cpuctx->ctx;
4575
4576         mutex_lock(&ctx->mutex);
4577         smp_call_function_single(cpu, __perf_counter_exit_cpu, NULL, 1);
4578         mutex_unlock(&ctx->mutex);
4579 }
4580 #else
4581 static inline void perf_counter_exit_cpu(int cpu) { }
4582 #endif
4583
4584 static int __cpuinit
4585 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
4586 {
4587         unsigned int cpu = (long)hcpu;
4588
4589         switch (action) {
4590
4591         case CPU_UP_PREPARE:
4592         case CPU_UP_PREPARE_FROZEN:
4593                 perf_counter_init_cpu(cpu);
4594                 break;
4595
4596         case CPU_ONLINE:
4597         case CPU_ONLINE_FROZEN:
4598                 hw_perf_counter_setup_online(cpu);
4599                 break;
4600
4601         case CPU_DOWN_PREPARE:
4602         case CPU_DOWN_PREPARE_FROZEN:
4603                 perf_counter_exit_cpu(cpu);
4604                 break;
4605
4606         default:
4607                 break;
4608         }
4609
4610         return NOTIFY_OK;
4611 }
4612
4613 /*
4614  * This has to have a higher priority than migration_notifier in sched.c.
4615  */
4616 static struct notifier_block __cpuinitdata perf_cpu_nb = {
4617         .notifier_call          = perf_cpu_notify,
4618         .priority               = 20,
4619 };
4620
4621 void __init perf_counter_init(void)
4622 {
4623         perf_cpu_notify(&perf_cpu_nb, (unsigned long)CPU_UP_PREPARE,
4624                         (void *)(long)smp_processor_id());
4625         perf_cpu_notify(&perf_cpu_nb, (unsigned long)CPU_ONLINE,
4626                         (void *)(long)smp_processor_id());
4627         register_cpu_notifier(&perf_cpu_nb);
4628 }
4629
4630 static ssize_t perf_show_reserve_percpu(struct sysdev_class *class, char *buf)
4631 {
4632         return sprintf(buf, "%d\n", perf_reserved_percpu);
4633 }
4634
4635 static ssize_t
4636 perf_set_reserve_percpu(struct sysdev_class *class,
4637                         const char *buf,
4638                         size_t count)
4639 {
4640         struct perf_cpu_context *cpuctx;
4641         unsigned long val;
4642         int err, cpu, mpt;
4643
4644         err = strict_strtoul(buf, 10, &val);
4645         if (err)
4646                 return err;
4647         if (val > perf_max_counters)
4648                 return -EINVAL;
4649
4650         spin_lock(&perf_resource_lock);
4651         perf_reserved_percpu = val;
4652         for_each_online_cpu(cpu) {
4653                 cpuctx = &per_cpu(perf_cpu_context, cpu);
4654                 spin_lock_irq(&cpuctx->ctx.lock);
4655                 mpt = min(perf_max_counters - cpuctx->ctx.nr_counters,
4656                           perf_max_counters - perf_reserved_percpu);
4657                 cpuctx->max_pertask = mpt;
4658                 spin_unlock_irq(&cpuctx->ctx.lock);
4659         }
4660         spin_unlock(&perf_resource_lock);
4661
4662         return count;
4663 }
4664
4665 static ssize_t perf_show_overcommit(struct sysdev_class *class, char *buf)
4666 {
4667         return sprintf(buf, "%d\n", perf_overcommit);
4668 }
4669
4670 static ssize_t
4671 perf_set_overcommit(struct sysdev_class *class, const char *buf, size_t count)
4672 {
4673         unsigned long val;
4674         int err;
4675
4676         err = strict_strtoul(buf, 10, &val);
4677         if (err)
4678                 return err;
4679         if (val > 1)
4680                 return -EINVAL;
4681
4682         spin_lock(&perf_resource_lock);
4683         perf_overcommit = val;
4684         spin_unlock(&perf_resource_lock);
4685
4686         return count;
4687 }
4688
4689 static SYSDEV_CLASS_ATTR(
4690                                 reserve_percpu,
4691                                 0644,
4692                                 perf_show_reserve_percpu,
4693                                 perf_set_reserve_percpu
4694                         );
4695
4696 static SYSDEV_CLASS_ATTR(
4697                                 overcommit,
4698                                 0644,
4699                                 perf_show_overcommit,
4700                                 perf_set_overcommit
4701                         );
4702
4703 static struct attribute *perfclass_attrs[] = {
4704         &attr_reserve_percpu.attr,
4705         &attr_overcommit.attr,
4706         NULL
4707 };
4708
4709 static struct attribute_group perfclass_attr_group = {
4710         .attrs                  = perfclass_attrs,
4711         .name                   = "perf_counters",
4712 };
4713
4714 static int __init perf_counter_sysfs_init(void)
4715 {
4716         return sysfs_create_group(&cpu_sysdev_class.kset.kobj,
4717                                   &perfclass_attr_group);
4718 }
4719 device_initcall(perf_counter_sysfs_init);