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