perf: Rework/fix the whole read vs group stuff
[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 int perf_counter_read_size(struct perf_counter *counter)
1696 {
1697         int entry = sizeof(u64); /* value */
1698         int size = 0;
1699         int nr = 1;
1700
1701         if (counter->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1702                 size += sizeof(u64);
1703
1704         if (counter->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1705                 size += sizeof(u64);
1706
1707         if (counter->attr.read_format & PERF_FORMAT_ID)
1708                 entry += sizeof(u64);
1709
1710         if (counter->attr.read_format & PERF_FORMAT_GROUP) {
1711                 nr += counter->group_leader->nr_siblings;
1712                 size += sizeof(u64);
1713         }
1714
1715         size += entry * nr;
1716
1717         return size;
1718 }
1719
1720 static u64 perf_counter_read_value(struct perf_counter *counter)
1721 {
1722         struct perf_counter *child;
1723         u64 total = 0;
1724
1725         total += perf_counter_read(counter);
1726         list_for_each_entry(child, &counter->child_list, child_list)
1727                 total += perf_counter_read(child);
1728
1729         return total;
1730 }
1731
1732 static int perf_counter_read_entry(struct perf_counter *counter,
1733                                    u64 read_format, char __user *buf)
1734 {
1735         int n = 0, count = 0;
1736         u64 values[2];
1737
1738         values[n++] = perf_counter_read_value(counter);
1739         if (read_format & PERF_FORMAT_ID)
1740                 values[n++] = primary_counter_id(counter);
1741
1742         count = n * sizeof(u64);
1743
1744         if (copy_to_user(buf, values, count))
1745                 return -EFAULT;
1746
1747         return count;
1748 }
1749
1750 static int perf_counter_read_group(struct perf_counter *counter,
1751                                    u64 read_format, char __user *buf)
1752 {
1753         struct perf_counter *leader = counter->group_leader, *sub;
1754         int n = 0, size = 0, err = -EFAULT;
1755         u64 values[3];
1756
1757         values[n++] = 1 + leader->nr_siblings;
1758         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
1759                 values[n++] = leader->total_time_enabled +
1760                         atomic64_read(&leader->child_total_time_enabled);
1761         }
1762         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
1763                 values[n++] = leader->total_time_running +
1764                         atomic64_read(&leader->child_total_time_running);
1765         }
1766
1767         size = n * sizeof(u64);
1768
1769         if (copy_to_user(buf, values, size))
1770                 return -EFAULT;
1771
1772         err = perf_counter_read_entry(leader, read_format, buf + size);
1773         if (err < 0)
1774                 return err;
1775
1776         size += err;
1777
1778         list_for_each_entry(sub, &leader->sibling_list, list_entry) {
1779                 err = perf_counter_read_entry(counter, read_format,
1780                                 buf + size);
1781                 if (err < 0)
1782                         return err;
1783
1784                 size += err;
1785         }
1786
1787         return size;
1788 }
1789
1790 static int perf_counter_read_one(struct perf_counter *counter,
1791                                  u64 read_format, char __user *buf)
1792 {
1793         u64 values[4];
1794         int n = 0;
1795
1796         values[n++] = perf_counter_read_value(counter);
1797         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
1798                 values[n++] = counter->total_time_enabled +
1799                         atomic64_read(&counter->child_total_time_enabled);
1800         }
1801         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
1802                 values[n++] = counter->total_time_running +
1803                         atomic64_read(&counter->child_total_time_running);
1804         }
1805         if (read_format & PERF_FORMAT_ID)
1806                 values[n++] = primary_counter_id(counter);
1807
1808         if (copy_to_user(buf, values, n * sizeof(u64)))
1809                 return -EFAULT;
1810
1811         return n * sizeof(u64);
1812 }
1813
1814 /*
1815  * Read the performance counter - simple non blocking version for now
1816  */
1817 static ssize_t
1818 perf_read_hw(struct perf_counter *counter, char __user *buf, size_t count)
1819 {
1820         u64 read_format = counter->attr.read_format;
1821         int ret;
1822
1823         /*
1824          * Return end-of-file for a read on a counter that is in
1825          * error state (i.e. because it was pinned but it couldn't be
1826          * scheduled on to the CPU at some point).
1827          */
1828         if (counter->state == PERF_COUNTER_STATE_ERROR)
1829                 return 0;
1830
1831         if (count < perf_counter_read_size(counter))
1832                 return -ENOSPC;
1833
1834         WARN_ON_ONCE(counter->ctx->parent_ctx);
1835         mutex_lock(&counter->child_mutex);
1836         if (read_format & PERF_FORMAT_GROUP)
1837                 ret = perf_counter_read_group(counter, read_format, buf);
1838         else
1839                 ret = perf_counter_read_one(counter, read_format, buf);
1840         mutex_unlock(&counter->child_mutex);
1841
1842         return ret;
1843 }
1844
1845 static ssize_t
1846 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
1847 {
1848         struct perf_counter *counter = file->private_data;
1849
1850         return perf_read_hw(counter, buf, count);
1851 }
1852
1853 static unsigned int perf_poll(struct file *file, poll_table *wait)
1854 {
1855         struct perf_counter *counter = file->private_data;
1856         struct perf_mmap_data *data;
1857         unsigned int events = POLL_HUP;
1858
1859         rcu_read_lock();
1860         data = rcu_dereference(counter->data);
1861         if (data)
1862                 events = atomic_xchg(&data->poll, 0);
1863         rcu_read_unlock();
1864
1865         poll_wait(file, &counter->waitq, wait);
1866
1867         return events;
1868 }
1869
1870 static void perf_counter_reset(struct perf_counter *counter)
1871 {
1872         (void)perf_counter_read(counter);
1873         atomic64_set(&counter->count, 0);
1874         perf_counter_update_userpage(counter);
1875 }
1876
1877 /*
1878  * Holding the top-level counter's child_mutex means that any
1879  * descendant process that has inherited this counter will block
1880  * in sync_child_counter if it goes to exit, thus satisfying the
1881  * task existence requirements of perf_counter_enable/disable.
1882  */
1883 static void perf_counter_for_each_child(struct perf_counter *counter,
1884                                         void (*func)(struct perf_counter *))
1885 {
1886         struct perf_counter *child;
1887
1888         WARN_ON_ONCE(counter->ctx->parent_ctx);
1889         mutex_lock(&counter->child_mutex);
1890         func(counter);
1891         list_for_each_entry(child, &counter->child_list, child_list)
1892                 func(child);
1893         mutex_unlock(&counter->child_mutex);
1894 }
1895
1896 static void perf_counter_for_each(struct perf_counter *counter,
1897                                   void (*func)(struct perf_counter *))
1898 {
1899         struct perf_counter_context *ctx = counter->ctx;
1900         struct perf_counter *sibling;
1901
1902         WARN_ON_ONCE(ctx->parent_ctx);
1903         mutex_lock(&ctx->mutex);
1904         counter = counter->group_leader;
1905
1906         perf_counter_for_each_child(counter, func);
1907         func(counter);
1908         list_for_each_entry(sibling, &counter->sibling_list, list_entry)
1909                 perf_counter_for_each_child(counter, func);
1910         mutex_unlock(&ctx->mutex);
1911 }
1912
1913 static int perf_counter_period(struct perf_counter *counter, u64 __user *arg)
1914 {
1915         struct perf_counter_context *ctx = counter->ctx;
1916         unsigned long size;
1917         int ret = 0;
1918         u64 value;
1919
1920         if (!counter->attr.sample_period)
1921                 return -EINVAL;
1922
1923         size = copy_from_user(&value, arg, sizeof(value));
1924         if (size != sizeof(value))
1925                 return -EFAULT;
1926
1927         if (!value)
1928                 return -EINVAL;
1929
1930         spin_lock_irq(&ctx->lock);
1931         if (counter->attr.freq) {
1932                 if (value > sysctl_perf_counter_sample_rate) {
1933                         ret = -EINVAL;
1934                         goto unlock;
1935                 }
1936
1937                 counter->attr.sample_freq = value;
1938         } else {
1939                 counter->attr.sample_period = value;
1940                 counter->hw.sample_period = value;
1941         }
1942 unlock:
1943         spin_unlock_irq(&ctx->lock);
1944
1945         return ret;
1946 }
1947
1948 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
1949 {
1950         struct perf_counter *counter = file->private_data;
1951         void (*func)(struct perf_counter *);
1952         u32 flags = arg;
1953
1954         switch (cmd) {
1955         case PERF_COUNTER_IOC_ENABLE:
1956                 func = perf_counter_enable;
1957                 break;
1958         case PERF_COUNTER_IOC_DISABLE:
1959                 func = perf_counter_disable;
1960                 break;
1961         case PERF_COUNTER_IOC_RESET:
1962                 func = perf_counter_reset;
1963                 break;
1964
1965         case PERF_COUNTER_IOC_REFRESH:
1966                 return perf_counter_refresh(counter, arg);
1967
1968         case PERF_COUNTER_IOC_PERIOD:
1969                 return perf_counter_period(counter, (u64 __user *)arg);
1970
1971         default:
1972                 return -ENOTTY;
1973         }
1974
1975         if (flags & PERF_IOC_FLAG_GROUP)
1976                 perf_counter_for_each(counter, func);
1977         else
1978                 perf_counter_for_each_child(counter, func);
1979
1980         return 0;
1981 }
1982
1983 int perf_counter_task_enable(void)
1984 {
1985         struct perf_counter *counter;
1986
1987         mutex_lock(&current->perf_counter_mutex);
1988         list_for_each_entry(counter, &current->perf_counter_list, owner_entry)
1989                 perf_counter_for_each_child(counter, perf_counter_enable);
1990         mutex_unlock(&current->perf_counter_mutex);
1991
1992         return 0;
1993 }
1994
1995 int perf_counter_task_disable(void)
1996 {
1997         struct perf_counter *counter;
1998
1999         mutex_lock(&current->perf_counter_mutex);
2000         list_for_each_entry(counter, &current->perf_counter_list, owner_entry)
2001                 perf_counter_for_each_child(counter, perf_counter_disable);
2002         mutex_unlock(&current->perf_counter_mutex);
2003
2004         return 0;
2005 }
2006
2007 static int perf_counter_index(struct perf_counter *counter)
2008 {
2009         if (counter->state != PERF_COUNTER_STATE_ACTIVE)
2010                 return 0;
2011
2012         return counter->hw.idx + 1 - PERF_COUNTER_INDEX_OFFSET;
2013 }
2014
2015 /*
2016  * Callers need to ensure there can be no nesting of this function, otherwise
2017  * the seqlock logic goes bad. We can not serialize this because the arch
2018  * code calls this from NMI context.
2019  */
2020 void perf_counter_update_userpage(struct perf_counter *counter)
2021 {
2022         struct perf_counter_mmap_page *userpg;
2023         struct perf_mmap_data *data;
2024
2025         rcu_read_lock();
2026         data = rcu_dereference(counter->data);
2027         if (!data)
2028                 goto unlock;
2029
2030         userpg = data->user_page;
2031
2032         /*
2033          * Disable preemption so as to not let the corresponding user-space
2034          * spin too long if we get preempted.
2035          */
2036         preempt_disable();
2037         ++userpg->lock;
2038         barrier();
2039         userpg->index = perf_counter_index(counter);
2040         userpg->offset = atomic64_read(&counter->count);
2041         if (counter->state == PERF_COUNTER_STATE_ACTIVE)
2042                 userpg->offset -= atomic64_read(&counter->hw.prev_count);
2043
2044         userpg->time_enabled = counter->total_time_enabled +
2045                         atomic64_read(&counter->child_total_time_enabled);
2046
2047         userpg->time_running = counter->total_time_running +
2048                         atomic64_read(&counter->child_total_time_running);
2049
2050         barrier();
2051         ++userpg->lock;
2052         preempt_enable();
2053 unlock:
2054         rcu_read_unlock();
2055 }
2056
2057 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
2058 {
2059         struct perf_counter *counter = vma->vm_file->private_data;
2060         struct perf_mmap_data *data;
2061         int ret = VM_FAULT_SIGBUS;
2062
2063         if (vmf->flags & FAULT_FLAG_MKWRITE) {
2064                 if (vmf->pgoff == 0)
2065                         ret = 0;
2066                 return ret;
2067         }
2068
2069         rcu_read_lock();
2070         data = rcu_dereference(counter->data);
2071         if (!data)
2072                 goto unlock;
2073
2074         if (vmf->pgoff == 0) {
2075                 vmf->page = virt_to_page(data->user_page);
2076         } else {
2077                 int nr = vmf->pgoff - 1;
2078
2079                 if ((unsigned)nr > data->nr_pages)
2080                         goto unlock;
2081
2082                 if (vmf->flags & FAULT_FLAG_WRITE)
2083                         goto unlock;
2084
2085                 vmf->page = virt_to_page(data->data_pages[nr]);
2086         }
2087
2088         get_page(vmf->page);
2089         vmf->page->mapping = vma->vm_file->f_mapping;
2090         vmf->page->index   = vmf->pgoff;
2091
2092         ret = 0;
2093 unlock:
2094         rcu_read_unlock();
2095
2096         return ret;
2097 }
2098
2099 static int perf_mmap_data_alloc(struct perf_counter *counter, int nr_pages)
2100 {
2101         struct perf_mmap_data *data;
2102         unsigned long size;
2103         int i;
2104
2105         WARN_ON(atomic_read(&counter->mmap_count));
2106
2107         size = sizeof(struct perf_mmap_data);
2108         size += nr_pages * sizeof(void *);
2109
2110         data = kzalloc(size, GFP_KERNEL);
2111         if (!data)
2112                 goto fail;
2113
2114         data->user_page = (void *)get_zeroed_page(GFP_KERNEL);
2115         if (!data->user_page)
2116                 goto fail_user_page;
2117
2118         for (i = 0; i < nr_pages; i++) {
2119                 data->data_pages[i] = (void *)get_zeroed_page(GFP_KERNEL);
2120                 if (!data->data_pages[i])
2121                         goto fail_data_pages;
2122         }
2123
2124         data->nr_pages = nr_pages;
2125         atomic_set(&data->lock, -1);
2126
2127         rcu_assign_pointer(counter->data, data);
2128
2129         return 0;
2130
2131 fail_data_pages:
2132         for (i--; i >= 0; i--)
2133                 free_page((unsigned long)data->data_pages[i]);
2134
2135         free_page((unsigned long)data->user_page);
2136
2137 fail_user_page:
2138         kfree(data);
2139
2140 fail:
2141         return -ENOMEM;
2142 }
2143
2144 static void perf_mmap_free_page(unsigned long addr)
2145 {
2146         struct page *page = virt_to_page((void *)addr);
2147
2148         page->mapping = NULL;
2149         __free_page(page);
2150 }
2151
2152 static void __perf_mmap_data_free(struct rcu_head *rcu_head)
2153 {
2154         struct perf_mmap_data *data;
2155         int i;
2156
2157         data = container_of(rcu_head, struct perf_mmap_data, rcu_head);
2158
2159         perf_mmap_free_page((unsigned long)data->user_page);
2160         for (i = 0; i < data->nr_pages; i++)
2161                 perf_mmap_free_page((unsigned long)data->data_pages[i]);
2162
2163         kfree(data);
2164 }
2165
2166 static void perf_mmap_data_free(struct perf_counter *counter)
2167 {
2168         struct perf_mmap_data *data = counter->data;
2169
2170         WARN_ON(atomic_read(&counter->mmap_count));
2171
2172         rcu_assign_pointer(counter->data, NULL);
2173         call_rcu(&data->rcu_head, __perf_mmap_data_free);
2174 }
2175
2176 static void perf_mmap_open(struct vm_area_struct *vma)
2177 {
2178         struct perf_counter *counter = vma->vm_file->private_data;
2179
2180         atomic_inc(&counter->mmap_count);
2181 }
2182
2183 static void perf_mmap_close(struct vm_area_struct *vma)
2184 {
2185         struct perf_counter *counter = vma->vm_file->private_data;
2186
2187         WARN_ON_ONCE(counter->ctx->parent_ctx);
2188         if (atomic_dec_and_mutex_lock(&counter->mmap_count, &counter->mmap_mutex)) {
2189                 struct user_struct *user = current_user();
2190
2191                 atomic_long_sub(counter->data->nr_pages + 1, &user->locked_vm);
2192                 vma->vm_mm->locked_vm -= counter->data->nr_locked;
2193                 perf_mmap_data_free(counter);
2194                 mutex_unlock(&counter->mmap_mutex);
2195         }
2196 }
2197
2198 static struct vm_operations_struct perf_mmap_vmops = {
2199         .open           = perf_mmap_open,
2200         .close          = perf_mmap_close,
2201         .fault          = perf_mmap_fault,
2202         .page_mkwrite   = perf_mmap_fault,
2203 };
2204
2205 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
2206 {
2207         struct perf_counter *counter = file->private_data;
2208         unsigned long user_locked, user_lock_limit;
2209         struct user_struct *user = current_user();
2210         unsigned long locked, lock_limit;
2211         unsigned long vma_size;
2212         unsigned long nr_pages;
2213         long user_extra, extra;
2214         int ret = 0;
2215
2216         if (!(vma->vm_flags & VM_SHARED))
2217                 return -EINVAL;
2218
2219         vma_size = vma->vm_end - vma->vm_start;
2220         nr_pages = (vma_size / PAGE_SIZE) - 1;
2221
2222         /*
2223          * If we have data pages ensure they're a power-of-two number, so we
2224          * can do bitmasks instead of modulo.
2225          */
2226         if (nr_pages != 0 && !is_power_of_2(nr_pages))
2227                 return -EINVAL;
2228
2229         if (vma_size != PAGE_SIZE * (1 + nr_pages))
2230                 return -EINVAL;
2231
2232         if (vma->vm_pgoff != 0)
2233                 return -EINVAL;
2234
2235         WARN_ON_ONCE(counter->ctx->parent_ctx);
2236         mutex_lock(&counter->mmap_mutex);
2237         if (atomic_inc_not_zero(&counter->mmap_count)) {
2238                 if (nr_pages != counter->data->nr_pages)
2239                         ret = -EINVAL;
2240                 goto unlock;
2241         }
2242
2243         user_extra = nr_pages + 1;
2244         user_lock_limit = sysctl_perf_counter_mlock >> (PAGE_SHIFT - 10);
2245
2246         /*
2247          * Increase the limit linearly with more CPUs:
2248          */
2249         user_lock_limit *= num_online_cpus();
2250
2251         user_locked = atomic_long_read(&user->locked_vm) + user_extra;
2252
2253         extra = 0;
2254         if (user_locked > user_lock_limit)
2255                 extra = user_locked - user_lock_limit;
2256
2257         lock_limit = current->signal->rlim[RLIMIT_MEMLOCK].rlim_cur;
2258         lock_limit >>= PAGE_SHIFT;
2259         locked = vma->vm_mm->locked_vm + extra;
2260
2261         if ((locked > lock_limit) && !capable(CAP_IPC_LOCK)) {
2262                 ret = -EPERM;
2263                 goto unlock;
2264         }
2265
2266         WARN_ON(counter->data);
2267         ret = perf_mmap_data_alloc(counter, nr_pages);
2268         if (ret)
2269                 goto unlock;
2270
2271         atomic_set(&counter->mmap_count, 1);
2272         atomic_long_add(user_extra, &user->locked_vm);
2273         vma->vm_mm->locked_vm += extra;
2274         counter->data->nr_locked = extra;
2275         if (vma->vm_flags & VM_WRITE)
2276                 counter->data->writable = 1;
2277
2278 unlock:
2279         mutex_unlock(&counter->mmap_mutex);
2280
2281         vma->vm_flags |= VM_RESERVED;
2282         vma->vm_ops = &perf_mmap_vmops;
2283
2284         return ret;
2285 }
2286
2287 static int perf_fasync(int fd, struct file *filp, int on)
2288 {
2289         struct inode *inode = filp->f_path.dentry->d_inode;
2290         struct perf_counter *counter = filp->private_data;
2291         int retval;
2292
2293         mutex_lock(&inode->i_mutex);
2294         retval = fasync_helper(fd, filp, on, &counter->fasync);
2295         mutex_unlock(&inode->i_mutex);
2296
2297         if (retval < 0)
2298                 return retval;
2299
2300         return 0;
2301 }
2302
2303 static const struct file_operations perf_fops = {
2304         .release                = perf_release,
2305         .read                   = perf_read,
2306         .poll                   = perf_poll,
2307         .unlocked_ioctl         = perf_ioctl,
2308         .compat_ioctl           = perf_ioctl,
2309         .mmap                   = perf_mmap,
2310         .fasync                 = perf_fasync,
2311 };
2312
2313 /*
2314  * Perf counter wakeup
2315  *
2316  * If there's data, ensure we set the poll() state and publish everything
2317  * to user-space before waking everybody up.
2318  */
2319
2320 void perf_counter_wakeup(struct perf_counter *counter)
2321 {
2322         wake_up_all(&counter->waitq);
2323
2324         if (counter->pending_kill) {
2325                 kill_fasync(&counter->fasync, SIGIO, counter->pending_kill);
2326                 counter->pending_kill = 0;
2327         }
2328 }
2329
2330 /*
2331  * Pending wakeups
2332  *
2333  * Handle the case where we need to wakeup up from NMI (or rq->lock) context.
2334  *
2335  * The NMI bit means we cannot possibly take locks. Therefore, maintain a
2336  * single linked list and use cmpxchg() to add entries lockless.
2337  */
2338
2339 static void perf_pending_counter(struct perf_pending_entry *entry)
2340 {
2341         struct perf_counter *counter = container_of(entry,
2342                         struct perf_counter, pending);
2343
2344         if (counter->pending_disable) {
2345                 counter->pending_disable = 0;
2346                 perf_counter_disable(counter);
2347         }
2348
2349         if (counter->pending_wakeup) {
2350                 counter->pending_wakeup = 0;
2351                 perf_counter_wakeup(counter);
2352         }
2353 }
2354
2355 #define PENDING_TAIL ((struct perf_pending_entry *)-1UL)
2356
2357 static DEFINE_PER_CPU(struct perf_pending_entry *, perf_pending_head) = {
2358         PENDING_TAIL,
2359 };
2360
2361 static void perf_pending_queue(struct perf_pending_entry *entry,
2362                                void (*func)(struct perf_pending_entry *))
2363 {
2364         struct perf_pending_entry **head;
2365
2366         if (cmpxchg(&entry->next, NULL, PENDING_TAIL) != NULL)
2367                 return;
2368
2369         entry->func = func;
2370
2371         head = &get_cpu_var(perf_pending_head);
2372
2373         do {
2374                 entry->next = *head;
2375         } while (cmpxchg(head, entry->next, entry) != entry->next);
2376
2377         set_perf_counter_pending();
2378
2379         put_cpu_var(perf_pending_head);
2380 }
2381
2382 static int __perf_pending_run(void)
2383 {
2384         struct perf_pending_entry *list;
2385         int nr = 0;
2386
2387         list = xchg(&__get_cpu_var(perf_pending_head), PENDING_TAIL);
2388         while (list != PENDING_TAIL) {
2389                 void (*func)(struct perf_pending_entry *);
2390                 struct perf_pending_entry *entry = list;
2391
2392                 list = list->next;
2393
2394                 func = entry->func;
2395                 entry->next = NULL;
2396                 /*
2397                  * Ensure we observe the unqueue before we issue the wakeup,
2398                  * so that we won't be waiting forever.
2399                  * -- see perf_not_pending().
2400                  */
2401                 smp_wmb();
2402
2403                 func(entry);
2404                 nr++;
2405         }
2406
2407         return nr;
2408 }
2409
2410 static inline int perf_not_pending(struct perf_counter *counter)
2411 {
2412         /*
2413          * If we flush on whatever cpu we run, there is a chance we don't
2414          * need to wait.
2415          */
2416         get_cpu();
2417         __perf_pending_run();
2418         put_cpu();
2419
2420         /*
2421          * Ensure we see the proper queue state before going to sleep
2422          * so that we do not miss the wakeup. -- see perf_pending_handle()
2423          */
2424         smp_rmb();
2425         return counter->pending.next == NULL;
2426 }
2427
2428 static void perf_pending_sync(struct perf_counter *counter)
2429 {
2430         wait_event(counter->waitq, perf_not_pending(counter));
2431 }
2432
2433 void perf_counter_do_pending(void)
2434 {
2435         __perf_pending_run();
2436 }
2437
2438 /*
2439  * Callchain support -- arch specific
2440  */
2441
2442 __weak struct perf_callchain_entry *perf_callchain(struct pt_regs *regs)
2443 {
2444         return NULL;
2445 }
2446
2447 /*
2448  * Output
2449  */
2450
2451 struct perf_output_handle {
2452         struct perf_counter     *counter;
2453         struct perf_mmap_data   *data;
2454         unsigned long           head;
2455         unsigned long           offset;
2456         int                     nmi;
2457         int                     sample;
2458         int                     locked;
2459         unsigned long           flags;
2460 };
2461
2462 static bool perf_output_space(struct perf_mmap_data *data,
2463                               unsigned int offset, unsigned int head)
2464 {
2465         unsigned long tail;
2466         unsigned long mask;
2467
2468         if (!data->writable)
2469                 return true;
2470
2471         mask = (data->nr_pages << PAGE_SHIFT) - 1;
2472         /*
2473          * Userspace could choose to issue a mb() before updating the tail
2474          * pointer. So that all reads will be completed before the write is
2475          * issued.
2476          */
2477         tail = ACCESS_ONCE(data->user_page->data_tail);
2478         smp_rmb();
2479
2480         offset = (offset - tail) & mask;
2481         head   = (head   - tail) & mask;
2482
2483         if ((int)(head - offset) < 0)
2484                 return false;
2485
2486         return true;
2487 }
2488
2489 static void perf_output_wakeup(struct perf_output_handle *handle)
2490 {
2491         atomic_set(&handle->data->poll, POLL_IN);
2492
2493         if (handle->nmi) {
2494                 handle->counter->pending_wakeup = 1;
2495                 perf_pending_queue(&handle->counter->pending,
2496                                    perf_pending_counter);
2497         } else
2498                 perf_counter_wakeup(handle->counter);
2499 }
2500
2501 /*
2502  * Curious locking construct.
2503  *
2504  * We need to ensure a later event doesn't publish a head when a former
2505  * event isn't done writing. However since we need to deal with NMIs we
2506  * cannot fully serialize things.
2507  *
2508  * What we do is serialize between CPUs so we only have to deal with NMI
2509  * nesting on a single CPU.
2510  *
2511  * We only publish the head (and generate a wakeup) when the outer-most
2512  * event completes.
2513  */
2514 static void perf_output_lock(struct perf_output_handle *handle)
2515 {
2516         struct perf_mmap_data *data = handle->data;
2517         int cpu;
2518
2519         handle->locked = 0;
2520
2521         local_irq_save(handle->flags);
2522         cpu = smp_processor_id();
2523
2524         if (in_nmi() && atomic_read(&data->lock) == cpu)
2525                 return;
2526
2527         while (atomic_cmpxchg(&data->lock, -1, cpu) != -1)
2528                 cpu_relax();
2529
2530         handle->locked = 1;
2531 }
2532
2533 static void perf_output_unlock(struct perf_output_handle *handle)
2534 {
2535         struct perf_mmap_data *data = handle->data;
2536         unsigned long head;
2537         int cpu;
2538
2539         data->done_head = data->head;
2540
2541         if (!handle->locked)
2542                 goto out;
2543
2544 again:
2545         /*
2546          * The xchg implies a full barrier that ensures all writes are done
2547          * before we publish the new head, matched by a rmb() in userspace when
2548          * reading this position.
2549          */
2550         while ((head = atomic_long_xchg(&data->done_head, 0)))
2551                 data->user_page->data_head = head;
2552
2553         /*
2554          * NMI can happen here, which means we can miss a done_head update.
2555          */
2556
2557         cpu = atomic_xchg(&data->lock, -1);
2558         WARN_ON_ONCE(cpu != smp_processor_id());
2559
2560         /*
2561          * Therefore we have to validate we did not indeed do so.
2562          */
2563         if (unlikely(atomic_long_read(&data->done_head))) {
2564                 /*
2565                  * Since we had it locked, we can lock it again.
2566                  */
2567                 while (atomic_cmpxchg(&data->lock, -1, cpu) != -1)
2568                         cpu_relax();
2569
2570                 goto again;
2571         }
2572
2573         if (atomic_xchg(&data->wakeup, 0))
2574                 perf_output_wakeup(handle);
2575 out:
2576         local_irq_restore(handle->flags);
2577 }
2578
2579 static void perf_output_copy(struct perf_output_handle *handle,
2580                              const void *buf, unsigned int len)
2581 {
2582         unsigned int pages_mask;
2583         unsigned int offset;
2584         unsigned int size;
2585         void **pages;
2586
2587         offset          = handle->offset;
2588         pages_mask      = handle->data->nr_pages - 1;
2589         pages           = handle->data->data_pages;
2590
2591         do {
2592                 unsigned int page_offset;
2593                 int nr;
2594
2595                 nr          = (offset >> PAGE_SHIFT) & pages_mask;
2596                 page_offset = offset & (PAGE_SIZE - 1);
2597                 size        = min_t(unsigned int, PAGE_SIZE - page_offset, len);
2598
2599                 memcpy(pages[nr] + page_offset, buf, size);
2600
2601                 len         -= size;
2602                 buf         += size;
2603                 offset      += size;
2604         } while (len);
2605
2606         handle->offset = offset;
2607
2608         /*
2609          * Check we didn't copy past our reservation window, taking the
2610          * possible unsigned int wrap into account.
2611          */
2612         WARN_ON_ONCE(((long)(handle->head - handle->offset)) < 0);
2613 }
2614
2615 #define perf_output_put(handle, x) \
2616         perf_output_copy((handle), &(x), sizeof(x))
2617
2618 static int perf_output_begin(struct perf_output_handle *handle,
2619                              struct perf_counter *counter, unsigned int size,
2620                              int nmi, int sample)
2621 {
2622         struct perf_mmap_data *data;
2623         unsigned int offset, head;
2624         int have_lost;
2625         struct {
2626                 struct perf_event_header header;
2627                 u64                      id;
2628                 u64                      lost;
2629         } lost_event;
2630
2631         /*
2632          * For inherited counters we send all the output towards the parent.
2633          */
2634         if (counter->parent)
2635                 counter = counter->parent;
2636
2637         rcu_read_lock();
2638         data = rcu_dereference(counter->data);
2639         if (!data)
2640                 goto out;
2641
2642         handle->data    = data;
2643         handle->counter = counter;
2644         handle->nmi     = nmi;
2645         handle->sample  = sample;
2646
2647         if (!data->nr_pages)
2648                 goto fail;
2649
2650         have_lost = atomic_read(&data->lost);
2651         if (have_lost)
2652                 size += sizeof(lost_event);
2653
2654         perf_output_lock(handle);
2655
2656         do {
2657                 offset = head = atomic_long_read(&data->head);
2658                 head += size;
2659                 if (unlikely(!perf_output_space(data, offset, head)))
2660                         goto fail;
2661         } while (atomic_long_cmpxchg(&data->head, offset, head) != offset);
2662
2663         handle->offset  = offset;
2664         handle->head    = head;
2665
2666         if ((offset >> PAGE_SHIFT) != (head >> PAGE_SHIFT))
2667                 atomic_set(&data->wakeup, 1);
2668
2669         if (have_lost) {
2670                 lost_event.header.type = PERF_EVENT_LOST;
2671                 lost_event.header.misc = 0;
2672                 lost_event.header.size = sizeof(lost_event);
2673                 lost_event.id          = counter->id;
2674                 lost_event.lost        = atomic_xchg(&data->lost, 0);
2675
2676                 perf_output_put(handle, lost_event);
2677         }
2678
2679         return 0;
2680
2681 fail:
2682         atomic_inc(&data->lost);
2683         perf_output_unlock(handle);
2684 out:
2685         rcu_read_unlock();
2686
2687         return -ENOSPC;
2688 }
2689
2690 static void perf_output_end(struct perf_output_handle *handle)
2691 {
2692         struct perf_counter *counter = handle->counter;
2693         struct perf_mmap_data *data = handle->data;
2694
2695         int wakeup_events = counter->attr.wakeup_events;
2696
2697         if (handle->sample && wakeup_events) {
2698                 int events = atomic_inc_return(&data->events);
2699                 if (events >= wakeup_events) {
2700                         atomic_sub(wakeup_events, &data->events);
2701                         atomic_set(&data->wakeup, 1);
2702                 }
2703         }
2704
2705         perf_output_unlock(handle);
2706         rcu_read_unlock();
2707 }
2708
2709 static u32 perf_counter_pid(struct perf_counter *counter, struct task_struct *p)
2710 {
2711         /*
2712          * only top level counters have the pid namespace they were created in
2713          */
2714         if (counter->parent)
2715                 counter = counter->parent;
2716
2717         return task_tgid_nr_ns(p, counter->ns);
2718 }
2719
2720 static u32 perf_counter_tid(struct perf_counter *counter, struct task_struct *p)
2721 {
2722         /*
2723          * only top level counters have the pid namespace they were created in
2724          */
2725         if (counter->parent)
2726                 counter = counter->parent;
2727
2728         return task_pid_nr_ns(p, counter->ns);
2729 }
2730
2731 static void perf_output_read_one(struct perf_output_handle *handle,
2732                                  struct perf_counter *counter)
2733 {
2734         u64 read_format = counter->attr.read_format;
2735         u64 values[4];
2736         int n = 0;
2737
2738         values[n++] = atomic64_read(&counter->count);
2739         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
2740                 values[n++] = counter->total_time_enabled +
2741                         atomic64_read(&counter->child_total_time_enabled);
2742         }
2743         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
2744                 values[n++] = counter->total_time_running +
2745                         atomic64_read(&counter->child_total_time_running);
2746         }
2747         if (read_format & PERF_FORMAT_ID)
2748                 values[n++] = primary_counter_id(counter);
2749
2750         perf_output_copy(handle, values, n * sizeof(u64));
2751 }
2752
2753 /*
2754  * XXX PERF_FORMAT_GROUP vs inherited counters seems difficult.
2755  */
2756 static void perf_output_read_group(struct perf_output_handle *handle,
2757                             struct perf_counter *counter)
2758 {
2759         struct perf_counter *leader = counter->group_leader, *sub;
2760         u64 read_format = counter->attr.read_format;
2761         u64 values[5];
2762         int n = 0;
2763
2764         values[n++] = 1 + leader->nr_siblings;
2765
2766         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
2767                 values[n++] = leader->total_time_enabled;
2768
2769         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
2770                 values[n++] = leader->total_time_running;
2771
2772         if (leader != counter)
2773                 leader->pmu->read(leader);
2774
2775         values[n++] = atomic64_read(&leader->count);
2776         if (read_format & PERF_FORMAT_ID)
2777                 values[n++] = primary_counter_id(leader);
2778
2779         perf_output_copy(handle, values, n * sizeof(u64));
2780
2781         list_for_each_entry(sub, &leader->sibling_list, list_entry) {
2782                 n = 0;
2783
2784                 if (sub != counter)
2785                         sub->pmu->read(sub);
2786
2787                 values[n++] = atomic64_read(&sub->count);
2788                 if (read_format & PERF_FORMAT_ID)
2789                         values[n++] = primary_counter_id(sub);
2790
2791                 perf_output_copy(handle, values, n * sizeof(u64));
2792         }
2793 }
2794
2795 static void perf_output_read(struct perf_output_handle *handle,
2796                              struct perf_counter *counter)
2797 {
2798         if (counter->attr.read_format & PERF_FORMAT_GROUP)
2799                 perf_output_read_group(handle, counter);
2800         else
2801                 perf_output_read_one(handle, counter);
2802 }
2803
2804 void perf_counter_output(struct perf_counter *counter, int nmi,
2805                                 struct perf_sample_data *data)
2806 {
2807         int ret;
2808         u64 sample_type = counter->attr.sample_type;
2809         struct perf_output_handle handle;
2810         struct perf_event_header header;
2811         u64 ip;
2812         struct {
2813                 u32 pid, tid;
2814         } tid_entry;
2815         struct perf_callchain_entry *callchain = NULL;
2816         int callchain_size = 0;
2817         u64 time;
2818         struct {
2819                 u32 cpu, reserved;
2820         } cpu_entry;
2821
2822         header.type = PERF_EVENT_SAMPLE;
2823         header.size = sizeof(header);
2824
2825         header.misc = 0;
2826         header.misc |= perf_misc_flags(data->regs);
2827
2828         if (sample_type & PERF_SAMPLE_IP) {
2829                 ip = perf_instruction_pointer(data->regs);
2830                 header.size += sizeof(ip);
2831         }
2832
2833         if (sample_type & PERF_SAMPLE_TID) {
2834                 /* namespace issues */
2835                 tid_entry.pid = perf_counter_pid(counter, current);
2836                 tid_entry.tid = perf_counter_tid(counter, current);
2837
2838                 header.size += sizeof(tid_entry);
2839         }
2840
2841         if (sample_type & PERF_SAMPLE_TIME) {
2842                 /*
2843                  * Maybe do better on x86 and provide cpu_clock_nmi()
2844                  */
2845                 time = sched_clock();
2846
2847                 header.size += sizeof(u64);
2848         }
2849
2850         if (sample_type & PERF_SAMPLE_ADDR)
2851                 header.size += sizeof(u64);
2852
2853         if (sample_type & PERF_SAMPLE_ID)
2854                 header.size += sizeof(u64);
2855
2856         if (sample_type & PERF_SAMPLE_STREAM_ID)
2857                 header.size += sizeof(u64);
2858
2859         if (sample_type & PERF_SAMPLE_CPU) {
2860                 header.size += sizeof(cpu_entry);
2861
2862                 cpu_entry.cpu = raw_smp_processor_id();
2863                 cpu_entry.reserved = 0;
2864         }
2865
2866         if (sample_type & PERF_SAMPLE_PERIOD)
2867                 header.size += sizeof(u64);
2868
2869         if (sample_type & PERF_SAMPLE_READ)
2870                 header.size += perf_counter_read_size(counter);
2871
2872         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
2873                 callchain = perf_callchain(data->regs);
2874
2875                 if (callchain) {
2876                         callchain_size = (1 + callchain->nr) * sizeof(u64);
2877                         header.size += callchain_size;
2878                 } else
2879                         header.size += sizeof(u64);
2880         }
2881
2882         if (sample_type & PERF_SAMPLE_RAW) {
2883                 int size = sizeof(u32);
2884
2885                 if (data->raw)
2886                         size += data->raw->size;
2887                 else
2888                         size += sizeof(u32);
2889
2890                 WARN_ON_ONCE(size & (sizeof(u64)-1));
2891                 header.size += size;
2892         }
2893
2894         ret = perf_output_begin(&handle, counter, header.size, nmi, 1);
2895         if (ret)
2896                 return;
2897
2898         perf_output_put(&handle, header);
2899
2900         if (sample_type & PERF_SAMPLE_IP)
2901                 perf_output_put(&handle, ip);
2902
2903         if (sample_type & PERF_SAMPLE_TID)
2904                 perf_output_put(&handle, tid_entry);
2905
2906         if (sample_type & PERF_SAMPLE_TIME)
2907                 perf_output_put(&handle, time);
2908
2909         if (sample_type & PERF_SAMPLE_ADDR)
2910                 perf_output_put(&handle, data->addr);
2911
2912         if (sample_type & PERF_SAMPLE_ID) {
2913                 u64 id = primary_counter_id(counter);
2914
2915                 perf_output_put(&handle, id);
2916         }
2917
2918         if (sample_type & PERF_SAMPLE_STREAM_ID)
2919                 perf_output_put(&handle, counter->id);
2920
2921         if (sample_type & PERF_SAMPLE_CPU)
2922                 perf_output_put(&handle, cpu_entry);
2923
2924         if (sample_type & PERF_SAMPLE_PERIOD)
2925                 perf_output_put(&handle, data->period);
2926
2927         if (sample_type & PERF_SAMPLE_READ)
2928                 perf_output_read(&handle, counter);
2929
2930         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
2931                 if (callchain)
2932                         perf_output_copy(&handle, callchain, callchain_size);
2933                 else {
2934                         u64 nr = 0;
2935                         perf_output_put(&handle, nr);
2936                 }
2937         }
2938
2939         if (sample_type & PERF_SAMPLE_RAW) {
2940                 if (data->raw) {
2941                         perf_output_put(&handle, data->raw->size);
2942                         perf_output_copy(&handle, data->raw->data, data->raw->size);
2943                 } else {
2944                         struct {
2945                                 u32     size;
2946                                 u32     data;
2947                         } raw = {
2948                                 .size = sizeof(u32),
2949                                 .data = 0,
2950                         };
2951                         perf_output_put(&handle, raw);
2952                 }
2953         }
2954
2955         perf_output_end(&handle);
2956 }
2957
2958 /*
2959  * read event
2960  */
2961
2962 struct perf_read_event {
2963         struct perf_event_header        header;
2964
2965         u32                             pid;
2966         u32                             tid;
2967 };
2968
2969 static void
2970 perf_counter_read_event(struct perf_counter *counter,
2971                         struct task_struct *task)
2972 {
2973         struct perf_output_handle handle;
2974         struct perf_read_event event = {
2975                 .header = {
2976                         .type = PERF_EVENT_READ,
2977                         .misc = 0,
2978                         .size = sizeof(event) + perf_counter_read_size(counter),
2979                 },
2980                 .pid = perf_counter_pid(counter, task),
2981                 .tid = perf_counter_tid(counter, task),
2982         };
2983         int ret;
2984
2985         ret = perf_output_begin(&handle, counter, event.header.size, 0, 0);
2986         if (ret)
2987                 return;
2988
2989         perf_output_put(&handle, event);
2990         perf_output_read(&handle, counter);
2991
2992         perf_output_end(&handle);
2993 }
2994
2995 /*
2996  * task tracking -- fork/exit
2997  *
2998  * enabled by: attr.comm | attr.mmap | attr.task
2999  */
3000
3001 struct perf_task_event {
3002         struct task_struct              *task;
3003         struct perf_counter_context     *task_ctx;
3004
3005         struct {
3006                 struct perf_event_header        header;
3007
3008                 u32                             pid;
3009                 u32                             ppid;
3010                 u32                             tid;
3011                 u32                             ptid;
3012         } event;
3013 };
3014
3015 static void perf_counter_task_output(struct perf_counter *counter,
3016                                      struct perf_task_event *task_event)
3017 {
3018         struct perf_output_handle handle;
3019         int size = task_event->event.header.size;
3020         struct task_struct *task = task_event->task;
3021         int ret = perf_output_begin(&handle, counter, size, 0, 0);
3022
3023         if (ret)
3024                 return;
3025
3026         task_event->event.pid = perf_counter_pid(counter, task);
3027         task_event->event.ppid = perf_counter_pid(counter, task->real_parent);
3028
3029         task_event->event.tid = perf_counter_tid(counter, task);
3030         task_event->event.ptid = perf_counter_tid(counter, task->real_parent);
3031
3032         perf_output_put(&handle, task_event->event);
3033         perf_output_end(&handle);
3034 }
3035
3036 static int perf_counter_task_match(struct perf_counter *counter)
3037 {
3038         if (counter->attr.comm || counter->attr.mmap || counter->attr.task)
3039                 return 1;
3040
3041         return 0;
3042 }
3043
3044 static void perf_counter_task_ctx(struct perf_counter_context *ctx,
3045                                   struct perf_task_event *task_event)
3046 {
3047         struct perf_counter *counter;
3048
3049         if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
3050                 return;
3051
3052         rcu_read_lock();
3053         list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
3054                 if (perf_counter_task_match(counter))
3055                         perf_counter_task_output(counter, task_event);
3056         }
3057         rcu_read_unlock();
3058 }
3059
3060 static void perf_counter_task_event(struct perf_task_event *task_event)
3061 {
3062         struct perf_cpu_context *cpuctx;
3063         struct perf_counter_context *ctx = task_event->task_ctx;
3064
3065         cpuctx = &get_cpu_var(perf_cpu_context);
3066         perf_counter_task_ctx(&cpuctx->ctx, task_event);
3067         put_cpu_var(perf_cpu_context);
3068
3069         rcu_read_lock();
3070         if (!ctx)
3071                 ctx = rcu_dereference(task_event->task->perf_counter_ctxp);
3072         if (ctx)
3073                 perf_counter_task_ctx(ctx, task_event);
3074         rcu_read_unlock();
3075 }
3076
3077 static void perf_counter_task(struct task_struct *task,
3078                               struct perf_counter_context *task_ctx,
3079                               int new)
3080 {
3081         struct perf_task_event task_event;
3082
3083         if (!atomic_read(&nr_comm_counters) &&
3084             !atomic_read(&nr_mmap_counters) &&
3085             !atomic_read(&nr_task_counters))
3086                 return;
3087
3088         task_event = (struct perf_task_event){
3089                 .task     = task,
3090                 .task_ctx = task_ctx,
3091                 .event    = {
3092                         .header = {
3093                                 .type = new ? PERF_EVENT_FORK : PERF_EVENT_EXIT,
3094                                 .misc = 0,
3095                                 .size = sizeof(task_event.event),
3096                         },
3097                         /* .pid  */
3098                         /* .ppid */
3099                         /* .tid  */
3100                         /* .ptid */
3101                 },
3102         };
3103
3104         perf_counter_task_event(&task_event);
3105 }
3106
3107 void perf_counter_fork(struct task_struct *task)
3108 {
3109         perf_counter_task(task, NULL, 1);
3110 }
3111
3112 /*
3113  * comm tracking
3114  */
3115
3116 struct perf_comm_event {
3117         struct task_struct      *task;
3118         char                    *comm;
3119         int                     comm_size;
3120
3121         struct {
3122                 struct perf_event_header        header;
3123
3124                 u32                             pid;
3125                 u32                             tid;
3126         } event;
3127 };
3128
3129 static void perf_counter_comm_output(struct perf_counter *counter,
3130                                      struct perf_comm_event *comm_event)
3131 {
3132         struct perf_output_handle handle;
3133         int size = comm_event->event.header.size;
3134         int ret = perf_output_begin(&handle, counter, size, 0, 0);
3135
3136         if (ret)
3137                 return;
3138
3139         comm_event->event.pid = perf_counter_pid(counter, comm_event->task);
3140         comm_event->event.tid = perf_counter_tid(counter, comm_event->task);
3141
3142         perf_output_put(&handle, comm_event->event);
3143         perf_output_copy(&handle, comm_event->comm,
3144                                    comm_event->comm_size);
3145         perf_output_end(&handle);
3146 }
3147
3148 static int perf_counter_comm_match(struct perf_counter *counter)
3149 {
3150         if (counter->attr.comm)
3151                 return 1;
3152
3153         return 0;
3154 }
3155
3156 static void perf_counter_comm_ctx(struct perf_counter_context *ctx,
3157                                   struct perf_comm_event *comm_event)
3158 {
3159         struct perf_counter *counter;
3160
3161         if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
3162                 return;
3163
3164         rcu_read_lock();
3165         list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
3166                 if (perf_counter_comm_match(counter))
3167                         perf_counter_comm_output(counter, comm_event);
3168         }
3169         rcu_read_unlock();
3170 }
3171
3172 static void perf_counter_comm_event(struct perf_comm_event *comm_event)
3173 {
3174         struct perf_cpu_context *cpuctx;
3175         struct perf_counter_context *ctx;
3176         unsigned int size;
3177         char comm[TASK_COMM_LEN];
3178
3179         memset(comm, 0, sizeof(comm));
3180         strncpy(comm, comm_event->task->comm, sizeof(comm));
3181         size = ALIGN(strlen(comm)+1, sizeof(u64));
3182
3183         comm_event->comm = comm;
3184         comm_event->comm_size = size;
3185
3186         comm_event->event.header.size = sizeof(comm_event->event) + size;
3187
3188         cpuctx = &get_cpu_var(perf_cpu_context);
3189         perf_counter_comm_ctx(&cpuctx->ctx, comm_event);
3190         put_cpu_var(perf_cpu_context);
3191
3192         rcu_read_lock();
3193         /*
3194          * doesn't really matter which of the child contexts the
3195          * events ends up in.
3196          */
3197         ctx = rcu_dereference(current->perf_counter_ctxp);
3198         if (ctx)
3199                 perf_counter_comm_ctx(ctx, comm_event);
3200         rcu_read_unlock();
3201 }
3202
3203 void perf_counter_comm(struct task_struct *task)
3204 {
3205         struct perf_comm_event comm_event;
3206
3207         if (task->perf_counter_ctxp)
3208                 perf_counter_enable_on_exec(task);
3209
3210         if (!atomic_read(&nr_comm_counters))
3211                 return;
3212
3213         comm_event = (struct perf_comm_event){
3214                 .task   = task,
3215                 /* .comm      */
3216                 /* .comm_size */
3217                 .event  = {
3218                         .header = {
3219                                 .type = PERF_EVENT_COMM,
3220                                 .misc = 0,
3221                                 /* .size */
3222                         },
3223                         /* .pid */
3224                         /* .tid */
3225                 },
3226         };
3227
3228         perf_counter_comm_event(&comm_event);
3229 }
3230
3231 /*
3232  * mmap tracking
3233  */
3234
3235 struct perf_mmap_event {
3236         struct vm_area_struct   *vma;
3237
3238         const char              *file_name;
3239         int                     file_size;
3240
3241         struct {
3242                 struct perf_event_header        header;
3243
3244                 u32                             pid;
3245                 u32                             tid;
3246                 u64                             start;
3247                 u64                             len;
3248                 u64                             pgoff;
3249         } event;
3250 };
3251
3252 static void perf_counter_mmap_output(struct perf_counter *counter,
3253                                      struct perf_mmap_event *mmap_event)
3254 {
3255         struct perf_output_handle handle;
3256         int size = mmap_event->event.header.size;
3257         int ret = perf_output_begin(&handle, counter, size, 0, 0);
3258
3259         if (ret)
3260                 return;
3261
3262         mmap_event->event.pid = perf_counter_pid(counter, current);
3263         mmap_event->event.tid = perf_counter_tid(counter, current);
3264
3265         perf_output_put(&handle, mmap_event->event);
3266         perf_output_copy(&handle, mmap_event->file_name,
3267                                    mmap_event->file_size);
3268         perf_output_end(&handle);
3269 }
3270
3271 static int perf_counter_mmap_match(struct perf_counter *counter,
3272                                    struct perf_mmap_event *mmap_event)
3273 {
3274         if (counter->attr.mmap)
3275                 return 1;
3276
3277         return 0;
3278 }
3279
3280 static void perf_counter_mmap_ctx(struct perf_counter_context *ctx,
3281                                   struct perf_mmap_event *mmap_event)
3282 {
3283         struct perf_counter *counter;
3284
3285         if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
3286                 return;
3287
3288         rcu_read_lock();
3289         list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
3290                 if (perf_counter_mmap_match(counter, mmap_event))
3291                         perf_counter_mmap_output(counter, mmap_event);
3292         }
3293         rcu_read_unlock();
3294 }
3295
3296 static void perf_counter_mmap_event(struct perf_mmap_event *mmap_event)
3297 {
3298         struct perf_cpu_context *cpuctx;
3299         struct perf_counter_context *ctx;
3300         struct vm_area_struct *vma = mmap_event->vma;
3301         struct file *file = vma->vm_file;
3302         unsigned int size;
3303         char tmp[16];
3304         char *buf = NULL;
3305         const char *name;
3306
3307         memset(tmp, 0, sizeof(tmp));
3308
3309         if (file) {
3310                 /*
3311                  * d_path works from the end of the buffer backwards, so we
3312                  * need to add enough zero bytes after the string to handle
3313                  * the 64bit alignment we do later.
3314                  */
3315                 buf = kzalloc(PATH_MAX + sizeof(u64), GFP_KERNEL);
3316                 if (!buf) {
3317                         name = strncpy(tmp, "//enomem", sizeof(tmp));
3318                         goto got_name;
3319                 }
3320                 name = d_path(&file->f_path, buf, PATH_MAX);
3321                 if (IS_ERR(name)) {
3322                         name = strncpy(tmp, "//toolong", sizeof(tmp));
3323                         goto got_name;
3324                 }
3325         } else {
3326                 if (arch_vma_name(mmap_event->vma)) {
3327                         name = strncpy(tmp, arch_vma_name(mmap_event->vma),
3328                                        sizeof(tmp));
3329                         goto got_name;
3330                 }
3331
3332                 if (!vma->vm_mm) {
3333                         name = strncpy(tmp, "[vdso]", sizeof(tmp));
3334                         goto got_name;
3335                 }
3336
3337                 name = strncpy(tmp, "//anon", sizeof(tmp));
3338                 goto got_name;
3339         }
3340
3341 got_name:
3342         size = ALIGN(strlen(name)+1, sizeof(u64));
3343
3344         mmap_event->file_name = name;
3345         mmap_event->file_size = size;
3346
3347         mmap_event->event.header.size = sizeof(mmap_event->event) + size;
3348
3349         cpuctx = &get_cpu_var(perf_cpu_context);
3350         perf_counter_mmap_ctx(&cpuctx->ctx, mmap_event);
3351         put_cpu_var(perf_cpu_context);
3352
3353         rcu_read_lock();
3354         /*
3355          * doesn't really matter which of the child contexts the
3356          * events ends up in.
3357          */
3358         ctx = rcu_dereference(current->perf_counter_ctxp);
3359         if (ctx)
3360                 perf_counter_mmap_ctx(ctx, mmap_event);
3361         rcu_read_unlock();
3362
3363         kfree(buf);
3364 }
3365
3366 void __perf_counter_mmap(struct vm_area_struct *vma)
3367 {
3368         struct perf_mmap_event mmap_event;
3369
3370         if (!atomic_read(&nr_mmap_counters))
3371                 return;
3372
3373         mmap_event = (struct perf_mmap_event){
3374                 .vma    = vma,
3375                 /* .file_name */
3376                 /* .file_size */
3377                 .event  = {
3378                         .header = {
3379                                 .type = PERF_EVENT_MMAP,
3380                                 .misc = 0,
3381                                 /* .size */
3382                         },
3383                         /* .pid */
3384                         /* .tid */
3385                         .start  = vma->vm_start,
3386                         .len    = vma->vm_end - vma->vm_start,
3387                         .pgoff  = vma->vm_pgoff,
3388                 },
3389         };
3390
3391         perf_counter_mmap_event(&mmap_event);
3392 }
3393
3394 /*
3395  * IRQ throttle logging
3396  */
3397
3398 static void perf_log_throttle(struct perf_counter *counter, int enable)
3399 {
3400         struct perf_output_handle handle;
3401         int ret;
3402
3403         struct {
3404                 struct perf_event_header        header;
3405                 u64                             time;
3406                 u64                             id;
3407                 u64                             stream_id;
3408         } throttle_event = {
3409                 .header = {
3410                         .type = PERF_EVENT_THROTTLE,
3411                         .misc = 0,
3412                         .size = sizeof(throttle_event),
3413                 },
3414                 .time           = sched_clock(),
3415                 .id             = primary_counter_id(counter),
3416                 .stream_id      = counter->id,
3417         };
3418
3419         if (enable)
3420                 throttle_event.header.type = PERF_EVENT_UNTHROTTLE;
3421
3422         ret = perf_output_begin(&handle, counter, sizeof(throttle_event), 1, 0);
3423         if (ret)
3424                 return;
3425
3426         perf_output_put(&handle, throttle_event);
3427         perf_output_end(&handle);
3428 }
3429
3430 /*
3431  * Generic counter overflow handling, sampling.
3432  */
3433
3434 int perf_counter_overflow(struct perf_counter *counter, int nmi,
3435                           struct perf_sample_data *data)
3436 {
3437         int events = atomic_read(&counter->event_limit);
3438         int throttle = counter->pmu->unthrottle != NULL;
3439         struct hw_perf_counter *hwc = &counter->hw;
3440         int ret = 0;
3441
3442         if (!throttle) {
3443                 hwc->interrupts++;
3444         } else {
3445                 if (hwc->interrupts != MAX_INTERRUPTS) {
3446                         hwc->interrupts++;
3447                         if (HZ * hwc->interrupts >
3448                                         (u64)sysctl_perf_counter_sample_rate) {
3449                                 hwc->interrupts = MAX_INTERRUPTS;
3450                                 perf_log_throttle(counter, 0);
3451                                 ret = 1;
3452                         }
3453                 } else {
3454                         /*
3455                          * Keep re-disabling counters even though on the previous
3456                          * pass we disabled it - just in case we raced with a
3457                          * sched-in and the counter got enabled again:
3458                          */
3459                         ret = 1;
3460                 }
3461         }
3462
3463         if (counter->attr.freq) {
3464                 u64 now = sched_clock();
3465                 s64 delta = now - hwc->freq_stamp;
3466
3467                 hwc->freq_stamp = now;
3468
3469                 if (delta > 0 && delta < TICK_NSEC)
3470                         perf_adjust_period(counter, NSEC_PER_SEC / (int)delta);
3471         }
3472
3473         /*
3474          * XXX event_limit might not quite work as expected on inherited
3475          * counters
3476          */
3477
3478         counter->pending_kill = POLL_IN;
3479         if (events && atomic_dec_and_test(&counter->event_limit)) {
3480                 ret = 1;
3481                 counter->pending_kill = POLL_HUP;
3482                 if (nmi) {
3483                         counter->pending_disable = 1;
3484                         perf_pending_queue(&counter->pending,
3485                                            perf_pending_counter);
3486                 } else
3487                         perf_counter_disable(counter);
3488         }
3489
3490         perf_counter_output(counter, nmi, data);
3491         return ret;
3492 }
3493
3494 /*
3495  * Generic software counter infrastructure
3496  */
3497
3498 /*
3499  * We directly increment counter->count and keep a second value in
3500  * counter->hw.period_left to count intervals. This period counter
3501  * is kept in the range [-sample_period, 0] so that we can use the
3502  * sign as trigger.
3503  */
3504
3505 static u64 perf_swcounter_set_period(struct perf_counter *counter)
3506 {
3507         struct hw_perf_counter *hwc = &counter->hw;
3508         u64 period = hwc->last_period;
3509         u64 nr, offset;
3510         s64 old, val;
3511
3512         hwc->last_period = hwc->sample_period;
3513
3514 again:
3515         old = val = atomic64_read(&hwc->period_left);
3516         if (val < 0)
3517                 return 0;
3518
3519         nr = div64_u64(period + val, period);
3520         offset = nr * period;
3521         val -= offset;
3522         if (atomic64_cmpxchg(&hwc->period_left, old, val) != old)
3523                 goto again;
3524
3525         return nr;
3526 }
3527
3528 static void perf_swcounter_overflow(struct perf_counter *counter,
3529                                     int nmi, struct perf_sample_data *data)
3530 {
3531         struct hw_perf_counter *hwc = &counter->hw;
3532         u64 overflow;
3533
3534         data->period = counter->hw.last_period;
3535         overflow = perf_swcounter_set_period(counter);
3536
3537         if (hwc->interrupts == MAX_INTERRUPTS)
3538                 return;
3539
3540         for (; overflow; overflow--) {
3541                 if (perf_counter_overflow(counter, nmi, data)) {
3542                         /*
3543                          * We inhibit the overflow from happening when
3544                          * hwc->interrupts == MAX_INTERRUPTS.
3545                          */
3546                         break;
3547                 }
3548         }
3549 }
3550
3551 static void perf_swcounter_unthrottle(struct perf_counter *counter)
3552 {
3553         /*
3554          * Nothing to do, we already reset hwc->interrupts.
3555          */
3556 }
3557
3558 static void perf_swcounter_add(struct perf_counter *counter, u64 nr,
3559                                int nmi, struct perf_sample_data *data)
3560 {
3561         struct hw_perf_counter *hwc = &counter->hw;
3562
3563         atomic64_add(nr, &counter->count);
3564
3565         if (!hwc->sample_period)
3566                 return;
3567
3568         if (!data->regs)
3569                 return;
3570
3571         if (!atomic64_add_negative(nr, &hwc->period_left))
3572                 perf_swcounter_overflow(counter, nmi, data);
3573 }
3574
3575 static int perf_swcounter_is_counting(struct perf_counter *counter)
3576 {
3577         /*
3578          * The counter is active, we're good!
3579          */
3580         if (counter->state == PERF_COUNTER_STATE_ACTIVE)
3581                 return 1;
3582
3583         /*
3584          * The counter is off/error, not counting.
3585          */
3586         if (counter->state != PERF_COUNTER_STATE_INACTIVE)
3587                 return 0;
3588
3589         /*
3590          * The counter is inactive, if the context is active
3591          * we're part of a group that didn't make it on the 'pmu',
3592          * not counting.
3593          */
3594         if (counter->ctx->is_active)
3595                 return 0;
3596
3597         /*
3598          * We're inactive and the context is too, this means the
3599          * task is scheduled out, we're counting events that happen
3600          * to us, like migration events.
3601          */
3602         return 1;
3603 }
3604
3605 static int perf_swcounter_match(struct perf_counter *counter,
3606                                 enum perf_type_id type,
3607                                 u32 event, struct pt_regs *regs)
3608 {
3609         if (!perf_swcounter_is_counting(counter))
3610                 return 0;
3611
3612         if (counter->attr.type != type)
3613                 return 0;
3614         if (counter->attr.config != event)
3615                 return 0;
3616
3617         if (regs) {
3618                 if (counter->attr.exclude_user && user_mode(regs))
3619                         return 0;
3620
3621                 if (counter->attr.exclude_kernel && !user_mode(regs))
3622                         return 0;
3623         }
3624
3625         return 1;
3626 }
3627
3628 static void perf_swcounter_ctx_event(struct perf_counter_context *ctx,
3629                                      enum perf_type_id type,
3630                                      u32 event, u64 nr, int nmi,
3631                                      struct perf_sample_data *data)
3632 {
3633         struct perf_counter *counter;
3634
3635         if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
3636                 return;
3637
3638         rcu_read_lock();
3639         list_for_each_entry_rcu(counter, &ctx->event_list, event_entry) {
3640                 if (perf_swcounter_match(counter, type, event, data->regs))
3641                         perf_swcounter_add(counter, nr, nmi, data);
3642         }
3643         rcu_read_unlock();
3644 }
3645
3646 static int *perf_swcounter_recursion_context(struct perf_cpu_context *cpuctx)
3647 {
3648         if (in_nmi())
3649                 return &cpuctx->recursion[3];
3650
3651         if (in_irq())
3652                 return &cpuctx->recursion[2];
3653
3654         if (in_softirq())
3655                 return &cpuctx->recursion[1];
3656
3657         return &cpuctx->recursion[0];
3658 }
3659
3660 static void do_perf_swcounter_event(enum perf_type_id type, u32 event,
3661                                     u64 nr, int nmi,
3662                                     struct perf_sample_data *data)
3663 {
3664         struct perf_cpu_context *cpuctx = &get_cpu_var(perf_cpu_context);
3665         int *recursion = perf_swcounter_recursion_context(cpuctx);
3666         struct perf_counter_context *ctx;
3667
3668         if (*recursion)
3669                 goto out;
3670
3671         (*recursion)++;
3672         barrier();
3673
3674         perf_swcounter_ctx_event(&cpuctx->ctx, type, event,
3675                                  nr, nmi, data);
3676         rcu_read_lock();
3677         /*
3678          * doesn't really matter which of the child contexts the
3679          * events ends up in.
3680          */
3681         ctx = rcu_dereference(current->perf_counter_ctxp);
3682         if (ctx)
3683                 perf_swcounter_ctx_event(ctx, type, event, nr, nmi, data);
3684         rcu_read_unlock();
3685
3686         barrier();
3687         (*recursion)--;
3688
3689 out:
3690         put_cpu_var(perf_cpu_context);
3691 }
3692
3693 void __perf_swcounter_event(u32 event, u64 nr, int nmi,
3694                             struct pt_regs *regs, u64 addr)
3695 {
3696         struct perf_sample_data data = {
3697                 .regs = regs,
3698                 .addr = addr,
3699         };
3700
3701         do_perf_swcounter_event(PERF_TYPE_SOFTWARE, event, nr, nmi, &data);
3702 }
3703
3704 static void perf_swcounter_read(struct perf_counter *counter)
3705 {
3706 }
3707
3708 static int perf_swcounter_enable(struct perf_counter *counter)
3709 {
3710         struct hw_perf_counter *hwc = &counter->hw;
3711
3712         if (hwc->sample_period) {
3713                 hwc->last_period = hwc->sample_period;
3714                 perf_swcounter_set_period(counter);
3715         }
3716         return 0;
3717 }
3718
3719 static void perf_swcounter_disable(struct perf_counter *counter)
3720 {
3721 }
3722
3723 static const struct pmu perf_ops_generic = {
3724         .enable         = perf_swcounter_enable,
3725         .disable        = perf_swcounter_disable,
3726         .read           = perf_swcounter_read,
3727         .unthrottle     = perf_swcounter_unthrottle,
3728 };
3729
3730 /*
3731  * hrtimer based swcounter callback
3732  */
3733
3734 static enum hrtimer_restart perf_swcounter_hrtimer(struct hrtimer *hrtimer)
3735 {
3736         enum hrtimer_restart ret = HRTIMER_RESTART;
3737         struct perf_sample_data data;
3738         struct perf_counter *counter;
3739         u64 period;
3740
3741         counter = container_of(hrtimer, struct perf_counter, hw.hrtimer);
3742         counter->pmu->read(counter);
3743
3744         data.addr = 0;
3745         data.regs = get_irq_regs();
3746         /*
3747          * In case we exclude kernel IPs or are somehow not in interrupt
3748          * context, provide the next best thing, the user IP.
3749          */
3750         if ((counter->attr.exclude_kernel || !data.regs) &&
3751                         !counter->attr.exclude_user)
3752                 data.regs = task_pt_regs(current);
3753
3754         if (data.regs) {
3755                 if (perf_counter_overflow(counter, 0, &data))
3756                         ret = HRTIMER_NORESTART;
3757         }
3758
3759         period = max_t(u64, 10000, counter->hw.sample_period);
3760         hrtimer_forward_now(hrtimer, ns_to_ktime(period));
3761
3762         return ret;
3763 }
3764
3765 /*
3766  * Software counter: cpu wall time clock
3767  */
3768
3769 static void cpu_clock_perf_counter_update(struct perf_counter *counter)
3770 {
3771         int cpu = raw_smp_processor_id();
3772         s64 prev;
3773         u64 now;
3774
3775         now = cpu_clock(cpu);
3776         prev = atomic64_read(&counter->hw.prev_count);
3777         atomic64_set(&counter->hw.prev_count, now);
3778         atomic64_add(now - prev, &counter->count);
3779 }
3780
3781 static int cpu_clock_perf_counter_enable(struct perf_counter *counter)
3782 {
3783         struct hw_perf_counter *hwc = &counter->hw;
3784         int cpu = raw_smp_processor_id();
3785
3786         atomic64_set(&hwc->prev_count, cpu_clock(cpu));
3787         hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3788         hwc->hrtimer.function = perf_swcounter_hrtimer;
3789         if (hwc->sample_period) {
3790                 u64 period = max_t(u64, 10000, hwc->sample_period);
3791                 __hrtimer_start_range_ns(&hwc->hrtimer,
3792                                 ns_to_ktime(period), 0,
3793                                 HRTIMER_MODE_REL, 0);
3794         }
3795
3796         return 0;
3797 }
3798
3799 static void cpu_clock_perf_counter_disable(struct perf_counter *counter)
3800 {
3801         if (counter->hw.sample_period)
3802                 hrtimer_cancel(&counter->hw.hrtimer);
3803         cpu_clock_perf_counter_update(counter);
3804 }
3805
3806 static void cpu_clock_perf_counter_read(struct perf_counter *counter)
3807 {
3808         cpu_clock_perf_counter_update(counter);
3809 }
3810
3811 static const struct pmu perf_ops_cpu_clock = {
3812         .enable         = cpu_clock_perf_counter_enable,
3813         .disable        = cpu_clock_perf_counter_disable,
3814         .read           = cpu_clock_perf_counter_read,
3815 };
3816
3817 /*
3818  * Software counter: task time clock
3819  */
3820
3821 static void task_clock_perf_counter_update(struct perf_counter *counter, u64 now)
3822 {
3823         u64 prev;
3824         s64 delta;
3825
3826         prev = atomic64_xchg(&counter->hw.prev_count, now);
3827         delta = now - prev;
3828         atomic64_add(delta, &counter->count);
3829 }
3830
3831 static int task_clock_perf_counter_enable(struct perf_counter *counter)
3832 {
3833         struct hw_perf_counter *hwc = &counter->hw;
3834         u64 now;
3835
3836         now = counter->ctx->time;
3837
3838         atomic64_set(&hwc->prev_count, now);
3839         hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3840         hwc->hrtimer.function = perf_swcounter_hrtimer;
3841         if (hwc->sample_period) {
3842                 u64 period = max_t(u64, 10000, hwc->sample_period);
3843                 __hrtimer_start_range_ns(&hwc->hrtimer,
3844                                 ns_to_ktime(period), 0,
3845                                 HRTIMER_MODE_REL, 0);
3846         }
3847
3848         return 0;
3849 }
3850
3851 static void task_clock_perf_counter_disable(struct perf_counter *counter)
3852 {
3853         if (counter->hw.sample_period)
3854                 hrtimer_cancel(&counter->hw.hrtimer);
3855         task_clock_perf_counter_update(counter, counter->ctx->time);
3856
3857 }
3858
3859 static void task_clock_perf_counter_read(struct perf_counter *counter)
3860 {
3861         u64 time;
3862
3863         if (!in_nmi()) {
3864                 update_context_time(counter->ctx);
3865                 time = counter->ctx->time;
3866         } else {
3867                 u64 now = perf_clock();
3868                 u64 delta = now - counter->ctx->timestamp;
3869                 time = counter->ctx->time + delta;
3870         }
3871
3872         task_clock_perf_counter_update(counter, time);
3873 }
3874
3875 static const struct pmu perf_ops_task_clock = {
3876         .enable         = task_clock_perf_counter_enable,
3877         .disable        = task_clock_perf_counter_disable,
3878         .read           = task_clock_perf_counter_read,
3879 };
3880
3881 #ifdef CONFIG_EVENT_PROFILE
3882 void perf_tpcounter_event(int event_id, u64 addr, u64 count, void *record,
3883                           int entry_size)
3884 {
3885         struct perf_raw_record raw = {
3886                 .size = entry_size,
3887                 .data = record,
3888         };
3889
3890         struct perf_sample_data data = {
3891                 .regs = get_irq_regs(),
3892                 .addr = addr,
3893                 .raw = &raw,
3894         };
3895
3896         if (!data.regs)
3897                 data.regs = task_pt_regs(current);
3898
3899         do_perf_swcounter_event(PERF_TYPE_TRACEPOINT, event_id, count, 1, &data);
3900 }
3901 EXPORT_SYMBOL_GPL(perf_tpcounter_event);
3902
3903 extern int ftrace_profile_enable(int);
3904 extern void ftrace_profile_disable(int);
3905
3906 static void tp_perf_counter_destroy(struct perf_counter *counter)
3907 {
3908         ftrace_profile_disable(counter->attr.config);
3909 }
3910
3911 static const struct pmu *tp_perf_counter_init(struct perf_counter *counter)
3912 {
3913         /*
3914          * Raw tracepoint data is a severe data leak, only allow root to
3915          * have these.
3916          */
3917         if ((counter->attr.sample_type & PERF_SAMPLE_RAW) &&
3918                         !capable(CAP_SYS_ADMIN))
3919                 return ERR_PTR(-EPERM);
3920
3921         if (ftrace_profile_enable(counter->attr.config))
3922                 return NULL;
3923
3924         counter->destroy = tp_perf_counter_destroy;
3925
3926         return &perf_ops_generic;
3927 }
3928 #else
3929 static const struct pmu *tp_perf_counter_init(struct perf_counter *counter)
3930 {
3931         return NULL;
3932 }
3933 #endif
3934
3935 atomic_t perf_swcounter_enabled[PERF_COUNT_SW_MAX];
3936
3937 static void sw_perf_counter_destroy(struct perf_counter *counter)
3938 {
3939         u64 event = counter->attr.config;
3940
3941         WARN_ON(counter->parent);
3942
3943         atomic_dec(&perf_swcounter_enabled[event]);
3944 }
3945
3946 static const struct pmu *sw_perf_counter_init(struct perf_counter *counter)
3947 {
3948         const struct pmu *pmu = NULL;
3949         u64 event = counter->attr.config;
3950
3951         /*
3952          * Software counters (currently) can't in general distinguish
3953          * between user, kernel and hypervisor events.
3954          * However, context switches and cpu migrations are considered
3955          * to be kernel events, and page faults are never hypervisor
3956          * events.
3957          */
3958         switch (event) {
3959         case PERF_COUNT_SW_CPU_CLOCK:
3960                 pmu = &perf_ops_cpu_clock;
3961
3962                 break;
3963         case PERF_COUNT_SW_TASK_CLOCK:
3964                 /*
3965                  * If the user instantiates this as a per-cpu counter,
3966                  * use the cpu_clock counter instead.
3967                  */
3968                 if (counter->ctx->task)
3969                         pmu = &perf_ops_task_clock;
3970                 else
3971                         pmu = &perf_ops_cpu_clock;
3972
3973                 break;
3974         case PERF_COUNT_SW_PAGE_FAULTS:
3975         case PERF_COUNT_SW_PAGE_FAULTS_MIN:
3976         case PERF_COUNT_SW_PAGE_FAULTS_MAJ:
3977         case PERF_COUNT_SW_CONTEXT_SWITCHES:
3978         case PERF_COUNT_SW_CPU_MIGRATIONS:
3979                 if (!counter->parent) {
3980                         atomic_inc(&perf_swcounter_enabled[event]);
3981                         counter->destroy = sw_perf_counter_destroy;
3982                 }
3983                 pmu = &perf_ops_generic;
3984                 break;
3985         }
3986
3987         return pmu;
3988 }
3989
3990 /*
3991  * Allocate and initialize a counter structure
3992  */
3993 static struct perf_counter *
3994 perf_counter_alloc(struct perf_counter_attr *attr,
3995                    int cpu,
3996                    struct perf_counter_context *ctx,
3997                    struct perf_counter *group_leader,
3998                    struct perf_counter *parent_counter,
3999                    gfp_t gfpflags)
4000 {
4001         const struct pmu *pmu;
4002         struct perf_counter *counter;
4003         struct hw_perf_counter *hwc;
4004         long err;
4005
4006         counter = kzalloc(sizeof(*counter), gfpflags);
4007         if (!counter)
4008                 return ERR_PTR(-ENOMEM);
4009
4010         /*
4011          * Single counters are their own group leaders, with an
4012          * empty sibling list:
4013          */
4014         if (!group_leader)
4015                 group_leader = counter;
4016
4017         mutex_init(&counter->child_mutex);
4018         INIT_LIST_HEAD(&counter->child_list);
4019
4020         INIT_LIST_HEAD(&counter->list_entry);
4021         INIT_LIST_HEAD(&counter->event_entry);
4022         INIT_LIST_HEAD(&counter->sibling_list);
4023         init_waitqueue_head(&counter->waitq);
4024
4025         mutex_init(&counter->mmap_mutex);
4026
4027         counter->cpu            = cpu;
4028         counter->attr           = *attr;
4029         counter->group_leader   = group_leader;
4030         counter->pmu            = NULL;
4031         counter->ctx            = ctx;
4032         counter->oncpu          = -1;
4033
4034         counter->parent         = parent_counter;
4035
4036         counter->ns             = get_pid_ns(current->nsproxy->pid_ns);
4037         counter->id             = atomic64_inc_return(&perf_counter_id);
4038
4039         counter->state          = PERF_COUNTER_STATE_INACTIVE;
4040
4041         if (attr->disabled)
4042                 counter->state = PERF_COUNTER_STATE_OFF;
4043
4044         pmu = NULL;
4045
4046         hwc = &counter->hw;
4047         hwc->sample_period = attr->sample_period;
4048         if (attr->freq && attr->sample_freq)
4049                 hwc->sample_period = 1;
4050
4051         atomic64_set(&hwc->period_left, hwc->sample_period);
4052
4053         /*
4054          * we currently do not support PERF_FORMAT_GROUP on inherited counters
4055          */
4056         if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
4057                 goto done;
4058
4059         switch (attr->type) {
4060         case PERF_TYPE_RAW:
4061         case PERF_TYPE_HARDWARE:
4062         case PERF_TYPE_HW_CACHE:
4063                 pmu = hw_perf_counter_init(counter);
4064                 break;
4065
4066         case PERF_TYPE_SOFTWARE:
4067                 pmu = sw_perf_counter_init(counter);
4068                 break;
4069
4070         case PERF_TYPE_TRACEPOINT:
4071                 pmu = tp_perf_counter_init(counter);
4072                 break;
4073
4074         default:
4075                 break;
4076         }
4077 done:
4078         err = 0;
4079         if (!pmu)
4080                 err = -EINVAL;
4081         else if (IS_ERR(pmu))
4082                 err = PTR_ERR(pmu);
4083
4084         if (err) {
4085                 if (counter->ns)
4086                         put_pid_ns(counter->ns);
4087                 kfree(counter);
4088                 return ERR_PTR(err);
4089         }
4090
4091         counter->pmu = pmu;
4092
4093         if (!counter->parent) {
4094                 atomic_inc(&nr_counters);
4095                 if (counter->attr.mmap)
4096                         atomic_inc(&nr_mmap_counters);
4097                 if (counter->attr.comm)
4098                         atomic_inc(&nr_comm_counters);
4099                 if (counter->attr.task)
4100                         atomic_inc(&nr_task_counters);
4101         }
4102
4103         return counter;
4104 }
4105
4106 static int perf_copy_attr(struct perf_counter_attr __user *uattr,
4107                           struct perf_counter_attr *attr)
4108 {
4109         int ret;
4110         u32 size;
4111
4112         if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
4113                 return -EFAULT;
4114
4115         /*
4116          * zero the full structure, so that a short copy will be nice.
4117          */
4118         memset(attr, 0, sizeof(*attr));
4119
4120         ret = get_user(size, &uattr->size);
4121         if (ret)
4122                 return ret;
4123
4124         if (size > PAGE_SIZE)   /* silly large */
4125                 goto err_size;
4126
4127         if (!size)              /* abi compat */
4128                 size = PERF_ATTR_SIZE_VER0;
4129
4130         if (size < PERF_ATTR_SIZE_VER0)
4131                 goto err_size;
4132
4133         /*
4134          * If we're handed a bigger struct than we know of,
4135          * ensure all the unknown bits are 0.
4136          */
4137         if (size > sizeof(*attr)) {
4138                 unsigned long val;
4139                 unsigned long __user *addr;
4140                 unsigned long __user *end;
4141
4142                 addr = PTR_ALIGN((void __user *)uattr + sizeof(*attr),
4143                                 sizeof(unsigned long));
4144                 end  = PTR_ALIGN((void __user *)uattr + size,
4145                                 sizeof(unsigned long));
4146
4147                 for (; addr < end; addr += sizeof(unsigned long)) {
4148                         ret = get_user(val, addr);
4149                         if (ret)
4150                                 return ret;
4151                         if (val)
4152                                 goto err_size;
4153                 }
4154         }
4155
4156         ret = copy_from_user(attr, uattr, size);
4157         if (ret)
4158                 return -EFAULT;
4159
4160         /*
4161          * If the type exists, the corresponding creation will verify
4162          * the attr->config.
4163          */
4164         if (attr->type >= PERF_TYPE_MAX)
4165                 return -EINVAL;
4166
4167         if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
4168                 return -EINVAL;
4169
4170         if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
4171                 return -EINVAL;
4172
4173         if (attr->read_format & ~(PERF_FORMAT_MAX-1))
4174                 return -EINVAL;
4175
4176 out:
4177         return ret;
4178
4179 err_size:
4180         put_user(sizeof(*attr), &uattr->size);
4181         ret = -E2BIG;
4182         goto out;
4183 }
4184
4185 /**
4186  * sys_perf_counter_open - open a performance counter, associate it to a task/cpu
4187  *
4188  * @attr_uptr:  event type attributes for monitoring/sampling
4189  * @pid:                target pid
4190  * @cpu:                target cpu
4191  * @group_fd:           group leader counter fd
4192  */
4193 SYSCALL_DEFINE5(perf_counter_open,
4194                 struct perf_counter_attr __user *, attr_uptr,
4195                 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
4196 {
4197         struct perf_counter *counter, *group_leader;
4198         struct perf_counter_attr attr;
4199         struct perf_counter_context *ctx;
4200         struct file *counter_file = NULL;
4201         struct file *group_file = NULL;
4202         int fput_needed = 0;
4203         int fput_needed2 = 0;
4204         int ret;
4205
4206         /* for future expandability... */
4207         if (flags)
4208                 return -EINVAL;
4209
4210         ret = perf_copy_attr(attr_uptr, &attr);
4211         if (ret)
4212                 return ret;
4213
4214         if (!attr.exclude_kernel) {
4215                 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
4216                         return -EACCES;
4217         }
4218
4219         if (attr.freq) {
4220                 if (attr.sample_freq > sysctl_perf_counter_sample_rate)
4221                         return -EINVAL;
4222         }
4223
4224         /*
4225          * Get the target context (task or percpu):
4226          */
4227         ctx = find_get_context(pid, cpu);
4228         if (IS_ERR(ctx))
4229                 return PTR_ERR(ctx);
4230
4231         /*
4232          * Look up the group leader (we will attach this counter to it):
4233          */
4234         group_leader = NULL;
4235         if (group_fd != -1) {
4236                 ret = -EINVAL;
4237                 group_file = fget_light(group_fd, &fput_needed);
4238                 if (!group_file)
4239                         goto err_put_context;
4240                 if (group_file->f_op != &perf_fops)
4241                         goto err_put_context;
4242
4243                 group_leader = group_file->private_data;
4244                 /*
4245                  * Do not allow a recursive hierarchy (this new sibling
4246                  * becoming part of another group-sibling):
4247                  */
4248                 if (group_leader->group_leader != group_leader)
4249                         goto err_put_context;
4250                 /*
4251                  * Do not allow to attach to a group in a different
4252                  * task or CPU context:
4253                  */
4254                 if (group_leader->ctx != ctx)
4255                         goto err_put_context;
4256                 /*
4257                  * Only a group leader can be exclusive or pinned
4258                  */
4259                 if (attr.exclusive || attr.pinned)
4260                         goto err_put_context;
4261         }
4262
4263         counter = perf_counter_alloc(&attr, cpu, ctx, group_leader,
4264                                      NULL, GFP_KERNEL);
4265         ret = PTR_ERR(counter);
4266         if (IS_ERR(counter))
4267                 goto err_put_context;
4268
4269         ret = anon_inode_getfd("[perf_counter]", &perf_fops, counter, 0);
4270         if (ret < 0)
4271                 goto err_free_put_context;
4272
4273         counter_file = fget_light(ret, &fput_needed2);
4274         if (!counter_file)
4275                 goto err_free_put_context;
4276
4277         counter->filp = counter_file;
4278         WARN_ON_ONCE(ctx->parent_ctx);
4279         mutex_lock(&ctx->mutex);
4280         perf_install_in_context(ctx, counter, cpu);
4281         ++ctx->generation;
4282         mutex_unlock(&ctx->mutex);
4283
4284         counter->owner = current;
4285         get_task_struct(current);
4286         mutex_lock(&current->perf_counter_mutex);
4287         list_add_tail(&counter->owner_entry, &current->perf_counter_list);
4288         mutex_unlock(&current->perf_counter_mutex);
4289
4290         fput_light(counter_file, fput_needed2);
4291
4292 out_fput:
4293         fput_light(group_file, fput_needed);
4294
4295         return ret;
4296
4297 err_free_put_context:
4298         kfree(counter);
4299
4300 err_put_context:
4301         put_ctx(ctx);
4302
4303         goto out_fput;
4304 }
4305
4306 /*
4307  * inherit a counter from parent task to child task:
4308  */
4309 static struct perf_counter *
4310 inherit_counter(struct perf_counter *parent_counter,
4311               struct task_struct *parent,
4312               struct perf_counter_context *parent_ctx,
4313               struct task_struct *child,
4314               struct perf_counter *group_leader,
4315               struct perf_counter_context *child_ctx)
4316 {
4317         struct perf_counter *child_counter;
4318
4319         /*
4320          * Instead of creating recursive hierarchies of counters,
4321          * we link inherited counters back to the original parent,
4322          * which has a filp for sure, which we use as the reference
4323          * count:
4324          */
4325         if (parent_counter->parent)
4326                 parent_counter = parent_counter->parent;
4327
4328         child_counter = perf_counter_alloc(&parent_counter->attr,
4329                                            parent_counter->cpu, child_ctx,
4330                                            group_leader, parent_counter,
4331                                            GFP_KERNEL);
4332         if (IS_ERR(child_counter))
4333                 return child_counter;
4334         get_ctx(child_ctx);
4335
4336         /*
4337          * Make the child state follow the state of the parent counter,
4338          * not its attr.disabled bit.  We hold the parent's mutex,
4339          * so we won't race with perf_counter_{en, dis}able_family.
4340          */
4341         if (parent_counter->state >= PERF_COUNTER_STATE_INACTIVE)
4342                 child_counter->state = PERF_COUNTER_STATE_INACTIVE;
4343         else
4344                 child_counter->state = PERF_COUNTER_STATE_OFF;
4345
4346         if (parent_counter->attr.freq)
4347                 child_counter->hw.sample_period = parent_counter->hw.sample_period;
4348
4349         /*
4350          * Link it up in the child's context:
4351          */
4352         add_counter_to_ctx(child_counter, child_ctx);
4353
4354         /*
4355          * Get a reference to the parent filp - we will fput it
4356          * when the child counter exits. This is safe to do because
4357          * we are in the parent and we know that the filp still
4358          * exists and has a nonzero count:
4359          */
4360         atomic_long_inc(&parent_counter->filp->f_count);
4361
4362         /*
4363          * Link this into the parent counter's child list
4364          */
4365         WARN_ON_ONCE(parent_counter->ctx->parent_ctx);
4366         mutex_lock(&parent_counter->child_mutex);
4367         list_add_tail(&child_counter->child_list, &parent_counter->child_list);
4368         mutex_unlock(&parent_counter->child_mutex);
4369
4370         return child_counter;
4371 }
4372
4373 static int inherit_group(struct perf_counter *parent_counter,
4374               struct task_struct *parent,
4375               struct perf_counter_context *parent_ctx,
4376               struct task_struct *child,
4377               struct perf_counter_context *child_ctx)
4378 {
4379         struct perf_counter *leader;
4380         struct perf_counter *sub;
4381         struct perf_counter *child_ctr;
4382
4383         leader = inherit_counter(parent_counter, parent, parent_ctx,
4384                                  child, NULL, child_ctx);
4385         if (IS_ERR(leader))
4386                 return PTR_ERR(leader);
4387         list_for_each_entry(sub, &parent_counter->sibling_list, list_entry) {
4388                 child_ctr = inherit_counter(sub, parent, parent_ctx,
4389                                             child, leader, child_ctx);
4390                 if (IS_ERR(child_ctr))
4391                         return PTR_ERR(child_ctr);
4392         }
4393         return 0;
4394 }
4395
4396 static void sync_child_counter(struct perf_counter *child_counter,
4397                                struct task_struct *child)
4398 {
4399         struct perf_counter *parent_counter = child_counter->parent;
4400         u64 child_val;
4401
4402         if (child_counter->attr.inherit_stat)
4403                 perf_counter_read_event(child_counter, child);
4404
4405         child_val = atomic64_read(&child_counter->count);
4406
4407         /*
4408          * Add back the child's count to the parent's count:
4409          */
4410         atomic64_add(child_val, &parent_counter->count);
4411         atomic64_add(child_counter->total_time_enabled,
4412                      &parent_counter->child_total_time_enabled);
4413         atomic64_add(child_counter->total_time_running,
4414                      &parent_counter->child_total_time_running);
4415
4416         /*
4417          * Remove this counter from the parent's list
4418          */
4419         WARN_ON_ONCE(parent_counter->ctx->parent_ctx);
4420         mutex_lock(&parent_counter->child_mutex);
4421         list_del_init(&child_counter->child_list);
4422         mutex_unlock(&parent_counter->child_mutex);
4423
4424         /*
4425          * Release the parent counter, if this was the last
4426          * reference to it.
4427          */
4428         fput(parent_counter->filp);
4429 }
4430
4431 static void
4432 __perf_counter_exit_task(struct perf_counter *child_counter,
4433                          struct perf_counter_context *child_ctx,
4434                          struct task_struct *child)
4435 {
4436         struct perf_counter *parent_counter;
4437
4438         update_counter_times(child_counter);
4439         perf_counter_remove_from_context(child_counter);
4440
4441         parent_counter = child_counter->parent;
4442         /*
4443          * It can happen that parent exits first, and has counters
4444          * that are still around due to the child reference. These
4445          * counters need to be zapped - but otherwise linger.
4446          */
4447         if (parent_counter) {
4448                 sync_child_counter(child_counter, child);
4449                 free_counter(child_counter);
4450         }
4451 }
4452
4453 /*
4454  * When a child task exits, feed back counter values to parent counters.
4455  */
4456 void perf_counter_exit_task(struct task_struct *child)
4457 {
4458         struct perf_counter *child_counter, *tmp;
4459         struct perf_counter_context *child_ctx;
4460         unsigned long flags;
4461
4462         if (likely(!child->perf_counter_ctxp)) {
4463                 perf_counter_task(child, NULL, 0);
4464                 return;
4465         }
4466
4467         local_irq_save(flags);
4468         /*
4469          * We can't reschedule here because interrupts are disabled,
4470          * and either child is current or it is a task that can't be
4471          * scheduled, so we are now safe from rescheduling changing
4472          * our context.
4473          */
4474         child_ctx = child->perf_counter_ctxp;
4475         __perf_counter_task_sched_out(child_ctx);
4476
4477         /*
4478          * Take the context lock here so that if find_get_context is
4479          * reading child->perf_counter_ctxp, we wait until it has
4480          * incremented the context's refcount before we do put_ctx below.
4481          */
4482         spin_lock(&child_ctx->lock);
4483         child->perf_counter_ctxp = NULL;
4484         /*
4485          * If this context is a clone; unclone it so it can't get
4486          * swapped to another process while we're removing all
4487          * the counters from it.
4488          */
4489         unclone_ctx(child_ctx);
4490         spin_unlock_irqrestore(&child_ctx->lock, flags);
4491
4492         /*
4493          * Report the task dead after unscheduling the counters so that we
4494          * won't get any samples after PERF_EVENT_EXIT. We can however still
4495          * get a few PERF_EVENT_READ events.
4496          */
4497         perf_counter_task(child, child_ctx, 0);
4498
4499         /*
4500          * We can recurse on the same lock type through:
4501          *
4502          *   __perf_counter_exit_task()
4503          *     sync_child_counter()
4504          *       fput(parent_counter->filp)
4505          *         perf_release()
4506          *           mutex_lock(&ctx->mutex)
4507          *
4508          * But since its the parent context it won't be the same instance.
4509          */
4510         mutex_lock_nested(&child_ctx->mutex, SINGLE_DEPTH_NESTING);
4511
4512 again:
4513         list_for_each_entry_safe(child_counter, tmp, &child_ctx->counter_list,
4514                                  list_entry)
4515                 __perf_counter_exit_task(child_counter, child_ctx, child);
4516
4517         /*
4518          * If the last counter was a group counter, it will have appended all
4519          * its siblings to the list, but we obtained 'tmp' before that which
4520          * will still point to the list head terminating the iteration.
4521          */
4522         if (!list_empty(&child_ctx->counter_list))
4523                 goto again;
4524
4525         mutex_unlock(&child_ctx->mutex);
4526
4527         put_ctx(child_ctx);
4528 }
4529
4530 /*
4531  * free an unexposed, unused context as created by inheritance by
4532  * init_task below, used by fork() in case of fail.
4533  */
4534 void perf_counter_free_task(struct task_struct *task)
4535 {
4536         struct perf_counter_context *ctx = task->perf_counter_ctxp;
4537         struct perf_counter *counter, *tmp;
4538
4539         if (!ctx)
4540                 return;
4541
4542         mutex_lock(&ctx->mutex);
4543 again:
4544         list_for_each_entry_safe(counter, tmp, &ctx->counter_list, list_entry) {
4545                 struct perf_counter *parent = counter->parent;
4546
4547                 if (WARN_ON_ONCE(!parent))
4548                         continue;
4549
4550                 mutex_lock(&parent->child_mutex);
4551                 list_del_init(&counter->child_list);
4552                 mutex_unlock(&parent->child_mutex);
4553
4554                 fput(parent->filp);
4555
4556                 list_del_counter(counter, ctx);
4557                 free_counter(counter);
4558         }
4559
4560         if (!list_empty(&ctx->counter_list))
4561                 goto again;
4562
4563         mutex_unlock(&ctx->mutex);
4564
4565         put_ctx(ctx);
4566 }
4567
4568 /*
4569  * Initialize the perf_counter context in task_struct
4570  */
4571 int perf_counter_init_task(struct task_struct *child)
4572 {
4573         struct perf_counter_context *child_ctx, *parent_ctx;
4574         struct perf_counter_context *cloned_ctx;
4575         struct perf_counter *counter;
4576         struct task_struct *parent = current;
4577         int inherited_all = 1;
4578         int ret = 0;
4579
4580         child->perf_counter_ctxp = NULL;
4581
4582         mutex_init(&child->perf_counter_mutex);
4583         INIT_LIST_HEAD(&child->perf_counter_list);
4584
4585         if (likely(!parent->perf_counter_ctxp))
4586                 return 0;
4587
4588         /*
4589          * This is executed from the parent task context, so inherit
4590          * counters that have been marked for cloning.
4591          * First allocate and initialize a context for the child.
4592          */
4593
4594         child_ctx = kmalloc(sizeof(struct perf_counter_context), GFP_KERNEL);
4595         if (!child_ctx)
4596                 return -ENOMEM;
4597
4598         __perf_counter_init_context(child_ctx, child);
4599         child->perf_counter_ctxp = child_ctx;
4600         get_task_struct(child);
4601
4602         /*
4603          * If the parent's context is a clone, pin it so it won't get
4604          * swapped under us.
4605          */
4606         parent_ctx = perf_pin_task_context(parent);
4607
4608         /*
4609          * No need to check if parent_ctx != NULL here; since we saw
4610          * it non-NULL earlier, the only reason for it to become NULL
4611          * is if we exit, and since we're currently in the middle of
4612          * a fork we can't be exiting at the same time.
4613          */
4614
4615         /*
4616          * Lock the parent list. No need to lock the child - not PID
4617          * hashed yet and not running, so nobody can access it.
4618          */
4619         mutex_lock(&parent_ctx->mutex);
4620
4621         /*
4622          * We dont have to disable NMIs - we are only looking at
4623          * the list, not manipulating it:
4624          */
4625         list_for_each_entry_rcu(counter, &parent_ctx->event_list, event_entry) {
4626                 if (counter != counter->group_leader)
4627                         continue;
4628
4629                 if (!counter->attr.inherit) {
4630                         inherited_all = 0;
4631                         continue;
4632                 }
4633
4634                 ret = inherit_group(counter, parent, parent_ctx,
4635                                              child, child_ctx);
4636                 if (ret) {
4637                         inherited_all = 0;
4638                         break;
4639                 }
4640         }
4641
4642         if (inherited_all) {
4643                 /*
4644                  * Mark the child context as a clone of the parent
4645                  * context, or of whatever the parent is a clone of.
4646                  * Note that if the parent is a clone, it could get
4647                  * uncloned at any point, but that doesn't matter
4648                  * because the list of counters and the generation
4649                  * count can't have changed since we took the mutex.
4650                  */
4651                 cloned_ctx = rcu_dereference(parent_ctx->parent_ctx);
4652                 if (cloned_ctx) {
4653                         child_ctx->parent_ctx = cloned_ctx;
4654                         child_ctx->parent_gen = parent_ctx->parent_gen;
4655                 } else {
4656                         child_ctx->parent_ctx = parent_ctx;
4657                         child_ctx->parent_gen = parent_ctx->generation;
4658                 }
4659                 get_ctx(child_ctx->parent_ctx);
4660         }
4661
4662         mutex_unlock(&parent_ctx->mutex);
4663
4664         perf_unpin_context(parent_ctx);
4665
4666         return ret;
4667 }
4668
4669 static void __cpuinit perf_counter_init_cpu(int cpu)
4670 {
4671         struct perf_cpu_context *cpuctx;
4672
4673         cpuctx = &per_cpu(perf_cpu_context, cpu);
4674         __perf_counter_init_context(&cpuctx->ctx, NULL);
4675
4676         spin_lock(&perf_resource_lock);
4677         cpuctx->max_pertask = perf_max_counters - perf_reserved_percpu;
4678         spin_unlock(&perf_resource_lock);
4679
4680         hw_perf_counter_setup(cpu);
4681 }
4682
4683 #ifdef CONFIG_HOTPLUG_CPU
4684 static void __perf_counter_exit_cpu(void *info)
4685 {
4686         struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
4687         struct perf_counter_context *ctx = &cpuctx->ctx;
4688         struct perf_counter *counter, *tmp;
4689
4690         list_for_each_entry_safe(counter, tmp, &ctx->counter_list, list_entry)
4691                 __perf_counter_remove_from_context(counter);
4692 }
4693 static void perf_counter_exit_cpu(int cpu)
4694 {
4695         struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
4696         struct perf_counter_context *ctx = &cpuctx->ctx;
4697
4698         mutex_lock(&ctx->mutex);
4699         smp_call_function_single(cpu, __perf_counter_exit_cpu, NULL, 1);
4700         mutex_unlock(&ctx->mutex);
4701 }
4702 #else
4703 static inline void perf_counter_exit_cpu(int cpu) { }
4704 #endif
4705
4706 static int __cpuinit
4707 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
4708 {
4709         unsigned int cpu = (long)hcpu;
4710
4711         switch (action) {
4712
4713         case CPU_UP_PREPARE:
4714         case CPU_UP_PREPARE_FROZEN:
4715                 perf_counter_init_cpu(cpu);
4716                 break;
4717
4718         case CPU_ONLINE:
4719         case CPU_ONLINE_FROZEN:
4720                 hw_perf_counter_setup_online(cpu);
4721                 break;
4722
4723         case CPU_DOWN_PREPARE:
4724         case CPU_DOWN_PREPARE_FROZEN:
4725                 perf_counter_exit_cpu(cpu);
4726                 break;
4727
4728         default:
4729                 break;
4730         }
4731
4732         return NOTIFY_OK;
4733 }
4734
4735 /*
4736  * This has to have a higher priority than migration_notifier in sched.c.
4737  */
4738 static struct notifier_block __cpuinitdata perf_cpu_nb = {
4739         .notifier_call          = perf_cpu_notify,
4740         .priority               = 20,
4741 };
4742
4743 void __init perf_counter_init(void)
4744 {
4745         perf_cpu_notify(&perf_cpu_nb, (unsigned long)CPU_UP_PREPARE,
4746                         (void *)(long)smp_processor_id());
4747         perf_cpu_notify(&perf_cpu_nb, (unsigned long)CPU_ONLINE,
4748                         (void *)(long)smp_processor_id());
4749         register_cpu_notifier(&perf_cpu_nb);
4750 }
4751
4752 static ssize_t perf_show_reserve_percpu(struct sysdev_class *class, char *buf)
4753 {
4754         return sprintf(buf, "%d\n", perf_reserved_percpu);
4755 }
4756
4757 static ssize_t
4758 perf_set_reserve_percpu(struct sysdev_class *class,
4759                         const char *buf,
4760                         size_t count)
4761 {
4762         struct perf_cpu_context *cpuctx;
4763         unsigned long val;
4764         int err, cpu, mpt;
4765
4766         err = strict_strtoul(buf, 10, &val);
4767         if (err)
4768                 return err;
4769         if (val > perf_max_counters)
4770                 return -EINVAL;
4771
4772         spin_lock(&perf_resource_lock);
4773         perf_reserved_percpu = val;
4774         for_each_online_cpu(cpu) {
4775                 cpuctx = &per_cpu(perf_cpu_context, cpu);
4776                 spin_lock_irq(&cpuctx->ctx.lock);
4777                 mpt = min(perf_max_counters - cpuctx->ctx.nr_counters,
4778                           perf_max_counters - perf_reserved_percpu);
4779                 cpuctx->max_pertask = mpt;
4780                 spin_unlock_irq(&cpuctx->ctx.lock);
4781         }
4782         spin_unlock(&perf_resource_lock);
4783
4784         return count;
4785 }
4786
4787 static ssize_t perf_show_overcommit(struct sysdev_class *class, char *buf)
4788 {
4789         return sprintf(buf, "%d\n", perf_overcommit);
4790 }
4791
4792 static ssize_t
4793 perf_set_overcommit(struct sysdev_class *class, const char *buf, size_t count)
4794 {
4795         unsigned long val;
4796         int err;
4797
4798         err = strict_strtoul(buf, 10, &val);
4799         if (err)
4800                 return err;
4801         if (val > 1)
4802                 return -EINVAL;
4803
4804         spin_lock(&perf_resource_lock);
4805         perf_overcommit = val;
4806         spin_unlock(&perf_resource_lock);
4807
4808         return count;
4809 }
4810
4811 static SYSDEV_CLASS_ATTR(
4812                                 reserve_percpu,
4813                                 0644,
4814                                 perf_show_reserve_percpu,
4815                                 perf_set_reserve_percpu
4816                         );
4817
4818 static SYSDEV_CLASS_ATTR(
4819                                 overcommit,
4820                                 0644,
4821                                 perf_show_overcommit,
4822                                 perf_set_overcommit
4823                         );
4824
4825 static struct attribute *perfclass_attrs[] = {
4826         &attr_reserve_percpu.attr,
4827         &attr_overcommit.attr,
4828         NULL
4829 };
4830
4831 static struct attribute_group perfclass_attr_group = {
4832         .attrs                  = perfclass_attrs,
4833         .name                   = "perf_counters",
4834 };
4835
4836 static int __init perf_counter_sysfs_init(void)
4837 {
4838         return sysfs_create_group(&cpu_sysdev_class.kset.kobj,
4839                                   &perfclass_attr_group);
4840 }
4841 device_initcall(perf_counter_sysfs_init);