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