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