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