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