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