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