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