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