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