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