perf,hw_breakpoint: Initialize hardware api earlier
[linux-flexiantxendom0-natty.git] / kernel / perf_event.c
1 /*
2  * Performance events 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/slab.h>
19 #include <linux/hash.h>
20 #include <linux/sysfs.h>
21 #include <linux/dcache.h>
22 #include <linux/percpu.h>
23 #include <linux/ptrace.h>
24 #include <linux/vmstat.h>
25 #include <linux/vmalloc.h>
26 #include <linux/hardirq.h>
27 #include <linux/rculist.h>
28 #include <linux/uaccess.h>
29 #include <linux/syscalls.h>
30 #include <linux/anon_inodes.h>
31 #include <linux/kernel_stat.h>
32 #include <linux/perf_event.h>
33 #include <linux/ftrace_event.h>
34 #include <linux/hw_breakpoint.h>
35
36 #include <asm/irq_regs.h>
37
38 atomic_t perf_task_events __read_mostly;
39 static atomic_t nr_mmap_events __read_mostly;
40 static atomic_t nr_comm_events __read_mostly;
41 static atomic_t nr_task_events __read_mostly;
42
43 static LIST_HEAD(pmus);
44 static DEFINE_MUTEX(pmus_lock);
45 static struct srcu_struct pmus_srcu;
46
47 /*
48  * perf event paranoia level:
49  *  -1 - not paranoid at all
50  *   0 - disallow raw tracepoint access for unpriv
51  *   1 - disallow cpu events for unpriv
52  *   2 - disallow kernel profiling for unpriv
53  */
54 int sysctl_perf_event_paranoid __read_mostly = 1;
55
56 int sysctl_perf_event_mlock __read_mostly = 512; /* 'free' kb per user */
57
58 /*
59  * max perf event sample rate
60  */
61 int sysctl_perf_event_sample_rate __read_mostly = 100000;
62
63 static atomic64_t perf_event_id;
64
65 void __weak perf_event_print_debug(void)        { }
66
67 extern __weak const char *perf_pmu_name(void)
68 {
69         return "pmu";
70 }
71
72 void perf_pmu_disable(struct pmu *pmu)
73 {
74         int *count = this_cpu_ptr(pmu->pmu_disable_count);
75         if (!(*count)++)
76                 pmu->pmu_disable(pmu);
77 }
78
79 void perf_pmu_enable(struct pmu *pmu)
80 {
81         int *count = this_cpu_ptr(pmu->pmu_disable_count);
82         if (!--(*count))
83                 pmu->pmu_enable(pmu);
84 }
85
86 static DEFINE_PER_CPU(struct list_head, rotation_list);
87
88 /*
89  * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
90  * because they're strictly cpu affine and rotate_start is called with IRQs
91  * disabled, while rotate_context is called from IRQ context.
92  */
93 static void perf_pmu_rotate_start(struct pmu *pmu)
94 {
95         struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
96         struct list_head *head = &__get_cpu_var(rotation_list);
97
98         WARN_ON(!irqs_disabled());
99
100         if (list_empty(&cpuctx->rotation_list))
101                 list_add(&cpuctx->rotation_list, head);
102 }
103
104 static void get_ctx(struct perf_event_context *ctx)
105 {
106         WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
107 }
108
109 static void free_ctx(struct rcu_head *head)
110 {
111         struct perf_event_context *ctx;
112
113         ctx = container_of(head, struct perf_event_context, rcu_head);
114         kfree(ctx);
115 }
116
117 static void put_ctx(struct perf_event_context *ctx)
118 {
119         if (atomic_dec_and_test(&ctx->refcount)) {
120                 if (ctx->parent_ctx)
121                         put_ctx(ctx->parent_ctx);
122                 if (ctx->task)
123                         put_task_struct(ctx->task);
124                 call_rcu(&ctx->rcu_head, free_ctx);
125         }
126 }
127
128 static void unclone_ctx(struct perf_event_context *ctx)
129 {
130         if (ctx->parent_ctx) {
131                 put_ctx(ctx->parent_ctx);
132                 ctx->parent_ctx = NULL;
133         }
134 }
135
136 /*
137  * If we inherit events we want to return the parent event id
138  * to userspace.
139  */
140 static u64 primary_event_id(struct perf_event *event)
141 {
142         u64 id = event->id;
143
144         if (event->parent)
145                 id = event->parent->id;
146
147         return id;
148 }
149
150 /*
151  * Get the perf_event_context for a task and lock it.
152  * This has to cope with with the fact that until it is locked,
153  * the context could get moved to another task.
154  */
155 static struct perf_event_context *
156 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
157 {
158         struct perf_event_context *ctx;
159
160         rcu_read_lock();
161 retry:
162         ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
163         if (ctx) {
164                 /*
165                  * If this context is a clone of another, it might
166                  * get swapped for another underneath us by
167                  * perf_event_task_sched_out, though the
168                  * rcu_read_lock() protects us from any context
169                  * getting freed.  Lock the context and check if it
170                  * got swapped before we could get the lock, and retry
171                  * if so.  If we locked the right context, then it
172                  * can't get swapped on us any more.
173                  */
174                 raw_spin_lock_irqsave(&ctx->lock, *flags);
175                 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
176                         raw_spin_unlock_irqrestore(&ctx->lock, *flags);
177                         goto retry;
178                 }
179
180                 if (!atomic_inc_not_zero(&ctx->refcount)) {
181                         raw_spin_unlock_irqrestore(&ctx->lock, *flags);
182                         ctx = NULL;
183                 }
184         }
185         rcu_read_unlock();
186         return ctx;
187 }
188
189 /*
190  * Get the context for a task and increment its pin_count so it
191  * can't get swapped to another task.  This also increments its
192  * reference count so that the context can't get freed.
193  */
194 static struct perf_event_context *
195 perf_pin_task_context(struct task_struct *task, int ctxn)
196 {
197         struct perf_event_context *ctx;
198         unsigned long flags;
199
200         ctx = perf_lock_task_context(task, ctxn, &flags);
201         if (ctx) {
202                 ++ctx->pin_count;
203                 raw_spin_unlock_irqrestore(&ctx->lock, flags);
204         }
205         return ctx;
206 }
207
208 static void perf_unpin_context(struct perf_event_context *ctx)
209 {
210         unsigned long flags;
211
212         raw_spin_lock_irqsave(&ctx->lock, flags);
213         --ctx->pin_count;
214         raw_spin_unlock_irqrestore(&ctx->lock, flags);
215         put_ctx(ctx);
216 }
217
218 static inline u64 perf_clock(void)
219 {
220         return local_clock();
221 }
222
223 /*
224  * Update the record of the current time in a context.
225  */
226 static void update_context_time(struct perf_event_context *ctx)
227 {
228         u64 now = perf_clock();
229
230         ctx->time += now - ctx->timestamp;
231         ctx->timestamp = now;
232 }
233
234 /*
235  * Update the total_time_enabled and total_time_running fields for a event.
236  */
237 static void update_event_times(struct perf_event *event)
238 {
239         struct perf_event_context *ctx = event->ctx;
240         u64 run_end;
241
242         if (event->state < PERF_EVENT_STATE_INACTIVE ||
243             event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
244                 return;
245
246         if (ctx->is_active)
247                 run_end = ctx->time;
248         else
249                 run_end = event->tstamp_stopped;
250
251         event->total_time_enabled = run_end - event->tstamp_enabled;
252
253         if (event->state == PERF_EVENT_STATE_INACTIVE)
254                 run_end = event->tstamp_stopped;
255         else
256                 run_end = ctx->time;
257
258         event->total_time_running = run_end - event->tstamp_running;
259 }
260
261 /*
262  * Update total_time_enabled and total_time_running for all events in a group.
263  */
264 static void update_group_times(struct perf_event *leader)
265 {
266         struct perf_event *event;
267
268         update_event_times(leader);
269         list_for_each_entry(event, &leader->sibling_list, group_entry)
270                 update_event_times(event);
271 }
272
273 static struct list_head *
274 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
275 {
276         if (event->attr.pinned)
277                 return &ctx->pinned_groups;
278         else
279                 return &ctx->flexible_groups;
280 }
281
282 /*
283  * Add a event from the lists for its context.
284  * Must be called with ctx->mutex and ctx->lock held.
285  */
286 static void
287 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
288 {
289         WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
290         event->attach_state |= PERF_ATTACH_CONTEXT;
291
292         /*
293          * If we're a stand alone event or group leader, we go to the context
294          * list, group events are kept attached to the group so that
295          * perf_group_detach can, at all times, locate all siblings.
296          */
297         if (event->group_leader == event) {
298                 struct list_head *list;
299
300                 if (is_software_event(event))
301                         event->group_flags |= PERF_GROUP_SOFTWARE;
302
303                 list = ctx_group_list(event, ctx);
304                 list_add_tail(&event->group_entry, list);
305         }
306
307         list_add_rcu(&event->event_entry, &ctx->event_list);
308         if (!ctx->nr_events)
309                 perf_pmu_rotate_start(ctx->pmu);
310         ctx->nr_events++;
311         if (event->attr.inherit_stat)
312                 ctx->nr_stat++;
313 }
314
315 static void perf_group_attach(struct perf_event *event)
316 {
317         struct perf_event *group_leader = event->group_leader;
318
319         /*
320          * We can have double attach due to group movement in perf_event_open.
321          */
322         if (event->attach_state & PERF_ATTACH_GROUP)
323                 return;
324
325         event->attach_state |= PERF_ATTACH_GROUP;
326
327         if (group_leader == event)
328                 return;
329
330         if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
331                         !is_software_event(event))
332                 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
333
334         list_add_tail(&event->group_entry, &group_leader->sibling_list);
335         group_leader->nr_siblings++;
336 }
337
338 /*
339  * Remove a event from the lists for its context.
340  * Must be called with ctx->mutex and ctx->lock held.
341  */
342 static void
343 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
344 {
345         /*
346          * We can have double detach due to exit/hot-unplug + close.
347          */
348         if (!(event->attach_state & PERF_ATTACH_CONTEXT))
349                 return;
350
351         event->attach_state &= ~PERF_ATTACH_CONTEXT;
352
353         ctx->nr_events--;
354         if (event->attr.inherit_stat)
355                 ctx->nr_stat--;
356
357         list_del_rcu(&event->event_entry);
358
359         if (event->group_leader == event)
360                 list_del_init(&event->group_entry);
361
362         update_group_times(event);
363
364         /*
365          * If event was in error state, then keep it
366          * that way, otherwise bogus counts will be
367          * returned on read(). The only way to get out
368          * of error state is by explicit re-enabling
369          * of the event
370          */
371         if (event->state > PERF_EVENT_STATE_OFF)
372                 event->state = PERF_EVENT_STATE_OFF;
373 }
374
375 static void perf_group_detach(struct perf_event *event)
376 {
377         struct perf_event *sibling, *tmp;
378         struct list_head *list = NULL;
379
380         /*
381          * We can have double detach due to exit/hot-unplug + close.
382          */
383         if (!(event->attach_state & PERF_ATTACH_GROUP))
384                 return;
385
386         event->attach_state &= ~PERF_ATTACH_GROUP;
387
388         /*
389          * If this is a sibling, remove it from its group.
390          */
391         if (event->group_leader != event) {
392                 list_del_init(&event->group_entry);
393                 event->group_leader->nr_siblings--;
394                 return;
395         }
396
397         if (!list_empty(&event->group_entry))
398                 list = &event->group_entry;
399
400         /*
401          * If this was a group event with sibling events then
402          * upgrade the siblings to singleton events by adding them
403          * to whatever list we are on.
404          */
405         list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
406                 if (list)
407                         list_move_tail(&sibling->group_entry, list);
408                 sibling->group_leader = sibling;
409
410                 /* Inherit group flags from the previous leader */
411                 sibling->group_flags = event->group_flags;
412         }
413 }
414
415 static inline int
416 event_filter_match(struct perf_event *event)
417 {
418         return event->cpu == -1 || event->cpu == smp_processor_id();
419 }
420
421 static void
422 event_sched_out(struct perf_event *event,
423                   struct perf_cpu_context *cpuctx,
424                   struct perf_event_context *ctx)
425 {
426         u64 delta;
427         /*
428          * An event which could not be activated because of
429          * filter mismatch still needs to have its timings
430          * maintained, otherwise bogus information is return
431          * via read() for time_enabled, time_running:
432          */
433         if (event->state == PERF_EVENT_STATE_INACTIVE
434             && !event_filter_match(event)) {
435                 delta = ctx->time - event->tstamp_stopped;
436                 event->tstamp_running += delta;
437                 event->tstamp_stopped = ctx->time;
438         }
439
440         if (event->state != PERF_EVENT_STATE_ACTIVE)
441                 return;
442
443         event->state = PERF_EVENT_STATE_INACTIVE;
444         if (event->pending_disable) {
445                 event->pending_disable = 0;
446                 event->state = PERF_EVENT_STATE_OFF;
447         }
448         event->tstamp_stopped = ctx->time;
449         event->pmu->del(event, 0);
450         event->oncpu = -1;
451
452         if (!is_software_event(event))
453                 cpuctx->active_oncpu--;
454         ctx->nr_active--;
455         if (event->attr.exclusive || !cpuctx->active_oncpu)
456                 cpuctx->exclusive = 0;
457 }
458
459 static void
460 group_sched_out(struct perf_event *group_event,
461                 struct perf_cpu_context *cpuctx,
462                 struct perf_event_context *ctx)
463 {
464         struct perf_event *event;
465         int state = group_event->state;
466
467         event_sched_out(group_event, cpuctx, ctx);
468
469         /*
470          * Schedule out siblings (if any):
471          */
472         list_for_each_entry(event, &group_event->sibling_list, group_entry)
473                 event_sched_out(event, cpuctx, ctx);
474
475         if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
476                 cpuctx->exclusive = 0;
477 }
478
479 static inline struct perf_cpu_context *
480 __get_cpu_context(struct perf_event_context *ctx)
481 {
482         return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
483 }
484
485 /*
486  * Cross CPU call to remove a performance event
487  *
488  * We disable the event on the hardware level first. After that we
489  * remove it from the context list.
490  */
491 static void __perf_event_remove_from_context(void *info)
492 {
493         struct perf_event *event = info;
494         struct perf_event_context *ctx = event->ctx;
495         struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
496
497         /*
498          * If this is a task context, we need to check whether it is
499          * the current task context of this cpu. If not it has been
500          * scheduled out before the smp call arrived.
501          */
502         if (ctx->task && cpuctx->task_ctx != ctx)
503                 return;
504
505         raw_spin_lock(&ctx->lock);
506
507         event_sched_out(event, cpuctx, ctx);
508
509         list_del_event(event, ctx);
510
511         raw_spin_unlock(&ctx->lock);
512 }
513
514
515 /*
516  * Remove the event from a task's (or a CPU's) list of events.
517  *
518  * Must be called with ctx->mutex held.
519  *
520  * CPU events are removed with a smp call. For task events we only
521  * call when the task is on a CPU.
522  *
523  * If event->ctx is a cloned context, callers must make sure that
524  * every task struct that event->ctx->task could possibly point to
525  * remains valid.  This is OK when called from perf_release since
526  * that only calls us on the top-level context, which can't be a clone.
527  * When called from perf_event_exit_task, it's OK because the
528  * context has been detached from its task.
529  */
530 static void perf_event_remove_from_context(struct perf_event *event)
531 {
532         struct perf_event_context *ctx = event->ctx;
533         struct task_struct *task = ctx->task;
534
535         if (!task) {
536                 /*
537                  * Per cpu events are removed via an smp call and
538                  * the removal is always successful.
539                  */
540                 smp_call_function_single(event->cpu,
541                                          __perf_event_remove_from_context,
542                                          event, 1);
543                 return;
544         }
545
546 retry:
547         task_oncpu_function_call(task, __perf_event_remove_from_context,
548                                  event);
549
550         raw_spin_lock_irq(&ctx->lock);
551         /*
552          * If the context is active we need to retry the smp call.
553          */
554         if (ctx->nr_active && !list_empty(&event->group_entry)) {
555                 raw_spin_unlock_irq(&ctx->lock);
556                 goto retry;
557         }
558
559         /*
560          * The lock prevents that this context is scheduled in so we
561          * can remove the event safely, if the call above did not
562          * succeed.
563          */
564         if (!list_empty(&event->group_entry))
565                 list_del_event(event, ctx);
566         raw_spin_unlock_irq(&ctx->lock);
567 }
568
569 /*
570  * Cross CPU call to disable a performance event
571  */
572 static void __perf_event_disable(void *info)
573 {
574         struct perf_event *event = info;
575         struct perf_event_context *ctx = event->ctx;
576         struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
577
578         /*
579          * If this is a per-task event, need to check whether this
580          * event's task is the current task on this cpu.
581          */
582         if (ctx->task && cpuctx->task_ctx != ctx)
583                 return;
584
585         raw_spin_lock(&ctx->lock);
586
587         /*
588          * If the event is on, turn it off.
589          * If it is in error state, leave it in error state.
590          */
591         if (event->state >= PERF_EVENT_STATE_INACTIVE) {
592                 update_context_time(ctx);
593                 update_group_times(event);
594                 if (event == event->group_leader)
595                         group_sched_out(event, cpuctx, ctx);
596                 else
597                         event_sched_out(event, cpuctx, ctx);
598                 event->state = PERF_EVENT_STATE_OFF;
599         }
600
601         raw_spin_unlock(&ctx->lock);
602 }
603
604 /*
605  * Disable a event.
606  *
607  * If event->ctx is a cloned context, callers must make sure that
608  * every task struct that event->ctx->task could possibly point to
609  * remains valid.  This condition is satisifed when called through
610  * perf_event_for_each_child or perf_event_for_each because they
611  * hold the top-level event's child_mutex, so any descendant that
612  * goes to exit will block in sync_child_event.
613  * When called from perf_pending_event it's OK because event->ctx
614  * is the current context on this CPU and preemption is disabled,
615  * hence we can't get into perf_event_task_sched_out for this context.
616  */
617 void perf_event_disable(struct perf_event *event)
618 {
619         struct perf_event_context *ctx = event->ctx;
620         struct task_struct *task = ctx->task;
621
622         if (!task) {
623                 /*
624                  * Disable the event on the cpu that it's on
625                  */
626                 smp_call_function_single(event->cpu, __perf_event_disable,
627                                          event, 1);
628                 return;
629         }
630
631 retry:
632         task_oncpu_function_call(task, __perf_event_disable, event);
633
634         raw_spin_lock_irq(&ctx->lock);
635         /*
636          * If the event is still active, we need to retry the cross-call.
637          */
638         if (event->state == PERF_EVENT_STATE_ACTIVE) {
639                 raw_spin_unlock_irq(&ctx->lock);
640                 goto retry;
641         }
642
643         /*
644          * Since we have the lock this context can't be scheduled
645          * in, so we can change the state safely.
646          */
647         if (event->state == PERF_EVENT_STATE_INACTIVE) {
648                 update_group_times(event);
649                 event->state = PERF_EVENT_STATE_OFF;
650         }
651
652         raw_spin_unlock_irq(&ctx->lock);
653 }
654
655 static int
656 event_sched_in(struct perf_event *event,
657                  struct perf_cpu_context *cpuctx,
658                  struct perf_event_context *ctx)
659 {
660         if (event->state <= PERF_EVENT_STATE_OFF)
661                 return 0;
662
663         event->state = PERF_EVENT_STATE_ACTIVE;
664         event->oncpu = smp_processor_id();
665         /*
666          * The new state must be visible before we turn it on in the hardware:
667          */
668         smp_wmb();
669
670         if (event->pmu->add(event, PERF_EF_START)) {
671                 event->state = PERF_EVENT_STATE_INACTIVE;
672                 event->oncpu = -1;
673                 return -EAGAIN;
674         }
675
676         event->tstamp_running += ctx->time - event->tstamp_stopped;
677
678         if (!is_software_event(event))
679                 cpuctx->active_oncpu++;
680         ctx->nr_active++;
681
682         if (event->attr.exclusive)
683                 cpuctx->exclusive = 1;
684
685         return 0;
686 }
687
688 static int
689 group_sched_in(struct perf_event *group_event,
690                struct perf_cpu_context *cpuctx,
691                struct perf_event_context *ctx)
692 {
693         struct perf_event *event, *partial_group = NULL;
694         struct pmu *pmu = group_event->pmu;
695         u64 now = ctx->time;
696         bool simulate = false;
697
698         if (group_event->state == PERF_EVENT_STATE_OFF)
699                 return 0;
700
701         pmu->start_txn(pmu);
702
703         if (event_sched_in(group_event, cpuctx, ctx)) {
704                 pmu->cancel_txn(pmu);
705                 return -EAGAIN;
706         }
707
708         /*
709          * Schedule in siblings as one group (if any):
710          */
711         list_for_each_entry(event, &group_event->sibling_list, group_entry) {
712                 if (event_sched_in(event, cpuctx, ctx)) {
713                         partial_group = event;
714                         goto group_error;
715                 }
716         }
717
718         if (!pmu->commit_txn(pmu))
719                 return 0;
720
721 group_error:
722         /*
723          * Groups can be scheduled in as one unit only, so undo any
724          * partial group before returning:
725          * The events up to the failed event are scheduled out normally,
726          * tstamp_stopped will be updated.
727          *
728          * The failed events and the remaining siblings need to have
729          * their timings updated as if they had gone thru event_sched_in()
730          * and event_sched_out(). This is required to get consistent timings
731          * across the group. This also takes care of the case where the group
732          * could never be scheduled by ensuring tstamp_stopped is set to mark
733          * the time the event was actually stopped, such that time delta
734          * calculation in update_event_times() is correct.
735          */
736         list_for_each_entry(event, &group_event->sibling_list, group_entry) {
737                 if (event == partial_group)
738                         simulate = true;
739
740                 if (simulate) {
741                         event->tstamp_running += now - event->tstamp_stopped;
742                         event->tstamp_stopped = now;
743                 } else {
744                         event_sched_out(event, cpuctx, ctx);
745                 }
746         }
747         event_sched_out(group_event, cpuctx, ctx);
748
749         pmu->cancel_txn(pmu);
750
751         return -EAGAIN;
752 }
753
754 /*
755  * Work out whether we can put this event group on the CPU now.
756  */
757 static int group_can_go_on(struct perf_event *event,
758                            struct perf_cpu_context *cpuctx,
759                            int can_add_hw)
760 {
761         /*
762          * Groups consisting entirely of software events can always go on.
763          */
764         if (event->group_flags & PERF_GROUP_SOFTWARE)
765                 return 1;
766         /*
767          * If an exclusive group is already on, no other hardware
768          * events can go on.
769          */
770         if (cpuctx->exclusive)
771                 return 0;
772         /*
773          * If this group is exclusive and there are already
774          * events on the CPU, it can't go on.
775          */
776         if (event->attr.exclusive && cpuctx->active_oncpu)
777                 return 0;
778         /*
779          * Otherwise, try to add it if all previous groups were able
780          * to go on.
781          */
782         return can_add_hw;
783 }
784
785 static void add_event_to_ctx(struct perf_event *event,
786                                struct perf_event_context *ctx)
787 {
788         list_add_event(event, ctx);
789         perf_group_attach(event);
790         event->tstamp_enabled = ctx->time;
791         event->tstamp_running = ctx->time;
792         event->tstamp_stopped = ctx->time;
793 }
794
795 /*
796  * Cross CPU call to install and enable a performance event
797  *
798  * Must be called with ctx->mutex held
799  */
800 static void __perf_install_in_context(void *info)
801 {
802         struct perf_event *event = info;
803         struct perf_event_context *ctx = event->ctx;
804         struct perf_event *leader = event->group_leader;
805         struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
806         int err;
807
808         /*
809          * If this is a task context, we need to check whether it is
810          * the current task context of this cpu. If not it has been
811          * scheduled out before the smp call arrived.
812          * Or possibly this is the right context but it isn't
813          * on this cpu because it had no events.
814          */
815         if (ctx->task && cpuctx->task_ctx != ctx) {
816                 if (cpuctx->task_ctx || ctx->task != current)
817                         return;
818                 cpuctx->task_ctx = ctx;
819         }
820
821         raw_spin_lock(&ctx->lock);
822         ctx->is_active = 1;
823         update_context_time(ctx);
824
825         add_event_to_ctx(event, ctx);
826
827         if (event->cpu != -1 && event->cpu != smp_processor_id())
828                 goto unlock;
829
830         /*
831          * Don't put the event on if it is disabled or if
832          * it is in a group and the group isn't on.
833          */
834         if (event->state != PERF_EVENT_STATE_INACTIVE ||
835             (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE))
836                 goto unlock;
837
838         /*
839          * An exclusive event can't go on if there are already active
840          * hardware events, and no hardware event can go on if there
841          * is already an exclusive event on.
842          */
843         if (!group_can_go_on(event, cpuctx, 1))
844                 err = -EEXIST;
845         else
846                 err = event_sched_in(event, cpuctx, ctx);
847
848         if (err) {
849                 /*
850                  * This event couldn't go on.  If it is in a group
851                  * then we have to pull the whole group off.
852                  * If the event group is pinned then put it in error state.
853                  */
854                 if (leader != event)
855                         group_sched_out(leader, cpuctx, ctx);
856                 if (leader->attr.pinned) {
857                         update_group_times(leader);
858                         leader->state = PERF_EVENT_STATE_ERROR;
859                 }
860         }
861
862 unlock:
863         raw_spin_unlock(&ctx->lock);
864 }
865
866 /*
867  * Attach a performance event to a context
868  *
869  * First we add the event to the list with the hardware enable bit
870  * in event->hw_config cleared.
871  *
872  * If the event is attached to a task which is on a CPU we use a smp
873  * call to enable it in the task context. The task might have been
874  * scheduled away, but we check this in the smp call again.
875  *
876  * Must be called with ctx->mutex held.
877  */
878 static void
879 perf_install_in_context(struct perf_event_context *ctx,
880                         struct perf_event *event,
881                         int cpu)
882 {
883         struct task_struct *task = ctx->task;
884
885         event->ctx = ctx;
886
887         if (!task) {
888                 /*
889                  * Per cpu events are installed via an smp call and
890                  * the install is always successful.
891                  */
892                 smp_call_function_single(cpu, __perf_install_in_context,
893                                          event, 1);
894                 return;
895         }
896
897 retry:
898         task_oncpu_function_call(task, __perf_install_in_context,
899                                  event);
900
901         raw_spin_lock_irq(&ctx->lock);
902         /*
903          * we need to retry the smp call.
904          */
905         if (ctx->is_active && list_empty(&event->group_entry)) {
906                 raw_spin_unlock_irq(&ctx->lock);
907                 goto retry;
908         }
909
910         /*
911          * The lock prevents that this context is scheduled in so we
912          * can add the event safely, if it the call above did not
913          * succeed.
914          */
915         if (list_empty(&event->group_entry))
916                 add_event_to_ctx(event, ctx);
917         raw_spin_unlock_irq(&ctx->lock);
918 }
919
920 /*
921  * Put a event into inactive state and update time fields.
922  * Enabling the leader of a group effectively enables all
923  * the group members that aren't explicitly disabled, so we
924  * have to update their ->tstamp_enabled also.
925  * Note: this works for group members as well as group leaders
926  * since the non-leader members' sibling_lists will be empty.
927  */
928 static void __perf_event_mark_enabled(struct perf_event *event,
929                                         struct perf_event_context *ctx)
930 {
931         struct perf_event *sub;
932
933         event->state = PERF_EVENT_STATE_INACTIVE;
934         event->tstamp_enabled = ctx->time - event->total_time_enabled;
935         list_for_each_entry(sub, &event->sibling_list, group_entry) {
936                 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
937                         sub->tstamp_enabled =
938                                 ctx->time - sub->total_time_enabled;
939                 }
940         }
941 }
942
943 /*
944  * Cross CPU call to enable a performance event
945  */
946 static void __perf_event_enable(void *info)
947 {
948         struct perf_event *event = info;
949         struct perf_event_context *ctx = event->ctx;
950         struct perf_event *leader = event->group_leader;
951         struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
952         int err;
953
954         /*
955          * If this is a per-task event, need to check whether this
956          * event's task is the current task on this cpu.
957          */
958         if (ctx->task && cpuctx->task_ctx != ctx) {
959                 if (cpuctx->task_ctx || ctx->task != current)
960                         return;
961                 cpuctx->task_ctx = ctx;
962         }
963
964         raw_spin_lock(&ctx->lock);
965         ctx->is_active = 1;
966         update_context_time(ctx);
967
968         if (event->state >= PERF_EVENT_STATE_INACTIVE)
969                 goto unlock;
970         __perf_event_mark_enabled(event, ctx);
971
972         if (event->cpu != -1 && event->cpu != smp_processor_id())
973                 goto unlock;
974
975         /*
976          * If the event is in a group and isn't the group leader,
977          * then don't put it on unless the group is on.
978          */
979         if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
980                 goto unlock;
981
982         if (!group_can_go_on(event, cpuctx, 1)) {
983                 err = -EEXIST;
984         } else {
985                 if (event == leader)
986                         err = group_sched_in(event, cpuctx, ctx);
987                 else
988                         err = event_sched_in(event, cpuctx, ctx);
989         }
990
991         if (err) {
992                 /*
993                  * If this event can't go on and it's part of a
994                  * group, then the whole group has to come off.
995                  */
996                 if (leader != event)
997                         group_sched_out(leader, cpuctx, ctx);
998                 if (leader->attr.pinned) {
999                         update_group_times(leader);
1000                         leader->state = PERF_EVENT_STATE_ERROR;
1001                 }
1002         }
1003
1004 unlock:
1005         raw_spin_unlock(&ctx->lock);
1006 }
1007
1008 /*
1009  * Enable a event.
1010  *
1011  * If event->ctx is a cloned context, callers must make sure that
1012  * every task struct that event->ctx->task could possibly point to
1013  * remains valid.  This condition is satisfied when called through
1014  * perf_event_for_each_child or perf_event_for_each as described
1015  * for perf_event_disable.
1016  */
1017 void perf_event_enable(struct perf_event *event)
1018 {
1019         struct perf_event_context *ctx = event->ctx;
1020         struct task_struct *task = ctx->task;
1021
1022         if (!task) {
1023                 /*
1024                  * Enable the event on the cpu that it's on
1025                  */
1026                 smp_call_function_single(event->cpu, __perf_event_enable,
1027                                          event, 1);
1028                 return;
1029         }
1030
1031         raw_spin_lock_irq(&ctx->lock);
1032         if (event->state >= PERF_EVENT_STATE_INACTIVE)
1033                 goto out;
1034
1035         /*
1036          * If the event is in error state, clear that first.
1037          * That way, if we see the event in error state below, we
1038          * know that it has gone back into error state, as distinct
1039          * from the task having been scheduled away before the
1040          * cross-call arrived.
1041          */
1042         if (event->state == PERF_EVENT_STATE_ERROR)
1043                 event->state = PERF_EVENT_STATE_OFF;
1044
1045 retry:
1046         raw_spin_unlock_irq(&ctx->lock);
1047         task_oncpu_function_call(task, __perf_event_enable, event);
1048
1049         raw_spin_lock_irq(&ctx->lock);
1050
1051         /*
1052          * If the context is active and the event is still off,
1053          * we need to retry the cross-call.
1054          */
1055         if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF)
1056                 goto retry;
1057
1058         /*
1059          * Since we have the lock this context can't be scheduled
1060          * in, so we can change the state safely.
1061          */
1062         if (event->state == PERF_EVENT_STATE_OFF)
1063                 __perf_event_mark_enabled(event, ctx);
1064
1065 out:
1066         raw_spin_unlock_irq(&ctx->lock);
1067 }
1068
1069 static int perf_event_refresh(struct perf_event *event, int refresh)
1070 {
1071         /*
1072          * not supported on inherited events
1073          */
1074         if (event->attr.inherit)
1075                 return -EINVAL;
1076
1077         atomic_add(refresh, &event->event_limit);
1078         perf_event_enable(event);
1079
1080         return 0;
1081 }
1082
1083 enum event_type_t {
1084         EVENT_FLEXIBLE = 0x1,
1085         EVENT_PINNED = 0x2,
1086         EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
1087 };
1088
1089 static void ctx_sched_out(struct perf_event_context *ctx,
1090                           struct perf_cpu_context *cpuctx,
1091                           enum event_type_t event_type)
1092 {
1093         struct perf_event *event;
1094
1095         raw_spin_lock(&ctx->lock);
1096         perf_pmu_disable(ctx->pmu);
1097         ctx->is_active = 0;
1098         if (likely(!ctx->nr_events))
1099                 goto out;
1100         update_context_time(ctx);
1101
1102         if (!ctx->nr_active)
1103                 goto out;
1104
1105         if (event_type & EVENT_PINNED) {
1106                 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
1107                         group_sched_out(event, cpuctx, ctx);
1108         }
1109
1110         if (event_type & EVENT_FLEXIBLE) {
1111                 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
1112                         group_sched_out(event, cpuctx, ctx);
1113         }
1114 out:
1115         perf_pmu_enable(ctx->pmu);
1116         raw_spin_unlock(&ctx->lock);
1117 }
1118
1119 /*
1120  * Test whether two contexts are equivalent, i.e. whether they
1121  * have both been cloned from the same version of the same context
1122  * and they both have the same number of enabled events.
1123  * If the number of enabled events is the same, then the set
1124  * of enabled events should be the same, because these are both
1125  * inherited contexts, therefore we can't access individual events
1126  * in them directly with an fd; we can only enable/disable all
1127  * events via prctl, or enable/disable all events in a family
1128  * via ioctl, which will have the same effect on both contexts.
1129  */
1130 static int context_equiv(struct perf_event_context *ctx1,
1131                          struct perf_event_context *ctx2)
1132 {
1133         return ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx
1134                 && ctx1->parent_gen == ctx2->parent_gen
1135                 && !ctx1->pin_count && !ctx2->pin_count;
1136 }
1137
1138 static void __perf_event_sync_stat(struct perf_event *event,
1139                                      struct perf_event *next_event)
1140 {
1141         u64 value;
1142
1143         if (!event->attr.inherit_stat)
1144                 return;
1145
1146         /*
1147          * Update the event value, we cannot use perf_event_read()
1148          * because we're in the middle of a context switch and have IRQs
1149          * disabled, which upsets smp_call_function_single(), however
1150          * we know the event must be on the current CPU, therefore we
1151          * don't need to use it.
1152          */
1153         switch (event->state) {
1154         case PERF_EVENT_STATE_ACTIVE:
1155                 event->pmu->read(event);
1156                 /* fall-through */
1157
1158         case PERF_EVENT_STATE_INACTIVE:
1159                 update_event_times(event);
1160                 break;
1161
1162         default:
1163                 break;
1164         }
1165
1166         /*
1167          * In order to keep per-task stats reliable we need to flip the event
1168          * values when we flip the contexts.
1169          */
1170         value = local64_read(&next_event->count);
1171         value = local64_xchg(&event->count, value);
1172         local64_set(&next_event->count, value);
1173
1174         swap(event->total_time_enabled, next_event->total_time_enabled);
1175         swap(event->total_time_running, next_event->total_time_running);
1176
1177         /*
1178          * Since we swizzled the values, update the user visible data too.
1179          */
1180         perf_event_update_userpage(event);
1181         perf_event_update_userpage(next_event);
1182 }
1183
1184 #define list_next_entry(pos, member) \
1185         list_entry(pos->member.next, typeof(*pos), member)
1186
1187 static void perf_event_sync_stat(struct perf_event_context *ctx,
1188                                    struct perf_event_context *next_ctx)
1189 {
1190         struct perf_event *event, *next_event;
1191
1192         if (!ctx->nr_stat)
1193                 return;
1194
1195         update_context_time(ctx);
1196
1197         event = list_first_entry(&ctx->event_list,
1198                                    struct perf_event, event_entry);
1199
1200         next_event = list_first_entry(&next_ctx->event_list,
1201                                         struct perf_event, event_entry);
1202
1203         while (&event->event_entry != &ctx->event_list &&
1204                &next_event->event_entry != &next_ctx->event_list) {
1205
1206                 __perf_event_sync_stat(event, next_event);
1207
1208                 event = list_next_entry(event, event_entry);
1209                 next_event = list_next_entry(next_event, event_entry);
1210         }
1211 }
1212
1213 void perf_event_context_sched_out(struct task_struct *task, int ctxn,
1214                                   struct task_struct *next)
1215 {
1216         struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
1217         struct perf_event_context *next_ctx;
1218         struct perf_event_context *parent;
1219         struct perf_cpu_context *cpuctx;
1220         int do_switch = 1;
1221
1222         if (likely(!ctx))
1223                 return;
1224
1225         cpuctx = __get_cpu_context(ctx);
1226         if (!cpuctx->task_ctx)
1227                 return;
1228
1229         rcu_read_lock();
1230         parent = rcu_dereference(ctx->parent_ctx);
1231         next_ctx = next->perf_event_ctxp[ctxn];
1232         if (parent && next_ctx &&
1233             rcu_dereference(next_ctx->parent_ctx) == parent) {
1234                 /*
1235                  * Looks like the two contexts are clones, so we might be
1236                  * able to optimize the context switch.  We lock both
1237                  * contexts and check that they are clones under the
1238                  * lock (including re-checking that neither has been
1239                  * uncloned in the meantime).  It doesn't matter which
1240                  * order we take the locks because no other cpu could
1241                  * be trying to lock both of these tasks.
1242                  */
1243                 raw_spin_lock(&ctx->lock);
1244                 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
1245                 if (context_equiv(ctx, next_ctx)) {
1246                         /*
1247                          * XXX do we need a memory barrier of sorts
1248                          * wrt to rcu_dereference() of perf_event_ctxp
1249                          */
1250                         task->perf_event_ctxp[ctxn] = next_ctx;
1251                         next->perf_event_ctxp[ctxn] = ctx;
1252                         ctx->task = next;
1253                         next_ctx->task = task;
1254                         do_switch = 0;
1255
1256                         perf_event_sync_stat(ctx, next_ctx);
1257                 }
1258                 raw_spin_unlock(&next_ctx->lock);
1259                 raw_spin_unlock(&ctx->lock);
1260         }
1261         rcu_read_unlock();
1262
1263         if (do_switch) {
1264                 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
1265                 cpuctx->task_ctx = NULL;
1266         }
1267 }
1268
1269 #define for_each_task_context_nr(ctxn)                                  \
1270         for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
1271
1272 /*
1273  * Called from scheduler to remove the events of the current task,
1274  * with interrupts disabled.
1275  *
1276  * We stop each event and update the event value in event->count.
1277  *
1278  * This does not protect us against NMI, but disable()
1279  * sets the disabled bit in the control field of event _before_
1280  * accessing the event control register. If a NMI hits, then it will
1281  * not restart the event.
1282  */
1283 void __perf_event_task_sched_out(struct task_struct *task,
1284                                  struct task_struct *next)
1285 {
1286         int ctxn;
1287
1288         perf_sw_event(PERF_COUNT_SW_CONTEXT_SWITCHES, 1, 1, NULL, 0);
1289
1290         for_each_task_context_nr(ctxn)
1291                 perf_event_context_sched_out(task, ctxn, next);
1292 }
1293
1294 static void task_ctx_sched_out(struct perf_event_context *ctx,
1295                                enum event_type_t event_type)
1296 {
1297         struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1298
1299         if (!cpuctx->task_ctx)
1300                 return;
1301
1302         if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
1303                 return;
1304
1305         ctx_sched_out(ctx, cpuctx, event_type);
1306         cpuctx->task_ctx = NULL;
1307 }
1308
1309 /*
1310  * Called with IRQs disabled
1311  */
1312 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
1313                               enum event_type_t event_type)
1314 {
1315         ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
1316 }
1317
1318 static void
1319 ctx_pinned_sched_in(struct perf_event_context *ctx,
1320                     struct perf_cpu_context *cpuctx)
1321 {
1322         struct perf_event *event;
1323
1324         list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
1325                 if (event->state <= PERF_EVENT_STATE_OFF)
1326                         continue;
1327                 if (event->cpu != -1 && event->cpu != smp_processor_id())
1328                         continue;
1329
1330                 if (group_can_go_on(event, cpuctx, 1))
1331                         group_sched_in(event, cpuctx, ctx);
1332
1333                 /*
1334                  * If this pinned group hasn't been scheduled,
1335                  * put it in error state.
1336                  */
1337                 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1338                         update_group_times(event);
1339                         event->state = PERF_EVENT_STATE_ERROR;
1340                 }
1341         }
1342 }
1343
1344 static void
1345 ctx_flexible_sched_in(struct perf_event_context *ctx,
1346                       struct perf_cpu_context *cpuctx)
1347 {
1348         struct perf_event *event;
1349         int can_add_hw = 1;
1350
1351         list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
1352                 /* Ignore events in OFF or ERROR state */
1353                 if (event->state <= PERF_EVENT_STATE_OFF)
1354                         continue;
1355                 /*
1356                  * Listen to the 'cpu' scheduling filter constraint
1357                  * of events:
1358                  */
1359                 if (event->cpu != -1 && event->cpu != smp_processor_id())
1360                         continue;
1361
1362                 if (group_can_go_on(event, cpuctx, can_add_hw)) {
1363                         if (group_sched_in(event, cpuctx, ctx))
1364                                 can_add_hw = 0;
1365                 }
1366         }
1367 }
1368
1369 static void
1370 ctx_sched_in(struct perf_event_context *ctx,
1371              struct perf_cpu_context *cpuctx,
1372              enum event_type_t event_type)
1373 {
1374         raw_spin_lock(&ctx->lock);
1375         ctx->is_active = 1;
1376         if (likely(!ctx->nr_events))
1377                 goto out;
1378
1379         ctx->timestamp = perf_clock();
1380
1381         /*
1382          * First go through the list and put on any pinned groups
1383          * in order to give them the best chance of going on.
1384          */
1385         if (event_type & EVENT_PINNED)
1386                 ctx_pinned_sched_in(ctx, cpuctx);
1387
1388         /* Then walk through the lower prio flexible groups */
1389         if (event_type & EVENT_FLEXIBLE)
1390                 ctx_flexible_sched_in(ctx, cpuctx);
1391
1392 out:
1393         raw_spin_unlock(&ctx->lock);
1394 }
1395
1396 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
1397                              enum event_type_t event_type)
1398 {
1399         struct perf_event_context *ctx = &cpuctx->ctx;
1400
1401         ctx_sched_in(ctx, cpuctx, event_type);
1402 }
1403
1404 static void task_ctx_sched_in(struct perf_event_context *ctx,
1405                               enum event_type_t event_type)
1406 {
1407         struct perf_cpu_context *cpuctx;
1408
1409         cpuctx = __get_cpu_context(ctx);
1410         if (cpuctx->task_ctx == ctx)
1411                 return;
1412
1413         ctx_sched_in(ctx, cpuctx, event_type);
1414         cpuctx->task_ctx = ctx;
1415 }
1416
1417 void perf_event_context_sched_in(struct perf_event_context *ctx)
1418 {
1419         struct perf_cpu_context *cpuctx;
1420
1421         cpuctx = __get_cpu_context(ctx);
1422         if (cpuctx->task_ctx == ctx)
1423                 return;
1424
1425         perf_pmu_disable(ctx->pmu);
1426         /*
1427          * We want to keep the following priority order:
1428          * cpu pinned (that don't need to move), task pinned,
1429          * cpu flexible, task flexible.
1430          */
1431         cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
1432
1433         ctx_sched_in(ctx, cpuctx, EVENT_PINNED);
1434         cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE);
1435         ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE);
1436
1437         cpuctx->task_ctx = ctx;
1438
1439         /*
1440          * Since these rotations are per-cpu, we need to ensure the
1441          * cpu-context we got scheduled on is actually rotating.
1442          */
1443         perf_pmu_rotate_start(ctx->pmu);
1444         perf_pmu_enable(ctx->pmu);
1445 }
1446
1447 /*
1448  * Called from scheduler to add the events of the current task
1449  * with interrupts disabled.
1450  *
1451  * We restore the event value and then enable it.
1452  *
1453  * This does not protect us against NMI, but enable()
1454  * sets the enabled bit in the control field of event _before_
1455  * accessing the event control register. If a NMI hits, then it will
1456  * keep the event running.
1457  */
1458 void __perf_event_task_sched_in(struct task_struct *task)
1459 {
1460         struct perf_event_context *ctx;
1461         int ctxn;
1462
1463         for_each_task_context_nr(ctxn) {
1464                 ctx = task->perf_event_ctxp[ctxn];
1465                 if (likely(!ctx))
1466                         continue;
1467
1468                 perf_event_context_sched_in(ctx);
1469         }
1470 }
1471
1472 #define MAX_INTERRUPTS (~0ULL)
1473
1474 static void perf_log_throttle(struct perf_event *event, int enable);
1475
1476 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
1477 {
1478         u64 frequency = event->attr.sample_freq;
1479         u64 sec = NSEC_PER_SEC;
1480         u64 divisor, dividend;
1481
1482         int count_fls, nsec_fls, frequency_fls, sec_fls;
1483
1484         count_fls = fls64(count);
1485         nsec_fls = fls64(nsec);
1486         frequency_fls = fls64(frequency);
1487         sec_fls = 30;
1488
1489         /*
1490          * We got @count in @nsec, with a target of sample_freq HZ
1491          * the target period becomes:
1492          *
1493          *             @count * 10^9
1494          * period = -------------------
1495          *          @nsec * sample_freq
1496          *
1497          */
1498
1499         /*
1500          * Reduce accuracy by one bit such that @a and @b converge
1501          * to a similar magnitude.
1502          */
1503 #define REDUCE_FLS(a, b)                \
1504 do {                                    \
1505         if (a##_fls > b##_fls) {        \
1506                 a >>= 1;                \
1507                 a##_fls--;              \
1508         } else {                        \
1509                 b >>= 1;                \
1510                 b##_fls--;              \
1511         }                               \
1512 } while (0)
1513
1514         /*
1515          * Reduce accuracy until either term fits in a u64, then proceed with
1516          * the other, so that finally we can do a u64/u64 division.
1517          */
1518         while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
1519                 REDUCE_FLS(nsec, frequency);
1520                 REDUCE_FLS(sec, count);
1521         }
1522
1523         if (count_fls + sec_fls > 64) {
1524                 divisor = nsec * frequency;
1525
1526                 while (count_fls + sec_fls > 64) {
1527                         REDUCE_FLS(count, sec);
1528                         divisor >>= 1;
1529                 }
1530
1531                 dividend = count * sec;
1532         } else {
1533                 dividend = count * sec;
1534
1535                 while (nsec_fls + frequency_fls > 64) {
1536                         REDUCE_FLS(nsec, frequency);
1537                         dividend >>= 1;
1538                 }
1539
1540                 divisor = nsec * frequency;
1541         }
1542
1543         if (!divisor)
1544                 return dividend;
1545
1546         return div64_u64(dividend, divisor);
1547 }
1548
1549 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count)
1550 {
1551         struct hw_perf_event *hwc = &event->hw;
1552         s64 period, sample_period;
1553         s64 delta;
1554
1555         period = perf_calculate_period(event, nsec, count);
1556
1557         delta = (s64)(period - hwc->sample_period);
1558         delta = (delta + 7) / 8; /* low pass filter */
1559
1560         sample_period = hwc->sample_period + delta;
1561
1562         if (!sample_period)
1563                 sample_period = 1;
1564
1565         hwc->sample_period = sample_period;
1566
1567         if (local64_read(&hwc->period_left) > 8*sample_period) {
1568                 event->pmu->stop(event, PERF_EF_UPDATE);
1569                 local64_set(&hwc->period_left, 0);
1570                 event->pmu->start(event, PERF_EF_RELOAD);
1571         }
1572 }
1573
1574 static void perf_ctx_adjust_freq(struct perf_event_context *ctx, u64 period)
1575 {
1576         struct perf_event *event;
1577         struct hw_perf_event *hwc;
1578         u64 interrupts, now;
1579         s64 delta;
1580
1581         raw_spin_lock(&ctx->lock);
1582         list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
1583                 if (event->state != PERF_EVENT_STATE_ACTIVE)
1584                         continue;
1585
1586                 if (event->cpu != -1 && event->cpu != smp_processor_id())
1587                         continue;
1588
1589                 hwc = &event->hw;
1590
1591                 interrupts = hwc->interrupts;
1592                 hwc->interrupts = 0;
1593
1594                 /*
1595                  * unthrottle events on the tick
1596                  */
1597                 if (interrupts == MAX_INTERRUPTS) {
1598                         perf_log_throttle(event, 1);
1599                         event->pmu->start(event, 0);
1600                 }
1601
1602                 if (!event->attr.freq || !event->attr.sample_freq)
1603                         continue;
1604
1605                 event->pmu->read(event);
1606                 now = local64_read(&event->count);
1607                 delta = now - hwc->freq_count_stamp;
1608                 hwc->freq_count_stamp = now;
1609
1610                 if (delta > 0)
1611                         perf_adjust_period(event, period, delta);
1612         }
1613         raw_spin_unlock(&ctx->lock);
1614 }
1615
1616 /*
1617  * Round-robin a context's events:
1618  */
1619 static void rotate_ctx(struct perf_event_context *ctx)
1620 {
1621         raw_spin_lock(&ctx->lock);
1622
1623         /* Rotate the first entry last of non-pinned groups */
1624         list_rotate_left(&ctx->flexible_groups);
1625
1626         raw_spin_unlock(&ctx->lock);
1627 }
1628
1629 /*
1630  * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
1631  * because they're strictly cpu affine and rotate_start is called with IRQs
1632  * disabled, while rotate_context is called from IRQ context.
1633  */
1634 static void perf_rotate_context(struct perf_cpu_context *cpuctx)
1635 {
1636         u64 interval = (u64)cpuctx->jiffies_interval * TICK_NSEC;
1637         struct perf_event_context *ctx = NULL;
1638         int rotate = 0, remove = 1;
1639
1640         if (cpuctx->ctx.nr_events) {
1641                 remove = 0;
1642                 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
1643                         rotate = 1;
1644         }
1645
1646         ctx = cpuctx->task_ctx;
1647         if (ctx && ctx->nr_events) {
1648                 remove = 0;
1649                 if (ctx->nr_events != ctx->nr_active)
1650                         rotate = 1;
1651         }
1652
1653         perf_pmu_disable(cpuctx->ctx.pmu);
1654         perf_ctx_adjust_freq(&cpuctx->ctx, interval);
1655         if (ctx)
1656                 perf_ctx_adjust_freq(ctx, interval);
1657
1658         if (!rotate)
1659                 goto done;
1660
1661         cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
1662         if (ctx)
1663                 task_ctx_sched_out(ctx, EVENT_FLEXIBLE);
1664
1665         rotate_ctx(&cpuctx->ctx);
1666         if (ctx)
1667                 rotate_ctx(ctx);
1668
1669         cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE);
1670         if (ctx)
1671                 task_ctx_sched_in(ctx, EVENT_FLEXIBLE);
1672
1673 done:
1674         if (remove)
1675                 list_del_init(&cpuctx->rotation_list);
1676
1677         perf_pmu_enable(cpuctx->ctx.pmu);
1678 }
1679
1680 void perf_event_task_tick(void)
1681 {
1682         struct list_head *head = &__get_cpu_var(rotation_list);
1683         struct perf_cpu_context *cpuctx, *tmp;
1684
1685         WARN_ON(!irqs_disabled());
1686
1687         list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) {
1688                 if (cpuctx->jiffies_interval == 1 ||
1689                                 !(jiffies % cpuctx->jiffies_interval))
1690                         perf_rotate_context(cpuctx);
1691         }
1692 }
1693
1694 static int event_enable_on_exec(struct perf_event *event,
1695                                 struct perf_event_context *ctx)
1696 {
1697         if (!event->attr.enable_on_exec)
1698                 return 0;
1699
1700         event->attr.enable_on_exec = 0;
1701         if (event->state >= PERF_EVENT_STATE_INACTIVE)
1702                 return 0;
1703
1704         __perf_event_mark_enabled(event, ctx);
1705
1706         return 1;
1707 }
1708
1709 /*
1710  * Enable all of a task's events that have been marked enable-on-exec.
1711  * This expects task == current.
1712  */
1713 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
1714 {
1715         struct perf_event *event;
1716         unsigned long flags;
1717         int enabled = 0;
1718         int ret;
1719
1720         local_irq_save(flags);
1721         if (!ctx || !ctx->nr_events)
1722                 goto out;
1723
1724         task_ctx_sched_out(ctx, EVENT_ALL);
1725
1726         raw_spin_lock(&ctx->lock);
1727
1728         list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
1729                 ret = event_enable_on_exec(event, ctx);
1730                 if (ret)
1731                         enabled = 1;
1732         }
1733
1734         list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
1735                 ret = event_enable_on_exec(event, ctx);
1736                 if (ret)
1737                         enabled = 1;
1738         }
1739
1740         /*
1741          * Unclone this context if we enabled any event.
1742          */
1743         if (enabled)
1744                 unclone_ctx(ctx);
1745
1746         raw_spin_unlock(&ctx->lock);
1747
1748         perf_event_context_sched_in(ctx);
1749 out:
1750         local_irq_restore(flags);
1751 }
1752
1753 /*
1754  * Cross CPU call to read the hardware event
1755  */
1756 static void __perf_event_read(void *info)
1757 {
1758         struct perf_event *event = info;
1759         struct perf_event_context *ctx = event->ctx;
1760         struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1761
1762         /*
1763          * If this is a task context, we need to check whether it is
1764          * the current task context of this cpu.  If not it has been
1765          * scheduled out before the smp call arrived.  In that case
1766          * event->count would have been updated to a recent sample
1767          * when the event was scheduled out.
1768          */
1769         if (ctx->task && cpuctx->task_ctx != ctx)
1770                 return;
1771
1772         raw_spin_lock(&ctx->lock);
1773         update_context_time(ctx);
1774         update_event_times(event);
1775         raw_spin_unlock(&ctx->lock);
1776
1777         event->pmu->read(event);
1778 }
1779
1780 static inline u64 perf_event_count(struct perf_event *event)
1781 {
1782         return local64_read(&event->count) + atomic64_read(&event->child_count);
1783 }
1784
1785 static u64 perf_event_read(struct perf_event *event)
1786 {
1787         /*
1788          * If event is enabled and currently active on a CPU, update the
1789          * value in the event structure:
1790          */
1791         if (event->state == PERF_EVENT_STATE_ACTIVE) {
1792                 smp_call_function_single(event->oncpu,
1793                                          __perf_event_read, event, 1);
1794         } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
1795                 struct perf_event_context *ctx = event->ctx;
1796                 unsigned long flags;
1797
1798                 raw_spin_lock_irqsave(&ctx->lock, flags);
1799                 /*
1800                  * may read while context is not active
1801                  * (e.g., thread is blocked), in that case
1802                  * we cannot update context time
1803                  */
1804                 if (ctx->is_active)
1805                         update_context_time(ctx);
1806                 update_event_times(event);
1807                 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1808         }
1809
1810         return perf_event_count(event);
1811 }
1812
1813 /*
1814  * Callchain support
1815  */
1816
1817 struct callchain_cpus_entries {
1818         struct rcu_head                 rcu_head;
1819         struct perf_callchain_entry     *cpu_entries[0];
1820 };
1821
1822 static DEFINE_PER_CPU(int, callchain_recursion[PERF_NR_CONTEXTS]);
1823 static atomic_t nr_callchain_events;
1824 static DEFINE_MUTEX(callchain_mutex);
1825 struct callchain_cpus_entries *callchain_cpus_entries;
1826
1827
1828 __weak void perf_callchain_kernel(struct perf_callchain_entry *entry,
1829                                   struct pt_regs *regs)
1830 {
1831 }
1832
1833 __weak void perf_callchain_user(struct perf_callchain_entry *entry,
1834                                 struct pt_regs *regs)
1835 {
1836 }
1837
1838 static void release_callchain_buffers_rcu(struct rcu_head *head)
1839 {
1840         struct callchain_cpus_entries *entries;
1841         int cpu;
1842
1843         entries = container_of(head, struct callchain_cpus_entries, rcu_head);
1844
1845         for_each_possible_cpu(cpu)
1846                 kfree(entries->cpu_entries[cpu]);
1847
1848         kfree(entries);
1849 }
1850
1851 static void release_callchain_buffers(void)
1852 {
1853         struct callchain_cpus_entries *entries;
1854
1855         entries = callchain_cpus_entries;
1856         rcu_assign_pointer(callchain_cpus_entries, NULL);
1857         call_rcu(&entries->rcu_head, release_callchain_buffers_rcu);
1858 }
1859
1860 static int alloc_callchain_buffers(void)
1861 {
1862         int cpu;
1863         int size;
1864         struct callchain_cpus_entries *entries;
1865
1866         /*
1867          * We can't use the percpu allocation API for data that can be
1868          * accessed from NMI. Use a temporary manual per cpu allocation
1869          * until that gets sorted out.
1870          */
1871         size = sizeof(*entries) + sizeof(struct perf_callchain_entry *) *
1872                 num_possible_cpus();
1873
1874         entries = kzalloc(size, GFP_KERNEL);
1875         if (!entries)
1876                 return -ENOMEM;
1877
1878         size = sizeof(struct perf_callchain_entry) * PERF_NR_CONTEXTS;
1879
1880         for_each_possible_cpu(cpu) {
1881                 entries->cpu_entries[cpu] = kmalloc_node(size, GFP_KERNEL,
1882                                                          cpu_to_node(cpu));
1883                 if (!entries->cpu_entries[cpu])
1884                         goto fail;
1885         }
1886
1887         rcu_assign_pointer(callchain_cpus_entries, entries);
1888
1889         return 0;
1890
1891 fail:
1892         for_each_possible_cpu(cpu)
1893                 kfree(entries->cpu_entries[cpu]);
1894         kfree(entries);
1895
1896         return -ENOMEM;
1897 }
1898
1899 static int get_callchain_buffers(void)
1900 {
1901         int err = 0;
1902         int count;
1903
1904         mutex_lock(&callchain_mutex);
1905
1906         count = atomic_inc_return(&nr_callchain_events);
1907         if (WARN_ON_ONCE(count < 1)) {
1908                 err = -EINVAL;
1909                 goto exit;
1910         }
1911
1912         if (count > 1) {
1913                 /* If the allocation failed, give up */
1914                 if (!callchain_cpus_entries)
1915                         err = -ENOMEM;
1916                 goto exit;
1917         }
1918
1919         err = alloc_callchain_buffers();
1920         if (err)
1921                 release_callchain_buffers();
1922 exit:
1923         mutex_unlock(&callchain_mutex);
1924
1925         return err;
1926 }
1927
1928 static void put_callchain_buffers(void)
1929 {
1930         if (atomic_dec_and_mutex_lock(&nr_callchain_events, &callchain_mutex)) {
1931                 release_callchain_buffers();
1932                 mutex_unlock(&callchain_mutex);
1933         }
1934 }
1935
1936 static int get_recursion_context(int *recursion)
1937 {
1938         int rctx;
1939
1940         if (in_nmi())
1941                 rctx = 3;
1942         else if (in_irq())
1943                 rctx = 2;
1944         else if (in_softirq())
1945                 rctx = 1;
1946         else
1947                 rctx = 0;
1948
1949         if (recursion[rctx])
1950                 return -1;
1951
1952         recursion[rctx]++;
1953         barrier();
1954
1955         return rctx;
1956 }
1957
1958 static inline void put_recursion_context(int *recursion, int rctx)
1959 {
1960         barrier();
1961         recursion[rctx]--;
1962 }
1963
1964 static struct perf_callchain_entry *get_callchain_entry(int *rctx)
1965 {
1966         int cpu;
1967         struct callchain_cpus_entries *entries;
1968
1969         *rctx = get_recursion_context(__get_cpu_var(callchain_recursion));
1970         if (*rctx == -1)
1971                 return NULL;
1972
1973         entries = rcu_dereference(callchain_cpus_entries);
1974         if (!entries)
1975                 return NULL;
1976
1977         cpu = smp_processor_id();
1978
1979         return &entries->cpu_entries[cpu][*rctx];
1980 }
1981
1982 static void
1983 put_callchain_entry(int rctx)
1984 {
1985         put_recursion_context(__get_cpu_var(callchain_recursion), rctx);
1986 }
1987
1988 static struct perf_callchain_entry *perf_callchain(struct pt_regs *regs)
1989 {
1990         int rctx;
1991         struct perf_callchain_entry *entry;
1992
1993
1994         entry = get_callchain_entry(&rctx);
1995         if (rctx == -1)
1996                 return NULL;
1997
1998         if (!entry)
1999                 goto exit_put;
2000
2001         entry->nr = 0;
2002
2003         if (!user_mode(regs)) {
2004                 perf_callchain_store(entry, PERF_CONTEXT_KERNEL);
2005                 perf_callchain_kernel(entry, regs);
2006                 if (current->mm)
2007                         regs = task_pt_regs(current);
2008                 else
2009                         regs = NULL;
2010         }
2011
2012         if (regs) {
2013                 perf_callchain_store(entry, PERF_CONTEXT_USER);
2014                 perf_callchain_user(entry, regs);
2015         }
2016
2017 exit_put:
2018         put_callchain_entry(rctx);
2019
2020         return entry;
2021 }
2022
2023 /*
2024  * Initialize the perf_event context in a task_struct:
2025  */
2026 static void __perf_event_init_context(struct perf_event_context *ctx)
2027 {
2028         raw_spin_lock_init(&ctx->lock);
2029         mutex_init(&ctx->mutex);
2030         INIT_LIST_HEAD(&ctx->pinned_groups);
2031         INIT_LIST_HEAD(&ctx->flexible_groups);
2032         INIT_LIST_HEAD(&ctx->event_list);
2033         atomic_set(&ctx->refcount, 1);
2034 }
2035
2036 static struct perf_event_context *
2037 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
2038 {
2039         struct perf_event_context *ctx;
2040
2041         ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
2042         if (!ctx)
2043                 return NULL;
2044
2045         __perf_event_init_context(ctx);
2046         if (task) {
2047                 ctx->task = task;
2048                 get_task_struct(task);
2049         }
2050         ctx->pmu = pmu;
2051
2052         return ctx;
2053 }
2054
2055 static struct task_struct *
2056 find_lively_task_by_vpid(pid_t vpid)
2057 {
2058         struct task_struct *task;
2059         int err;
2060
2061         rcu_read_lock();
2062         if (!vpid)
2063                 task = current;
2064         else
2065                 task = find_task_by_vpid(vpid);
2066         if (task)
2067                 get_task_struct(task);
2068         rcu_read_unlock();
2069
2070         if (!task)
2071                 return ERR_PTR(-ESRCH);
2072
2073         /*
2074          * Can't attach events to a dying task.
2075          */
2076         err = -ESRCH;
2077         if (task->flags & PF_EXITING)
2078                 goto errout;
2079
2080         /* Reuse ptrace permission checks for now. */
2081         err = -EACCES;
2082         if (!ptrace_may_access(task, PTRACE_MODE_READ))
2083                 goto errout;
2084
2085         return task;
2086 errout:
2087         put_task_struct(task);
2088         return ERR_PTR(err);
2089
2090 }
2091
2092 static struct perf_event_context *
2093 find_get_context(struct pmu *pmu, struct task_struct *task, int cpu)
2094 {
2095         struct perf_event_context *ctx;
2096         struct perf_cpu_context *cpuctx;
2097         unsigned long flags;
2098         int ctxn, err;
2099
2100         if (!task && cpu != -1) {
2101                 /* Must be root to operate on a CPU event: */
2102                 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
2103                         return ERR_PTR(-EACCES);
2104
2105                 if (cpu < 0 || cpu >= nr_cpumask_bits)
2106                         return ERR_PTR(-EINVAL);
2107
2108                 /*
2109                  * We could be clever and allow to attach a event to an
2110                  * offline CPU and activate it when the CPU comes up, but
2111                  * that's for later.
2112                  */
2113                 if (!cpu_online(cpu))
2114                         return ERR_PTR(-ENODEV);
2115
2116                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
2117                 ctx = &cpuctx->ctx;
2118                 get_ctx(ctx);
2119
2120                 return ctx;
2121         }
2122
2123         err = -EINVAL;
2124         ctxn = pmu->task_ctx_nr;
2125         if (ctxn < 0)
2126                 goto errout;
2127
2128 retry:
2129         ctx = perf_lock_task_context(task, ctxn, &flags);
2130         if (ctx) {
2131                 unclone_ctx(ctx);
2132                 raw_spin_unlock_irqrestore(&ctx->lock, flags);
2133         }
2134
2135         if (!ctx) {
2136                 ctx = alloc_perf_context(pmu, task);
2137                 err = -ENOMEM;
2138                 if (!ctx)
2139                         goto errout;
2140
2141                 get_ctx(ctx);
2142
2143                 if (cmpxchg(&task->perf_event_ctxp[ctxn], NULL, ctx)) {
2144                         /*
2145                          * We raced with some other task; use
2146                          * the context they set.
2147                          */
2148                         put_task_struct(task);
2149                         kfree(ctx);
2150                         goto retry;
2151                 }
2152         }
2153
2154         return ctx;
2155
2156 errout:
2157         return ERR_PTR(err);
2158 }
2159
2160 static void perf_event_free_filter(struct perf_event *event);
2161
2162 static void free_event_rcu(struct rcu_head *head)
2163 {
2164         struct perf_event *event;
2165
2166         event = container_of(head, struct perf_event, rcu_head);
2167         if (event->ns)
2168                 put_pid_ns(event->ns);
2169         perf_event_free_filter(event);
2170         kfree(event);
2171 }
2172
2173 static void perf_buffer_put(struct perf_buffer *buffer);
2174
2175 static void free_event(struct perf_event *event)
2176 {
2177         irq_work_sync(&event->pending);
2178
2179         if (!event->parent) {
2180                 if (event->attach_state & PERF_ATTACH_TASK)
2181                         jump_label_dec(&perf_task_events);
2182                 if (event->attr.mmap || event->attr.mmap_data)
2183                         atomic_dec(&nr_mmap_events);
2184                 if (event->attr.comm)
2185                         atomic_dec(&nr_comm_events);
2186                 if (event->attr.task)
2187                         atomic_dec(&nr_task_events);
2188                 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
2189                         put_callchain_buffers();
2190         }
2191
2192         if (event->buffer) {
2193                 perf_buffer_put(event->buffer);
2194                 event->buffer = NULL;
2195         }
2196
2197         if (event->destroy)
2198                 event->destroy(event);
2199
2200         if (event->ctx)
2201                 put_ctx(event->ctx);
2202
2203         call_rcu(&event->rcu_head, free_event_rcu);
2204 }
2205
2206 int perf_event_release_kernel(struct perf_event *event)
2207 {
2208         struct perf_event_context *ctx = event->ctx;
2209
2210         /*
2211          * Remove from the PMU, can't get re-enabled since we got
2212          * here because the last ref went.
2213          */
2214         perf_event_disable(event);
2215
2216         WARN_ON_ONCE(ctx->parent_ctx);
2217         /*
2218          * There are two ways this annotation is useful:
2219          *
2220          *  1) there is a lock recursion from perf_event_exit_task
2221          *     see the comment there.
2222          *
2223          *  2) there is a lock-inversion with mmap_sem through
2224          *     perf_event_read_group(), which takes faults while
2225          *     holding ctx->mutex, however this is called after
2226          *     the last filedesc died, so there is no possibility
2227          *     to trigger the AB-BA case.
2228          */
2229         mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
2230         raw_spin_lock_irq(&ctx->lock);
2231         perf_group_detach(event);
2232         list_del_event(event, ctx);
2233         raw_spin_unlock_irq(&ctx->lock);
2234         mutex_unlock(&ctx->mutex);
2235
2236         mutex_lock(&event->owner->perf_event_mutex);
2237         list_del_init(&event->owner_entry);
2238         mutex_unlock(&event->owner->perf_event_mutex);
2239         put_task_struct(event->owner);
2240
2241         free_event(event);
2242
2243         return 0;
2244 }
2245 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
2246
2247 /*
2248  * Called when the last reference to the file is gone.
2249  */
2250 static int perf_release(struct inode *inode, struct file *file)
2251 {
2252         struct perf_event *event = file->private_data;
2253
2254         file->private_data = NULL;
2255
2256         return perf_event_release_kernel(event);
2257 }
2258
2259 static int perf_event_read_size(struct perf_event *event)
2260 {
2261         int entry = sizeof(u64); /* value */
2262         int size = 0;
2263         int nr = 1;
2264
2265         if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
2266                 size += sizeof(u64);
2267
2268         if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
2269                 size += sizeof(u64);
2270
2271         if (event->attr.read_format & PERF_FORMAT_ID)
2272                 entry += sizeof(u64);
2273
2274         if (event->attr.read_format & PERF_FORMAT_GROUP) {
2275                 nr += event->group_leader->nr_siblings;
2276                 size += sizeof(u64);
2277         }
2278
2279         size += entry * nr;
2280
2281         return size;
2282 }
2283
2284 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
2285 {
2286         struct perf_event *child;
2287         u64 total = 0;
2288
2289         *enabled = 0;
2290         *running = 0;
2291
2292         mutex_lock(&event->child_mutex);
2293         total += perf_event_read(event);
2294         *enabled += event->total_time_enabled +
2295                         atomic64_read(&event->child_total_time_enabled);
2296         *running += event->total_time_running +
2297                         atomic64_read(&event->child_total_time_running);
2298
2299         list_for_each_entry(child, &event->child_list, child_list) {
2300                 total += perf_event_read(child);
2301                 *enabled += child->total_time_enabled;
2302                 *running += child->total_time_running;
2303         }
2304         mutex_unlock(&event->child_mutex);
2305
2306         return total;
2307 }
2308 EXPORT_SYMBOL_GPL(perf_event_read_value);
2309
2310 static int perf_event_read_group(struct perf_event *event,
2311                                    u64 read_format, char __user *buf)
2312 {
2313         struct perf_event *leader = event->group_leader, *sub;
2314         int n = 0, size = 0, ret = -EFAULT;
2315         struct perf_event_context *ctx = leader->ctx;
2316         u64 values[5];
2317         u64 count, enabled, running;
2318
2319         mutex_lock(&ctx->mutex);
2320         count = perf_event_read_value(leader, &enabled, &running);
2321
2322         values[n++] = 1 + leader->nr_siblings;
2323         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
2324                 values[n++] = enabled;
2325         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
2326                 values[n++] = running;
2327         values[n++] = count;
2328         if (read_format & PERF_FORMAT_ID)
2329                 values[n++] = primary_event_id(leader);
2330
2331         size = n * sizeof(u64);
2332
2333         if (copy_to_user(buf, values, size))
2334                 goto unlock;
2335
2336         ret = size;
2337
2338         list_for_each_entry(sub, &leader->sibling_list, group_entry) {
2339                 n = 0;
2340
2341                 values[n++] = perf_event_read_value(sub, &enabled, &running);
2342                 if (read_format & PERF_FORMAT_ID)
2343                         values[n++] = primary_event_id(sub);
2344
2345                 size = n * sizeof(u64);
2346
2347                 if (copy_to_user(buf + ret, values, size)) {
2348                         ret = -EFAULT;
2349                         goto unlock;
2350                 }
2351
2352                 ret += size;
2353         }
2354 unlock:
2355         mutex_unlock(&ctx->mutex);
2356
2357         return ret;
2358 }
2359
2360 static int perf_event_read_one(struct perf_event *event,
2361                                  u64 read_format, char __user *buf)
2362 {
2363         u64 enabled, running;
2364         u64 values[4];
2365         int n = 0;
2366
2367         values[n++] = perf_event_read_value(event, &enabled, &running);
2368         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
2369                 values[n++] = enabled;
2370         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
2371                 values[n++] = running;
2372         if (read_format & PERF_FORMAT_ID)
2373                 values[n++] = primary_event_id(event);
2374
2375         if (copy_to_user(buf, values, n * sizeof(u64)))
2376                 return -EFAULT;
2377
2378         return n * sizeof(u64);
2379 }
2380
2381 /*
2382  * Read the performance event - simple non blocking version for now
2383  */
2384 static ssize_t
2385 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
2386 {
2387         u64 read_format = event->attr.read_format;
2388         int ret;
2389
2390         /*
2391          * Return end-of-file for a read on a event that is in
2392          * error state (i.e. because it was pinned but it couldn't be
2393          * scheduled on to the CPU at some point).
2394          */
2395         if (event->state == PERF_EVENT_STATE_ERROR)
2396                 return 0;
2397
2398         if (count < perf_event_read_size(event))
2399                 return -ENOSPC;
2400
2401         WARN_ON_ONCE(event->ctx->parent_ctx);
2402         if (read_format & PERF_FORMAT_GROUP)
2403                 ret = perf_event_read_group(event, read_format, buf);
2404         else
2405                 ret = perf_event_read_one(event, read_format, buf);
2406
2407         return ret;
2408 }
2409
2410 static ssize_t
2411 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
2412 {
2413         struct perf_event *event = file->private_data;
2414
2415         return perf_read_hw(event, buf, count);
2416 }
2417
2418 static unsigned int perf_poll(struct file *file, poll_table *wait)
2419 {
2420         struct perf_event *event = file->private_data;
2421         struct perf_buffer *buffer;
2422         unsigned int events = POLL_HUP;
2423
2424         rcu_read_lock();
2425         buffer = rcu_dereference(event->buffer);
2426         if (buffer)
2427                 events = atomic_xchg(&buffer->poll, 0);
2428         rcu_read_unlock();
2429
2430         poll_wait(file, &event->waitq, wait);
2431
2432         return events;
2433 }
2434
2435 static void perf_event_reset(struct perf_event *event)
2436 {
2437         (void)perf_event_read(event);
2438         local64_set(&event->count, 0);
2439         perf_event_update_userpage(event);
2440 }
2441
2442 /*
2443  * Holding the top-level event's child_mutex means that any
2444  * descendant process that has inherited this event will block
2445  * in sync_child_event if it goes to exit, thus satisfying the
2446  * task existence requirements of perf_event_enable/disable.
2447  */
2448 static void perf_event_for_each_child(struct perf_event *event,
2449                                         void (*func)(struct perf_event *))
2450 {
2451         struct perf_event *child;
2452
2453         WARN_ON_ONCE(event->ctx->parent_ctx);
2454         mutex_lock(&event->child_mutex);
2455         func(event);
2456         list_for_each_entry(child, &event->child_list, child_list)
2457                 func(child);
2458         mutex_unlock(&event->child_mutex);
2459 }
2460
2461 static void perf_event_for_each(struct perf_event *event,
2462                                   void (*func)(struct perf_event *))
2463 {
2464         struct perf_event_context *ctx = event->ctx;
2465         struct perf_event *sibling;
2466
2467         WARN_ON_ONCE(ctx->parent_ctx);
2468         mutex_lock(&ctx->mutex);
2469         event = event->group_leader;
2470
2471         perf_event_for_each_child(event, func);
2472         func(event);
2473         list_for_each_entry(sibling, &event->sibling_list, group_entry)
2474                 perf_event_for_each_child(event, func);
2475         mutex_unlock(&ctx->mutex);
2476 }
2477
2478 static int perf_event_period(struct perf_event *event, u64 __user *arg)
2479 {
2480         struct perf_event_context *ctx = event->ctx;
2481         int ret = 0;
2482         u64 value;
2483
2484         if (!event->attr.sample_period)
2485                 return -EINVAL;
2486
2487         if (copy_from_user(&value, arg, sizeof(value)))
2488                 return -EFAULT;
2489
2490         if (!value)
2491                 return -EINVAL;
2492
2493         raw_spin_lock_irq(&ctx->lock);
2494         if (event->attr.freq) {
2495                 if (value > sysctl_perf_event_sample_rate) {
2496                         ret = -EINVAL;
2497                         goto unlock;
2498                 }
2499
2500                 event->attr.sample_freq = value;
2501         } else {
2502                 event->attr.sample_period = value;
2503                 event->hw.sample_period = value;
2504         }
2505 unlock:
2506         raw_spin_unlock_irq(&ctx->lock);
2507
2508         return ret;
2509 }
2510
2511 static const struct file_operations perf_fops;
2512
2513 static struct perf_event *perf_fget_light(int fd, int *fput_needed)
2514 {
2515         struct file *file;
2516
2517         file = fget_light(fd, fput_needed);
2518         if (!file)
2519                 return ERR_PTR(-EBADF);
2520
2521         if (file->f_op != &perf_fops) {
2522                 fput_light(file, *fput_needed);
2523                 *fput_needed = 0;
2524                 return ERR_PTR(-EBADF);
2525         }
2526
2527         return file->private_data;
2528 }
2529
2530 static int perf_event_set_output(struct perf_event *event,
2531                                  struct perf_event *output_event);
2532 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
2533
2534 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2535 {
2536         struct perf_event *event = file->private_data;
2537         void (*func)(struct perf_event *);
2538         u32 flags = arg;
2539
2540         switch (cmd) {
2541         case PERF_EVENT_IOC_ENABLE:
2542                 func = perf_event_enable;
2543                 break;
2544         case PERF_EVENT_IOC_DISABLE:
2545                 func = perf_event_disable;
2546                 break;
2547         case PERF_EVENT_IOC_RESET:
2548                 func = perf_event_reset;
2549                 break;
2550
2551         case PERF_EVENT_IOC_REFRESH:
2552                 return perf_event_refresh(event, arg);
2553
2554         case PERF_EVENT_IOC_PERIOD:
2555                 return perf_event_period(event, (u64 __user *)arg);
2556
2557         case PERF_EVENT_IOC_SET_OUTPUT:
2558         {
2559                 struct perf_event *output_event = NULL;
2560                 int fput_needed = 0;
2561                 int ret;
2562
2563                 if (arg != -1) {
2564                         output_event = perf_fget_light(arg, &fput_needed);
2565                         if (IS_ERR(output_event))
2566                                 return PTR_ERR(output_event);
2567                 }
2568
2569                 ret = perf_event_set_output(event, output_event);
2570                 if (output_event)
2571                         fput_light(output_event->filp, fput_needed);
2572
2573                 return ret;
2574         }
2575
2576         case PERF_EVENT_IOC_SET_FILTER:
2577                 return perf_event_set_filter(event, (void __user *)arg);
2578
2579         default:
2580                 return -ENOTTY;
2581         }
2582
2583         if (flags & PERF_IOC_FLAG_GROUP)
2584                 perf_event_for_each(event, func);
2585         else
2586                 perf_event_for_each_child(event, func);
2587
2588         return 0;
2589 }
2590
2591 int perf_event_task_enable(void)
2592 {
2593         struct perf_event *event;
2594
2595         mutex_lock(&current->perf_event_mutex);
2596         list_for_each_entry(event, &current->perf_event_list, owner_entry)
2597                 perf_event_for_each_child(event, perf_event_enable);
2598         mutex_unlock(&current->perf_event_mutex);
2599
2600         return 0;
2601 }
2602
2603 int perf_event_task_disable(void)
2604 {
2605         struct perf_event *event;
2606
2607         mutex_lock(&current->perf_event_mutex);
2608         list_for_each_entry(event, &current->perf_event_list, owner_entry)
2609                 perf_event_for_each_child(event, perf_event_disable);
2610         mutex_unlock(&current->perf_event_mutex);
2611
2612         return 0;
2613 }
2614
2615 #ifndef PERF_EVENT_INDEX_OFFSET
2616 # define PERF_EVENT_INDEX_OFFSET 0
2617 #endif
2618
2619 static int perf_event_index(struct perf_event *event)
2620 {
2621         if (event->hw.state & PERF_HES_STOPPED)
2622                 return 0;
2623
2624         if (event->state != PERF_EVENT_STATE_ACTIVE)
2625                 return 0;
2626
2627         return event->hw.idx + 1 - PERF_EVENT_INDEX_OFFSET;
2628 }
2629
2630 /*
2631  * Callers need to ensure there can be no nesting of this function, otherwise
2632  * the seqlock logic goes bad. We can not serialize this because the arch
2633  * code calls this from NMI context.
2634  */
2635 void perf_event_update_userpage(struct perf_event *event)
2636 {
2637         struct perf_event_mmap_page *userpg;
2638         struct perf_buffer *buffer;
2639
2640         rcu_read_lock();
2641         buffer = rcu_dereference(event->buffer);
2642         if (!buffer)
2643                 goto unlock;
2644
2645         userpg = buffer->user_page;
2646
2647         /*
2648          * Disable preemption so as to not let the corresponding user-space
2649          * spin too long if we get preempted.
2650          */
2651         preempt_disable();
2652         ++userpg->lock;
2653         barrier();
2654         userpg->index = perf_event_index(event);
2655         userpg->offset = perf_event_count(event);
2656         if (event->state == PERF_EVENT_STATE_ACTIVE)
2657                 userpg->offset -= local64_read(&event->hw.prev_count);
2658
2659         userpg->time_enabled = event->total_time_enabled +
2660                         atomic64_read(&event->child_total_time_enabled);
2661
2662         userpg->time_running = event->total_time_running +
2663                         atomic64_read(&event->child_total_time_running);
2664
2665         barrier();
2666         ++userpg->lock;
2667         preempt_enable();
2668 unlock:
2669         rcu_read_unlock();
2670 }
2671
2672 static unsigned long perf_data_size(struct perf_buffer *buffer);
2673
2674 static void
2675 perf_buffer_init(struct perf_buffer *buffer, long watermark, int flags)
2676 {
2677         long max_size = perf_data_size(buffer);
2678
2679         if (watermark)
2680                 buffer->watermark = min(max_size, watermark);
2681
2682         if (!buffer->watermark)
2683                 buffer->watermark = max_size / 2;
2684
2685         if (flags & PERF_BUFFER_WRITABLE)
2686                 buffer->writable = 1;
2687
2688         atomic_set(&buffer->refcount, 1);
2689 }
2690
2691 #ifndef CONFIG_PERF_USE_VMALLOC
2692
2693 /*
2694  * Back perf_mmap() with regular GFP_KERNEL-0 pages.
2695  */
2696
2697 static struct page *
2698 perf_mmap_to_page(struct perf_buffer *buffer, unsigned long pgoff)
2699 {
2700         if (pgoff > buffer->nr_pages)
2701                 return NULL;
2702
2703         if (pgoff == 0)
2704                 return virt_to_page(buffer->user_page);
2705
2706         return virt_to_page(buffer->data_pages[pgoff - 1]);
2707 }
2708
2709 static void *perf_mmap_alloc_page(int cpu)
2710 {
2711         struct page *page;
2712         int node;
2713
2714         node = (cpu == -1) ? cpu : cpu_to_node(cpu);
2715         page = alloc_pages_node(node, GFP_KERNEL | __GFP_ZERO, 0);
2716         if (!page)
2717                 return NULL;
2718
2719         return page_address(page);
2720 }
2721
2722 static struct perf_buffer *
2723 perf_buffer_alloc(int nr_pages, long watermark, int cpu, int flags)
2724 {
2725         struct perf_buffer *buffer;
2726         unsigned long size;
2727         int i;
2728
2729         size = sizeof(struct perf_buffer);
2730         size += nr_pages * sizeof(void *);
2731
2732         buffer = kzalloc(size, GFP_KERNEL);
2733         if (!buffer)
2734                 goto fail;
2735
2736         buffer->user_page = perf_mmap_alloc_page(cpu);
2737         if (!buffer->user_page)
2738                 goto fail_user_page;
2739
2740         for (i = 0; i < nr_pages; i++) {
2741                 buffer->data_pages[i] = perf_mmap_alloc_page(cpu);
2742                 if (!buffer->data_pages[i])
2743                         goto fail_data_pages;
2744         }
2745
2746         buffer->nr_pages = nr_pages;
2747
2748         perf_buffer_init(buffer, watermark, flags);
2749
2750         return buffer;
2751
2752 fail_data_pages:
2753         for (i--; i >= 0; i--)
2754                 free_page((unsigned long)buffer->data_pages[i]);
2755
2756         free_page((unsigned long)buffer->user_page);
2757
2758 fail_user_page:
2759         kfree(buffer);
2760
2761 fail:
2762         return NULL;
2763 }
2764
2765 static void perf_mmap_free_page(unsigned long addr)
2766 {
2767         struct page *page = virt_to_page((void *)addr);
2768
2769         page->mapping = NULL;
2770         __free_page(page);
2771 }
2772
2773 static void perf_buffer_free(struct perf_buffer *buffer)
2774 {
2775         int i;
2776
2777         perf_mmap_free_page((unsigned long)buffer->user_page);
2778         for (i = 0; i < buffer->nr_pages; i++)
2779                 perf_mmap_free_page((unsigned long)buffer->data_pages[i]);
2780         kfree(buffer);
2781 }
2782
2783 static inline int page_order(struct perf_buffer *buffer)
2784 {
2785         return 0;
2786 }
2787
2788 #else
2789
2790 /*
2791  * Back perf_mmap() with vmalloc memory.
2792  *
2793  * Required for architectures that have d-cache aliasing issues.
2794  */
2795
2796 static inline int page_order(struct perf_buffer *buffer)
2797 {
2798         return buffer->page_order;
2799 }
2800
2801 static struct page *
2802 perf_mmap_to_page(struct perf_buffer *buffer, unsigned long pgoff)
2803 {
2804         if (pgoff > (1UL << page_order(buffer)))
2805                 return NULL;
2806
2807         return vmalloc_to_page((void *)buffer->user_page + pgoff * PAGE_SIZE);
2808 }
2809
2810 static void perf_mmap_unmark_page(void *addr)
2811 {
2812         struct page *page = vmalloc_to_page(addr);
2813
2814         page->mapping = NULL;
2815 }
2816
2817 static void perf_buffer_free_work(struct work_struct *work)
2818 {
2819         struct perf_buffer *buffer;
2820         void *base;
2821         int i, nr;
2822
2823         buffer = container_of(work, struct perf_buffer, work);
2824         nr = 1 << page_order(buffer);
2825
2826         base = buffer->user_page;
2827         for (i = 0; i < nr + 1; i++)
2828                 perf_mmap_unmark_page(base + (i * PAGE_SIZE));
2829
2830         vfree(base);
2831         kfree(buffer);
2832 }
2833
2834 static void perf_buffer_free(struct perf_buffer *buffer)
2835 {
2836         schedule_work(&buffer->work);
2837 }
2838
2839 static struct perf_buffer *
2840 perf_buffer_alloc(int nr_pages, long watermark, int cpu, int flags)
2841 {
2842         struct perf_buffer *buffer;
2843         unsigned long size;
2844         void *all_buf;
2845
2846         size = sizeof(struct perf_buffer);
2847         size += sizeof(void *);
2848
2849         buffer = kzalloc(size, GFP_KERNEL);
2850         if (!buffer)
2851                 goto fail;
2852
2853         INIT_WORK(&buffer->work, perf_buffer_free_work);
2854
2855         all_buf = vmalloc_user((nr_pages + 1) * PAGE_SIZE);
2856         if (!all_buf)
2857                 goto fail_all_buf;
2858
2859         buffer->user_page = all_buf;
2860         buffer->data_pages[0] = all_buf + PAGE_SIZE;
2861         buffer->page_order = ilog2(nr_pages);
2862         buffer->nr_pages = 1;
2863
2864         perf_buffer_init(buffer, watermark, flags);
2865
2866         return buffer;
2867
2868 fail_all_buf:
2869         kfree(buffer);
2870
2871 fail:
2872         return NULL;
2873 }
2874
2875 #endif
2876
2877 static unsigned long perf_data_size(struct perf_buffer *buffer)
2878 {
2879         return buffer->nr_pages << (PAGE_SHIFT + page_order(buffer));
2880 }
2881
2882 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
2883 {
2884         struct perf_event *event = vma->vm_file->private_data;
2885         struct perf_buffer *buffer;
2886         int ret = VM_FAULT_SIGBUS;
2887
2888         if (vmf->flags & FAULT_FLAG_MKWRITE) {
2889                 if (vmf->pgoff == 0)
2890                         ret = 0;
2891                 return ret;
2892         }
2893
2894         rcu_read_lock();
2895         buffer = rcu_dereference(event->buffer);
2896         if (!buffer)
2897                 goto unlock;
2898
2899         if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
2900                 goto unlock;
2901
2902         vmf->page = perf_mmap_to_page(buffer, vmf->pgoff);
2903         if (!vmf->page)
2904                 goto unlock;
2905
2906         get_page(vmf->page);
2907         vmf->page->mapping = vma->vm_file->f_mapping;
2908         vmf->page->index   = vmf->pgoff;
2909
2910         ret = 0;
2911 unlock:
2912         rcu_read_unlock();
2913
2914         return ret;
2915 }
2916
2917 static void perf_buffer_free_rcu(struct rcu_head *rcu_head)
2918 {
2919         struct perf_buffer *buffer;
2920
2921         buffer = container_of(rcu_head, struct perf_buffer, rcu_head);
2922         perf_buffer_free(buffer);
2923 }
2924
2925 static struct perf_buffer *perf_buffer_get(struct perf_event *event)
2926 {
2927         struct perf_buffer *buffer;
2928
2929         rcu_read_lock();
2930         buffer = rcu_dereference(event->buffer);
2931         if (buffer) {
2932                 if (!atomic_inc_not_zero(&buffer->refcount))
2933                         buffer = NULL;
2934         }
2935         rcu_read_unlock();
2936
2937         return buffer;
2938 }
2939
2940 static void perf_buffer_put(struct perf_buffer *buffer)
2941 {
2942         if (!atomic_dec_and_test(&buffer->refcount))
2943                 return;
2944
2945         call_rcu(&buffer->rcu_head, perf_buffer_free_rcu);
2946 }
2947
2948 static void perf_mmap_open(struct vm_area_struct *vma)
2949 {
2950         struct perf_event *event = vma->vm_file->private_data;
2951
2952         atomic_inc(&event->mmap_count);
2953 }
2954
2955 static void perf_mmap_close(struct vm_area_struct *vma)
2956 {
2957         struct perf_event *event = vma->vm_file->private_data;
2958
2959         if (atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex)) {
2960                 unsigned long size = perf_data_size(event->buffer);
2961                 struct user_struct *user = event->mmap_user;
2962                 struct perf_buffer *buffer = event->buffer;
2963
2964                 atomic_long_sub((size >> PAGE_SHIFT) + 1, &user->locked_vm);
2965                 vma->vm_mm->locked_vm -= event->mmap_locked;
2966                 rcu_assign_pointer(event->buffer, NULL);
2967                 mutex_unlock(&event->mmap_mutex);
2968
2969                 perf_buffer_put(buffer);
2970                 free_uid(user);
2971         }
2972 }
2973
2974 static const struct vm_operations_struct perf_mmap_vmops = {
2975         .open           = perf_mmap_open,
2976         .close          = perf_mmap_close,
2977         .fault          = perf_mmap_fault,
2978         .page_mkwrite   = perf_mmap_fault,
2979 };
2980
2981 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
2982 {
2983         struct perf_event *event = file->private_data;
2984         unsigned long user_locked, user_lock_limit;
2985         struct user_struct *user = current_user();
2986         unsigned long locked, lock_limit;
2987         struct perf_buffer *buffer;
2988         unsigned long vma_size;
2989         unsigned long nr_pages;
2990         long user_extra, extra;
2991         int ret = 0, flags = 0;
2992
2993         /*
2994          * Don't allow mmap() of inherited per-task counters. This would
2995          * create a performance issue due to all children writing to the
2996          * same buffer.
2997          */
2998         if (event->cpu == -1 && event->attr.inherit)
2999                 return -EINVAL;
3000
3001         if (!(vma->vm_flags & VM_SHARED))
3002                 return -EINVAL;
3003
3004         vma_size = vma->vm_end - vma->vm_start;
3005         nr_pages = (vma_size / PAGE_SIZE) - 1;
3006
3007         /*
3008          * If we have buffer pages ensure they're a power-of-two number, so we
3009          * can do bitmasks instead of modulo.
3010          */
3011         if (nr_pages != 0 && !is_power_of_2(nr_pages))
3012                 return -EINVAL;
3013
3014         if (vma_size != PAGE_SIZE * (1 + nr_pages))
3015                 return -EINVAL;
3016
3017         if (vma->vm_pgoff != 0)
3018                 return -EINVAL;
3019
3020         WARN_ON_ONCE(event->ctx->parent_ctx);
3021         mutex_lock(&event->mmap_mutex);
3022         if (event->buffer) {
3023                 if (event->buffer->nr_pages == nr_pages)
3024                         atomic_inc(&event->buffer->refcount);
3025                 else
3026                         ret = -EINVAL;
3027                 goto unlock;
3028         }
3029
3030         user_extra = nr_pages + 1;
3031         user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
3032
3033         /*
3034          * Increase the limit linearly with more CPUs:
3035          */
3036         user_lock_limit *= num_online_cpus();
3037
3038         user_locked = atomic_long_read(&user->locked_vm) + user_extra;
3039
3040         extra = 0;
3041         if (user_locked > user_lock_limit)
3042                 extra = user_locked - user_lock_limit;
3043
3044         lock_limit = rlimit(RLIMIT_MEMLOCK);
3045         lock_limit >>= PAGE_SHIFT;
3046         locked = vma->vm_mm->locked_vm + extra;
3047
3048         if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
3049                 !capable(CAP_IPC_LOCK)) {
3050                 ret = -EPERM;
3051                 goto unlock;
3052         }
3053
3054         WARN_ON(event->buffer);
3055
3056         if (vma->vm_flags & VM_WRITE)
3057                 flags |= PERF_BUFFER_WRITABLE;
3058
3059         buffer = perf_buffer_alloc(nr_pages, event->attr.wakeup_watermark,
3060                                    event->cpu, flags);
3061         if (!buffer) {
3062                 ret = -ENOMEM;
3063                 goto unlock;
3064         }
3065         rcu_assign_pointer(event->buffer, buffer);
3066
3067         atomic_long_add(user_extra, &user->locked_vm);
3068         event->mmap_locked = extra;
3069         event->mmap_user = get_current_user();
3070         vma->vm_mm->locked_vm += event->mmap_locked;
3071
3072 unlock:
3073         if (!ret)
3074                 atomic_inc(&event->mmap_count);
3075         mutex_unlock(&event->mmap_mutex);
3076
3077         vma->vm_flags |= VM_RESERVED;
3078         vma->vm_ops = &perf_mmap_vmops;
3079
3080         return ret;
3081 }
3082
3083 static int perf_fasync(int fd, struct file *filp, int on)
3084 {
3085         struct inode *inode = filp->f_path.dentry->d_inode;
3086         struct perf_event *event = filp->private_data;
3087         int retval;
3088
3089         mutex_lock(&inode->i_mutex);
3090         retval = fasync_helper(fd, filp, on, &event->fasync);
3091         mutex_unlock(&inode->i_mutex);
3092
3093         if (retval < 0)
3094                 return retval;
3095
3096         return 0;
3097 }
3098
3099 static const struct file_operations perf_fops = {
3100         .llseek                 = no_llseek,
3101         .release                = perf_release,
3102         .read                   = perf_read,
3103         .poll                   = perf_poll,
3104         .unlocked_ioctl         = perf_ioctl,
3105         .compat_ioctl           = perf_ioctl,
3106         .mmap                   = perf_mmap,
3107         .fasync                 = perf_fasync,
3108 };
3109
3110 /*
3111  * Perf event wakeup
3112  *
3113  * If there's data, ensure we set the poll() state and publish everything
3114  * to user-space before waking everybody up.
3115  */
3116
3117 void perf_event_wakeup(struct perf_event *event)
3118 {
3119         wake_up_all(&event->waitq);
3120
3121         if (event->pending_kill) {
3122                 kill_fasync(&event->fasync, SIGIO, event->pending_kill);
3123                 event->pending_kill = 0;
3124         }
3125 }
3126
3127 static void perf_pending_event(struct irq_work *entry)
3128 {
3129         struct perf_event *event = container_of(entry,
3130                         struct perf_event, pending);
3131
3132         if (event->pending_disable) {
3133                 event->pending_disable = 0;
3134                 __perf_event_disable(event);
3135         }
3136
3137         if (event->pending_wakeup) {
3138                 event->pending_wakeup = 0;
3139                 perf_event_wakeup(event);
3140         }
3141 }
3142
3143 /*
3144  * We assume there is only KVM supporting the callbacks.
3145  * Later on, we might change it to a list if there is
3146  * another virtualization implementation supporting the callbacks.
3147  */
3148 struct perf_guest_info_callbacks *perf_guest_cbs;
3149
3150 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
3151 {
3152         perf_guest_cbs = cbs;
3153         return 0;
3154 }
3155 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
3156
3157 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
3158 {
3159         perf_guest_cbs = NULL;
3160         return 0;
3161 }
3162 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
3163
3164 /*
3165  * Output
3166  */
3167 static bool perf_output_space(struct perf_buffer *buffer, unsigned long tail,
3168                               unsigned long offset, unsigned long head)
3169 {
3170         unsigned long mask;
3171
3172         if (!buffer->writable)
3173                 return true;
3174
3175         mask = perf_data_size(buffer) - 1;
3176
3177         offset = (offset - tail) & mask;
3178         head   = (head   - tail) & mask;
3179
3180         if ((int)(head - offset) < 0)
3181                 return false;
3182
3183         return true;
3184 }
3185
3186 static void perf_output_wakeup(struct perf_output_handle *handle)
3187 {
3188         atomic_set(&handle->buffer->poll, POLL_IN);
3189
3190         if (handle->nmi) {
3191                 handle->event->pending_wakeup = 1;
3192                 irq_work_queue(&handle->event->pending);
3193         } else
3194                 perf_event_wakeup(handle->event);
3195 }
3196
3197 /*
3198  * We need to ensure a later event_id doesn't publish a head when a former
3199  * event isn't done writing. However since we need to deal with NMIs we
3200  * cannot fully serialize things.
3201  *
3202  * We only publish the head (and generate a wakeup) when the outer-most
3203  * event completes.
3204  */
3205 static void perf_output_get_handle(struct perf_output_handle *handle)
3206 {
3207         struct perf_buffer *buffer = handle->buffer;
3208
3209         preempt_disable();
3210         local_inc(&buffer->nest);
3211         handle->wakeup = local_read(&buffer->wakeup);
3212 }
3213
3214 static void perf_output_put_handle(struct perf_output_handle *handle)
3215 {
3216         struct perf_buffer *buffer = handle->buffer;
3217         unsigned long head;
3218
3219 again:
3220         head = local_read(&buffer->head);
3221
3222         /*
3223          * IRQ/NMI can happen here, which means we can miss a head update.
3224          */
3225
3226         if (!local_dec_and_test(&buffer->nest))
3227                 goto out;
3228
3229         /*
3230          * Publish the known good head. Rely on the full barrier implied
3231          * by atomic_dec_and_test() order the buffer->head read and this
3232          * write.
3233          */
3234         buffer->user_page->data_head = head;
3235
3236         /*
3237          * Now check if we missed an update, rely on the (compiler)
3238          * barrier in atomic_dec_and_test() to re-read buffer->head.
3239          */
3240         if (unlikely(head != local_read(&buffer->head))) {
3241                 local_inc(&buffer->nest);
3242                 goto again;
3243         }
3244
3245         if (handle->wakeup != local_read(&buffer->wakeup))
3246                 perf_output_wakeup(handle);
3247
3248 out:
3249         preempt_enable();
3250 }
3251
3252 __always_inline void perf_output_copy(struct perf_output_handle *handle,
3253                       const void *buf, unsigned int len)
3254 {
3255         do {
3256                 unsigned long size = min_t(unsigned long, handle->size, len);
3257
3258                 memcpy(handle->addr, buf, size);
3259
3260                 len -= size;
3261                 handle->addr += size;
3262                 buf += size;
3263                 handle->size -= size;
3264                 if (!handle->size) {
3265                         struct perf_buffer *buffer = handle->buffer;
3266
3267                         handle->page++;
3268                         handle->page &= buffer->nr_pages - 1;
3269                         handle->addr = buffer->data_pages[handle->page];
3270                         handle->size = PAGE_SIZE << page_order(buffer);
3271                 }
3272         } while (len);
3273 }
3274
3275 int perf_output_begin(struct perf_output_handle *handle,
3276                       struct perf_event *event, unsigned int size,
3277                       int nmi, int sample)
3278 {
3279         struct perf_buffer *buffer;
3280         unsigned long tail, offset, head;
3281         int have_lost;
3282         struct {
3283                 struct perf_event_header header;
3284                 u64                      id;
3285                 u64                      lost;
3286         } lost_event;
3287
3288         rcu_read_lock();
3289         /*
3290          * For inherited events we send all the output towards the parent.
3291          */
3292         if (event->parent)
3293                 event = event->parent;
3294
3295         buffer = rcu_dereference(event->buffer);
3296         if (!buffer)
3297                 goto out;
3298
3299         handle->buffer  = buffer;
3300         handle->event   = event;
3301         handle->nmi     = nmi;
3302         handle->sample  = sample;
3303
3304         if (!buffer->nr_pages)
3305                 goto out;
3306
3307         have_lost = local_read(&buffer->lost);
3308         if (have_lost)
3309                 size += sizeof(lost_event);
3310
3311         perf_output_get_handle(handle);
3312
3313         do {
3314                 /*
3315                  * Userspace could choose to issue a mb() before updating the
3316                  * tail pointer. So that all reads will be completed before the
3317                  * write is issued.
3318                  */
3319                 tail = ACCESS_ONCE(buffer->user_page->data_tail);
3320                 smp_rmb();
3321                 offset = head = local_read(&buffer->head);
3322                 head += size;
3323                 if (unlikely(!perf_output_space(buffer, tail, offset, head)))
3324                         goto fail;
3325         } while (local_cmpxchg(&buffer->head, offset, head) != offset);
3326
3327         if (head - local_read(&buffer->wakeup) > buffer->watermark)
3328                 local_add(buffer->watermark, &buffer->wakeup);
3329
3330         handle->page = offset >> (PAGE_SHIFT + page_order(buffer));
3331         handle->page &= buffer->nr_pages - 1;
3332         handle->size = offset & ((PAGE_SIZE << page_order(buffer)) - 1);
3333         handle->addr = buffer->data_pages[handle->page];
3334         handle->addr += handle->size;
3335         handle->size = (PAGE_SIZE << page_order(buffer)) - handle->size;
3336
3337         if (have_lost) {
3338                 lost_event.header.type = PERF_RECORD_LOST;
3339                 lost_event.header.misc = 0;
3340                 lost_event.header.size = sizeof(lost_event);
3341                 lost_event.id          = event->id;
3342                 lost_event.lost        = local_xchg(&buffer->lost, 0);
3343
3344                 perf_output_put(handle, lost_event);
3345         }
3346
3347         return 0;
3348
3349 fail:
3350         local_inc(&buffer->lost);
3351         perf_output_put_handle(handle);
3352 out:
3353         rcu_read_unlock();
3354
3355         return -ENOSPC;
3356 }
3357
3358 void perf_output_end(struct perf_output_handle *handle)
3359 {
3360         struct perf_event *event = handle->event;
3361         struct perf_buffer *buffer = handle->buffer;
3362
3363         int wakeup_events = event->attr.wakeup_events;
3364
3365         if (handle->sample && wakeup_events) {
3366                 int events = local_inc_return(&buffer->events);
3367                 if (events >= wakeup_events) {
3368                         local_sub(wakeup_events, &buffer->events);
3369                         local_inc(&buffer->wakeup);
3370                 }
3371         }
3372
3373         perf_output_put_handle(handle);
3374         rcu_read_unlock();
3375 }
3376
3377 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
3378 {
3379         /*
3380          * only top level events have the pid namespace they were created in
3381          */
3382         if (event->parent)
3383                 event = event->parent;
3384
3385         return task_tgid_nr_ns(p, event->ns);
3386 }
3387
3388 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
3389 {
3390         /*
3391          * only top level events have the pid namespace they were created in
3392          */
3393         if (event->parent)
3394                 event = event->parent;
3395
3396         return task_pid_nr_ns(p, event->ns);
3397 }
3398
3399 static void perf_output_read_one(struct perf_output_handle *handle,
3400                                  struct perf_event *event)
3401 {
3402         u64 read_format = event->attr.read_format;
3403         u64 values[4];
3404         int n = 0;
3405
3406         values[n++] = perf_event_count(event);
3407         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
3408                 values[n++] = event->total_time_enabled +
3409                         atomic64_read(&event->child_total_time_enabled);
3410         }
3411         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
3412                 values[n++] = event->total_time_running +
3413                         atomic64_read(&event->child_total_time_running);
3414         }
3415         if (read_format & PERF_FORMAT_ID)
3416                 values[n++] = primary_event_id(event);
3417
3418         perf_output_copy(handle, values, n * sizeof(u64));
3419 }
3420
3421 /*
3422  * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
3423  */
3424 static void perf_output_read_group(struct perf_output_handle *handle,
3425                             struct perf_event *event)
3426 {
3427         struct perf_event *leader = event->group_leader, *sub;
3428         u64 read_format = event->attr.read_format;
3429         u64 values[5];
3430         int n = 0;
3431
3432         values[n++] = 1 + leader->nr_siblings;
3433
3434         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3435                 values[n++] = leader->total_time_enabled;
3436
3437         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3438                 values[n++] = leader->total_time_running;
3439
3440         if (leader != event)
3441                 leader->pmu->read(leader);
3442
3443         values[n++] = perf_event_count(leader);
3444         if (read_format & PERF_FORMAT_ID)
3445                 values[n++] = primary_event_id(leader);
3446
3447         perf_output_copy(handle, values, n * sizeof(u64));
3448
3449         list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3450                 n = 0;
3451
3452                 if (sub != event)
3453                         sub->pmu->read(sub);
3454
3455                 values[n++] = perf_event_count(sub);
3456                 if (read_format & PERF_FORMAT_ID)
3457                         values[n++] = primary_event_id(sub);
3458
3459                 perf_output_copy(handle, values, n * sizeof(u64));
3460         }
3461 }
3462
3463 static void perf_output_read(struct perf_output_handle *handle,
3464                              struct perf_event *event)
3465 {
3466         if (event->attr.read_format & PERF_FORMAT_GROUP)
3467                 perf_output_read_group(handle, event);
3468         else
3469                 perf_output_read_one(handle, event);
3470 }
3471
3472 void perf_output_sample(struct perf_output_handle *handle,
3473                         struct perf_event_header *header,
3474                         struct perf_sample_data *data,
3475                         struct perf_event *event)
3476 {
3477         u64 sample_type = data->type;
3478
3479         perf_output_put(handle, *header);
3480
3481         if (sample_type & PERF_SAMPLE_IP)
3482                 perf_output_put(handle, data->ip);
3483
3484         if (sample_type & PERF_SAMPLE_TID)
3485                 perf_output_put(handle, data->tid_entry);
3486
3487         if (sample_type & PERF_SAMPLE_TIME)
3488                 perf_output_put(handle, data->time);
3489
3490         if (sample_type & PERF_SAMPLE_ADDR)
3491                 perf_output_put(handle, data->addr);
3492
3493         if (sample_type & PERF_SAMPLE_ID)
3494                 perf_output_put(handle, data->id);
3495
3496         if (sample_type & PERF_SAMPLE_STREAM_ID)
3497                 perf_output_put(handle, data->stream_id);
3498
3499         if (sample_type & PERF_SAMPLE_CPU)
3500                 perf_output_put(handle, data->cpu_entry);
3501
3502         if (sample_type & PERF_SAMPLE_PERIOD)
3503                 perf_output_put(handle, data->period);
3504
3505         if (sample_type & PERF_SAMPLE_READ)
3506                 perf_output_read(handle, event);
3507
3508         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
3509                 if (data->callchain) {
3510                         int size = 1;
3511
3512                         if (data->callchain)
3513                                 size += data->callchain->nr;
3514
3515                         size *= sizeof(u64);
3516
3517                         perf_output_copy(handle, data->callchain, size);
3518                 } else {
3519                         u64 nr = 0;
3520                         perf_output_put(handle, nr);
3521                 }
3522         }
3523
3524         if (sample_type & PERF_SAMPLE_RAW) {
3525                 if (data->raw) {
3526                         perf_output_put(handle, data->raw->size);
3527                         perf_output_copy(handle, data->raw->data,
3528                                          data->raw->size);
3529                 } else {
3530                         struct {
3531                                 u32     size;
3532                                 u32     data;
3533                         } raw = {
3534                                 .size = sizeof(u32),
3535                                 .data = 0,
3536                         };
3537                         perf_output_put(handle, raw);
3538                 }
3539         }
3540 }
3541
3542 void perf_prepare_sample(struct perf_event_header *header,
3543                          struct perf_sample_data *data,
3544                          struct perf_event *event,
3545                          struct pt_regs *regs)
3546 {
3547         u64 sample_type = event->attr.sample_type;
3548
3549         data->type = sample_type;
3550
3551         header->type = PERF_RECORD_SAMPLE;
3552         header->size = sizeof(*header);
3553
3554         header->misc = 0;
3555         header->misc |= perf_misc_flags(regs);
3556
3557         if (sample_type & PERF_SAMPLE_IP) {
3558                 data->ip = perf_instruction_pointer(regs);
3559
3560                 header->size += sizeof(data->ip);
3561         }
3562
3563         if (sample_type & PERF_SAMPLE_TID) {
3564                 /* namespace issues */
3565                 data->tid_entry.pid = perf_event_pid(event, current);
3566                 data->tid_entry.tid = perf_event_tid(event, current);
3567
3568                 header->size += sizeof(data->tid_entry);
3569         }
3570
3571         if (sample_type & PERF_SAMPLE_TIME) {
3572                 data->time = perf_clock();
3573
3574                 header->size += sizeof(data->time);
3575         }
3576
3577         if (sample_type & PERF_SAMPLE_ADDR)
3578                 header->size += sizeof(data->addr);
3579
3580         if (sample_type & PERF_SAMPLE_ID) {
3581                 data->id = primary_event_id(event);
3582
3583                 header->size += sizeof(data->id);
3584         }
3585
3586         if (sample_type & PERF_SAMPLE_STREAM_ID) {
3587                 data->stream_id = event->id;
3588
3589                 header->size += sizeof(data->stream_id);
3590         }
3591
3592         if (sample_type & PERF_SAMPLE_CPU) {
3593                 data->cpu_entry.cpu             = raw_smp_processor_id();
3594                 data->cpu_entry.reserved        = 0;
3595
3596                 header->size += sizeof(data->cpu_entry);
3597         }
3598
3599         if (sample_type & PERF_SAMPLE_PERIOD)
3600                 header->size += sizeof(data->period);
3601
3602         if (sample_type & PERF_SAMPLE_READ)
3603                 header->size += perf_event_read_size(event);
3604
3605         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
3606                 int size = 1;
3607
3608                 data->callchain = perf_callchain(regs);
3609
3610                 if (data->callchain)
3611                         size += data->callchain->nr;
3612
3613                 header->size += size * sizeof(u64);
3614         }
3615
3616         if (sample_type & PERF_SAMPLE_RAW) {
3617                 int size = sizeof(u32);
3618
3619                 if (data->raw)
3620                         size += data->raw->size;
3621                 else
3622                         size += sizeof(u32);
3623
3624                 WARN_ON_ONCE(size & (sizeof(u64)-1));
3625                 header->size += size;
3626         }
3627 }
3628
3629 static void perf_event_output(struct perf_event *event, int nmi,
3630                                 struct perf_sample_data *data,
3631                                 struct pt_regs *regs)
3632 {
3633         struct perf_output_handle handle;
3634         struct perf_event_header header;
3635
3636         /* protect the callchain buffers */
3637         rcu_read_lock();
3638
3639         perf_prepare_sample(&header, data, event, regs);
3640
3641         if (perf_output_begin(&handle, event, header.size, nmi, 1))
3642                 goto exit;
3643
3644         perf_output_sample(&handle, &header, data, event);
3645
3646         perf_output_end(&handle);
3647
3648 exit:
3649         rcu_read_unlock();
3650 }
3651
3652 /*
3653  * read event_id
3654  */
3655
3656 struct perf_read_event {
3657         struct perf_event_header        header;
3658
3659         u32                             pid;
3660         u32                             tid;
3661 };
3662
3663 static void
3664 perf_event_read_event(struct perf_event *event,
3665                         struct task_struct *task)
3666 {
3667         struct perf_output_handle handle;
3668         struct perf_read_event read_event = {
3669                 .header = {
3670                         .type = PERF_RECORD_READ,
3671                         .misc = 0,
3672                         .size = sizeof(read_event) + perf_event_read_size(event),
3673                 },
3674                 .pid = perf_event_pid(event, task),
3675                 .tid = perf_event_tid(event, task),
3676         };
3677         int ret;
3678
3679         ret = perf_output_begin(&handle, event, read_event.header.size, 0, 0);
3680         if (ret)
3681                 return;
3682
3683         perf_output_put(&handle, read_event);
3684         perf_output_read(&handle, event);
3685
3686         perf_output_end(&handle);
3687 }
3688
3689 /*
3690  * task tracking -- fork/exit
3691  *
3692  * enabled by: attr.comm | attr.mmap | attr.mmap_data | attr.task
3693  */
3694
3695 struct perf_task_event {
3696         struct task_struct              *task;
3697         struct perf_event_context       *task_ctx;
3698
3699         struct {
3700                 struct perf_event_header        header;
3701
3702                 u32                             pid;
3703                 u32                             ppid;
3704                 u32                             tid;
3705                 u32                             ptid;
3706                 u64                             time;
3707         } event_id;
3708 };
3709
3710 static void perf_event_task_output(struct perf_event *event,
3711                                      struct perf_task_event *task_event)
3712 {
3713         struct perf_output_handle handle;
3714         struct task_struct *task = task_event->task;
3715         int size, ret;
3716
3717         size  = task_event->event_id.header.size;
3718         ret = perf_output_begin(&handle, event, size, 0, 0);
3719
3720         if (ret)
3721                 return;
3722
3723         task_event->event_id.pid = perf_event_pid(event, task);
3724         task_event->event_id.ppid = perf_event_pid(event, current);
3725
3726         task_event->event_id.tid = perf_event_tid(event, task);
3727         task_event->event_id.ptid = perf_event_tid(event, current);
3728
3729         perf_output_put(&handle, task_event->event_id);
3730
3731         perf_output_end(&handle);
3732 }
3733
3734 static int perf_event_task_match(struct perf_event *event)
3735 {
3736         if (event->state < PERF_EVENT_STATE_INACTIVE)
3737                 return 0;
3738
3739         if (event->cpu != -1 && event->cpu != smp_processor_id())
3740                 return 0;
3741
3742         if (event->attr.comm || event->attr.mmap ||
3743             event->attr.mmap_data || event->attr.task)
3744                 return 1;
3745
3746         return 0;
3747 }
3748
3749 static void perf_event_task_ctx(struct perf_event_context *ctx,
3750                                   struct perf_task_event *task_event)
3751 {
3752         struct perf_event *event;
3753
3754         list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3755                 if (perf_event_task_match(event))
3756                         perf_event_task_output(event, task_event);
3757         }
3758 }
3759
3760 static void perf_event_task_event(struct perf_task_event *task_event)
3761 {
3762         struct perf_cpu_context *cpuctx;
3763         struct perf_event_context *ctx;
3764         struct pmu *pmu;
3765         int ctxn;
3766
3767         rcu_read_lock();
3768         list_for_each_entry_rcu(pmu, &pmus, entry) {
3769                 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
3770                 perf_event_task_ctx(&cpuctx->ctx, task_event);
3771
3772                 ctx = task_event->task_ctx;
3773                 if (!ctx) {
3774                         ctxn = pmu->task_ctx_nr;
3775                         if (ctxn < 0)
3776                                 goto next;
3777                         ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
3778                 }
3779                 if (ctx)
3780                         perf_event_task_ctx(ctx, task_event);
3781 next:
3782                 put_cpu_ptr(pmu->pmu_cpu_context);
3783         }
3784         rcu_read_unlock();
3785 }
3786
3787 static void perf_event_task(struct task_struct *task,
3788                               struct perf_event_context *task_ctx,
3789                               int new)
3790 {
3791         struct perf_task_event task_event;
3792
3793         if (!atomic_read(&nr_comm_events) &&
3794             !atomic_read(&nr_mmap_events) &&
3795             !atomic_read(&nr_task_events))
3796                 return;
3797
3798         task_event = (struct perf_task_event){
3799                 .task     = task,
3800                 .task_ctx = task_ctx,
3801                 .event_id    = {
3802                         .header = {
3803                                 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
3804                                 .misc = 0,
3805                                 .size = sizeof(task_event.event_id),
3806                         },
3807                         /* .pid  */
3808                         /* .ppid */
3809                         /* .tid  */
3810                         /* .ptid */
3811                         .time = perf_clock(),
3812                 },
3813         };
3814
3815         perf_event_task_event(&task_event);
3816 }
3817
3818 void perf_event_fork(struct task_struct *task)
3819 {
3820         perf_event_task(task, NULL, 1);
3821 }
3822
3823 /*
3824  * comm tracking
3825  */
3826
3827 struct perf_comm_event {
3828         struct task_struct      *task;
3829         char                    *comm;
3830         int                     comm_size;
3831
3832         struct {
3833                 struct perf_event_header        header;
3834
3835                 u32                             pid;
3836                 u32                             tid;
3837         } event_id;
3838 };
3839
3840 static void perf_event_comm_output(struct perf_event *event,
3841                                      struct perf_comm_event *comm_event)
3842 {
3843         struct perf_output_handle handle;
3844         int size = comm_event->event_id.header.size;
3845         int ret = perf_output_begin(&handle, event, size, 0, 0);
3846
3847         if (ret)
3848                 return;
3849
3850         comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
3851         comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
3852
3853         perf_output_put(&handle, comm_event->event_id);
3854         perf_output_copy(&handle, comm_event->comm,
3855                                    comm_event->comm_size);
3856         perf_output_end(&handle);
3857 }
3858
3859 static int perf_event_comm_match(struct perf_event *event)
3860 {
3861         if (event->state < PERF_EVENT_STATE_INACTIVE)
3862                 return 0;
3863
3864         if (event->cpu != -1 && event->cpu != smp_processor_id())
3865                 return 0;
3866
3867         if (event->attr.comm)
3868                 return 1;
3869
3870         return 0;
3871 }
3872
3873 static void perf_event_comm_ctx(struct perf_event_context *ctx,
3874                                   struct perf_comm_event *comm_event)
3875 {
3876         struct perf_event *event;
3877
3878         list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3879                 if (perf_event_comm_match(event))
3880                         perf_event_comm_output(event, comm_event);
3881         }
3882 }
3883
3884 static void perf_event_comm_event(struct perf_comm_event *comm_event)
3885 {
3886         struct perf_cpu_context *cpuctx;
3887         struct perf_event_context *ctx;
3888         char comm[TASK_COMM_LEN];
3889         unsigned int size;
3890         struct pmu *pmu;
3891         int ctxn;
3892
3893         memset(comm, 0, sizeof(comm));
3894         strlcpy(comm, comm_event->task->comm, sizeof(comm));
3895         size = ALIGN(strlen(comm)+1, sizeof(u64));
3896
3897         comm_event->comm = comm;
3898         comm_event->comm_size = size;
3899
3900         comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
3901
3902         rcu_read_lock();
3903         list_for_each_entry_rcu(pmu, &pmus, entry) {
3904                 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
3905                 perf_event_comm_ctx(&cpuctx->ctx, comm_event);
3906
3907                 ctxn = pmu->task_ctx_nr;
3908                 if (ctxn < 0)
3909                         goto next;
3910
3911                 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
3912                 if (ctx)
3913                         perf_event_comm_ctx(ctx, comm_event);
3914 next:
3915                 put_cpu_ptr(pmu->pmu_cpu_context);
3916         }
3917         rcu_read_unlock();
3918 }
3919
3920 void perf_event_comm(struct task_struct *task)
3921 {
3922         struct perf_comm_event comm_event;
3923         struct perf_event_context *ctx;
3924         int ctxn;
3925
3926         for_each_task_context_nr(ctxn) {
3927                 ctx = task->perf_event_ctxp[ctxn];
3928                 if (!ctx)
3929                         continue;
3930
3931                 perf_event_enable_on_exec(ctx);
3932         }
3933
3934         if (!atomic_read(&nr_comm_events))
3935                 return;
3936
3937         comm_event = (struct perf_comm_event){
3938                 .task   = task,
3939                 /* .comm      */
3940                 /* .comm_size */
3941                 .event_id  = {
3942                         .header = {
3943                                 .type = PERF_RECORD_COMM,
3944                                 .misc = 0,
3945                                 /* .size */
3946                         },
3947                         /* .pid */
3948                         /* .tid */
3949                 },
3950         };
3951
3952         perf_event_comm_event(&comm_event);
3953 }
3954
3955 /*
3956  * mmap tracking
3957  */
3958
3959 struct perf_mmap_event {
3960         struct vm_area_struct   *vma;
3961
3962         const char              *file_name;
3963         int                     file_size;
3964
3965         struct {
3966                 struct perf_event_header        header;
3967
3968                 u32                             pid;
3969                 u32                             tid;
3970                 u64                             start;
3971                 u64                             len;
3972                 u64                             pgoff;
3973         } event_id;
3974 };
3975
3976 static void perf_event_mmap_output(struct perf_event *event,
3977                                      struct perf_mmap_event *mmap_event)
3978 {
3979         struct perf_output_handle handle;
3980         int size = mmap_event->event_id.header.size;
3981         int ret = perf_output_begin(&handle, event, size, 0, 0);
3982
3983         if (ret)
3984                 return;
3985
3986         mmap_event->event_id.pid = perf_event_pid(event, current);
3987         mmap_event->event_id.tid = perf_event_tid(event, current);
3988
3989         perf_output_put(&handle, mmap_event->event_id);
3990         perf_output_copy(&handle, mmap_event->file_name,
3991                                    mmap_event->file_size);
3992         perf_output_end(&handle);
3993 }
3994
3995 static int perf_event_mmap_match(struct perf_event *event,
3996                                    struct perf_mmap_event *mmap_event,
3997                                    int executable)
3998 {
3999         if (event->state < PERF_EVENT_STATE_INACTIVE)
4000                 return 0;
4001
4002         if (event->cpu != -1 && event->cpu != smp_processor_id())
4003                 return 0;
4004
4005         if ((!executable && event->attr.mmap_data) ||
4006             (executable && event->attr.mmap))
4007                 return 1;
4008
4009         return 0;
4010 }
4011
4012 static void perf_event_mmap_ctx(struct perf_event_context *ctx,
4013                                   struct perf_mmap_event *mmap_event,
4014                                   int executable)
4015 {
4016         struct perf_event *event;
4017
4018         list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4019                 if (perf_event_mmap_match(event, mmap_event, executable))
4020                         perf_event_mmap_output(event, mmap_event);
4021         }
4022 }
4023
4024 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
4025 {
4026         struct perf_cpu_context *cpuctx;
4027         struct perf_event_context *ctx;
4028         struct vm_area_struct *vma = mmap_event->vma;
4029         struct file *file = vma->vm_file;
4030         unsigned int size;
4031         char tmp[16];
4032         char *buf = NULL;
4033         const char *name;
4034         struct pmu *pmu;
4035         int ctxn;
4036
4037         memset(tmp, 0, sizeof(tmp));
4038
4039         if (file) {
4040                 /*
4041                  * d_path works from the end of the buffer backwards, so we
4042                  * need to add enough zero bytes after the string to handle
4043                  * the 64bit alignment we do later.
4044                  */
4045                 buf = kzalloc(PATH_MAX + sizeof(u64), GFP_KERNEL);
4046                 if (!buf) {
4047                         name = strncpy(tmp, "//enomem", sizeof(tmp));
4048                         goto got_name;
4049                 }
4050                 name = d_path(&file->f_path, buf, PATH_MAX);
4051                 if (IS_ERR(name)) {
4052                         name = strncpy(tmp, "//toolong", sizeof(tmp));
4053                         goto got_name;
4054                 }
4055         } else {
4056                 if (arch_vma_name(mmap_event->vma)) {
4057                         name = strncpy(tmp, arch_vma_name(mmap_event->vma),
4058                                        sizeof(tmp));
4059                         goto got_name;
4060                 }
4061
4062                 if (!vma->vm_mm) {
4063                         name = strncpy(tmp, "[vdso]", sizeof(tmp));
4064                         goto got_name;
4065                 } else if (vma->vm_start <= vma->vm_mm->start_brk &&
4066                                 vma->vm_end >= vma->vm_mm->brk) {
4067                         name = strncpy(tmp, "[heap]", sizeof(tmp));
4068                         goto got_name;
4069                 } else if (vma->vm_start <= vma->vm_mm->start_stack &&
4070                                 vma->vm_end >= vma->vm_mm->start_stack) {
4071                         name = strncpy(tmp, "[stack]", sizeof(tmp));
4072                         goto got_name;
4073                 }
4074
4075                 name = strncpy(tmp, "//anon", sizeof(tmp));
4076                 goto got_name;
4077         }
4078
4079 got_name:
4080         size = ALIGN(strlen(name)+1, sizeof(u64));
4081
4082         mmap_event->file_name = name;
4083         mmap_event->file_size = size;
4084
4085         mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
4086
4087         rcu_read_lock();
4088         list_for_each_entry_rcu(pmu, &pmus, entry) {
4089                 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4090                 perf_event_mmap_ctx(&cpuctx->ctx, mmap_event,
4091                                         vma->vm_flags & VM_EXEC);
4092
4093                 ctxn = pmu->task_ctx_nr;
4094                 if (ctxn < 0)
4095                         goto next;
4096
4097                 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4098                 if (ctx) {
4099                         perf_event_mmap_ctx(ctx, mmap_event,
4100                                         vma->vm_flags & VM_EXEC);
4101                 }
4102 next:
4103                 put_cpu_ptr(pmu->pmu_cpu_context);
4104         }
4105         rcu_read_unlock();
4106
4107         kfree(buf);
4108 }
4109
4110 void perf_event_mmap(struct vm_area_struct *vma)
4111 {
4112         struct perf_mmap_event mmap_event;
4113
4114         if (!atomic_read(&nr_mmap_events))
4115                 return;
4116
4117         mmap_event = (struct perf_mmap_event){
4118                 .vma    = vma,
4119                 /* .file_name */
4120                 /* .file_size */
4121                 .event_id  = {
4122                         .header = {
4123                                 .type = PERF_RECORD_MMAP,
4124                                 .misc = PERF_RECORD_MISC_USER,
4125                                 /* .size */
4126                         },
4127                         /* .pid */
4128                         /* .tid */
4129                         .start  = vma->vm_start,
4130                         .len    = vma->vm_end - vma->vm_start,
4131                         .pgoff  = (u64)vma->vm_pgoff << PAGE_SHIFT,
4132                 },
4133         };
4134
4135         perf_event_mmap_event(&mmap_event);
4136 }
4137
4138 /*
4139  * IRQ throttle logging
4140  */
4141
4142 static void perf_log_throttle(struct perf_event *event, int enable)
4143 {
4144         struct perf_output_handle handle;
4145         int ret;
4146
4147         struct {
4148                 struct perf_event_header        header;
4149                 u64                             time;
4150                 u64                             id;
4151                 u64                             stream_id;
4152         } throttle_event = {
4153                 .header = {
4154                         .type = PERF_RECORD_THROTTLE,
4155                         .misc = 0,
4156                         .size = sizeof(throttle_event),
4157                 },
4158                 .time           = perf_clock(),
4159                 .id             = primary_event_id(event),
4160                 .stream_id      = event->id,
4161         };
4162
4163         if (enable)
4164                 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
4165
4166         ret = perf_output_begin(&handle, event, sizeof(throttle_event), 1, 0);
4167         if (ret)
4168                 return;
4169
4170         perf_output_put(&handle, throttle_event);
4171         perf_output_end(&handle);
4172 }
4173
4174 /*
4175  * Generic event overflow handling, sampling.
4176  */
4177
4178 static int __perf_event_overflow(struct perf_event *event, int nmi,
4179                                    int throttle, struct perf_sample_data *data,
4180                                    struct pt_regs *regs)
4181 {
4182         int events = atomic_read(&event->event_limit);
4183         struct hw_perf_event *hwc = &event->hw;
4184         int ret = 0;
4185
4186         if (!throttle) {
4187                 hwc->interrupts++;
4188         } else {
4189                 if (hwc->interrupts != MAX_INTERRUPTS) {
4190                         hwc->interrupts++;
4191                         if (HZ * hwc->interrupts >
4192                                         (u64)sysctl_perf_event_sample_rate) {
4193                                 hwc->interrupts = MAX_INTERRUPTS;
4194                                 perf_log_throttle(event, 0);
4195                                 ret = 1;
4196                         }
4197                 } else {
4198                         /*
4199                          * Keep re-disabling events even though on the previous
4200                          * pass we disabled it - just in case we raced with a
4201                          * sched-in and the event got enabled again:
4202                          */
4203                         ret = 1;
4204                 }
4205         }
4206
4207         if (event->attr.freq) {
4208                 u64 now = perf_clock();
4209                 s64 delta = now - hwc->freq_time_stamp;
4210
4211                 hwc->freq_time_stamp = now;
4212
4213                 if (delta > 0 && delta < 2*TICK_NSEC)
4214                         perf_adjust_period(event, delta, hwc->last_period);
4215         }
4216
4217         /*
4218          * XXX event_limit might not quite work as expected on inherited
4219          * events
4220          */
4221
4222         event->pending_kill = POLL_IN;
4223         if (events && atomic_dec_and_test(&event->event_limit)) {
4224                 ret = 1;
4225                 event->pending_kill = POLL_HUP;
4226                 if (nmi) {
4227                         event->pending_disable = 1;
4228                         irq_work_queue(&event->pending);
4229                 } else
4230                         perf_event_disable(event);
4231         }
4232
4233         if (event->overflow_handler)
4234                 event->overflow_handler(event, nmi, data, regs);
4235         else
4236                 perf_event_output(event, nmi, data, regs);
4237
4238         return ret;
4239 }
4240
4241 int perf_event_overflow(struct perf_event *event, int nmi,
4242                           struct perf_sample_data *data,
4243                           struct pt_regs *regs)
4244 {
4245         return __perf_event_overflow(event, nmi, 1, data, regs);
4246 }
4247
4248 /*
4249  * Generic software event infrastructure
4250  */
4251
4252 struct swevent_htable {
4253         struct swevent_hlist            *swevent_hlist;
4254         struct mutex                    hlist_mutex;
4255         int                             hlist_refcount;
4256
4257         /* Recursion avoidance in each contexts */
4258         int                             recursion[PERF_NR_CONTEXTS];
4259 };
4260
4261 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
4262
4263 /*
4264  * We directly increment event->count and keep a second value in
4265  * event->hw.period_left to count intervals. This period event
4266  * is kept in the range [-sample_period, 0] so that we can use the
4267  * sign as trigger.
4268  */
4269
4270 static u64 perf_swevent_set_period(struct perf_event *event)
4271 {
4272         struct hw_perf_event *hwc = &event->hw;
4273         u64 period = hwc->last_period;
4274         u64 nr, offset;
4275         s64 old, val;
4276
4277         hwc->last_period = hwc->sample_period;
4278
4279 again:
4280         old = val = local64_read(&hwc->period_left);
4281         if (val < 0)
4282                 return 0;
4283
4284         nr = div64_u64(period + val, period);
4285         offset = nr * period;
4286         val -= offset;
4287         if (local64_cmpxchg(&hwc->period_left, old, val) != old)
4288                 goto again;
4289
4290         return nr;
4291 }
4292
4293 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
4294                                     int nmi, struct perf_sample_data *data,
4295                                     struct pt_regs *regs)
4296 {
4297         struct hw_perf_event *hwc = &event->hw;
4298         int throttle = 0;
4299
4300         data->period = event->hw.last_period;
4301         if (!overflow)
4302                 overflow = perf_swevent_set_period(event);
4303
4304         if (hwc->interrupts == MAX_INTERRUPTS)
4305                 return;
4306
4307         for (; overflow; overflow--) {
4308                 if (__perf_event_overflow(event, nmi, throttle,
4309                                             data, regs)) {
4310                         /*
4311                          * We inhibit the overflow from happening when
4312                          * hwc->interrupts == MAX_INTERRUPTS.
4313                          */
4314                         break;
4315                 }
4316                 throttle = 1;
4317         }
4318 }
4319
4320 static void perf_swevent_event(struct perf_event *event, u64 nr,
4321                                int nmi, struct perf_sample_data *data,
4322                                struct pt_regs *regs)
4323 {
4324         struct hw_perf_event *hwc = &event->hw;
4325
4326         local64_add(nr, &event->count);
4327
4328         if (!regs)
4329                 return;
4330
4331         if (!hwc->sample_period)
4332                 return;
4333
4334         if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
4335                 return perf_swevent_overflow(event, 1, nmi, data, regs);
4336
4337         if (local64_add_negative(nr, &hwc->period_left))
4338                 return;
4339
4340         perf_swevent_overflow(event, 0, nmi, data, regs);
4341 }
4342
4343 static int perf_exclude_event(struct perf_event *event,
4344                               struct pt_regs *regs)
4345 {
4346         if (event->hw.state & PERF_HES_STOPPED)
4347                 return 0;
4348
4349         if (regs) {
4350                 if (event->attr.exclude_user && user_mode(regs))
4351                         return 1;
4352
4353                 if (event->attr.exclude_kernel && !user_mode(regs))
4354                         return 1;
4355         }
4356
4357         return 0;
4358 }
4359
4360 static int perf_swevent_match(struct perf_event *event,
4361                                 enum perf_type_id type,
4362                                 u32 event_id,
4363                                 struct perf_sample_data *data,
4364                                 struct pt_regs *regs)
4365 {
4366         if (event->attr.type != type)
4367                 return 0;
4368
4369         if (event->attr.config != event_id)
4370                 return 0;
4371
4372         if (perf_exclude_event(event, regs))
4373                 return 0;
4374
4375         return 1;
4376 }
4377
4378 static inline u64 swevent_hash(u64 type, u32 event_id)
4379 {
4380         u64 val = event_id | (type << 32);
4381
4382         return hash_64(val, SWEVENT_HLIST_BITS);
4383 }
4384
4385 static inline struct hlist_head *
4386 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
4387 {
4388         u64 hash = swevent_hash(type, event_id);
4389
4390         return &hlist->heads[hash];
4391 }
4392
4393 /* For the read side: events when they trigger */
4394 static inline struct hlist_head *
4395 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
4396 {
4397         struct swevent_hlist *hlist;
4398
4399         hlist = rcu_dereference(swhash->swevent_hlist);
4400         if (!hlist)
4401                 return NULL;
4402
4403         return __find_swevent_head(hlist, type, event_id);
4404 }
4405
4406 /* For the event head insertion and removal in the hlist */
4407 static inline struct hlist_head *
4408 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
4409 {
4410         struct swevent_hlist *hlist;
4411         u32 event_id = event->attr.config;
4412         u64 type = event->attr.type;
4413
4414         /*
4415          * Event scheduling is always serialized against hlist allocation
4416          * and release. Which makes the protected version suitable here.
4417          * The context lock guarantees that.
4418          */
4419         hlist = rcu_dereference_protected(swhash->swevent_hlist,
4420                                           lockdep_is_held(&event->ctx->lock));
4421         if (!hlist)
4422                 return NULL;
4423
4424         return __find_swevent_head(hlist, type, event_id);
4425 }
4426
4427 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
4428                                     u64 nr, int nmi,
4429                                     struct perf_sample_data *data,
4430                                     struct pt_regs *regs)
4431 {
4432         struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
4433         struct perf_event *event;
4434         struct hlist_node *node;
4435         struct hlist_head *head;
4436
4437         rcu_read_lock();
4438         head = find_swevent_head_rcu(swhash, type, event_id);
4439         if (!head)
4440                 goto end;
4441
4442         hlist_for_each_entry_rcu(event, node, head, hlist_entry) {
4443                 if (perf_swevent_match(event, type, event_id, data, regs))
4444                         perf_swevent_event(event, nr, nmi, data, regs);
4445         }
4446 end:
4447         rcu_read_unlock();
4448 }
4449
4450 int perf_swevent_get_recursion_context(void)
4451 {
4452         struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
4453
4454         return get_recursion_context(swhash->recursion);
4455 }
4456 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
4457
4458 void inline perf_swevent_put_recursion_context(int rctx)
4459 {
4460         struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
4461
4462         put_recursion_context(swhash->recursion, rctx);
4463 }
4464
4465 void __perf_sw_event(u32 event_id, u64 nr, int nmi,
4466                             struct pt_regs *regs, u64 addr)
4467 {
4468         struct perf_sample_data data;
4469         int rctx;
4470
4471         preempt_disable_notrace();
4472         rctx = perf_swevent_get_recursion_context();
4473         if (rctx < 0)
4474                 return;
4475
4476         perf_sample_data_init(&data, addr);
4477
4478         do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, nmi, &data, regs);
4479
4480         perf_swevent_put_recursion_context(rctx);
4481         preempt_enable_notrace();
4482 }
4483
4484 static void perf_swevent_read(struct perf_event *event)
4485 {
4486 }
4487
4488 static int perf_swevent_add(struct perf_event *event, int flags)
4489 {
4490         struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
4491         struct hw_perf_event *hwc = &event->hw;
4492         struct hlist_head *head;
4493
4494         if (hwc->sample_period) {
4495                 hwc->last_period = hwc->sample_period;
4496                 perf_swevent_set_period(event);
4497         }
4498
4499         hwc->state = !(flags & PERF_EF_START);
4500
4501         head = find_swevent_head(swhash, event);
4502         if (WARN_ON_ONCE(!head))
4503                 return -EINVAL;
4504
4505         hlist_add_head_rcu(&event->hlist_entry, head);
4506
4507         return 0;
4508 }
4509
4510 static void perf_swevent_del(struct perf_event *event, int flags)
4511 {
4512         hlist_del_rcu(&event->hlist_entry);
4513 }
4514
4515 static void perf_swevent_start(struct perf_event *event, int flags)
4516 {
4517         event->hw.state = 0;
4518 }
4519
4520 static void perf_swevent_stop(struct perf_event *event, int flags)
4521 {
4522         event->hw.state = PERF_HES_STOPPED;
4523 }
4524
4525 /* Deref the hlist from the update side */
4526 static inline struct swevent_hlist *
4527 swevent_hlist_deref(struct swevent_htable *swhash)
4528 {
4529         return rcu_dereference_protected(swhash->swevent_hlist,
4530                                          lockdep_is_held(&swhash->hlist_mutex));
4531 }
4532
4533 static void swevent_hlist_release_rcu(struct rcu_head *rcu_head)
4534 {
4535         struct swevent_hlist *hlist;
4536
4537         hlist = container_of(rcu_head, struct swevent_hlist, rcu_head);
4538         kfree(hlist);
4539 }
4540
4541 static void swevent_hlist_release(struct swevent_htable *swhash)
4542 {
4543         struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
4544
4545         if (!hlist)
4546                 return;
4547
4548         rcu_assign_pointer(swhash->swevent_hlist, NULL);
4549         call_rcu(&hlist->rcu_head, swevent_hlist_release_rcu);
4550 }
4551
4552 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
4553 {
4554         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
4555
4556         mutex_lock(&swhash->hlist_mutex);
4557
4558         if (!--swhash->hlist_refcount)
4559                 swevent_hlist_release(swhash);
4560
4561         mutex_unlock(&swhash->hlist_mutex);
4562 }
4563
4564 static void swevent_hlist_put(struct perf_event *event)
4565 {
4566         int cpu;
4567
4568         if (event->cpu != -1) {
4569                 swevent_hlist_put_cpu(event, event->cpu);
4570                 return;
4571         }
4572
4573         for_each_possible_cpu(cpu)
4574                 swevent_hlist_put_cpu(event, cpu);
4575 }
4576
4577 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
4578 {
4579         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
4580         int err = 0;
4581
4582         mutex_lock(&swhash->hlist_mutex);
4583
4584         if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
4585                 struct swevent_hlist *hlist;
4586
4587                 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
4588                 if (!hlist) {
4589                         err = -ENOMEM;
4590                         goto exit;
4591                 }
4592                 rcu_assign_pointer(swhash->swevent_hlist, hlist);
4593         }
4594         swhash->hlist_refcount++;
4595 exit:
4596         mutex_unlock(&swhash->hlist_mutex);
4597
4598         return err;
4599 }
4600
4601 static int swevent_hlist_get(struct perf_event *event)
4602 {
4603         int err;
4604         int cpu, failed_cpu;
4605
4606         if (event->cpu != -1)
4607                 return swevent_hlist_get_cpu(event, event->cpu);
4608
4609         get_online_cpus();
4610         for_each_possible_cpu(cpu) {
4611                 err = swevent_hlist_get_cpu(event, cpu);
4612                 if (err) {
4613                         failed_cpu = cpu;
4614                         goto fail;
4615                 }
4616         }
4617         put_online_cpus();
4618
4619         return 0;
4620 fail:
4621         for_each_possible_cpu(cpu) {
4622                 if (cpu == failed_cpu)
4623                         break;
4624                 swevent_hlist_put_cpu(event, cpu);
4625         }
4626
4627         put_online_cpus();
4628         return err;
4629 }
4630
4631 atomic_t perf_swevent_enabled[PERF_COUNT_SW_MAX];
4632
4633 static void sw_perf_event_destroy(struct perf_event *event)
4634 {
4635         u64 event_id = event->attr.config;
4636
4637         WARN_ON(event->parent);
4638
4639         jump_label_dec(&perf_swevent_enabled[event_id]);
4640         swevent_hlist_put(event);
4641 }
4642
4643 static int perf_swevent_init(struct perf_event *event)
4644 {
4645         int event_id = event->attr.config;
4646
4647         if (event->attr.type != PERF_TYPE_SOFTWARE)
4648                 return -ENOENT;
4649
4650         switch (event_id) {
4651         case PERF_COUNT_SW_CPU_CLOCK:
4652         case PERF_COUNT_SW_TASK_CLOCK:
4653                 return -ENOENT;
4654
4655         default:
4656                 break;
4657         }
4658
4659         if (event_id > PERF_COUNT_SW_MAX)
4660                 return -ENOENT;
4661
4662         if (!event->parent) {
4663                 int err;
4664
4665                 err = swevent_hlist_get(event);
4666                 if (err)
4667                         return err;
4668
4669                 jump_label_inc(&perf_swevent_enabled[event_id]);
4670                 event->destroy = sw_perf_event_destroy;
4671         }
4672
4673         return 0;
4674 }
4675
4676 static struct pmu perf_swevent = {
4677         .task_ctx_nr    = perf_sw_context,
4678
4679         .event_init     = perf_swevent_init,
4680         .add            = perf_swevent_add,
4681         .del            = perf_swevent_del,
4682         .start          = perf_swevent_start,
4683         .stop           = perf_swevent_stop,
4684         .read           = perf_swevent_read,
4685 };
4686
4687 #ifdef CONFIG_EVENT_TRACING
4688
4689 static int perf_tp_filter_match(struct perf_event *event,
4690                                 struct perf_sample_data *data)
4691 {
4692         void *record = data->raw->data;
4693
4694         if (likely(!event->filter) || filter_match_preds(event->filter, record))
4695                 return 1;
4696         return 0;
4697 }
4698
4699 static int perf_tp_event_match(struct perf_event *event,
4700                                 struct perf_sample_data *data,
4701                                 struct pt_regs *regs)
4702 {
4703         /*
4704          * All tracepoints are from kernel-space.
4705          */
4706         if (event->attr.exclude_kernel)
4707                 return 0;
4708
4709         if (!perf_tp_filter_match(event, data))
4710                 return 0;
4711
4712         return 1;
4713 }
4714
4715 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
4716                    struct pt_regs *regs, struct hlist_head *head, int rctx)
4717 {
4718         struct perf_sample_data data;
4719         struct perf_event *event;
4720         struct hlist_node *node;
4721
4722         struct perf_raw_record raw = {
4723                 .size = entry_size,
4724                 .data = record,
4725         };
4726
4727         perf_sample_data_init(&data, addr);
4728         data.raw = &raw;
4729
4730         hlist_for_each_entry_rcu(event, node, head, hlist_entry) {
4731                 if (perf_tp_event_match(event, &data, regs))
4732                         perf_swevent_event(event, count, 1, &data, regs);
4733         }
4734
4735         perf_swevent_put_recursion_context(rctx);
4736 }
4737 EXPORT_SYMBOL_GPL(perf_tp_event);
4738
4739 static void tp_perf_event_destroy(struct perf_event *event)
4740 {
4741         perf_trace_destroy(event);
4742 }
4743
4744 static int perf_tp_event_init(struct perf_event *event)
4745 {
4746         int err;
4747
4748         if (event->attr.type != PERF_TYPE_TRACEPOINT)
4749                 return -ENOENT;
4750
4751         /*
4752          * Raw tracepoint data is a severe data leak, only allow root to
4753          * have these.
4754          */
4755         if ((event->attr.sample_type & PERF_SAMPLE_RAW) &&
4756                         perf_paranoid_tracepoint_raw() &&
4757                         !capable(CAP_SYS_ADMIN))
4758                 return -EPERM;
4759
4760         err = perf_trace_init(event);
4761         if (err)
4762                 return err;
4763
4764         event->destroy = tp_perf_event_destroy;
4765
4766         return 0;
4767 }
4768
4769 static struct pmu perf_tracepoint = {
4770         .task_ctx_nr    = perf_sw_context,
4771
4772         .event_init     = perf_tp_event_init,
4773         .add            = perf_trace_add,
4774         .del            = perf_trace_del,
4775         .start          = perf_swevent_start,
4776         .stop           = perf_swevent_stop,
4777         .read           = perf_swevent_read,
4778 };
4779
4780 static inline void perf_tp_register(void)
4781 {
4782         perf_pmu_register(&perf_tracepoint);
4783 }
4784
4785 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
4786 {
4787         char *filter_str;
4788         int ret;
4789
4790         if (event->attr.type != PERF_TYPE_TRACEPOINT)
4791                 return -EINVAL;
4792
4793         filter_str = strndup_user(arg, PAGE_SIZE);
4794         if (IS_ERR(filter_str))
4795                 return PTR_ERR(filter_str);
4796
4797         ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
4798
4799         kfree(filter_str);
4800         return ret;
4801 }
4802
4803 static void perf_event_free_filter(struct perf_event *event)
4804 {
4805         ftrace_profile_free_filter(event);
4806 }
4807
4808 #else
4809
4810 static inline void perf_tp_register(void)
4811 {
4812 }
4813
4814 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
4815 {
4816         return -ENOENT;
4817 }
4818
4819 static void perf_event_free_filter(struct perf_event *event)
4820 {
4821 }
4822
4823 #endif /* CONFIG_EVENT_TRACING */
4824
4825 #ifdef CONFIG_HAVE_HW_BREAKPOINT
4826 void perf_bp_event(struct perf_event *bp, void *data)
4827 {
4828         struct perf_sample_data sample;
4829         struct pt_regs *regs = data;
4830
4831         perf_sample_data_init(&sample, bp->attr.bp_addr);
4832
4833         if (!bp->hw.state && !perf_exclude_event(bp, regs))
4834                 perf_swevent_event(bp, 1, 1, &sample, regs);
4835 }
4836 #endif
4837
4838 /*
4839  * hrtimer based swevent callback
4840  */
4841
4842 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
4843 {
4844         enum hrtimer_restart ret = HRTIMER_RESTART;
4845         struct perf_sample_data data;
4846         struct pt_regs *regs;
4847         struct perf_event *event;
4848         u64 period;
4849
4850         event = container_of(hrtimer, struct perf_event, hw.hrtimer);
4851         event->pmu->read(event);
4852
4853         perf_sample_data_init(&data, 0);
4854         data.period = event->hw.last_period;
4855         regs = get_irq_regs();
4856
4857         if (regs && !perf_exclude_event(event, regs)) {
4858                 if (!(event->attr.exclude_idle && current->pid == 0))
4859                         if (perf_event_overflow(event, 0, &data, regs))
4860                                 ret = HRTIMER_NORESTART;
4861         }
4862
4863         period = max_t(u64, 10000, event->hw.sample_period);
4864         hrtimer_forward_now(hrtimer, ns_to_ktime(period));
4865
4866         return ret;
4867 }
4868
4869 static void perf_swevent_start_hrtimer(struct perf_event *event)
4870 {
4871         struct hw_perf_event *hwc = &event->hw;
4872
4873         hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
4874         hwc->hrtimer.function = perf_swevent_hrtimer;
4875         if (hwc->sample_period) {
4876                 s64 period = local64_read(&hwc->period_left);
4877
4878                 if (period) {
4879                         if (period < 0)
4880                                 period = 10000;
4881
4882                         local64_set(&hwc->period_left, 0);
4883                 } else {
4884                         period = max_t(u64, 10000, hwc->sample_period);
4885                 }
4886                 __hrtimer_start_range_ns(&hwc->hrtimer,
4887                                 ns_to_ktime(period), 0,
4888                                 HRTIMER_MODE_REL_PINNED, 0);
4889         }
4890 }
4891
4892 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
4893 {
4894         struct hw_perf_event *hwc = &event->hw;
4895
4896         if (hwc->sample_period) {
4897                 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
4898                 local64_set(&hwc->period_left, ktime_to_ns(remaining));
4899
4900                 hrtimer_cancel(&hwc->hrtimer);
4901         }
4902 }
4903
4904 /*
4905  * Software event: cpu wall time clock
4906  */
4907
4908 static void cpu_clock_event_update(struct perf_event *event)
4909 {
4910         s64 prev;
4911         u64 now;
4912
4913         now = local_clock();
4914         prev = local64_xchg(&event->hw.prev_count, now);
4915         local64_add(now - prev, &event->count);
4916 }
4917
4918 static void cpu_clock_event_start(struct perf_event *event, int flags)
4919 {
4920         local64_set(&event->hw.prev_count, local_clock());
4921         perf_swevent_start_hrtimer(event);
4922 }
4923
4924 static void cpu_clock_event_stop(struct perf_event *event, int flags)
4925 {
4926         perf_swevent_cancel_hrtimer(event);
4927         cpu_clock_event_update(event);
4928 }
4929
4930 static int cpu_clock_event_add(struct perf_event *event, int flags)
4931 {
4932         if (flags & PERF_EF_START)
4933                 cpu_clock_event_start(event, flags);
4934
4935         return 0;
4936 }
4937
4938 static void cpu_clock_event_del(struct perf_event *event, int flags)
4939 {
4940         cpu_clock_event_stop(event, flags);
4941 }
4942
4943 static void cpu_clock_event_read(struct perf_event *event)
4944 {
4945         cpu_clock_event_update(event);
4946 }
4947
4948 static int cpu_clock_event_init(struct perf_event *event)
4949 {
4950         if (event->attr.type != PERF_TYPE_SOFTWARE)
4951                 return -ENOENT;
4952
4953         if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
4954                 return -ENOENT;
4955
4956         return 0;
4957 }
4958
4959 static struct pmu perf_cpu_clock = {
4960         .task_ctx_nr    = perf_sw_context,
4961
4962         .event_init     = cpu_clock_event_init,
4963         .add            = cpu_clock_event_add,
4964         .del            = cpu_clock_event_del,
4965         .start          = cpu_clock_event_start,
4966         .stop           = cpu_clock_event_stop,
4967         .read           = cpu_clock_event_read,
4968 };
4969
4970 /*
4971  * Software event: task time clock
4972  */
4973
4974 static void task_clock_event_update(struct perf_event *event, u64 now)
4975 {
4976         u64 prev;
4977         s64 delta;
4978
4979         prev = local64_xchg(&event->hw.prev_count, now);
4980         delta = now - prev;
4981         local64_add(delta, &event->count);
4982 }
4983
4984 static void task_clock_event_start(struct perf_event *event, int flags)
4985 {
4986         local64_set(&event->hw.prev_count, event->ctx->time);
4987         perf_swevent_start_hrtimer(event);
4988 }
4989
4990 static void task_clock_event_stop(struct perf_event *event, int flags)
4991 {
4992         perf_swevent_cancel_hrtimer(event);
4993         task_clock_event_update(event, event->ctx->time);
4994 }
4995
4996 static int task_clock_event_add(struct perf_event *event, int flags)
4997 {
4998         if (flags & PERF_EF_START)
4999                 task_clock_event_start(event, flags);
5000
5001         return 0;
5002 }
5003
5004 static void task_clock_event_del(struct perf_event *event, int flags)
5005 {
5006         task_clock_event_stop(event, PERF_EF_UPDATE);
5007 }
5008
5009 static void task_clock_event_read(struct perf_event *event)
5010 {
5011         u64 time;
5012
5013         if (!in_nmi()) {
5014                 update_context_time(event->ctx);
5015                 time = event->ctx->time;
5016         } else {
5017                 u64 now = perf_clock();
5018                 u64 delta = now - event->ctx->timestamp;
5019                 time = event->ctx->time + delta;
5020         }
5021
5022         task_clock_event_update(event, time);
5023 }
5024
5025 static int task_clock_event_init(struct perf_event *event)
5026 {
5027         if (event->attr.type != PERF_TYPE_SOFTWARE)
5028                 return -ENOENT;
5029
5030         if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
5031                 return -ENOENT;
5032
5033         return 0;
5034 }
5035
5036 static struct pmu perf_task_clock = {
5037         .task_ctx_nr    = perf_sw_context,
5038
5039         .event_init     = task_clock_event_init,
5040         .add            = task_clock_event_add,
5041         .del            = task_clock_event_del,
5042         .start          = task_clock_event_start,
5043         .stop           = task_clock_event_stop,
5044         .read           = task_clock_event_read,
5045 };
5046
5047 static void perf_pmu_nop_void(struct pmu *pmu)
5048 {
5049 }
5050
5051 static int perf_pmu_nop_int(struct pmu *pmu)
5052 {
5053         return 0;
5054 }
5055
5056 static void perf_pmu_start_txn(struct pmu *pmu)
5057 {
5058         perf_pmu_disable(pmu);
5059 }
5060
5061 static int perf_pmu_commit_txn(struct pmu *pmu)
5062 {
5063         perf_pmu_enable(pmu);
5064         return 0;
5065 }
5066
5067 static void perf_pmu_cancel_txn(struct pmu *pmu)
5068 {
5069         perf_pmu_enable(pmu);
5070 }
5071
5072 /*
5073  * Ensures all contexts with the same task_ctx_nr have the same
5074  * pmu_cpu_context too.
5075  */
5076 static void *find_pmu_context(int ctxn)
5077 {
5078         struct pmu *pmu;
5079
5080         if (ctxn < 0)
5081                 return NULL;
5082
5083         list_for_each_entry(pmu, &pmus, entry) {
5084                 if (pmu->task_ctx_nr == ctxn)
5085                         return pmu->pmu_cpu_context;
5086         }
5087
5088         return NULL;
5089 }
5090
5091 static void free_pmu_context(void * __percpu cpu_context)
5092 {
5093         struct pmu *pmu;
5094
5095         mutex_lock(&pmus_lock);
5096         /*
5097          * Like a real lame refcount.
5098          */
5099         list_for_each_entry(pmu, &pmus, entry) {
5100                 if (pmu->pmu_cpu_context == cpu_context)
5101                         goto out;
5102         }
5103
5104         free_percpu(cpu_context);
5105 out:
5106         mutex_unlock(&pmus_lock);
5107 }
5108
5109 int perf_pmu_register(struct pmu *pmu)
5110 {
5111         int cpu, ret;
5112
5113         mutex_lock(&pmus_lock);
5114         ret = -ENOMEM;
5115         pmu->pmu_disable_count = alloc_percpu(int);
5116         if (!pmu->pmu_disable_count)
5117                 goto unlock;
5118
5119         pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
5120         if (pmu->pmu_cpu_context)
5121                 goto got_cpu_context;
5122
5123         pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
5124         if (!pmu->pmu_cpu_context)
5125                 goto free_pdc;
5126
5127         for_each_possible_cpu(cpu) {
5128                 struct perf_cpu_context *cpuctx;
5129
5130                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
5131                 __perf_event_init_context(&cpuctx->ctx);
5132                 cpuctx->ctx.type = cpu_context;
5133                 cpuctx->ctx.pmu = pmu;
5134                 cpuctx->jiffies_interval = 1;
5135                 INIT_LIST_HEAD(&cpuctx->rotation_list);
5136         }
5137
5138 got_cpu_context:
5139         if (!pmu->start_txn) {
5140                 if (pmu->pmu_enable) {
5141                         /*
5142                          * If we have pmu_enable/pmu_disable calls, install
5143                          * transaction stubs that use that to try and batch
5144                          * hardware accesses.
5145                          */
5146                         pmu->start_txn  = perf_pmu_start_txn;
5147                         pmu->commit_txn = perf_pmu_commit_txn;
5148                         pmu->cancel_txn = perf_pmu_cancel_txn;
5149                 } else {
5150                         pmu->start_txn  = perf_pmu_nop_void;
5151                         pmu->commit_txn = perf_pmu_nop_int;
5152                         pmu->cancel_txn = perf_pmu_nop_void;
5153                 }
5154         }
5155
5156         if (!pmu->pmu_enable) {
5157                 pmu->pmu_enable  = perf_pmu_nop_void;
5158                 pmu->pmu_disable = perf_pmu_nop_void;
5159         }
5160
5161         list_add_rcu(&pmu->entry, &pmus);
5162         ret = 0;
5163 unlock:
5164         mutex_unlock(&pmus_lock);
5165
5166         return ret;
5167
5168 free_pdc:
5169         free_percpu(pmu->pmu_disable_count);
5170         goto unlock;
5171 }
5172
5173 void perf_pmu_unregister(struct pmu *pmu)
5174 {
5175         mutex_lock(&pmus_lock);
5176         list_del_rcu(&pmu->entry);
5177         mutex_unlock(&pmus_lock);
5178
5179         /*
5180          * We dereference the pmu list under both SRCU and regular RCU, so
5181          * synchronize against both of those.
5182          */
5183         synchronize_srcu(&pmus_srcu);
5184         synchronize_rcu();
5185
5186         free_percpu(pmu->pmu_disable_count);
5187         free_pmu_context(pmu->pmu_cpu_context);
5188 }
5189
5190 struct pmu *perf_init_event(struct perf_event *event)
5191 {
5192         struct pmu *pmu = NULL;
5193         int idx;
5194
5195         idx = srcu_read_lock(&pmus_srcu);
5196         list_for_each_entry_rcu(pmu, &pmus, entry) {
5197                 int ret = pmu->event_init(event);
5198                 if (!ret)
5199                         goto unlock;
5200
5201                 if (ret != -ENOENT) {
5202                         pmu = ERR_PTR(ret);
5203                         goto unlock;
5204                 }
5205         }
5206         pmu = ERR_PTR(-ENOENT);
5207 unlock:
5208         srcu_read_unlock(&pmus_srcu, idx);
5209
5210         return pmu;
5211 }
5212
5213 /*
5214  * Allocate and initialize a event structure
5215  */
5216 static struct perf_event *
5217 perf_event_alloc(struct perf_event_attr *attr, int cpu,
5218                  struct task_struct *task,
5219                  struct perf_event *group_leader,
5220                  struct perf_event *parent_event,
5221                  perf_overflow_handler_t overflow_handler)
5222 {
5223         struct pmu *pmu;
5224         struct perf_event *event;
5225         struct hw_perf_event *hwc;
5226         long err;
5227
5228         event = kzalloc(sizeof(*event), GFP_KERNEL);
5229         if (!event)
5230                 return ERR_PTR(-ENOMEM);
5231
5232         /*
5233          * Single events are their own group leaders, with an
5234          * empty sibling list:
5235          */
5236         if (!group_leader)
5237                 group_leader = event;
5238
5239         mutex_init(&event->child_mutex);
5240         INIT_LIST_HEAD(&event->child_list);
5241
5242         INIT_LIST_HEAD(&event->group_entry);
5243         INIT_LIST_HEAD(&event->event_entry);
5244         INIT_LIST_HEAD(&event->sibling_list);
5245         init_waitqueue_head(&event->waitq);
5246         init_irq_work(&event->pending, perf_pending_event);
5247
5248         mutex_init(&event->mmap_mutex);
5249
5250         event->cpu              = cpu;
5251         event->attr             = *attr;
5252         event->group_leader     = group_leader;
5253         event->pmu              = NULL;
5254         event->oncpu            = -1;
5255
5256         event->parent           = parent_event;
5257
5258         event->ns               = get_pid_ns(current->nsproxy->pid_ns);
5259         event->id               = atomic64_inc_return(&perf_event_id);
5260
5261         event->state            = PERF_EVENT_STATE_INACTIVE;
5262
5263         if (task) {
5264                 event->attach_state = PERF_ATTACH_TASK;
5265 #ifdef CONFIG_HAVE_HW_BREAKPOINT
5266                 /*
5267                  * hw_breakpoint is a bit difficult here..
5268                  */
5269                 if (attr->type == PERF_TYPE_BREAKPOINT)
5270                         event->hw.bp_target = task;
5271 #endif
5272         }
5273
5274         if (!overflow_handler && parent_event)
5275                 overflow_handler = parent_event->overflow_handler;
5276         
5277         event->overflow_handler = overflow_handler;
5278
5279         if (attr->disabled)
5280                 event->state = PERF_EVENT_STATE_OFF;
5281
5282         pmu = NULL;
5283
5284         hwc = &event->hw;
5285         hwc->sample_period = attr->sample_period;
5286         if (attr->freq && attr->sample_freq)
5287                 hwc->sample_period = 1;
5288         hwc->last_period = hwc->sample_period;
5289
5290         local64_set(&hwc->period_left, hwc->sample_period);
5291
5292         /*
5293          * we currently do not support PERF_FORMAT_GROUP on inherited events
5294          */
5295         if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
5296                 goto done;
5297
5298         pmu = perf_init_event(event);
5299
5300 done:
5301         err = 0;
5302         if (!pmu)
5303                 err = -EINVAL;
5304         else if (IS_ERR(pmu))
5305                 err = PTR_ERR(pmu);
5306
5307         if (err) {
5308                 if (event->ns)
5309                         put_pid_ns(event->ns);
5310                 kfree(event);
5311                 return ERR_PTR(err);
5312         }
5313
5314         event->pmu = pmu;
5315
5316         if (!event->parent) {
5317                 if (event->attach_state & PERF_ATTACH_TASK)
5318                         jump_label_inc(&perf_task_events);
5319                 if (event->attr.mmap || event->attr.mmap_data)
5320                         atomic_inc(&nr_mmap_events);
5321                 if (event->attr.comm)
5322                         atomic_inc(&nr_comm_events);
5323                 if (event->attr.task)
5324                         atomic_inc(&nr_task_events);
5325                 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
5326                         err = get_callchain_buffers();
5327                         if (err) {
5328                                 free_event(event);
5329                                 return ERR_PTR(err);
5330                         }
5331                 }
5332         }
5333
5334         return event;
5335 }
5336
5337 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5338                           struct perf_event_attr *attr)
5339 {
5340         u32 size;
5341         int ret;
5342
5343         if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
5344                 return -EFAULT;
5345
5346         /*
5347          * zero the full structure, so that a short copy will be nice.
5348          */
5349         memset(attr, 0, sizeof(*attr));
5350
5351         ret = get_user(size, &uattr->size);
5352         if (ret)
5353                 return ret;
5354
5355         if (size > PAGE_SIZE)   /* silly large */
5356                 goto err_size;
5357
5358         if (!size)              /* abi compat */
5359                 size = PERF_ATTR_SIZE_VER0;
5360
5361         if (size < PERF_ATTR_SIZE_VER0)
5362                 goto err_size;
5363
5364         /*
5365          * If we're handed a bigger struct than we know of,
5366          * ensure all the unknown bits are 0 - i.e. new
5367          * user-space does not rely on any kernel feature
5368          * extensions we dont know about yet.
5369          */
5370         if (size > sizeof(*attr)) {
5371                 unsigned char __user *addr;
5372                 unsigned char __user *end;
5373                 unsigned char val;
5374
5375                 addr = (void __user *)uattr + sizeof(*attr);
5376                 end  = (void __user *)uattr + size;
5377
5378                 for (; addr < end; addr++) {
5379                         ret = get_user(val, addr);
5380                         if (ret)
5381                                 return ret;
5382                         if (val)
5383                                 goto err_size;
5384                 }
5385                 size = sizeof(*attr);
5386         }
5387
5388         ret = copy_from_user(attr, uattr, size);
5389         if (ret)
5390                 return -EFAULT;
5391
5392         /*
5393          * If the type exists, the corresponding creation will verify
5394          * the attr->config.
5395          */
5396         if (attr->type >= PERF_TYPE_MAX)
5397                 return -EINVAL;
5398
5399         if (attr->__reserved_1)
5400                 return -EINVAL;
5401
5402         if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
5403                 return -EINVAL;
5404
5405         if (attr->read_format & ~(PERF_FORMAT_MAX-1))
5406                 return -EINVAL;
5407
5408 out:
5409         return ret;
5410
5411 err_size:
5412         put_user(sizeof(*attr), &uattr->size);
5413         ret = -E2BIG;
5414         goto out;
5415 }
5416
5417 static int
5418 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
5419 {
5420         struct perf_buffer *buffer = NULL, *old_buffer = NULL;
5421         int ret = -EINVAL;
5422
5423         if (!output_event)
5424                 goto set;
5425
5426         /* don't allow circular references */
5427         if (event == output_event)
5428                 goto out;
5429
5430         /*
5431          * Don't allow cross-cpu buffers
5432          */
5433         if (output_event->cpu != event->cpu)
5434                 goto out;
5435
5436         /*
5437          * If its not a per-cpu buffer, it must be the same task.
5438          */
5439         if (output_event->cpu == -1 && output_event->ctx != event->ctx)
5440                 goto out;
5441
5442 set:
5443         mutex_lock(&event->mmap_mutex);
5444         /* Can't redirect output if we've got an active mmap() */
5445         if (atomic_read(&event->mmap_count))
5446                 goto unlock;
5447
5448         if (output_event) {
5449                 /* get the buffer we want to redirect to */
5450                 buffer = perf_buffer_get(output_event);
5451                 if (!buffer)
5452                         goto unlock;
5453         }
5454
5455         old_buffer = event->buffer;
5456         rcu_assign_pointer(event->buffer, buffer);
5457         ret = 0;
5458 unlock:
5459         mutex_unlock(&event->mmap_mutex);
5460
5461         if (old_buffer)
5462                 perf_buffer_put(old_buffer);
5463 out:
5464         return ret;
5465 }
5466
5467 /**
5468  * sys_perf_event_open - open a performance event, associate it to a task/cpu
5469  *
5470  * @attr_uptr:  event_id type attributes for monitoring/sampling
5471  * @pid:                target pid
5472  * @cpu:                target cpu
5473  * @group_fd:           group leader event fd
5474  */
5475 SYSCALL_DEFINE5(perf_event_open,
5476                 struct perf_event_attr __user *, attr_uptr,
5477                 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
5478 {
5479         struct perf_event *group_leader = NULL, *output_event = NULL;
5480         struct perf_event *event, *sibling;
5481         struct perf_event_attr attr;
5482         struct perf_event_context *ctx;
5483         struct file *event_file = NULL;
5484         struct file *group_file = NULL;
5485         struct task_struct *task = NULL;
5486         struct pmu *pmu;
5487         int event_fd;
5488         int move_group = 0;
5489         int fput_needed = 0;
5490         int err;
5491
5492         /* for future expandability... */
5493         if (flags & ~(PERF_FLAG_FD_NO_GROUP | PERF_FLAG_FD_OUTPUT))
5494                 return -EINVAL;
5495
5496         err = perf_copy_attr(attr_uptr, &attr);
5497         if (err)
5498                 return err;
5499
5500         if (!attr.exclude_kernel) {
5501                 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
5502                         return -EACCES;
5503         }
5504
5505         if (attr.freq) {
5506                 if (attr.sample_freq > sysctl_perf_event_sample_rate)
5507                         return -EINVAL;
5508         }
5509
5510         event_fd = get_unused_fd_flags(O_RDWR);
5511         if (event_fd < 0)
5512                 return event_fd;
5513
5514         if (group_fd != -1) {
5515                 group_leader = perf_fget_light(group_fd, &fput_needed);
5516                 if (IS_ERR(group_leader)) {
5517                         err = PTR_ERR(group_leader);
5518                         goto err_fd;
5519                 }
5520                 group_file = group_leader->filp;
5521                 if (flags & PERF_FLAG_FD_OUTPUT)
5522                         output_event = group_leader;
5523                 if (flags & PERF_FLAG_FD_NO_GROUP)
5524                         group_leader = NULL;
5525         }
5526
5527         if (pid != -1) {
5528                 task = find_lively_task_by_vpid(pid);
5529                 if (IS_ERR(task)) {
5530                         err = PTR_ERR(task);
5531                         goto err_group_fd;
5532                 }
5533         }
5534
5535         event = perf_event_alloc(&attr, cpu, task, group_leader, NULL, NULL);
5536         if (IS_ERR(event)) {
5537                 err = PTR_ERR(event);
5538                 goto err_task;
5539         }
5540
5541         /*
5542          * Special case software events and allow them to be part of
5543          * any hardware group.
5544          */
5545         pmu = event->pmu;
5546
5547         if (group_leader &&
5548             (is_software_event(event) != is_software_event(group_leader))) {
5549                 if (is_software_event(event)) {
5550                         /*
5551                          * If event and group_leader are not both a software
5552                          * event, and event is, then group leader is not.
5553                          *
5554                          * Allow the addition of software events to !software
5555                          * groups, this is safe because software events never
5556                          * fail to schedule.
5557                          */
5558                         pmu = group_leader->pmu;
5559                 } else if (is_software_event(group_leader) &&
5560                            (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
5561                         /*
5562                          * In case the group is a pure software group, and we
5563                          * try to add a hardware event, move the whole group to
5564                          * the hardware context.
5565                          */
5566                         move_group = 1;
5567                 }
5568         }
5569
5570         /*
5571          * Get the target context (task or percpu):
5572          */
5573         ctx = find_get_context(pmu, task, cpu);
5574         if (IS_ERR(ctx)) {
5575                 err = PTR_ERR(ctx);
5576                 goto err_alloc;
5577         }
5578
5579         /*
5580          * Look up the group leader (we will attach this event to it):
5581          */
5582         if (group_leader) {
5583                 err = -EINVAL;
5584
5585                 /*
5586                  * Do not allow a recursive hierarchy (this new sibling
5587                  * becoming part of another group-sibling):
5588                  */
5589                 if (group_leader->group_leader != group_leader)
5590                         goto err_context;
5591                 /*
5592                  * Do not allow to attach to a group in a different
5593                  * task or CPU context:
5594                  */
5595                 if (move_group) {
5596                         if (group_leader->ctx->type != ctx->type)
5597                                 goto err_context;
5598                 } else {
5599                         if (group_leader->ctx != ctx)
5600                                 goto err_context;
5601                 }
5602
5603                 /*
5604                  * Only a group leader can be exclusive or pinned
5605                  */
5606                 if (attr.exclusive || attr.pinned)
5607                         goto err_context;
5608         }
5609
5610         if (output_event) {
5611                 err = perf_event_set_output(event, output_event);
5612                 if (err)
5613                         goto err_context;
5614         }
5615
5616         event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, O_RDWR);
5617         if (IS_ERR(event_file)) {
5618                 err = PTR_ERR(event_file);
5619                 goto err_context;
5620         }
5621
5622         if (move_group) {
5623                 struct perf_event_context *gctx = group_leader->ctx;
5624
5625                 mutex_lock(&gctx->mutex);
5626                 perf_event_remove_from_context(group_leader);
5627                 list_for_each_entry(sibling, &group_leader->sibling_list,
5628                                     group_entry) {
5629                         perf_event_remove_from_context(sibling);
5630                         put_ctx(gctx);
5631                 }
5632                 mutex_unlock(&gctx->mutex);
5633                 put_ctx(gctx);
5634         }
5635
5636         event->filp = event_file;
5637         WARN_ON_ONCE(ctx->parent_ctx);
5638         mutex_lock(&ctx->mutex);
5639
5640         if (move_group) {
5641                 perf_install_in_context(ctx, group_leader, cpu);
5642                 get_ctx(ctx);
5643                 list_for_each_entry(sibling, &group_leader->sibling_list,
5644                                     group_entry) {
5645                         perf_install_in_context(ctx, sibling, cpu);
5646                         get_ctx(ctx);
5647                 }
5648         }
5649
5650         perf_install_in_context(ctx, event, cpu);
5651         ++ctx->generation;
5652         mutex_unlock(&ctx->mutex);
5653
5654         event->owner = current;
5655         get_task_struct(current);
5656         mutex_lock(&current->perf_event_mutex);
5657         list_add_tail(&event->owner_entry, &current->perf_event_list);
5658         mutex_unlock(&current->perf_event_mutex);
5659
5660         /*
5661          * Drop the reference on the group_event after placing the
5662          * new event on the sibling_list. This ensures destruction
5663          * of the group leader will find the pointer to itself in
5664          * perf_group_detach().
5665          */
5666         fput_light(group_file, fput_needed);
5667         fd_install(event_fd, event_file);
5668         return event_fd;
5669
5670 err_context:
5671         put_ctx(ctx);
5672 err_alloc:
5673         free_event(event);
5674 err_task:
5675         if (task)
5676                 put_task_struct(task);
5677 err_group_fd:
5678         fput_light(group_file, fput_needed);
5679 err_fd:
5680         put_unused_fd(event_fd);
5681         return err;
5682 }
5683
5684 /**
5685  * perf_event_create_kernel_counter
5686  *
5687  * @attr: attributes of the counter to create
5688  * @cpu: cpu in which the counter is bound
5689  * @task: task to profile (NULL for percpu)
5690  */
5691 struct perf_event *
5692 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
5693                                  struct task_struct *task,
5694                                  perf_overflow_handler_t overflow_handler)
5695 {
5696         struct perf_event_context *ctx;
5697         struct perf_event *event;
5698         int err;
5699
5700         /*
5701          * Get the target context (task or percpu):
5702          */
5703
5704         event = perf_event_alloc(attr, cpu, task, NULL, NULL, overflow_handler);
5705         if (IS_ERR(event)) {
5706                 err = PTR_ERR(event);
5707                 goto err;
5708         }
5709
5710         ctx = find_get_context(event->pmu, task, cpu);
5711         if (IS_ERR(ctx)) {
5712                 err = PTR_ERR(ctx);
5713                 goto err_free;
5714         }
5715
5716         event->filp = NULL;
5717         WARN_ON_ONCE(ctx->parent_ctx);
5718         mutex_lock(&ctx->mutex);
5719         perf_install_in_context(ctx, event, cpu);
5720         ++ctx->generation;
5721         mutex_unlock(&ctx->mutex);
5722
5723         event->owner = current;
5724         get_task_struct(current);
5725         mutex_lock(&current->perf_event_mutex);
5726         list_add_tail(&event->owner_entry, &current->perf_event_list);
5727         mutex_unlock(&current->perf_event_mutex);
5728
5729         return event;
5730
5731 err_free:
5732         free_event(event);
5733 err:
5734         return ERR_PTR(err);
5735 }
5736 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
5737
5738 static void sync_child_event(struct perf_event *child_event,
5739                                struct task_struct *child)
5740 {
5741         struct perf_event *parent_event = child_event->parent;
5742         u64 child_val;
5743
5744         if (child_event->attr.inherit_stat)
5745                 perf_event_read_event(child_event, child);
5746
5747         child_val = perf_event_count(child_event);
5748
5749         /*
5750          * Add back the child's count to the parent's count:
5751          */
5752         atomic64_add(child_val, &parent_event->child_count);
5753         atomic64_add(child_event->total_time_enabled,
5754                      &parent_event->child_total_time_enabled);
5755         atomic64_add(child_event->total_time_running,
5756                      &parent_event->child_total_time_running);
5757
5758         /*
5759          * Remove this event from the parent's list
5760          */
5761         WARN_ON_ONCE(parent_event->ctx->parent_ctx);
5762         mutex_lock(&parent_event->child_mutex);
5763         list_del_init(&child_event->child_list);
5764         mutex_unlock(&parent_event->child_mutex);
5765
5766         /*
5767          * Release the parent event, if this was the last
5768          * reference to it.
5769          */
5770         fput(parent_event->filp);
5771 }
5772
5773 static void
5774 __perf_event_exit_task(struct perf_event *child_event,
5775                          struct perf_event_context *child_ctx,
5776                          struct task_struct *child)
5777 {
5778         struct perf_event *parent_event;
5779
5780         perf_event_remove_from_context(child_event);
5781
5782         parent_event = child_event->parent;
5783         /*
5784          * It can happen that parent exits first, and has events
5785          * that are still around due to the child reference. These
5786          * events need to be zapped - but otherwise linger.
5787          */
5788         if (parent_event) {
5789                 sync_child_event(child_event, child);
5790                 free_event(child_event);
5791         }
5792 }
5793
5794 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
5795 {
5796         struct perf_event *child_event, *tmp;
5797         struct perf_event_context *child_ctx;
5798         unsigned long flags;
5799
5800         if (likely(!child->perf_event_ctxp[ctxn])) {
5801                 perf_event_task(child, NULL, 0);
5802                 return;
5803         }
5804
5805         local_irq_save(flags);
5806         /*
5807          * We can't reschedule here because interrupts are disabled,
5808          * and either child is current or it is a task that can't be
5809          * scheduled, so we are now safe from rescheduling changing
5810          * our context.
5811          */
5812         child_ctx = child->perf_event_ctxp[ctxn];
5813         task_ctx_sched_out(child_ctx, EVENT_ALL);
5814
5815         /*
5816          * Take the context lock here so that if find_get_context is
5817          * reading child->perf_event_ctxp, we wait until it has
5818          * incremented the context's refcount before we do put_ctx below.
5819          */
5820         raw_spin_lock(&child_ctx->lock);
5821         child->perf_event_ctxp[ctxn] = NULL;
5822         /*
5823          * If this context is a clone; unclone it so it can't get
5824          * swapped to another process while we're removing all
5825          * the events from it.
5826          */
5827         unclone_ctx(child_ctx);
5828         update_context_time(child_ctx);
5829         raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
5830
5831         /*
5832          * Report the task dead after unscheduling the events so that we
5833          * won't get any samples after PERF_RECORD_EXIT. We can however still
5834          * get a few PERF_RECORD_READ events.
5835          */
5836         perf_event_task(child, child_ctx, 0);
5837
5838         /*
5839          * We can recurse on the same lock type through:
5840          *
5841          *   __perf_event_exit_task()
5842          *     sync_child_event()
5843          *       fput(parent_event->filp)
5844          *         perf_release()
5845          *           mutex_lock(&ctx->mutex)
5846          *
5847          * But since its the parent context it won't be the same instance.
5848          */
5849         mutex_lock(&child_ctx->mutex);
5850
5851 again:
5852         list_for_each_entry_safe(child_event, tmp, &child_ctx->pinned_groups,
5853                                  group_entry)
5854                 __perf_event_exit_task(child_event, child_ctx, child);
5855
5856         list_for_each_entry_safe(child_event, tmp, &child_ctx->flexible_groups,
5857                                  group_entry)
5858                 __perf_event_exit_task(child_event, child_ctx, child);
5859
5860         /*
5861          * If the last event was a group event, it will have appended all
5862          * its siblings to the list, but we obtained 'tmp' before that which
5863          * will still point to the list head terminating the iteration.
5864          */
5865         if (!list_empty(&child_ctx->pinned_groups) ||
5866             !list_empty(&child_ctx->flexible_groups))
5867                 goto again;
5868
5869         mutex_unlock(&child_ctx->mutex);
5870
5871         put_ctx(child_ctx);
5872 }
5873
5874 /*
5875  * When a child task exits, feed back event values to parent events.
5876  */
5877 void perf_event_exit_task(struct task_struct *child)
5878 {
5879         int ctxn;
5880
5881         for_each_task_context_nr(ctxn)
5882                 perf_event_exit_task_context(child, ctxn);
5883 }
5884
5885 static void perf_free_event(struct perf_event *event,
5886                             struct perf_event_context *ctx)
5887 {
5888         struct perf_event *parent = event->parent;
5889
5890         if (WARN_ON_ONCE(!parent))
5891                 return;
5892
5893         mutex_lock(&parent->child_mutex);
5894         list_del_init(&event->child_list);
5895         mutex_unlock(&parent->child_mutex);
5896
5897         fput(parent->filp);
5898
5899         perf_group_detach(event);
5900         list_del_event(event, ctx);
5901         free_event(event);
5902 }
5903
5904 /*
5905  * free an unexposed, unused context as created by inheritance by
5906  * perf_event_init_task below, used by fork() in case of fail.
5907  */
5908 void perf_event_free_task(struct task_struct *task)
5909 {
5910         struct perf_event_context *ctx;
5911         struct perf_event *event, *tmp;
5912         int ctxn;
5913
5914         for_each_task_context_nr(ctxn) {
5915                 ctx = task->perf_event_ctxp[ctxn];
5916                 if (!ctx)
5917                         continue;
5918
5919                 mutex_lock(&ctx->mutex);
5920 again:
5921                 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
5922                                 group_entry)
5923                         perf_free_event(event, ctx);
5924
5925                 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
5926                                 group_entry)
5927                         perf_free_event(event, ctx);
5928
5929                 if (!list_empty(&ctx->pinned_groups) ||
5930                                 !list_empty(&ctx->flexible_groups))
5931                         goto again;
5932
5933                 mutex_unlock(&ctx->mutex);
5934
5935                 put_ctx(ctx);
5936         }
5937 }
5938
5939 void perf_event_delayed_put(struct task_struct *task)
5940 {
5941         int ctxn;
5942
5943         for_each_task_context_nr(ctxn)
5944                 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
5945 }
5946
5947 /*
5948  * inherit a event from parent task to child task:
5949  */
5950 static struct perf_event *
5951 inherit_event(struct perf_event *parent_event,
5952               struct task_struct *parent,
5953               struct perf_event_context *parent_ctx,
5954               struct task_struct *child,
5955               struct perf_event *group_leader,
5956               struct perf_event_context *child_ctx)
5957 {
5958         struct perf_event *child_event;
5959         unsigned long flags;
5960
5961         /*
5962          * Instead of creating recursive hierarchies of events,
5963          * we link inherited events back to the original parent,
5964          * which has a filp for sure, which we use as the reference
5965          * count:
5966          */
5967         if (parent_event->parent)
5968                 parent_event = parent_event->parent;
5969
5970         child_event = perf_event_alloc(&parent_event->attr,
5971                                            parent_event->cpu,
5972                                            child,
5973                                            group_leader, parent_event,
5974                                            NULL);
5975         if (IS_ERR(child_event))
5976                 return child_event;
5977         get_ctx(child_ctx);
5978
5979         /*
5980          * Make the child state follow the state of the parent event,
5981          * not its attr.disabled bit.  We hold the parent's mutex,
5982          * so we won't race with perf_event_{en, dis}able_family.
5983          */
5984         if (parent_event->state >= PERF_EVENT_STATE_INACTIVE)
5985                 child_event->state = PERF_EVENT_STATE_INACTIVE;
5986         else
5987                 child_event->state = PERF_EVENT_STATE_OFF;
5988
5989         if (parent_event->attr.freq) {
5990                 u64 sample_period = parent_event->hw.sample_period;
5991                 struct hw_perf_event *hwc = &child_event->hw;
5992
5993                 hwc->sample_period = sample_period;
5994                 hwc->last_period   = sample_period;
5995
5996                 local64_set(&hwc->period_left, sample_period);
5997         }
5998
5999         child_event->ctx = child_ctx;
6000         child_event->overflow_handler = parent_event->overflow_handler;
6001
6002         /*
6003          * Link it up in the child's context:
6004          */
6005         raw_spin_lock_irqsave(&child_ctx->lock, flags);
6006         add_event_to_ctx(child_event, child_ctx);
6007         raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
6008
6009         /*
6010          * Get a reference to the parent filp - we will fput it
6011          * when the child event exits. This is safe to do because
6012          * we are in the parent and we know that the filp still
6013          * exists and has a nonzero count:
6014          */
6015         atomic_long_inc(&parent_event->filp->f_count);
6016
6017         /*
6018          * Link this into the parent event's child list
6019          */
6020         WARN_ON_ONCE(parent_event->ctx->parent_ctx);
6021         mutex_lock(&parent_event->child_mutex);
6022         list_add_tail(&child_event->child_list, &parent_event->child_list);
6023         mutex_unlock(&parent_event->child_mutex);
6024
6025         return child_event;
6026 }
6027
6028 static int inherit_group(struct perf_event *parent_event,
6029               struct task_struct *parent,
6030               struct perf_event_context *parent_ctx,
6031               struct task_struct *child,
6032               struct perf_event_context *child_ctx)
6033 {
6034         struct perf_event *leader;
6035         struct perf_event *sub;
6036         struct perf_event *child_ctr;
6037
6038         leader = inherit_event(parent_event, parent, parent_ctx,
6039                                  child, NULL, child_ctx);
6040         if (IS_ERR(leader))
6041                 return PTR_ERR(leader);
6042         list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
6043                 child_ctr = inherit_event(sub, parent, parent_ctx,
6044                                             child, leader, child_ctx);
6045                 if (IS_ERR(child_ctr))
6046                         return PTR_ERR(child_ctr);
6047         }
6048         return 0;
6049 }
6050
6051 static int
6052 inherit_task_group(struct perf_event *event, struct task_struct *parent,
6053                    struct perf_event_context *parent_ctx,
6054                    struct task_struct *child, int ctxn,
6055                    int *inherited_all)
6056 {
6057         int ret;
6058         struct perf_event_context *child_ctx;
6059
6060         if (!event->attr.inherit) {
6061                 *inherited_all = 0;
6062                 return 0;
6063         }
6064
6065         child_ctx = child->perf_event_ctxp[ctxn];
6066         if (!child_ctx) {
6067                 /*
6068                  * This is executed from the parent task context, so
6069                  * inherit events that have been marked for cloning.
6070                  * First allocate and initialize a context for the
6071                  * child.
6072                  */
6073
6074                 child_ctx = alloc_perf_context(event->pmu, child);
6075                 if (!child_ctx)
6076                         return -ENOMEM;
6077
6078                 child->perf_event_ctxp[ctxn] = child_ctx;
6079         }
6080
6081         ret = inherit_group(event, parent, parent_ctx,
6082                             child, child_ctx);
6083
6084         if (ret)
6085                 *inherited_all = 0;
6086
6087         return ret;
6088 }
6089
6090 /*
6091  * Initialize the perf_event context in task_struct
6092  */
6093 int perf_event_init_context(struct task_struct *child, int ctxn)
6094 {
6095         struct perf_event_context *child_ctx, *parent_ctx;
6096         struct perf_event_context *cloned_ctx;
6097         struct perf_event *event;
6098         struct task_struct *parent = current;
6099         int inherited_all = 1;
6100         int ret = 0;
6101
6102         child->perf_event_ctxp[ctxn] = NULL;
6103
6104         mutex_init(&child->perf_event_mutex);
6105         INIT_LIST_HEAD(&child->perf_event_list);
6106
6107         if (likely(!parent->perf_event_ctxp[ctxn]))
6108                 return 0;
6109
6110         /*
6111          * If the parent's context is a clone, pin it so it won't get
6112          * swapped under us.
6113          */
6114         parent_ctx = perf_pin_task_context(parent, ctxn);
6115
6116         /*
6117          * No need to check if parent_ctx != NULL here; since we saw
6118          * it non-NULL earlier, the only reason for it to become NULL
6119          * is if we exit, and since we're currently in the middle of
6120          * a fork we can't be exiting at the same time.
6121          */
6122
6123         /*
6124          * Lock the parent list. No need to lock the child - not PID
6125          * hashed yet and not running, so nobody can access it.
6126          */
6127         mutex_lock(&parent_ctx->mutex);
6128
6129         /*
6130          * We dont have to disable NMIs - we are only looking at
6131          * the list, not manipulating it:
6132          */
6133         list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
6134                 ret = inherit_task_group(event, parent, parent_ctx,
6135                                          child, ctxn, &inherited_all);
6136                 if (ret)
6137                         break;
6138         }
6139
6140         list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
6141                 ret = inherit_task_group(event, parent, parent_ctx,
6142                                          child, ctxn, &inherited_all);
6143                 if (ret)
6144                         break;
6145         }
6146
6147         child_ctx = child->perf_event_ctxp[ctxn];
6148
6149         if (child_ctx && inherited_all) {
6150                 /*
6151                  * Mark the child context as a clone of the parent
6152                  * context, or of whatever the parent is a clone of.
6153                  * Note that if the parent is a clone, it could get
6154                  * uncloned at any point, but that doesn't matter
6155                  * because the list of events and the generation
6156                  * count can't have changed since we took the mutex.
6157                  */
6158                 cloned_ctx = rcu_dereference(parent_ctx->parent_ctx);
6159                 if (cloned_ctx) {
6160                         child_ctx->parent_ctx = cloned_ctx;
6161                         child_ctx->parent_gen = parent_ctx->parent_gen;
6162                 } else {
6163                         child_ctx->parent_ctx = parent_ctx;
6164                         child_ctx->parent_gen = parent_ctx->generation;
6165                 }
6166                 get_ctx(child_ctx->parent_ctx);
6167         }
6168
6169         mutex_unlock(&parent_ctx->mutex);
6170
6171         perf_unpin_context(parent_ctx);
6172
6173         return ret;
6174 }
6175
6176 /*
6177  * Initialize the perf_event context in task_struct
6178  */
6179 int perf_event_init_task(struct task_struct *child)
6180 {
6181         int ctxn, ret;
6182
6183         for_each_task_context_nr(ctxn) {
6184                 ret = perf_event_init_context(child, ctxn);
6185                 if (ret)
6186                         return ret;
6187         }
6188
6189         return 0;
6190 }
6191
6192 static void __init perf_event_init_all_cpus(void)
6193 {
6194         struct swevent_htable *swhash;
6195         int cpu;
6196
6197         for_each_possible_cpu(cpu) {
6198                 swhash = &per_cpu(swevent_htable, cpu);
6199                 mutex_init(&swhash->hlist_mutex);
6200                 INIT_LIST_HEAD(&per_cpu(rotation_list, cpu));
6201         }
6202 }
6203
6204 static void __cpuinit perf_event_init_cpu(int cpu)
6205 {
6206         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6207
6208         mutex_lock(&swhash->hlist_mutex);
6209         if (swhash->hlist_refcount > 0) {
6210                 struct swevent_hlist *hlist;
6211
6212                 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
6213                 WARN_ON(!hlist);
6214                 rcu_assign_pointer(swhash->swevent_hlist, hlist);
6215         }
6216         mutex_unlock(&swhash->hlist_mutex);
6217 }
6218
6219 #ifdef CONFIG_HOTPLUG_CPU
6220 static void perf_pmu_rotate_stop(struct pmu *pmu)
6221 {
6222         struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
6223
6224         WARN_ON(!irqs_disabled());
6225
6226         list_del_init(&cpuctx->rotation_list);
6227 }
6228
6229 static void __perf_event_exit_context(void *__info)
6230 {
6231         struct perf_event_context *ctx = __info;
6232         struct perf_event *event, *tmp;
6233
6234         perf_pmu_rotate_stop(ctx->pmu);
6235
6236         list_for_each_entry_safe(event, tmp, &ctx->pinned_groups, group_entry)
6237                 __perf_event_remove_from_context(event);
6238         list_for_each_entry_safe(event, tmp, &ctx->flexible_groups, group_entry)
6239                 __perf_event_remove_from_context(event);
6240 }
6241
6242 static void perf_event_exit_cpu_context(int cpu)
6243 {
6244         struct perf_event_context *ctx;
6245         struct pmu *pmu;
6246         int idx;
6247
6248         idx = srcu_read_lock(&pmus_srcu);
6249         list_for_each_entry_rcu(pmu, &pmus, entry) {
6250                 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
6251
6252                 mutex_lock(&ctx->mutex);
6253                 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
6254                 mutex_unlock(&ctx->mutex);
6255         }
6256         srcu_read_unlock(&pmus_srcu, idx);
6257 }
6258
6259 static void perf_event_exit_cpu(int cpu)
6260 {
6261         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6262
6263         mutex_lock(&swhash->hlist_mutex);
6264         swevent_hlist_release(swhash);
6265         mutex_unlock(&swhash->hlist_mutex);
6266
6267         perf_event_exit_cpu_context(cpu);
6268 }
6269 #else
6270 static inline void perf_event_exit_cpu(int cpu) { }
6271 #endif
6272
6273 static int __cpuinit
6274 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
6275 {
6276         unsigned int cpu = (long)hcpu;
6277
6278         switch (action & ~CPU_TASKS_FROZEN) {
6279
6280         case CPU_UP_PREPARE:
6281         case CPU_DOWN_FAILED:
6282                 perf_event_init_cpu(cpu);
6283                 break;
6284
6285         case CPU_UP_CANCELED:
6286         case CPU_DOWN_PREPARE:
6287                 perf_event_exit_cpu(cpu);
6288                 break;
6289
6290         default:
6291                 break;
6292         }
6293
6294         return NOTIFY_OK;
6295 }
6296
6297 void __init perf_event_init(void)
6298 {
6299         int ret;
6300
6301         perf_event_init_all_cpus();
6302         init_srcu_struct(&pmus_srcu);
6303         perf_pmu_register(&perf_swevent);
6304         perf_pmu_register(&perf_cpu_clock);
6305         perf_pmu_register(&perf_task_clock);
6306         perf_tp_register();
6307         perf_cpu_notifier(perf_cpu_notify);
6308
6309         ret = init_hw_breakpoint();
6310         WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
6311 }