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