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