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