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