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