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