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