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