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