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