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