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