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