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