perf: Handle compat ioctl
[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 void perf_event_wakeup(struct perf_event *event)
3946 {
3947         ring_buffer_wakeup(event);
3948
3949         if (event->pending_kill) {
3950                 kill_fasync(&event->fasync, SIGIO, event->pending_kill);
3951                 event->pending_kill = 0;
3952         }
3953 }
3954
3955 static void perf_pending_event(struct irq_work *entry)
3956 {
3957         struct perf_event *event = container_of(entry,
3958                         struct perf_event, pending);
3959
3960         if (event->pending_disable) {
3961                 event->pending_disable = 0;
3962                 __perf_event_disable(event);
3963         }
3964
3965         if (event->pending_wakeup) {
3966                 event->pending_wakeup = 0;
3967                 perf_event_wakeup(event);
3968         }
3969 }
3970
3971 /*
3972  * We assume there is only KVM supporting the callbacks.
3973  * Later on, we might change it to a list if there is
3974  * another virtualization implementation supporting the callbacks.
3975  */
3976 struct perf_guest_info_callbacks *perf_guest_cbs;
3977
3978 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
3979 {
3980         perf_guest_cbs = cbs;
3981         return 0;
3982 }
3983 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
3984
3985 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
3986 {
3987         perf_guest_cbs = NULL;
3988         return 0;
3989 }
3990 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
3991
3992 static void __perf_event_header__init_id(struct perf_event_header *header,
3993                                          struct perf_sample_data *data,
3994                                          struct perf_event *event)
3995 {
3996         u64 sample_type = event->attr.sample_type;
3997
3998         data->type = sample_type;
3999         header->size += event->id_header_size;
4000
4001         if (sample_type & PERF_SAMPLE_TID) {
4002                 /* namespace issues */
4003                 data->tid_entry.pid = perf_event_pid(event, current);
4004                 data->tid_entry.tid = perf_event_tid(event, current);
4005         }
4006
4007         if (sample_type & PERF_SAMPLE_TIME)
4008                 data->time = perf_clock();
4009
4010         if (sample_type & PERF_SAMPLE_ID)
4011                 data->id = primary_event_id(event);
4012
4013         if (sample_type & PERF_SAMPLE_STREAM_ID)
4014                 data->stream_id = event->id;
4015
4016         if (sample_type & PERF_SAMPLE_CPU) {
4017                 data->cpu_entry.cpu      = raw_smp_processor_id();
4018                 data->cpu_entry.reserved = 0;
4019         }
4020 }
4021
4022 void perf_event_header__init_id(struct perf_event_header *header,
4023                                 struct perf_sample_data *data,
4024                                 struct perf_event *event)
4025 {
4026         if (event->attr.sample_id_all)
4027                 __perf_event_header__init_id(header, data, event);
4028 }
4029
4030 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
4031                                            struct perf_sample_data *data)
4032 {
4033         u64 sample_type = data->type;
4034
4035         if (sample_type & PERF_SAMPLE_TID)
4036                 perf_output_put(handle, data->tid_entry);
4037
4038         if (sample_type & PERF_SAMPLE_TIME)
4039                 perf_output_put(handle, data->time);
4040
4041         if (sample_type & PERF_SAMPLE_ID)
4042                 perf_output_put(handle, data->id);
4043
4044         if (sample_type & PERF_SAMPLE_STREAM_ID)
4045                 perf_output_put(handle, data->stream_id);
4046
4047         if (sample_type & PERF_SAMPLE_CPU)
4048                 perf_output_put(handle, data->cpu_entry);
4049 }
4050
4051 void perf_event__output_id_sample(struct perf_event *event,
4052                                   struct perf_output_handle *handle,
4053                                   struct perf_sample_data *sample)
4054 {
4055         if (event->attr.sample_id_all)
4056                 __perf_event__output_id_sample(handle, sample);
4057 }
4058
4059 static void perf_output_read_one(struct perf_output_handle *handle,
4060                                  struct perf_event *event,
4061                                  u64 enabled, u64 running)
4062 {
4063         u64 read_format = event->attr.read_format;
4064         u64 values[4];
4065         int n = 0;
4066
4067         values[n++] = perf_event_count(event);
4068         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4069                 values[n++] = enabled +
4070                         atomic64_read(&event->child_total_time_enabled);
4071         }
4072         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4073                 values[n++] = running +
4074                         atomic64_read(&event->child_total_time_running);
4075         }
4076         if (read_format & PERF_FORMAT_ID)
4077                 values[n++] = primary_event_id(event);
4078
4079         __output_copy(handle, values, n * sizeof(u64));
4080 }
4081
4082 /*
4083  * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
4084  */
4085 static void perf_output_read_group(struct perf_output_handle *handle,
4086                             struct perf_event *event,
4087                             u64 enabled, u64 running)
4088 {
4089         struct perf_event *leader = event->group_leader, *sub;
4090         u64 read_format = event->attr.read_format;
4091         u64 values[5];
4092         int n = 0;
4093
4094         values[n++] = 1 + leader->nr_siblings;
4095
4096         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4097                 values[n++] = enabled;
4098
4099         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4100                 values[n++] = running;
4101
4102         if (leader != event)
4103                 leader->pmu->read(leader);
4104
4105         values[n++] = perf_event_count(leader);
4106         if (read_format & PERF_FORMAT_ID)
4107                 values[n++] = primary_event_id(leader);
4108
4109         __output_copy(handle, values, n * sizeof(u64));
4110
4111         list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4112                 n = 0;
4113
4114                 if (sub != event)
4115                         sub->pmu->read(sub);
4116
4117                 values[n++] = perf_event_count(sub);
4118                 if (read_format & PERF_FORMAT_ID)
4119                         values[n++] = primary_event_id(sub);
4120
4121                 __output_copy(handle, values, n * sizeof(u64));
4122         }
4123 }
4124
4125 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
4126                                  PERF_FORMAT_TOTAL_TIME_RUNNING)
4127
4128 static void perf_output_read(struct perf_output_handle *handle,
4129                              struct perf_event *event)
4130 {
4131         u64 enabled = 0, running = 0;
4132         u64 read_format = event->attr.read_format;
4133
4134         /*
4135          * compute total_time_enabled, total_time_running
4136          * based on snapshot values taken when the event
4137          * was last scheduled in.
4138          *
4139          * we cannot simply called update_context_time()
4140          * because of locking issue as we are called in
4141          * NMI context
4142          */
4143         if (read_format & PERF_FORMAT_TOTAL_TIMES)
4144                 calc_timer_values(event, &enabled, &running);
4145
4146         if (event->attr.read_format & PERF_FORMAT_GROUP)
4147                 perf_output_read_group(handle, event, enabled, running);
4148         else
4149                 perf_output_read_one(handle, event, enabled, running);
4150 }
4151
4152 void perf_output_sample(struct perf_output_handle *handle,
4153                         struct perf_event_header *header,
4154                         struct perf_sample_data *data,
4155                         struct perf_event *event)
4156 {
4157         u64 sample_type = data->type;
4158
4159         perf_output_put(handle, *header);
4160
4161         if (sample_type & PERF_SAMPLE_IP)
4162                 perf_output_put(handle, data->ip);
4163
4164         if (sample_type & PERF_SAMPLE_TID)
4165                 perf_output_put(handle, data->tid_entry);
4166
4167         if (sample_type & PERF_SAMPLE_TIME)
4168                 perf_output_put(handle, data->time);
4169
4170         if (sample_type & PERF_SAMPLE_ADDR)
4171                 perf_output_put(handle, data->addr);
4172
4173         if (sample_type & PERF_SAMPLE_ID)
4174                 perf_output_put(handle, data->id);
4175
4176         if (sample_type & PERF_SAMPLE_STREAM_ID)
4177                 perf_output_put(handle, data->stream_id);
4178
4179         if (sample_type & PERF_SAMPLE_CPU)
4180                 perf_output_put(handle, data->cpu_entry);
4181
4182         if (sample_type & PERF_SAMPLE_PERIOD)
4183                 perf_output_put(handle, data->period);
4184
4185         if (sample_type & PERF_SAMPLE_READ)
4186                 perf_output_read(handle, event);
4187
4188         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4189                 if (data->callchain) {
4190                         int size = 1;
4191
4192                         if (data->callchain)
4193                                 size += data->callchain->nr;
4194
4195                         size *= sizeof(u64);
4196
4197                         __output_copy(handle, data->callchain, size);
4198                 } else {
4199                         u64 nr = 0;
4200                         perf_output_put(handle, nr);
4201                 }
4202         }
4203
4204         if (sample_type & PERF_SAMPLE_RAW) {
4205                 if (data->raw) {
4206                         perf_output_put(handle, data->raw->size);
4207                         __output_copy(handle, data->raw->data,
4208                                            data->raw->size);
4209                 } else {
4210                         struct {
4211                                 u32     size;
4212                                 u32     data;
4213                         } raw = {
4214                                 .size = sizeof(u32),
4215                                 .data = 0,
4216                         };
4217                         perf_output_put(handle, raw);
4218                 }
4219         }
4220
4221         if (!event->attr.watermark) {
4222                 int wakeup_events = event->attr.wakeup_events;
4223
4224                 if (wakeup_events) {
4225                         struct ring_buffer *rb = handle->rb;
4226                         int events = local_inc_return(&rb->events);
4227
4228                         if (events >= wakeup_events) {
4229                                 local_sub(wakeup_events, &rb->events);
4230                                 local_inc(&rb->wakeup);
4231                         }
4232                 }
4233         }
4234 }
4235
4236 void perf_prepare_sample(struct perf_event_header *header,
4237                          struct perf_sample_data *data,
4238                          struct perf_event *event,
4239                          struct pt_regs *regs)
4240 {
4241         u64 sample_type = event->attr.sample_type;
4242
4243         header->type = PERF_RECORD_SAMPLE;
4244         header->size = sizeof(*header) + event->header_size;
4245
4246         header->misc = 0;
4247         header->misc |= perf_misc_flags(regs);
4248
4249         __perf_event_header__init_id(header, data, event);
4250
4251         if (sample_type & PERF_SAMPLE_IP)
4252                 data->ip = perf_instruction_pointer(regs);
4253
4254         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4255                 int size = 1;
4256
4257                 data->callchain = perf_callchain(regs);
4258
4259                 if (data->callchain)
4260                         size += data->callchain->nr;
4261
4262                 header->size += size * sizeof(u64);
4263         }
4264
4265         if (sample_type & PERF_SAMPLE_RAW) {
4266                 int size = sizeof(u32);
4267
4268                 if (data->raw)
4269                         size += data->raw->size;
4270                 else
4271                         size += sizeof(u32);
4272
4273                 WARN_ON_ONCE(size & (sizeof(u64)-1));
4274                 header->size += size;
4275         }
4276 }
4277
4278 static void perf_event_output(struct perf_event *event,
4279                                 struct perf_sample_data *data,
4280                                 struct pt_regs *regs)
4281 {
4282         struct perf_output_handle handle;
4283         struct perf_event_header header;
4284
4285         /* protect the callchain buffers */
4286         rcu_read_lock();
4287
4288         perf_prepare_sample(&header, data, event, regs);
4289
4290         if (perf_output_begin(&handle, event, header.size))
4291                 goto exit;
4292
4293         perf_output_sample(&handle, &header, data, event);
4294
4295         perf_output_end(&handle);
4296
4297 exit:
4298         rcu_read_unlock();
4299 }
4300
4301 /*
4302  * read event_id
4303  */
4304
4305 struct perf_read_event {
4306         struct perf_event_header        header;
4307
4308         u32                             pid;
4309         u32                             tid;
4310 };
4311
4312 static void
4313 perf_event_read_event(struct perf_event *event,
4314                         struct task_struct *task)
4315 {
4316         struct perf_output_handle handle;
4317         struct perf_sample_data sample;
4318         struct perf_read_event read_event = {
4319                 .header = {
4320                         .type = PERF_RECORD_READ,
4321                         .misc = 0,
4322                         .size = sizeof(read_event) + event->read_size,
4323                 },
4324                 .pid = perf_event_pid(event, task),
4325                 .tid = perf_event_tid(event, task),
4326         };
4327         int ret;
4328
4329         perf_event_header__init_id(&read_event.header, &sample, event);
4330         ret = perf_output_begin(&handle, event, read_event.header.size);
4331         if (ret)
4332                 return;
4333
4334         perf_output_put(&handle, read_event);
4335         perf_output_read(&handle, event);
4336         perf_event__output_id_sample(event, &handle, &sample);
4337
4338         perf_output_end(&handle);
4339 }
4340
4341 /*
4342  * task tracking -- fork/exit
4343  *
4344  * enabled by: attr.comm | attr.mmap | attr.mmap_data | attr.task
4345  */
4346
4347 struct perf_task_event {
4348         struct task_struct              *task;
4349         struct perf_event_context       *task_ctx;
4350
4351         struct {
4352                 struct perf_event_header        header;
4353
4354                 u32                             pid;
4355                 u32                             ppid;
4356                 u32                             tid;
4357                 u32                             ptid;
4358                 u64                             time;
4359         } event_id;
4360 };
4361
4362 static void perf_event_task_output(struct perf_event *event,
4363                                      struct perf_task_event *task_event)
4364 {
4365         struct perf_output_handle handle;
4366         struct perf_sample_data sample;
4367         struct task_struct *task = task_event->task;
4368         int ret, size = task_event->event_id.header.size;
4369
4370         perf_event_header__init_id(&task_event->event_id.header, &sample, event);
4371
4372         ret = perf_output_begin(&handle, event,
4373                                 task_event->event_id.header.size);
4374         if (ret)
4375                 goto out;
4376
4377         task_event->event_id.pid = perf_event_pid(event, task);
4378         task_event->event_id.ppid = perf_event_pid(event, current);
4379
4380         task_event->event_id.tid = perf_event_tid(event, task);
4381         task_event->event_id.ptid = perf_event_tid(event, current);
4382
4383         perf_output_put(&handle, task_event->event_id);
4384
4385         perf_event__output_id_sample(event, &handle, &sample);
4386
4387         perf_output_end(&handle);
4388 out:
4389         task_event->event_id.header.size = size;
4390 }
4391
4392 static int perf_event_task_match(struct perf_event *event)
4393 {
4394         if (event->state < PERF_EVENT_STATE_INACTIVE)
4395                 return 0;
4396
4397         if (!event_filter_match(event))
4398                 return 0;
4399
4400         if (event->attr.comm || event->attr.mmap ||
4401             event->attr.mmap_data || event->attr.task)
4402                 return 1;
4403
4404         return 0;
4405 }
4406
4407 static void perf_event_task_ctx(struct perf_event_context *ctx,
4408                                   struct perf_task_event *task_event)
4409 {
4410         struct perf_event *event;
4411
4412         list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4413                 if (perf_event_task_match(event))
4414                         perf_event_task_output(event, task_event);
4415         }
4416 }
4417
4418 static void perf_event_task_event(struct perf_task_event *task_event)
4419 {
4420         struct perf_cpu_context *cpuctx;
4421         struct perf_event_context *ctx;
4422         struct pmu *pmu;
4423         int ctxn;
4424
4425         rcu_read_lock();
4426         list_for_each_entry_rcu(pmu, &pmus, entry) {
4427                 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4428                 if (cpuctx->unique_pmu != pmu)
4429                         goto next;
4430                 perf_event_task_ctx(&cpuctx->ctx, task_event);
4431
4432                 ctx = task_event->task_ctx;
4433                 if (!ctx) {
4434                         ctxn = pmu->task_ctx_nr;
4435                         if (ctxn < 0)
4436                                 goto next;
4437                         ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4438                 }
4439                 if (ctx)
4440                         perf_event_task_ctx(ctx, task_event);
4441 next:
4442                 put_cpu_ptr(pmu->pmu_cpu_context);
4443         }
4444         rcu_read_unlock();
4445 }
4446
4447 static void perf_event_task(struct task_struct *task,
4448                               struct perf_event_context *task_ctx,
4449                               int new)
4450 {
4451         struct perf_task_event task_event;
4452
4453         if (!atomic_read(&nr_comm_events) &&
4454             !atomic_read(&nr_mmap_events) &&
4455             !atomic_read(&nr_task_events))
4456                 return;
4457
4458         task_event = (struct perf_task_event){
4459                 .task     = task,
4460                 .task_ctx = task_ctx,
4461                 .event_id    = {
4462                         .header = {
4463                                 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
4464                                 .misc = 0,
4465                                 .size = sizeof(task_event.event_id),
4466                         },
4467                         /* .pid  */
4468                         /* .ppid */
4469                         /* .tid  */
4470                         /* .ptid */
4471                         .time = perf_clock(),
4472                 },
4473         };
4474
4475         perf_event_task_event(&task_event);
4476 }
4477
4478 void perf_event_fork(struct task_struct *task)
4479 {
4480         perf_event_task(task, NULL, 1);
4481 }
4482
4483 /*
4484  * comm tracking
4485  */
4486
4487 struct perf_comm_event {
4488         struct task_struct      *task;
4489         char                    *comm;
4490         int                     comm_size;
4491
4492         struct {
4493                 struct perf_event_header        header;
4494
4495                 u32                             pid;
4496                 u32                             tid;
4497         } event_id;
4498 };
4499
4500 static void perf_event_comm_output(struct perf_event *event,
4501                                      struct perf_comm_event *comm_event)
4502 {
4503         struct perf_output_handle handle;
4504         struct perf_sample_data sample;
4505         int size = comm_event->event_id.header.size;
4506         int ret;
4507
4508         perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
4509         ret = perf_output_begin(&handle, event,
4510                                 comm_event->event_id.header.size);
4511
4512         if (ret)
4513                 goto out;
4514
4515         comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
4516         comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
4517
4518         perf_output_put(&handle, comm_event->event_id);
4519         __output_copy(&handle, comm_event->comm,
4520                                    comm_event->comm_size);
4521
4522         perf_event__output_id_sample(event, &handle, &sample);
4523
4524         perf_output_end(&handle);
4525 out:
4526         comm_event->event_id.header.size = size;
4527 }
4528
4529 static int perf_event_comm_match(struct perf_event *event)
4530 {
4531         if (event->state < PERF_EVENT_STATE_INACTIVE)
4532                 return 0;
4533
4534         if (!event_filter_match(event))
4535                 return 0;
4536
4537         if (event->attr.comm)
4538                 return 1;
4539
4540         return 0;
4541 }
4542
4543 static void perf_event_comm_ctx(struct perf_event_context *ctx,
4544                                   struct perf_comm_event *comm_event)
4545 {
4546         struct perf_event *event;
4547
4548         list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4549                 if (perf_event_comm_match(event))
4550                         perf_event_comm_output(event, comm_event);
4551         }
4552 }
4553
4554 static void perf_event_comm_event(struct perf_comm_event *comm_event)
4555 {
4556         struct perf_cpu_context *cpuctx;
4557         struct perf_event_context *ctx;
4558         char comm[TASK_COMM_LEN];
4559         unsigned int size;
4560         struct pmu *pmu;
4561         int ctxn;
4562
4563         memset(comm, 0, sizeof(comm));
4564         strlcpy(comm, comm_event->task->comm, sizeof(comm));
4565         size = ALIGN(strlen(comm)+1, sizeof(u64));
4566
4567         comm_event->comm = comm;
4568         comm_event->comm_size = size;
4569
4570         comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
4571         rcu_read_lock();
4572         list_for_each_entry_rcu(pmu, &pmus, entry) {
4573                 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4574                 if (cpuctx->unique_pmu != pmu)
4575                         goto next;
4576                 perf_event_comm_ctx(&cpuctx->ctx, comm_event);
4577
4578                 ctxn = pmu->task_ctx_nr;
4579                 if (ctxn < 0)
4580                         goto next;
4581
4582                 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4583                 if (ctx)
4584                         perf_event_comm_ctx(ctx, comm_event);
4585 next:
4586                 put_cpu_ptr(pmu->pmu_cpu_context);
4587         }
4588         rcu_read_unlock();
4589 }
4590
4591 void perf_event_comm(struct task_struct *task)
4592 {
4593         struct perf_comm_event comm_event;
4594         struct perf_event_context *ctx;
4595         int ctxn;
4596
4597         for_each_task_context_nr(ctxn) {
4598                 ctx = task->perf_event_ctxp[ctxn];
4599                 if (!ctx)
4600                         continue;
4601
4602                 perf_event_enable_on_exec(ctx);
4603         }
4604
4605         if (!atomic_read(&nr_comm_events))
4606                 return;
4607
4608         comm_event = (struct perf_comm_event){
4609                 .task   = task,
4610                 /* .comm      */
4611                 /* .comm_size */
4612                 .event_id  = {
4613                         .header = {
4614                                 .type = PERF_RECORD_COMM,
4615                                 .misc = 0,
4616                                 /* .size */
4617                         },
4618                         /* .pid */
4619                         /* .tid */
4620                 },
4621         };
4622
4623         perf_event_comm_event(&comm_event);
4624 }
4625
4626 /*
4627  * mmap tracking
4628  */
4629
4630 struct perf_mmap_event {
4631         struct vm_area_struct   *vma;
4632
4633         const char              *file_name;
4634         int                     file_size;
4635
4636         struct {
4637                 struct perf_event_header        header;
4638
4639                 u32                             pid;
4640                 u32                             tid;
4641                 u64                             start;
4642                 u64                             len;
4643                 u64                             pgoff;
4644         } event_id;
4645 };
4646
4647 static void perf_event_mmap_output(struct perf_event *event,
4648                                      struct perf_mmap_event *mmap_event)
4649 {
4650         struct perf_output_handle handle;
4651         struct perf_sample_data sample;
4652         int size = mmap_event->event_id.header.size;
4653         int ret;
4654
4655         perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
4656         ret = perf_output_begin(&handle, event,
4657                                 mmap_event->event_id.header.size);
4658         if (ret)
4659                 goto out;
4660
4661         mmap_event->event_id.pid = perf_event_pid(event, current);
4662         mmap_event->event_id.tid = perf_event_tid(event, current);
4663
4664         perf_output_put(&handle, mmap_event->event_id);
4665         __output_copy(&handle, mmap_event->file_name,
4666                                    mmap_event->file_size);
4667
4668         perf_event__output_id_sample(event, &handle, &sample);
4669
4670         perf_output_end(&handle);
4671 out:
4672         mmap_event->event_id.header.size = size;
4673 }
4674
4675 static int perf_event_mmap_match(struct perf_event *event,
4676                                    struct perf_mmap_event *mmap_event,
4677                                    int executable)
4678 {
4679         if (event->state < PERF_EVENT_STATE_INACTIVE)
4680                 return 0;
4681
4682         if (!event_filter_match(event))
4683                 return 0;
4684
4685         if ((!executable && event->attr.mmap_data) ||
4686             (executable && event->attr.mmap))
4687                 return 1;
4688
4689         return 0;
4690 }
4691
4692 static void perf_event_mmap_ctx(struct perf_event_context *ctx,
4693                                   struct perf_mmap_event *mmap_event,
4694                                   int executable)
4695 {
4696         struct perf_event *event;
4697
4698         list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4699                 if (perf_event_mmap_match(event, mmap_event, executable))
4700                         perf_event_mmap_output(event, mmap_event);
4701         }
4702 }
4703
4704 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
4705 {
4706         struct perf_cpu_context *cpuctx;
4707         struct perf_event_context *ctx;
4708         struct vm_area_struct *vma = mmap_event->vma;
4709         struct file *file = vma->vm_file;
4710         unsigned int size;
4711         char tmp[16];
4712         char *buf = NULL;
4713         const char *name;
4714         struct pmu *pmu;
4715         int ctxn;
4716
4717         memset(tmp, 0, sizeof(tmp));
4718
4719         if (file) {
4720                 /*
4721                  * d_path works from the end of the rb backwards, so we
4722                  * need to add enough zero bytes after the string to handle
4723                  * the 64bit alignment we do later.
4724                  */
4725                 buf = kzalloc(PATH_MAX + sizeof(u64), GFP_KERNEL);
4726                 if (!buf) {
4727                         name = strncpy(tmp, "//enomem", sizeof(tmp));
4728                         goto got_name;
4729                 }
4730                 name = d_path(&file->f_path, buf, PATH_MAX);
4731                 if (IS_ERR(name)) {
4732                         name = strncpy(tmp, "//toolong", sizeof(tmp));
4733                         goto got_name;
4734                 }
4735         } else {
4736                 if (arch_vma_name(mmap_event->vma)) {
4737                         name = strncpy(tmp, arch_vma_name(mmap_event->vma),
4738                                        sizeof(tmp));
4739                         goto got_name;
4740                 }
4741
4742                 if (!vma->vm_mm) {
4743                         name = strncpy(tmp, "[vdso]", sizeof(tmp));
4744                         goto got_name;
4745                 } else if (vma->vm_start <= vma->vm_mm->start_brk &&
4746                                 vma->vm_end >= vma->vm_mm->brk) {
4747                         name = strncpy(tmp, "[heap]", sizeof(tmp));
4748                         goto got_name;
4749                 } else if (vma->vm_start <= vma->vm_mm->start_stack &&
4750                                 vma->vm_end >= vma->vm_mm->start_stack) {
4751                         name = strncpy(tmp, "[stack]", sizeof(tmp));
4752                         goto got_name;
4753                 }
4754
4755                 name = strncpy(tmp, "//anon", sizeof(tmp));
4756                 goto got_name;
4757         }
4758
4759 got_name:
4760         size = ALIGN(strlen(name)+1, sizeof(u64));
4761
4762         mmap_event->file_name = name;
4763         mmap_event->file_size = size;
4764
4765         mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
4766
4767         rcu_read_lock();
4768         list_for_each_entry_rcu(pmu, &pmus, entry) {
4769                 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4770                 if (cpuctx->unique_pmu != pmu)
4771                         goto next;
4772                 perf_event_mmap_ctx(&cpuctx->ctx, mmap_event,
4773                                         vma->vm_flags & VM_EXEC);
4774
4775                 ctxn = pmu->task_ctx_nr;
4776                 if (ctxn < 0)
4777                         goto next;
4778
4779                 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4780                 if (ctx) {
4781                         perf_event_mmap_ctx(ctx, mmap_event,
4782                                         vma->vm_flags & VM_EXEC);
4783                 }
4784 next:
4785                 put_cpu_ptr(pmu->pmu_cpu_context);
4786         }
4787         rcu_read_unlock();
4788
4789         kfree(buf);
4790 }
4791
4792 void perf_event_mmap(struct vm_area_struct *vma)
4793 {
4794         struct perf_mmap_event mmap_event;
4795
4796         if (!atomic_read(&nr_mmap_events))
4797                 return;
4798
4799         mmap_event = (struct perf_mmap_event){
4800                 .vma    = vma,
4801                 /* .file_name */
4802                 /* .file_size */
4803                 .event_id  = {
4804                         .header = {
4805                                 .type = PERF_RECORD_MMAP,
4806                                 .misc = PERF_RECORD_MISC_USER,
4807                                 /* .size */
4808                         },
4809                         /* .pid */
4810                         /* .tid */
4811                         .start  = vma->vm_start,
4812                         .len    = vma->vm_end - vma->vm_start,
4813                         .pgoff  = (u64)vma->vm_pgoff << PAGE_SHIFT,
4814                 },
4815         };
4816
4817         perf_event_mmap_event(&mmap_event);
4818 }
4819
4820 /*
4821  * IRQ throttle logging
4822  */
4823
4824 static void perf_log_throttle(struct perf_event *event, int enable)
4825 {
4826         struct perf_output_handle handle;
4827         struct perf_sample_data sample;
4828         int ret;
4829
4830         struct {
4831                 struct perf_event_header        header;
4832                 u64                             time;
4833                 u64                             id;
4834                 u64                             stream_id;
4835         } throttle_event = {
4836                 .header = {
4837                         .type = PERF_RECORD_THROTTLE,
4838                         .misc = 0,
4839                         .size = sizeof(throttle_event),
4840                 },
4841                 .time           = perf_clock(),
4842                 .id             = primary_event_id(event),
4843                 .stream_id      = event->id,
4844         };
4845
4846         if (enable)
4847                 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
4848
4849         perf_event_header__init_id(&throttle_event.header, &sample, event);
4850
4851         ret = perf_output_begin(&handle, event,
4852                                 throttle_event.header.size);
4853         if (ret)
4854                 return;
4855
4856         perf_output_put(&handle, throttle_event);
4857         perf_event__output_id_sample(event, &handle, &sample);
4858         perf_output_end(&handle);
4859 }
4860
4861 /*
4862  * Generic event overflow handling, sampling.
4863  */
4864
4865 static int __perf_event_overflow(struct perf_event *event,
4866                                    int throttle, struct perf_sample_data *data,
4867                                    struct pt_regs *regs)
4868 {
4869         int events = atomic_read(&event->event_limit);
4870         struct hw_perf_event *hwc = &event->hw;
4871         int ret = 0;
4872
4873         /*
4874          * Non-sampling counters might still use the PMI to fold short
4875          * hardware counters, ignore those.
4876          */
4877         if (unlikely(!is_sampling_event(event)))
4878                 return 0;
4879
4880         if (unlikely(hwc->interrupts >= max_samples_per_tick)) {
4881                 if (throttle) {
4882                         hwc->interrupts = MAX_INTERRUPTS;
4883                         perf_log_throttle(event, 0);
4884                         ret = 1;
4885                 }
4886         } else
4887                 hwc->interrupts++;
4888
4889         if (event->attr.freq) {
4890                 u64 now = perf_clock();
4891                 s64 delta = now - hwc->freq_time_stamp;
4892
4893                 hwc->freq_time_stamp = now;
4894
4895                 if (delta > 0 && delta < 2*TICK_NSEC)
4896                         perf_adjust_period(event, delta, hwc->last_period);
4897         }
4898
4899         /*
4900          * XXX event_limit might not quite work as expected on inherited
4901          * events
4902          */
4903
4904         event->pending_kill = POLL_IN;
4905         if (events && atomic_dec_and_test(&event->event_limit)) {
4906                 ret = 1;
4907                 event->pending_kill = POLL_HUP;
4908                 event->pending_disable = 1;
4909                 irq_work_queue(&event->pending);
4910         }
4911
4912         if (event->overflow_handler)
4913                 event->overflow_handler(event, data, regs);
4914         else
4915                 perf_event_output(event, data, regs);
4916
4917         if (event->fasync && event->pending_kill) {
4918                 event->pending_wakeup = 1;
4919                 irq_work_queue(&event->pending);
4920         }
4921
4922         return ret;
4923 }
4924
4925 int perf_event_overflow(struct perf_event *event,
4926                           struct perf_sample_data *data,
4927                           struct pt_regs *regs)
4928 {
4929         return __perf_event_overflow(event, 1, data, regs);
4930 }
4931
4932 /*
4933  * Generic software event infrastructure
4934  */
4935
4936 struct swevent_htable {
4937         struct swevent_hlist            *swevent_hlist;
4938         struct mutex                    hlist_mutex;
4939         int                             hlist_refcount;
4940
4941         /* Recursion avoidance in each contexts */
4942         int                             recursion[PERF_NR_CONTEXTS];
4943
4944         /* Keeps track of cpu being initialized/exited */
4945         bool                            online;
4946 };
4947
4948 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
4949
4950 /*
4951  * We directly increment event->count and keep a second value in
4952  * event->hw.period_left to count intervals. This period event
4953  * is kept in the range [-sample_period, 0] so that we can use the
4954  * sign as trigger.
4955  */
4956
4957 static u64 perf_swevent_set_period(struct perf_event *event)
4958 {
4959         struct hw_perf_event *hwc = &event->hw;
4960         u64 period = hwc->last_period;
4961         u64 nr, offset;
4962         s64 old, val;
4963
4964         hwc->last_period = hwc->sample_period;
4965
4966 again:
4967         old = val = local64_read(&hwc->period_left);
4968         if (val < 0)
4969                 return 0;
4970
4971         nr = div64_u64(period + val, period);
4972         offset = nr * period;
4973         val -= offset;
4974         if (local64_cmpxchg(&hwc->period_left, old, val) != old)
4975                 goto again;
4976
4977         return nr;
4978 }
4979
4980 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
4981                                     struct perf_sample_data *data,
4982                                     struct pt_regs *regs)
4983 {
4984         struct hw_perf_event *hwc = &event->hw;
4985         int throttle = 0;
4986
4987         data->period = event->hw.last_period;
4988         if (!overflow)
4989                 overflow = perf_swevent_set_period(event);
4990
4991         if (hwc->interrupts == MAX_INTERRUPTS)
4992                 return;
4993
4994         for (; overflow; overflow--) {
4995                 if (__perf_event_overflow(event, throttle,
4996                                             data, regs)) {
4997                         /*
4998                          * We inhibit the overflow from happening when
4999                          * hwc->interrupts == MAX_INTERRUPTS.
5000                          */
5001                         break;
5002                 }
5003                 throttle = 1;
5004         }
5005 }
5006
5007 static void perf_swevent_event(struct perf_event *event, u64 nr,
5008                                struct perf_sample_data *data,
5009                                struct pt_regs *regs)
5010 {
5011         struct hw_perf_event *hwc = &event->hw;
5012
5013         local64_add(nr, &event->count);
5014
5015         if (!regs)
5016                 return;
5017
5018         if (!is_sampling_event(event))
5019                 return;
5020
5021         if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
5022                 return perf_swevent_overflow(event, 1, data, regs);
5023
5024         if (local64_add_negative(nr, &hwc->period_left))
5025                 return;
5026
5027         perf_swevent_overflow(event, 0, data, regs);
5028 }
5029
5030 static int perf_exclude_event(struct perf_event *event,
5031                               struct pt_regs *regs)
5032 {
5033         if (event->hw.state & PERF_HES_STOPPED)
5034                 return 1;
5035
5036         if (regs) {
5037                 if (event->attr.exclude_user && user_mode(regs))
5038                         return 1;
5039
5040                 if (event->attr.exclude_kernel && !user_mode(regs))
5041                         return 1;
5042         }
5043
5044         return 0;
5045 }
5046
5047 static int perf_swevent_match(struct perf_event *event,
5048                                 enum perf_type_id type,
5049                                 u32 event_id,
5050                                 struct perf_sample_data *data,
5051                                 struct pt_regs *regs)
5052 {
5053         if (event->attr.type != type)
5054                 return 0;
5055
5056         if (event->attr.config != event_id)
5057                 return 0;
5058
5059         if (perf_exclude_event(event, regs))
5060                 return 0;
5061
5062         return 1;
5063 }
5064
5065 static inline u64 swevent_hash(u64 type, u32 event_id)
5066 {
5067         u64 val = event_id | (type << 32);
5068
5069         return hash_64(val, SWEVENT_HLIST_BITS);
5070 }
5071
5072 static inline struct hlist_head *
5073 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
5074 {
5075         u64 hash = swevent_hash(type, event_id);
5076
5077         return &hlist->heads[hash];
5078 }
5079
5080 /* For the read side: events when they trigger */
5081 static inline struct hlist_head *
5082 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
5083 {
5084         struct swevent_hlist *hlist;
5085
5086         hlist = rcu_dereference(swhash->swevent_hlist);
5087         if (!hlist)
5088                 return NULL;
5089
5090         return __find_swevent_head(hlist, type, event_id);
5091 }
5092
5093 /* For the event head insertion and removal in the hlist */
5094 static inline struct hlist_head *
5095 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
5096 {
5097         struct swevent_hlist *hlist;
5098         u32 event_id = event->attr.config;
5099         u64 type = event->attr.type;
5100
5101         /*
5102          * Event scheduling is always serialized against hlist allocation
5103          * and release. Which makes the protected version suitable here.
5104          * The context lock guarantees that.
5105          */
5106         hlist = rcu_dereference_protected(swhash->swevent_hlist,
5107                                           lockdep_is_held(&event->ctx->lock));
5108         if (!hlist)
5109                 return NULL;
5110
5111         return __find_swevent_head(hlist, type, event_id);
5112 }
5113
5114 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
5115                                     u64 nr,
5116                                     struct perf_sample_data *data,
5117                                     struct pt_regs *regs)
5118 {
5119         struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5120         struct perf_event *event;
5121         struct hlist_node *node;
5122         struct hlist_head *head;
5123
5124         rcu_read_lock();
5125         head = find_swevent_head_rcu(swhash, type, event_id);
5126         if (!head)
5127                 goto end;
5128
5129         hlist_for_each_entry_rcu(event, node, head, hlist_entry) {
5130                 if (perf_swevent_match(event, type, event_id, data, regs))
5131                         perf_swevent_event(event, nr, data, regs);
5132         }
5133 end:
5134         rcu_read_unlock();
5135 }
5136
5137 int perf_swevent_get_recursion_context(void)
5138 {
5139         struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5140
5141         return get_recursion_context(swhash->recursion);
5142 }
5143 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
5144
5145 inline void perf_swevent_put_recursion_context(int rctx)
5146 {
5147         struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5148
5149         put_recursion_context(swhash->recursion, rctx);
5150 }
5151
5152 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
5153 {
5154         struct perf_sample_data data;
5155         int rctx;
5156
5157         preempt_disable_notrace();
5158         rctx = perf_swevent_get_recursion_context();
5159         if (rctx < 0)
5160                 return;
5161
5162         perf_sample_data_init(&data, addr);
5163
5164         do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
5165
5166         perf_swevent_put_recursion_context(rctx);
5167         preempt_enable_notrace();
5168 }
5169
5170 static void perf_swevent_read(struct perf_event *event)
5171 {
5172 }
5173
5174 static int perf_swevent_add(struct perf_event *event, int flags)
5175 {
5176         struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5177         struct hw_perf_event *hwc = &event->hw;
5178         struct hlist_head *head;
5179
5180         if (is_sampling_event(event)) {
5181                 hwc->last_period = hwc->sample_period;
5182                 perf_swevent_set_period(event);
5183         }
5184
5185         hwc->state = !(flags & PERF_EF_START);
5186
5187         head = find_swevent_head(swhash, event);
5188         if (!head) {
5189                 /*
5190                  * We can race with cpu hotplug code. Do not
5191                  * WARN if the cpu just got unplugged.
5192                  */
5193                 WARN_ON_ONCE(swhash->online);
5194                 return -EINVAL;
5195         }
5196
5197         hlist_add_head_rcu(&event->hlist_entry, head);
5198
5199         return 0;
5200 }
5201
5202 static void perf_swevent_del(struct perf_event *event, int flags)
5203 {
5204         hlist_del_rcu(&event->hlist_entry);
5205 }
5206
5207 static void perf_swevent_start(struct perf_event *event, int flags)
5208 {
5209         event->hw.state = 0;
5210 }
5211
5212 static void perf_swevent_stop(struct perf_event *event, int flags)
5213 {
5214         event->hw.state = PERF_HES_STOPPED;
5215 }
5216
5217 /* Deref the hlist from the update side */
5218 static inline struct swevent_hlist *
5219 swevent_hlist_deref(struct swevent_htable *swhash)
5220 {
5221         return rcu_dereference_protected(swhash->swevent_hlist,
5222                                          lockdep_is_held(&swhash->hlist_mutex));
5223 }
5224
5225 static void swevent_hlist_release(struct swevent_htable *swhash)
5226 {
5227         struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
5228
5229         if (!hlist)
5230                 return;
5231
5232         rcu_assign_pointer(swhash->swevent_hlist, NULL);
5233         kfree_rcu(hlist, rcu_head);
5234 }
5235
5236 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
5237 {
5238         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5239
5240         mutex_lock(&swhash->hlist_mutex);
5241
5242         if (!--swhash->hlist_refcount)
5243                 swevent_hlist_release(swhash);
5244
5245         mutex_unlock(&swhash->hlist_mutex);
5246 }
5247
5248 static void swevent_hlist_put(struct perf_event *event)
5249 {
5250         int cpu;
5251
5252         if (event->cpu != -1) {
5253                 swevent_hlist_put_cpu(event, event->cpu);
5254                 return;
5255         }
5256
5257         for_each_possible_cpu(cpu)
5258                 swevent_hlist_put_cpu(event, cpu);
5259 }
5260
5261 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
5262 {
5263         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5264         int err = 0;
5265
5266         mutex_lock(&swhash->hlist_mutex);
5267
5268         if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
5269                 struct swevent_hlist *hlist;
5270
5271                 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
5272                 if (!hlist) {
5273                         err = -ENOMEM;
5274                         goto exit;
5275                 }
5276                 rcu_assign_pointer(swhash->swevent_hlist, hlist);
5277         }
5278         swhash->hlist_refcount++;
5279 exit:
5280         mutex_unlock(&swhash->hlist_mutex);
5281
5282         return err;
5283 }
5284
5285 static int swevent_hlist_get(struct perf_event *event)
5286 {
5287         int err;
5288         int cpu, failed_cpu;
5289
5290         if (event->cpu != -1)
5291                 return swevent_hlist_get_cpu(event, event->cpu);
5292
5293         get_online_cpus();
5294         for_each_possible_cpu(cpu) {
5295                 err = swevent_hlist_get_cpu(event, cpu);
5296                 if (err) {
5297                         failed_cpu = cpu;
5298                         goto fail;
5299                 }
5300         }
5301         put_online_cpus();
5302
5303         return 0;
5304 fail:
5305         for_each_possible_cpu(cpu) {
5306                 if (cpu == failed_cpu)
5307                         break;
5308                 swevent_hlist_put_cpu(event, cpu);
5309         }
5310
5311         put_online_cpus();
5312         return err;
5313 }
5314
5315 struct jump_label_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
5316
5317 static void sw_perf_event_destroy(struct perf_event *event)
5318 {
5319         u64 event_id = event->attr.config;
5320
5321         WARN_ON(event->parent);
5322
5323         jump_label_dec(&perf_swevent_enabled[event_id]);
5324         swevent_hlist_put(event);
5325 }
5326
5327 static int perf_swevent_init(struct perf_event *event)
5328 {
5329         u64 event_id = event->attr.config;
5330
5331         if (event->attr.type != PERF_TYPE_SOFTWARE)
5332                 return -ENOENT;
5333
5334         switch (event_id) {
5335         case PERF_COUNT_SW_CPU_CLOCK:
5336         case PERF_COUNT_SW_TASK_CLOCK:
5337                 return -ENOENT;
5338
5339         default:
5340                 break;
5341         }
5342
5343         if (event_id >= PERF_COUNT_SW_MAX)
5344                 return -ENOENT;
5345
5346         if (!event->parent) {
5347                 int err;
5348
5349                 err = swevent_hlist_get(event);
5350                 if (err)
5351                         return err;
5352
5353                 jump_label_inc(&perf_swevent_enabled[event_id]);
5354                 event->destroy = sw_perf_event_destroy;
5355         }
5356
5357         return 0;
5358 }
5359
5360 static struct pmu perf_swevent = {
5361         .task_ctx_nr    = perf_sw_context,
5362
5363         .event_init     = perf_swevent_init,
5364         .add            = perf_swevent_add,
5365         .del            = perf_swevent_del,
5366         .start          = perf_swevent_start,
5367         .stop           = perf_swevent_stop,
5368         .read           = perf_swevent_read,
5369 };
5370
5371 #ifdef CONFIG_EVENT_TRACING
5372
5373 static int perf_tp_filter_match(struct perf_event *event,
5374                                 struct perf_sample_data *data)
5375 {
5376         void *record = data->raw->data;
5377
5378         if (likely(!event->filter) || filter_match_preds(event->filter, record))
5379                 return 1;
5380         return 0;
5381 }
5382
5383 static int perf_tp_event_match(struct perf_event *event,
5384                                 struct perf_sample_data *data,
5385                                 struct pt_regs *regs)
5386 {
5387         if (event->hw.state & PERF_HES_STOPPED)
5388                 return 0;
5389         /*
5390          * All tracepoints are from kernel-space.
5391          */
5392         if (event->attr.exclude_kernel)
5393                 return 0;
5394
5395         if (!perf_tp_filter_match(event, data))
5396                 return 0;
5397
5398         return 1;
5399 }
5400
5401 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
5402                    struct pt_regs *regs, struct hlist_head *head, int rctx)
5403 {
5404         struct perf_sample_data data;
5405         struct perf_event *event;
5406         struct hlist_node *node;
5407
5408         struct perf_raw_record raw = {
5409                 .size = entry_size,
5410                 .data = record,
5411         };
5412
5413         perf_sample_data_init(&data, addr);
5414         data.raw = &raw;
5415
5416         hlist_for_each_entry_rcu(event, node, head, hlist_entry) {
5417                 if (perf_tp_event_match(event, &data, regs))
5418                         perf_swevent_event(event, count, &data, regs);
5419         }
5420
5421         perf_swevent_put_recursion_context(rctx);
5422 }
5423 EXPORT_SYMBOL_GPL(perf_tp_event);
5424
5425 static void tp_perf_event_destroy(struct perf_event *event)
5426 {
5427         perf_trace_destroy(event);
5428 }
5429
5430 static int perf_tp_event_init(struct perf_event *event)
5431 {
5432         int err;
5433
5434         if (event->attr.type != PERF_TYPE_TRACEPOINT)
5435                 return -ENOENT;
5436
5437         err = perf_trace_init(event);
5438         if (err)
5439                 return err;
5440
5441         event->destroy = tp_perf_event_destroy;
5442
5443         return 0;
5444 }
5445
5446 static struct pmu perf_tracepoint = {
5447         .task_ctx_nr    = perf_sw_context,
5448
5449         .event_init     = perf_tp_event_init,
5450         .add            = perf_trace_add,
5451         .del            = perf_trace_del,
5452         .start          = perf_swevent_start,
5453         .stop           = perf_swevent_stop,
5454         .read           = perf_swevent_read,
5455 };
5456
5457 static inline void perf_tp_register(void)
5458 {
5459         perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
5460 }
5461
5462 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
5463 {
5464         char *filter_str;
5465         int ret;
5466
5467         if (event->attr.type != PERF_TYPE_TRACEPOINT)
5468                 return -EINVAL;
5469
5470         filter_str = strndup_user(arg, PAGE_SIZE);
5471         if (IS_ERR(filter_str))
5472                 return PTR_ERR(filter_str);
5473
5474         ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
5475
5476         kfree(filter_str);
5477         return ret;
5478 }
5479
5480 static void perf_event_free_filter(struct perf_event *event)
5481 {
5482         ftrace_profile_free_filter(event);
5483 }
5484
5485 #else
5486
5487 static inline void perf_tp_register(void)
5488 {
5489 }
5490
5491 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
5492 {
5493         return -ENOENT;
5494 }
5495
5496 static void perf_event_free_filter(struct perf_event *event)
5497 {
5498 }
5499
5500 #endif /* CONFIG_EVENT_TRACING */
5501
5502 #ifdef CONFIG_HAVE_HW_BREAKPOINT
5503 void perf_bp_event(struct perf_event *bp, void *data)
5504 {
5505         struct perf_sample_data sample;
5506         struct pt_regs *regs = data;
5507
5508         perf_sample_data_init(&sample, bp->attr.bp_addr);
5509
5510         if (!bp->hw.state && !perf_exclude_event(bp, regs))
5511                 perf_swevent_event(bp, 1, &sample, regs);
5512 }
5513 #endif
5514
5515 /*
5516  * hrtimer based swevent callback
5517  */
5518
5519 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
5520 {
5521         enum hrtimer_restart ret = HRTIMER_RESTART;
5522         struct perf_sample_data data;
5523         struct pt_regs *regs;
5524         struct perf_event *event;
5525         u64 period;
5526
5527         event = container_of(hrtimer, struct perf_event, hw.hrtimer);
5528
5529         if (event->state != PERF_EVENT_STATE_ACTIVE)
5530                 return HRTIMER_NORESTART;
5531
5532         event->pmu->read(event);
5533
5534         perf_sample_data_init(&data, 0);
5535         data.period = event->hw.last_period;
5536         regs = get_irq_regs();
5537
5538         if (regs && !perf_exclude_event(event, regs)) {
5539                 if (!(event->attr.exclude_idle && current->pid == 0))
5540                         if (perf_event_overflow(event, &data, regs))
5541                                 ret = HRTIMER_NORESTART;
5542         }
5543
5544         period = max_t(u64, 10000, event->hw.sample_period);
5545         hrtimer_forward_now(hrtimer, ns_to_ktime(period));
5546
5547         return ret;
5548 }
5549
5550 static void perf_swevent_start_hrtimer(struct perf_event *event)
5551 {
5552         struct hw_perf_event *hwc = &event->hw;
5553         s64 period;
5554
5555         if (!is_sampling_event(event))
5556                 return;
5557
5558         period = local64_read(&hwc->period_left);
5559         if (period) {
5560                 if (period < 0)
5561                         period = 10000;
5562
5563                 local64_set(&hwc->period_left, 0);
5564         } else {
5565                 period = max_t(u64, 10000, hwc->sample_period);
5566         }
5567         __hrtimer_start_range_ns(&hwc->hrtimer,
5568                                 ns_to_ktime(period), 0,
5569                                 HRTIMER_MODE_REL_PINNED, 0);
5570 }
5571
5572 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
5573 {
5574         struct hw_perf_event *hwc = &event->hw;
5575
5576         if (is_sampling_event(event)) {
5577                 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
5578                 local64_set(&hwc->period_left, ktime_to_ns(remaining));
5579
5580                 hrtimer_cancel(&hwc->hrtimer);
5581         }
5582 }
5583
5584 static void perf_swevent_init_hrtimer(struct perf_event *event)
5585 {
5586         struct hw_perf_event *hwc = &event->hw;
5587
5588         if (!is_sampling_event(event))
5589                 return;
5590
5591         hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
5592         hwc->hrtimer.function = perf_swevent_hrtimer;
5593
5594         /*
5595          * Since hrtimers have a fixed rate, we can do a static freq->period
5596          * mapping and avoid the whole period adjust feedback stuff.
5597          */
5598         if (event->attr.freq) {
5599                 long freq = event->attr.sample_freq;
5600
5601                 event->attr.sample_period = NSEC_PER_SEC / freq;
5602                 hwc->sample_period = event->attr.sample_period;
5603                 local64_set(&hwc->period_left, hwc->sample_period);
5604                 event->attr.freq = 0;
5605         }
5606 }
5607
5608 /*
5609  * Software event: cpu wall time clock
5610  */
5611
5612 static void cpu_clock_event_update(struct perf_event *event)
5613 {
5614         s64 prev;
5615         u64 now;
5616
5617         now = local_clock();
5618         prev = local64_xchg(&event->hw.prev_count, now);
5619         local64_add(now - prev, &event->count);
5620 }
5621
5622 static void cpu_clock_event_start(struct perf_event *event, int flags)
5623 {
5624         local64_set(&event->hw.prev_count, local_clock());
5625         perf_swevent_start_hrtimer(event);
5626 }
5627
5628 static void cpu_clock_event_stop(struct perf_event *event, int flags)
5629 {
5630         perf_swevent_cancel_hrtimer(event);
5631         cpu_clock_event_update(event);
5632 }
5633
5634 static int cpu_clock_event_add(struct perf_event *event, int flags)
5635 {
5636         if (flags & PERF_EF_START)
5637                 cpu_clock_event_start(event, flags);
5638
5639         return 0;
5640 }
5641
5642 static void cpu_clock_event_del(struct perf_event *event, int flags)
5643 {
5644         cpu_clock_event_stop(event, flags);
5645 }
5646
5647 static void cpu_clock_event_read(struct perf_event *event)
5648 {
5649         cpu_clock_event_update(event);
5650 }
5651
5652 static int cpu_clock_event_init(struct perf_event *event)
5653 {
5654         if (event->attr.type != PERF_TYPE_SOFTWARE)
5655                 return -ENOENT;
5656
5657         if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
5658                 return -ENOENT;
5659
5660         perf_swevent_init_hrtimer(event);
5661
5662         return 0;
5663 }
5664
5665 static struct pmu perf_cpu_clock = {
5666         .task_ctx_nr    = perf_sw_context,
5667
5668         .event_init     = cpu_clock_event_init,
5669         .add            = cpu_clock_event_add,
5670         .del            = cpu_clock_event_del,
5671         .start          = cpu_clock_event_start,
5672         .stop           = cpu_clock_event_stop,
5673         .read           = cpu_clock_event_read,
5674 };
5675
5676 /*
5677  * Software event: task time clock
5678  */
5679
5680 static void task_clock_event_update(struct perf_event *event, u64 now)
5681 {
5682         u64 prev;
5683         s64 delta;
5684
5685         prev = local64_xchg(&event->hw.prev_count, now);
5686         delta = now - prev;
5687         local64_add(delta, &event->count);
5688 }
5689
5690 static void task_clock_event_start(struct perf_event *event, int flags)
5691 {
5692         local64_set(&event->hw.prev_count, event->ctx->time);
5693         perf_swevent_start_hrtimer(event);
5694 }
5695
5696 static void task_clock_event_stop(struct perf_event *event, int flags)
5697 {
5698         perf_swevent_cancel_hrtimer(event);
5699         task_clock_event_update(event, event->ctx->time);
5700 }
5701
5702 static int task_clock_event_add(struct perf_event *event, int flags)
5703 {
5704         if (flags & PERF_EF_START)
5705                 task_clock_event_start(event, flags);
5706
5707         return 0;
5708 }
5709
5710 static void task_clock_event_del(struct perf_event *event, int flags)
5711 {
5712         task_clock_event_stop(event, PERF_EF_UPDATE);
5713 }
5714
5715 static void task_clock_event_read(struct perf_event *event)
5716 {
5717         u64 now = perf_clock();
5718         u64 delta = now - event->ctx->timestamp;
5719         u64 time = event->ctx->time + delta;
5720
5721         task_clock_event_update(event, time);
5722 }
5723
5724 static int task_clock_event_init(struct perf_event *event)
5725 {
5726         if (event->attr.type != PERF_TYPE_SOFTWARE)
5727                 return -ENOENT;
5728
5729         if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
5730                 return -ENOENT;
5731
5732         perf_swevent_init_hrtimer(event);
5733
5734         return 0;
5735 }
5736
5737 static struct pmu perf_task_clock = {
5738         .task_ctx_nr    = perf_sw_context,
5739
5740         .event_init     = task_clock_event_init,
5741         .add            = task_clock_event_add,
5742         .del            = task_clock_event_del,
5743         .start          = task_clock_event_start,
5744         .stop           = task_clock_event_stop,
5745         .read           = task_clock_event_read,
5746 };
5747
5748 static void perf_pmu_nop_void(struct pmu *pmu)
5749 {
5750 }
5751
5752 static int perf_pmu_nop_int(struct pmu *pmu)
5753 {
5754         return 0;
5755 }
5756
5757 static void perf_pmu_start_txn(struct pmu *pmu)
5758 {
5759         perf_pmu_disable(pmu);
5760 }
5761
5762 static int perf_pmu_commit_txn(struct pmu *pmu)
5763 {
5764         perf_pmu_enable(pmu);
5765         return 0;
5766 }
5767
5768 static void perf_pmu_cancel_txn(struct pmu *pmu)
5769 {
5770         perf_pmu_enable(pmu);
5771 }
5772
5773 /*
5774  * Ensures all contexts with the same task_ctx_nr have the same
5775  * pmu_cpu_context too.
5776  */
5777 static void *find_pmu_context(int ctxn)
5778 {
5779         struct pmu *pmu;
5780
5781         if (ctxn < 0)
5782                 return NULL;
5783
5784         list_for_each_entry(pmu, &pmus, entry) {
5785                 if (pmu->task_ctx_nr == ctxn)
5786                         return pmu->pmu_cpu_context;
5787         }
5788
5789         return NULL;
5790 }
5791
5792 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
5793 {
5794         int cpu;
5795
5796         for_each_possible_cpu(cpu) {
5797                 struct perf_cpu_context *cpuctx;
5798
5799                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
5800
5801                 if (cpuctx->unique_pmu == old_pmu)
5802                         cpuctx->unique_pmu = pmu;
5803         }
5804 }
5805
5806 static void free_pmu_context(struct pmu *pmu)
5807 {
5808         struct pmu *i;
5809
5810         mutex_lock(&pmus_lock);
5811         /*
5812          * Like a real lame refcount.
5813          */
5814         list_for_each_entry(i, &pmus, entry) {
5815                 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
5816                         update_pmu_context(i, pmu);
5817                         goto out;
5818                 }
5819         }
5820
5821         free_percpu(pmu->pmu_cpu_context);
5822 out:
5823         mutex_unlock(&pmus_lock);
5824 }
5825 static struct idr pmu_idr;
5826
5827 static ssize_t
5828 type_show(struct device *dev, struct device_attribute *attr, char *page)
5829 {
5830         struct pmu *pmu = dev_get_drvdata(dev);
5831
5832         return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
5833 }
5834
5835 static struct device_attribute pmu_dev_attrs[] = {
5836        __ATTR_RO(type),
5837        __ATTR_NULL,
5838 };
5839
5840 static int pmu_bus_running;
5841 static struct bus_type pmu_bus = {
5842         .name           = "event_source",
5843         .dev_attrs      = pmu_dev_attrs,
5844 };
5845
5846 static void pmu_dev_release(struct device *dev)
5847 {
5848         kfree(dev);
5849 }
5850
5851 static int pmu_dev_alloc(struct pmu *pmu)
5852 {
5853         int ret = -ENOMEM;
5854
5855         pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
5856         if (!pmu->dev)
5857                 goto out;
5858
5859         device_initialize(pmu->dev);
5860         ret = dev_set_name(pmu->dev, "%s", pmu->name);
5861         if (ret)
5862                 goto free_dev;
5863
5864         dev_set_drvdata(pmu->dev, pmu);
5865         pmu->dev->bus = &pmu_bus;
5866         pmu->dev->release = pmu_dev_release;
5867         ret = device_add(pmu->dev);
5868         if (ret)
5869                 goto free_dev;
5870
5871 out:
5872         return ret;
5873
5874 free_dev:
5875         put_device(pmu->dev);
5876         goto out;
5877 }
5878
5879 static struct lock_class_key cpuctx_mutex;
5880 static struct lock_class_key cpuctx_lock;
5881
5882 int perf_pmu_register(struct pmu *pmu, char *name, int type)
5883 {
5884         int cpu, ret;
5885
5886         mutex_lock(&pmus_lock);
5887         ret = -ENOMEM;
5888         pmu->pmu_disable_count = alloc_percpu(int);
5889         if (!pmu->pmu_disable_count)
5890                 goto unlock;
5891
5892         pmu->type = -1;
5893         if (!name)
5894                 goto skip_type;
5895         pmu->name = name;
5896
5897         if (type < 0) {
5898                 int err = idr_pre_get(&pmu_idr, GFP_KERNEL);
5899                 if (!err)
5900                         goto free_pdc;
5901
5902                 err = idr_get_new_above(&pmu_idr, pmu, PERF_TYPE_MAX, &type);
5903                 if (err) {
5904                         ret = err;
5905                         goto free_pdc;
5906                 }
5907         }
5908         pmu->type = type;
5909
5910         if (pmu_bus_running) {
5911                 ret = pmu_dev_alloc(pmu);
5912                 if (ret)
5913                         goto free_idr;
5914         }
5915
5916 skip_type:
5917         pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
5918         if (pmu->pmu_cpu_context)
5919                 goto got_cpu_context;
5920
5921         ret = -ENOMEM;
5922         pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
5923         if (!pmu->pmu_cpu_context)
5924                 goto free_dev;
5925
5926         for_each_possible_cpu(cpu) {
5927                 struct perf_cpu_context *cpuctx;
5928
5929                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
5930                 __perf_event_init_context(&cpuctx->ctx);
5931                 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
5932                 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
5933                 cpuctx->ctx.type = cpu_context;
5934                 cpuctx->ctx.pmu = pmu;
5935                 cpuctx->jiffies_interval = 1;
5936                 INIT_LIST_HEAD(&cpuctx->rotation_list);
5937                 cpuctx->unique_pmu = pmu;
5938         }
5939
5940 got_cpu_context:
5941         if (!pmu->start_txn) {
5942                 if (pmu->pmu_enable) {
5943                         /*
5944                          * If we have pmu_enable/pmu_disable calls, install
5945                          * transaction stubs that use that to try and batch
5946                          * hardware accesses.
5947                          */
5948                         pmu->start_txn  = perf_pmu_start_txn;
5949                         pmu->commit_txn = perf_pmu_commit_txn;
5950                         pmu->cancel_txn = perf_pmu_cancel_txn;
5951                 } else {
5952                         pmu->start_txn  = perf_pmu_nop_void;
5953                         pmu->commit_txn = perf_pmu_nop_int;
5954                         pmu->cancel_txn = perf_pmu_nop_void;
5955                 }
5956         }
5957
5958         if (!pmu->pmu_enable) {
5959                 pmu->pmu_enable  = perf_pmu_nop_void;
5960                 pmu->pmu_disable = perf_pmu_nop_void;
5961         }
5962
5963         list_add_rcu(&pmu->entry, &pmus);
5964         ret = 0;
5965 unlock:
5966         mutex_unlock(&pmus_lock);
5967
5968         return ret;
5969
5970 free_dev:
5971         device_del(pmu->dev);
5972         put_device(pmu->dev);
5973
5974 free_idr:
5975         if (pmu->type >= PERF_TYPE_MAX)
5976                 idr_remove(&pmu_idr, pmu->type);
5977
5978 free_pdc:
5979         free_percpu(pmu->pmu_disable_count);
5980         goto unlock;
5981 }
5982
5983 void perf_pmu_unregister(struct pmu *pmu)
5984 {
5985         mutex_lock(&pmus_lock);
5986         list_del_rcu(&pmu->entry);
5987         mutex_unlock(&pmus_lock);
5988
5989         /*
5990          * We dereference the pmu list under both SRCU and regular RCU, so
5991          * synchronize against both of those.
5992          */
5993         synchronize_srcu(&pmus_srcu);
5994         synchronize_rcu();
5995
5996         free_percpu(pmu->pmu_disable_count);
5997         if (pmu->type >= PERF_TYPE_MAX)
5998                 idr_remove(&pmu_idr, pmu->type);
5999         device_del(pmu->dev);
6000         put_device(pmu->dev);
6001         free_pmu_context(pmu);
6002 }
6003
6004 struct pmu *perf_init_event(struct perf_event *event)
6005 {
6006         struct pmu *pmu = NULL;
6007         int idx;
6008         int ret;
6009
6010         idx = srcu_read_lock(&pmus_srcu);
6011
6012         rcu_read_lock();
6013         pmu = idr_find(&pmu_idr, event->attr.type);
6014         rcu_read_unlock();
6015         if (pmu) {
6016                 event->pmu = pmu;
6017                 ret = pmu->event_init(event);
6018                 if (ret)
6019                         pmu = ERR_PTR(ret);
6020                 goto unlock;
6021         }
6022
6023         list_for_each_entry_rcu(pmu, &pmus, entry) {
6024                 event->pmu = pmu;
6025                 ret = pmu->event_init(event);
6026                 if (!ret)
6027                         goto unlock;
6028
6029                 if (ret != -ENOENT) {
6030                         pmu = ERR_PTR(ret);
6031                         goto unlock;
6032                 }
6033         }
6034         pmu = ERR_PTR(-ENOENT);
6035 unlock:
6036         srcu_read_unlock(&pmus_srcu, idx);
6037
6038         return pmu;
6039 }
6040
6041 /*
6042  * Allocate and initialize a event structure
6043  */
6044 static struct perf_event *
6045 perf_event_alloc(struct perf_event_attr *attr, int cpu,
6046                  struct task_struct *task,
6047                  struct perf_event *group_leader,
6048                  struct perf_event *parent_event,
6049                  perf_overflow_handler_t overflow_handler,
6050                  void *context)
6051 {
6052         struct pmu *pmu;
6053         struct perf_event *event;
6054         struct hw_perf_event *hwc;
6055         long err;
6056
6057         if ((unsigned)cpu >= nr_cpu_ids) {
6058                 if (!task || cpu != -1)
6059                         return ERR_PTR(-EINVAL);
6060         }
6061
6062         event = kzalloc(sizeof(*event), GFP_KERNEL);
6063         if (!event)
6064                 return ERR_PTR(-ENOMEM);
6065
6066         /*
6067          * Single events are their own group leaders, with an
6068          * empty sibling list:
6069          */
6070         if (!group_leader)
6071                 group_leader = event;
6072
6073         mutex_init(&event->child_mutex);
6074         INIT_LIST_HEAD(&event->child_list);
6075
6076         INIT_LIST_HEAD(&event->group_entry);
6077         INIT_LIST_HEAD(&event->event_entry);
6078         INIT_LIST_HEAD(&event->sibling_list);
6079         INIT_LIST_HEAD(&event->rb_entry);
6080
6081         init_waitqueue_head(&event->waitq);
6082         init_irq_work(&event->pending, perf_pending_event);
6083
6084         mutex_init(&event->mmap_mutex);
6085
6086         atomic_long_set(&event->refcount, 1);
6087         event->cpu              = cpu;
6088         event->attr             = *attr;
6089         event->group_leader     = group_leader;
6090         event->pmu              = NULL;
6091         event->oncpu            = -1;
6092
6093         event->parent           = parent_event;
6094
6095         event->ns               = get_pid_ns(current->nsproxy->pid_ns);
6096         event->id               = atomic64_inc_return(&perf_event_id);
6097
6098         event->state            = PERF_EVENT_STATE_INACTIVE;
6099
6100         if (task) {
6101                 event->attach_state = PERF_ATTACH_TASK;
6102 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6103                 /*
6104                  * hw_breakpoint is a bit difficult here..
6105                  */
6106                 if (attr->type == PERF_TYPE_BREAKPOINT)
6107                         event->hw.bp_target = task;
6108 #endif
6109         }
6110
6111         if (!overflow_handler && parent_event) {
6112                 overflow_handler = parent_event->overflow_handler;
6113                 context = parent_event->overflow_handler_context;
6114         }
6115
6116         event->overflow_handler = overflow_handler;
6117         event->overflow_handler_context = context;
6118
6119         perf_event__state_init(event);
6120
6121         pmu = NULL;
6122
6123         hwc = &event->hw;
6124         hwc->sample_period = attr->sample_period;
6125         if (attr->freq && attr->sample_freq)
6126                 hwc->sample_period = 1;
6127         hwc->last_period = hwc->sample_period;
6128
6129         local64_set(&hwc->period_left, hwc->sample_period);
6130
6131         /*
6132          * we currently do not support PERF_FORMAT_GROUP on inherited events
6133          */
6134         if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
6135                 goto done;
6136
6137         pmu = perf_init_event(event);
6138
6139 done:
6140         err = 0;
6141         if (!pmu)
6142                 err = -EINVAL;
6143         else if (IS_ERR(pmu))
6144                 err = PTR_ERR(pmu);
6145
6146         if (err) {
6147                 if (event->ns)
6148                         put_pid_ns(event->ns);
6149                 kfree(event);
6150                 return ERR_PTR(err);
6151         }
6152
6153         if (!event->parent) {
6154                 if (event->attach_state & PERF_ATTACH_TASK)
6155                         jump_label_inc(&perf_sched_events);
6156                 if (event->attr.mmap || event->attr.mmap_data)
6157                         atomic_inc(&nr_mmap_events);
6158                 if (event->attr.comm)
6159                         atomic_inc(&nr_comm_events);
6160                 if (event->attr.task)
6161                         atomic_inc(&nr_task_events);
6162                 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
6163                         err = get_callchain_buffers();
6164                         if (err) {
6165                                 free_event(event);
6166                                 return ERR_PTR(err);
6167                         }
6168                 }
6169         }
6170
6171         return event;
6172 }
6173
6174 static int perf_copy_attr(struct perf_event_attr __user *uattr,
6175                           struct perf_event_attr *attr)
6176 {
6177         u32 size;
6178         int ret;
6179
6180         if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
6181                 return -EFAULT;
6182
6183         /*
6184          * zero the full structure, so that a short copy will be nice.
6185          */
6186         memset(attr, 0, sizeof(*attr));
6187
6188         ret = get_user(size, &uattr->size);
6189         if (ret)
6190                 return ret;
6191
6192         if (size > PAGE_SIZE)   /* silly large */
6193                 goto err_size;
6194
6195         if (!size)              /* abi compat */
6196                 size = PERF_ATTR_SIZE_VER0;
6197
6198         if (size < PERF_ATTR_SIZE_VER0)
6199                 goto err_size;
6200
6201         /*
6202          * If we're handed a bigger struct than we know of,
6203          * ensure all the unknown bits are 0 - i.e. new
6204          * user-space does not rely on any kernel feature
6205          * extensions we dont know about yet.
6206          */
6207         if (size > sizeof(*attr)) {
6208                 unsigned char __user *addr;
6209                 unsigned char __user *end;
6210                 unsigned char val;
6211
6212                 addr = (void __user *)uattr + sizeof(*attr);
6213                 end  = (void __user *)uattr + size;
6214
6215                 for (; addr < end; addr++) {
6216                         ret = get_user(val, addr);
6217                         if (ret)
6218                                 return ret;
6219                         if (val)
6220                                 goto err_size;
6221                 }
6222                 size = sizeof(*attr);
6223         }
6224
6225         ret = copy_from_user(attr, uattr, size);
6226         if (ret)
6227                 return -EFAULT;
6228
6229         if (attr->__reserved_1)
6230                 return -EINVAL;
6231
6232         if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
6233                 return -EINVAL;
6234
6235         if (attr->read_format & ~(PERF_FORMAT_MAX-1))
6236                 return -EINVAL;
6237
6238 out:
6239         return ret;
6240
6241 err_size:
6242         put_user(sizeof(*attr), &uattr->size);
6243         ret = -E2BIG;
6244         goto out;
6245 }
6246
6247 static int
6248 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
6249 {
6250         struct ring_buffer *rb = NULL, *old_rb = NULL;
6251         int ret = -EINVAL;
6252
6253         if (!output_event)
6254                 goto set;
6255
6256         /* don't allow circular references */
6257         if (event == output_event)
6258                 goto out;
6259
6260         /*
6261          * Don't allow cross-cpu buffers
6262          */
6263         if (output_event->cpu != event->cpu)
6264                 goto out;
6265
6266         /*
6267          * If its not a per-cpu rb, it must be the same task.
6268          */
6269         if (output_event->cpu == -1 && output_event->ctx != event->ctx)
6270                 goto out;
6271
6272 set:
6273         mutex_lock(&event->mmap_mutex);
6274         /* Can't redirect output if we've got an active mmap() */
6275         if (atomic_read(&event->mmap_count))
6276                 goto unlock;
6277
6278         old_rb = event->rb;
6279
6280         if (output_event) {
6281                 /* get the rb we want to redirect to */
6282                 rb = ring_buffer_get(output_event);
6283                 if (!rb)
6284                         goto unlock;
6285         }
6286
6287         if (old_rb)
6288                 ring_buffer_detach(event, old_rb);
6289
6290         if (rb)
6291                 ring_buffer_attach(event, rb);
6292
6293         rcu_assign_pointer(event->rb, rb);
6294
6295         if (old_rb) {
6296                 ring_buffer_put(old_rb);
6297                 /*
6298                  * Since we detached before setting the new rb, so that we
6299                  * could attach the new rb, we could have missed a wakeup.
6300                  * Provide it now.
6301                  */
6302                 wake_up_all(&event->waitq);
6303         }
6304
6305         ret = 0;
6306 unlock:
6307         mutex_unlock(&event->mmap_mutex);
6308
6309 out:
6310         return ret;
6311 }
6312
6313 /**
6314  * sys_perf_event_open - open a performance event, associate it to a task/cpu
6315  *
6316  * @attr_uptr:  event_id type attributes for monitoring/sampling
6317  * @pid:                target pid
6318  * @cpu:                target cpu
6319  * @group_fd:           group leader event fd
6320  */
6321 SYSCALL_DEFINE5(perf_event_open,
6322                 struct perf_event_attr __user *, attr_uptr,
6323                 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
6324 {
6325         struct perf_event *group_leader = NULL, *output_event = NULL;
6326         struct perf_event *event, *sibling;
6327         struct perf_event_attr attr;
6328         struct perf_event_context *ctx;
6329         struct file *event_file = NULL;
6330         struct file *group_file = NULL;
6331         struct task_struct *task = NULL;
6332         struct pmu *pmu;
6333         int event_fd;
6334         int move_group = 0;
6335         int fput_needed = 0;
6336         int err;
6337
6338         /* for future expandability... */
6339         if (flags & ~PERF_FLAG_ALL)
6340                 return -EINVAL;
6341
6342         err = perf_copy_attr(attr_uptr, &attr);
6343         if (err)
6344                 return err;
6345
6346         if (!attr.exclude_kernel) {
6347                 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
6348                         return -EACCES;
6349         }
6350
6351         if (attr.freq) {
6352                 if (attr.sample_freq > sysctl_perf_event_sample_rate)
6353                         return -EINVAL;
6354         } else {
6355                 if (attr.sample_period & (1ULL << 63))
6356                         return -EINVAL;
6357         }
6358
6359         /*
6360          * In cgroup mode, the pid argument is used to pass the fd
6361          * opened to the cgroup directory in cgroupfs. The cpu argument
6362          * designates the cpu on which to monitor threads from that
6363          * cgroup.
6364          */
6365         if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
6366                 return -EINVAL;
6367
6368         event_fd = get_unused_fd_flags(O_RDWR);
6369         if (event_fd < 0)
6370                 return event_fd;
6371
6372         if (group_fd != -1) {
6373                 group_file = perf_fget_light(group_fd, &fput_needed);
6374                 if (IS_ERR(group_file)) {
6375                         err = PTR_ERR(group_file);
6376                         goto err_fd;
6377                 }
6378                 group_leader = group_file->private_data;
6379                 if (flags & PERF_FLAG_FD_OUTPUT)
6380                         output_event = group_leader;
6381                 if (flags & PERF_FLAG_FD_NO_GROUP)
6382                         group_leader = NULL;
6383         }
6384
6385         if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
6386                 task = find_lively_task_by_vpid(pid);
6387                 if (IS_ERR(task)) {
6388                         err = PTR_ERR(task);
6389                         goto err_group_fd;
6390                 }
6391         }
6392
6393         event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
6394                                  NULL, NULL);
6395         if (IS_ERR(event)) {
6396                 err = PTR_ERR(event);
6397                 goto err_task;
6398         }
6399
6400         if (flags & PERF_FLAG_PID_CGROUP) {
6401                 err = perf_cgroup_connect(pid, event, &attr, group_leader);
6402                 if (err)
6403                         goto err_alloc;
6404                 /*
6405                  * one more event:
6406                  * - that has cgroup constraint on event->cpu
6407                  * - that may need work on context switch
6408                  */
6409                 atomic_inc(&per_cpu(perf_cgroup_events, event->cpu));
6410                 jump_label_inc(&perf_sched_events);
6411         }
6412
6413         /*
6414          * Special case software events and allow them to be part of
6415          * any hardware group.
6416          */
6417         pmu = event->pmu;
6418
6419         if (group_leader &&
6420             (is_software_event(event) != is_software_event(group_leader))) {
6421                 if (is_software_event(event)) {
6422                         /*
6423                          * If event and group_leader are not both a software
6424                          * event, and event is, then group leader is not.
6425                          *
6426                          * Allow the addition of software events to !software
6427                          * groups, this is safe because software events never
6428                          * fail to schedule.
6429                          */
6430                         pmu = group_leader->pmu;
6431                 } else if (is_software_event(group_leader) &&
6432                            (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
6433                         /*
6434                          * In case the group is a pure software group, and we
6435                          * try to add a hardware event, move the whole group to
6436                          * the hardware context.
6437                          */
6438                         move_group = 1;
6439                 }
6440         }
6441
6442         /*
6443          * Get the target context (task or percpu):
6444          */
6445         ctx = find_get_context(pmu, task, cpu);
6446         if (IS_ERR(ctx)) {
6447                 err = PTR_ERR(ctx);
6448                 goto err_alloc;
6449         }
6450
6451         if (task) {
6452                 put_task_struct(task);
6453                 task = NULL;
6454         }
6455
6456         /*
6457          * Look up the group leader (we will attach this event to it):
6458          */
6459         if (group_leader) {
6460                 err = -EINVAL;
6461
6462                 /*
6463                  * Do not allow a recursive hierarchy (this new sibling
6464                  * becoming part of another group-sibling):
6465                  */
6466                 if (group_leader->group_leader != group_leader)
6467                         goto err_context;
6468                 /*
6469                  * Do not allow to attach to a group in a different
6470                  * task or CPU context:
6471                  */
6472                 if (move_group) {
6473                         if (group_leader->ctx->type != ctx->type)
6474                                 goto err_context;
6475                 } else {
6476                         if (group_leader->ctx != ctx)
6477                                 goto err_context;
6478                 }
6479
6480                 /*
6481                  * Only a group leader can be exclusive or pinned
6482                  */
6483                 if (attr.exclusive || attr.pinned)
6484                         goto err_context;
6485         }
6486
6487         if (output_event) {
6488                 err = perf_event_set_output(event, output_event);
6489                 if (err)
6490                         goto err_context;
6491         }
6492
6493         event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, O_RDWR);
6494         if (IS_ERR(event_file)) {
6495                 err = PTR_ERR(event_file);
6496                 goto err_context;
6497         }
6498
6499         if (move_group) {
6500                 struct perf_event_context *gctx = group_leader->ctx;
6501
6502                 mutex_lock(&gctx->mutex);
6503                 perf_remove_from_context(group_leader, false);
6504
6505                 /*
6506                  * Removing from the context ends up with disabled
6507                  * event. What we want here is event in the initial
6508                  * startup state, ready to be add into new context.
6509                  */
6510                 perf_event__state_init(group_leader);
6511                 list_for_each_entry(sibling, &group_leader->sibling_list,
6512                                     group_entry) {
6513                         perf_remove_from_context(sibling, false);
6514                         perf_event__state_init(sibling);
6515                         put_ctx(gctx);
6516                 }
6517                 mutex_unlock(&gctx->mutex);
6518                 put_ctx(gctx);
6519         }
6520
6521         WARN_ON_ONCE(ctx->parent_ctx);
6522         mutex_lock(&ctx->mutex);
6523
6524         if (move_group) {
6525                 perf_install_in_context(ctx, group_leader, cpu);
6526                 get_ctx(ctx);
6527                 list_for_each_entry(sibling, &group_leader->sibling_list,
6528                                     group_entry) {
6529                         perf_install_in_context(ctx, sibling, cpu);
6530                         get_ctx(ctx);
6531                 }
6532         }
6533
6534         perf_install_in_context(ctx, event, cpu);
6535         ++ctx->generation;
6536         perf_unpin_context(ctx);
6537         mutex_unlock(&ctx->mutex);
6538
6539         event->owner = current;
6540
6541         mutex_lock(&current->perf_event_mutex);
6542         list_add_tail(&event->owner_entry, &current->perf_event_list);
6543         mutex_unlock(&current->perf_event_mutex);
6544
6545         /*
6546          * Precalculate sample_data sizes
6547          */
6548         perf_event__header_size(event);
6549         perf_event__id_header_size(event);
6550
6551         /*
6552          * Drop the reference on the group_event after placing the
6553          * new event on the sibling_list. This ensures destruction
6554          * of the group leader will find the pointer to itself in
6555          * perf_group_detach().
6556          */
6557         fput_light(group_file, fput_needed);
6558         fd_install(event_fd, event_file);
6559         return event_fd;
6560
6561 err_context:
6562         perf_unpin_context(ctx);
6563         put_ctx(ctx);
6564 err_alloc:
6565         free_event(event);
6566 err_task:
6567         if (task)
6568                 put_task_struct(task);
6569 err_group_fd:
6570         fput_light(group_file, fput_needed);
6571 err_fd:
6572         put_unused_fd(event_fd);
6573         return err;
6574 }
6575
6576 /**
6577  * perf_event_create_kernel_counter
6578  *
6579  * @attr: attributes of the counter to create
6580  * @cpu: cpu in which the counter is bound
6581  * @task: task to profile (NULL for percpu)
6582  */
6583 struct perf_event *
6584 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
6585                                  struct task_struct *task,
6586                                  perf_overflow_handler_t overflow_handler,
6587                                  void *context)
6588 {
6589         struct perf_event_context *ctx;
6590         struct perf_event *event;
6591         int err;
6592
6593         /*
6594          * Get the target context (task or percpu):
6595          */
6596
6597         event = perf_event_alloc(attr, cpu, task, NULL, NULL,
6598                                  overflow_handler, context);
6599         if (IS_ERR(event)) {
6600                 err = PTR_ERR(event);
6601                 goto err;
6602         }
6603
6604         ctx = find_get_context(event->pmu, task, cpu);
6605         if (IS_ERR(ctx)) {
6606                 err = PTR_ERR(ctx);
6607                 goto err_free;
6608         }
6609
6610         WARN_ON_ONCE(ctx->parent_ctx);
6611         mutex_lock(&ctx->mutex);
6612         perf_install_in_context(ctx, event, cpu);
6613         ++ctx->generation;
6614         perf_unpin_context(ctx);
6615         mutex_unlock(&ctx->mutex);
6616
6617         return event;
6618
6619 err_free:
6620         free_event(event);
6621 err:
6622         return ERR_PTR(err);
6623 }
6624 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
6625
6626 static void sync_child_event(struct perf_event *child_event,
6627                                struct task_struct *child)
6628 {
6629         struct perf_event *parent_event = child_event->parent;
6630         u64 child_val;
6631
6632         if (child_event->attr.inherit_stat)
6633                 perf_event_read_event(child_event, child);
6634
6635         child_val = perf_event_count(child_event);
6636
6637         /*
6638          * Add back the child's count to the parent's count:
6639          */
6640         atomic64_add(child_val, &parent_event->child_count);
6641         atomic64_add(child_event->total_time_enabled,
6642                      &parent_event->child_total_time_enabled);
6643         atomic64_add(child_event->total_time_running,
6644                      &parent_event->child_total_time_running);
6645
6646         /*
6647          * Remove this event from the parent's list
6648          */
6649         WARN_ON_ONCE(parent_event->ctx->parent_ctx);
6650         mutex_lock(&parent_event->child_mutex);
6651         list_del_init(&child_event->child_list);
6652         mutex_unlock(&parent_event->child_mutex);
6653
6654         /*
6655          * Release the parent event, if this was the last
6656          * reference to it.
6657          */
6658         put_event(parent_event);
6659 }
6660
6661 static void
6662 __perf_event_exit_task(struct perf_event *child_event,
6663                          struct perf_event_context *child_ctx,
6664                          struct task_struct *child)
6665 {
6666         perf_remove_from_context(child_event, !!child_event->parent);
6667
6668         /*
6669          * It can happen that the parent exits first, and has events
6670          * that are still around due to the child reference. These
6671          * events need to be zapped.
6672          */
6673         if (child_event->parent) {
6674                 sync_child_event(child_event, child);
6675                 free_event(child_event);
6676         }
6677 }
6678
6679 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
6680 {
6681         struct perf_event *child_event, *tmp;
6682         struct perf_event_context *child_ctx;
6683         unsigned long flags;
6684
6685         if (likely(!child->perf_event_ctxp[ctxn])) {
6686                 perf_event_task(child, NULL, 0);
6687                 return;
6688         }
6689
6690         local_irq_save(flags);
6691         /*
6692          * We can't reschedule here because interrupts are disabled,
6693          * and either child is current or it is a task that can't be
6694          * scheduled, so we are now safe from rescheduling changing
6695          * our context.
6696          */
6697         child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
6698
6699         /*
6700          * Take the context lock here so that if find_get_context is
6701          * reading child->perf_event_ctxp, we wait until it has
6702          * incremented the context's refcount before we do put_ctx below.
6703          */
6704         raw_spin_lock(&child_ctx->lock);
6705         task_ctx_sched_out(child_ctx);
6706         child->perf_event_ctxp[ctxn] = NULL;
6707         /*
6708          * If this context is a clone; unclone it so it can't get
6709          * swapped to another process while we're removing all
6710          * the events from it.
6711          */
6712         unclone_ctx(child_ctx);
6713         update_context_time(child_ctx);
6714         raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
6715
6716         /*
6717          * Report the task dead after unscheduling the events so that we
6718          * won't get any samples after PERF_RECORD_EXIT. We can however still
6719          * get a few PERF_RECORD_READ events.
6720          */
6721         perf_event_task(child, child_ctx, 0);
6722
6723         /*
6724          * We can recurse on the same lock type through:
6725          *
6726          *   __perf_event_exit_task()
6727          *     sync_child_event()
6728          *       put_event()
6729          *         mutex_lock(&ctx->mutex)
6730          *
6731          * But since its the parent context it won't be the same instance.
6732          */
6733         mutex_lock(&child_ctx->mutex);
6734
6735 again:
6736         list_for_each_entry_safe(child_event, tmp, &child_ctx->pinned_groups,
6737                                  group_entry)
6738                 __perf_event_exit_task(child_event, child_ctx, child);
6739
6740         list_for_each_entry_safe(child_event, tmp, &child_ctx->flexible_groups,
6741                                  group_entry)
6742                 __perf_event_exit_task(child_event, child_ctx, child);
6743
6744         /*
6745          * If the last event was a group event, it will have appended all
6746          * its siblings to the list, but we obtained 'tmp' before that which
6747          * will still point to the list head terminating the iteration.
6748          */
6749         if (!list_empty(&child_ctx->pinned_groups) ||
6750             !list_empty(&child_ctx->flexible_groups))
6751                 goto again;
6752
6753         mutex_unlock(&child_ctx->mutex);
6754
6755         put_ctx(child_ctx);
6756 }
6757
6758 /*
6759  * When a child task exits, feed back event values to parent events.
6760  */
6761 void perf_event_exit_task(struct task_struct *child)
6762 {
6763         struct perf_event *event, *tmp;
6764         int ctxn;
6765
6766         mutex_lock(&child->perf_event_mutex);
6767         list_for_each_entry_safe(event, tmp, &child->perf_event_list,
6768                                  owner_entry) {
6769                 list_del_init(&event->owner_entry);
6770
6771                 /*
6772                  * Ensure the list deletion is visible before we clear
6773                  * the owner, closes a race against perf_release() where
6774                  * we need to serialize on the owner->perf_event_mutex.
6775                  */
6776                 smp_wmb();
6777                 event->owner = NULL;
6778         }
6779         mutex_unlock(&child->perf_event_mutex);
6780
6781         for_each_task_context_nr(ctxn)
6782                 perf_event_exit_task_context(child, ctxn);
6783 }
6784
6785 static void perf_free_event(struct perf_event *event,
6786                             struct perf_event_context *ctx)
6787 {
6788         struct perf_event *parent = event->parent;
6789
6790         if (WARN_ON_ONCE(!parent))
6791                 return;
6792
6793         mutex_lock(&parent->child_mutex);
6794         list_del_init(&event->child_list);
6795         mutex_unlock(&parent->child_mutex);
6796
6797         put_event(parent);
6798
6799         perf_group_detach(event);
6800         list_del_event(event, ctx);
6801         free_event(event);
6802 }
6803
6804 /*
6805  * free an unexposed, unused context as created by inheritance by
6806  * perf_event_init_task below, used by fork() in case of fail.
6807  */
6808 void perf_event_free_task(struct task_struct *task)
6809 {
6810         struct perf_event_context *ctx;
6811         struct perf_event *event, *tmp;
6812         int ctxn;
6813
6814         for_each_task_context_nr(ctxn) {
6815                 ctx = task->perf_event_ctxp[ctxn];
6816                 if (!ctx)
6817                         continue;
6818
6819                 mutex_lock(&ctx->mutex);
6820 again:
6821                 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
6822                                 group_entry)
6823                         perf_free_event(event, ctx);
6824
6825                 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
6826                                 group_entry)
6827                         perf_free_event(event, ctx);
6828
6829                 if (!list_empty(&ctx->pinned_groups) ||
6830                                 !list_empty(&ctx->flexible_groups))
6831                         goto again;
6832
6833                 mutex_unlock(&ctx->mutex);
6834
6835                 put_ctx(ctx);
6836         }
6837 }
6838
6839 void perf_event_delayed_put(struct task_struct *task)
6840 {
6841         int ctxn;
6842
6843         for_each_task_context_nr(ctxn)
6844                 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
6845 }
6846
6847 /*
6848  * inherit a event from parent task to child task:
6849  */
6850 static struct perf_event *
6851 inherit_event(struct perf_event *parent_event,
6852               struct task_struct *parent,
6853               struct perf_event_context *parent_ctx,
6854               struct task_struct *child,
6855               struct perf_event *group_leader,
6856               struct perf_event_context *child_ctx)
6857 {
6858         struct perf_event *child_event;
6859         unsigned long flags;
6860
6861         /*
6862          * Instead of creating recursive hierarchies of events,
6863          * we link inherited events back to the original parent,
6864          * which has a filp for sure, which we use as the reference
6865          * count:
6866          */
6867         if (parent_event->parent)
6868                 parent_event = parent_event->parent;
6869
6870         child_event = perf_event_alloc(&parent_event->attr,
6871                                            parent_event->cpu,
6872                                            child,
6873                                            group_leader, parent_event,
6874                                            NULL, NULL);
6875         if (IS_ERR(child_event))
6876                 return child_event;
6877
6878         if (!atomic_long_inc_not_zero(&parent_event->refcount)) {
6879                 free_event(child_event);
6880                 return NULL;
6881         }
6882
6883         get_ctx(child_ctx);
6884
6885         /*
6886          * Make the child state follow the state of the parent event,
6887          * not its attr.disabled bit.  We hold the parent's mutex,
6888          * so we won't race with perf_event_{en, dis}able_family.
6889          */
6890         if (parent_event->state >= PERF_EVENT_STATE_INACTIVE)
6891                 child_event->state = PERF_EVENT_STATE_INACTIVE;
6892         else
6893                 child_event->state = PERF_EVENT_STATE_OFF;
6894
6895         if (parent_event->attr.freq) {
6896                 u64 sample_period = parent_event->hw.sample_period;
6897                 struct hw_perf_event *hwc = &child_event->hw;
6898
6899                 hwc->sample_period = sample_period;
6900                 hwc->last_period   = sample_period;
6901
6902                 local64_set(&hwc->period_left, sample_period);
6903         }
6904
6905         child_event->ctx = child_ctx;
6906         child_event->overflow_handler = parent_event->overflow_handler;
6907         child_event->overflow_handler_context
6908                 = parent_event->overflow_handler_context;
6909
6910         /*
6911          * Precalculate sample_data sizes
6912          */
6913         perf_event__header_size(child_event);
6914         perf_event__id_header_size(child_event);
6915
6916         /*
6917          * Link it up in the child's context:
6918          */
6919         raw_spin_lock_irqsave(&child_ctx->lock, flags);
6920         add_event_to_ctx(child_event, child_ctx);
6921         raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
6922
6923         /*
6924          * Link this into the parent event's child list
6925          */
6926         WARN_ON_ONCE(parent_event->ctx->parent_ctx);
6927         mutex_lock(&parent_event->child_mutex);
6928         list_add_tail(&child_event->child_list, &parent_event->child_list);
6929         mutex_unlock(&parent_event->child_mutex);
6930
6931         return child_event;
6932 }
6933
6934 static int inherit_group(struct perf_event *parent_event,
6935               struct task_struct *parent,
6936               struct perf_event_context *parent_ctx,
6937               struct task_struct *child,
6938               struct perf_event_context *child_ctx)
6939 {
6940         struct perf_event *leader;
6941         struct perf_event *sub;
6942         struct perf_event *child_ctr;
6943
6944         leader = inherit_event(parent_event, parent, parent_ctx,
6945                                  child, NULL, child_ctx);
6946         if (IS_ERR(leader))
6947                 return PTR_ERR(leader);
6948         list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
6949                 child_ctr = inherit_event(sub, parent, parent_ctx,
6950                                             child, leader, child_ctx);
6951                 if (IS_ERR(child_ctr))
6952                         return PTR_ERR(child_ctr);
6953         }
6954         return 0;
6955 }
6956
6957 static int
6958 inherit_task_group(struct perf_event *event, struct task_struct *parent,
6959                    struct perf_event_context *parent_ctx,
6960                    struct task_struct *child, int ctxn,
6961                    int *inherited_all)
6962 {
6963         int ret;
6964         struct perf_event_context *child_ctx;
6965
6966         if (!event->attr.inherit) {
6967                 *inherited_all = 0;
6968                 return 0;
6969         }
6970
6971         child_ctx = child->perf_event_ctxp[ctxn];
6972         if (!child_ctx) {
6973                 /*
6974                  * This is executed from the parent task context, so
6975                  * inherit events that have been marked for cloning.
6976                  * First allocate and initialize a context for the
6977                  * child.
6978                  */
6979
6980                 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
6981                 if (!child_ctx)
6982                         return -ENOMEM;
6983
6984                 child->perf_event_ctxp[ctxn] = child_ctx;
6985         }
6986
6987         ret = inherit_group(event, parent, parent_ctx,
6988                             child, child_ctx);
6989
6990         if (ret)
6991                 *inherited_all = 0;
6992
6993         return ret;
6994 }
6995
6996 /*
6997  * Initialize the perf_event context in task_struct
6998  */
6999 int perf_event_init_context(struct task_struct *child, int ctxn)
7000 {
7001         struct perf_event_context *child_ctx, *parent_ctx;
7002         struct perf_event_context *cloned_ctx;
7003         struct perf_event *event;
7004         struct task_struct *parent = current;
7005         int inherited_all = 1;
7006         unsigned long flags;
7007         int ret = 0;
7008
7009         if (likely(!parent->perf_event_ctxp[ctxn]))
7010                 return 0;
7011
7012         /*
7013          * If the parent's context is a clone, pin it so it won't get
7014          * swapped under us.
7015          */
7016         parent_ctx = perf_pin_task_context(parent, ctxn);
7017
7018         /*
7019          * No need to check if parent_ctx != NULL here; since we saw
7020          * it non-NULL earlier, the only reason for it to become NULL
7021          * is if we exit, and since we're currently in the middle of
7022          * a fork we can't be exiting at the same time.
7023          */
7024
7025         /*
7026          * Lock the parent list. No need to lock the child - not PID
7027          * hashed yet and not running, so nobody can access it.
7028          */
7029         mutex_lock(&parent_ctx->mutex);
7030
7031         /*
7032          * We dont have to disable NMIs - we are only looking at
7033          * the list, not manipulating it:
7034          */
7035         list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
7036                 ret = inherit_task_group(event, parent, parent_ctx,
7037                                          child, ctxn, &inherited_all);
7038                 if (ret)
7039                         break;
7040         }
7041
7042         /*
7043          * We can't hold ctx->lock when iterating the ->flexible_group list due
7044          * to allocations, but we need to prevent rotation because
7045          * rotate_ctx() will change the list from interrupt context.
7046          */
7047         raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7048         parent_ctx->rotate_disable = 1;
7049         raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7050
7051         list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
7052                 ret = inherit_task_group(event, parent, parent_ctx,
7053                                          child, ctxn, &inherited_all);
7054                 if (ret)
7055                         break;
7056         }
7057
7058         raw_spin_lock_irqsave(&parent_ctx->lock, flags);
7059         parent_ctx->rotate_disable = 0;
7060
7061         child_ctx = child->perf_event_ctxp[ctxn];
7062
7063         if (child_ctx && inherited_all) {
7064                 /*
7065                  * Mark the child context as a clone of the parent
7066                  * context, or of whatever the parent is a clone of.
7067                  *
7068                  * Note that if the parent is a clone, the holding of
7069                  * parent_ctx->lock avoids it from being uncloned.
7070                  */
7071                 cloned_ctx = parent_ctx->parent_ctx;
7072                 if (cloned_ctx) {
7073                         child_ctx->parent_ctx = cloned_ctx;
7074                         child_ctx->parent_gen = parent_ctx->parent_gen;
7075                 } else {
7076                         child_ctx->parent_ctx = parent_ctx;
7077                         child_ctx->parent_gen = parent_ctx->generation;
7078                 }
7079                 get_ctx(child_ctx->parent_ctx);
7080         }
7081
7082         raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
7083         mutex_unlock(&parent_ctx->mutex);
7084
7085         perf_unpin_context(parent_ctx);
7086         put_ctx(parent_ctx);
7087
7088         return ret;
7089 }
7090
7091 /*
7092  * Initialize the perf_event context in task_struct
7093  */
7094 int perf_event_init_task(struct task_struct *child)
7095 {
7096         int ctxn, ret;
7097
7098         memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
7099         mutex_init(&child->perf_event_mutex);
7100         INIT_LIST_HEAD(&child->perf_event_list);
7101
7102         for_each_task_context_nr(ctxn) {
7103                 ret = perf_event_init_context(child, ctxn);
7104                 if (ret) {
7105                         perf_event_free_task(child);
7106                         return ret;
7107                 }
7108         }
7109
7110         return 0;
7111 }
7112
7113 static void __init perf_event_init_all_cpus(void)
7114 {
7115         struct swevent_htable *swhash;
7116         int cpu;
7117
7118         for_each_possible_cpu(cpu) {
7119                 swhash = &per_cpu(swevent_htable, cpu);
7120                 mutex_init(&swhash->hlist_mutex);
7121                 INIT_LIST_HEAD(&per_cpu(rotation_list, cpu));
7122         }
7123 }
7124
7125 static void __cpuinit perf_event_init_cpu(int cpu)
7126 {
7127         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7128
7129         mutex_lock(&swhash->hlist_mutex);
7130         swhash->online = true;
7131         if (swhash->hlist_refcount > 0) {
7132                 struct swevent_hlist *hlist;
7133
7134                 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
7135                 WARN_ON(!hlist);
7136                 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7137         }
7138         mutex_unlock(&swhash->hlist_mutex);
7139 }
7140
7141 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC
7142 static void perf_pmu_rotate_stop(struct pmu *pmu)
7143 {
7144         struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7145
7146         WARN_ON(!irqs_disabled());
7147
7148         list_del_init(&cpuctx->rotation_list);
7149 }
7150
7151 static void __perf_event_exit_context(void *__info)
7152 {
7153         struct remove_event re = { .detach_group = false };
7154         struct perf_event_context *ctx = __info;
7155
7156         perf_pmu_rotate_stop(ctx->pmu);
7157
7158         rcu_read_lock();
7159         list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
7160                 __perf_remove_from_context(&re);
7161         rcu_read_unlock();
7162 }
7163
7164 static void perf_event_exit_cpu_context(int cpu)
7165 {
7166         struct perf_event_context *ctx;
7167         struct pmu *pmu;
7168         int idx;
7169
7170         idx = srcu_read_lock(&pmus_srcu);
7171         list_for_each_entry_rcu(pmu, &pmus, entry) {
7172                 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
7173
7174                 mutex_lock(&ctx->mutex);
7175                 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
7176                 mutex_unlock(&ctx->mutex);
7177         }
7178         srcu_read_unlock(&pmus_srcu, idx);
7179 }
7180
7181 static void perf_event_exit_cpu(int cpu)
7182 {
7183         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7184
7185         perf_event_exit_cpu_context(cpu);
7186
7187         mutex_lock(&swhash->hlist_mutex);
7188         swhash->online = false;
7189         swevent_hlist_release(swhash);
7190         mutex_unlock(&swhash->hlist_mutex);
7191 }
7192 #else
7193 static inline void perf_event_exit_cpu(int cpu) { }
7194 #endif
7195
7196 static int
7197 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
7198 {
7199         int cpu;
7200
7201         for_each_online_cpu(cpu)
7202                 perf_event_exit_cpu(cpu);
7203
7204         return NOTIFY_OK;
7205 }
7206
7207 /*
7208  * Run the perf reboot notifier at the very last possible moment so that
7209  * the generic watchdog code runs as long as possible.
7210  */
7211 static struct notifier_block perf_reboot_notifier = {
7212         .notifier_call = perf_reboot,
7213         .priority = INT_MIN,
7214 };
7215
7216 static int __cpuinit
7217 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
7218 {
7219         unsigned int cpu = (long)hcpu;
7220
7221         switch (action & ~CPU_TASKS_FROZEN) {
7222
7223         case CPU_UP_PREPARE:
7224         case CPU_DOWN_FAILED:
7225                 perf_event_init_cpu(cpu);
7226                 break;
7227
7228         case CPU_UP_CANCELED:
7229         case CPU_DOWN_PREPARE:
7230                 perf_event_exit_cpu(cpu);
7231                 break;
7232
7233         default:
7234                 break;
7235         }
7236
7237         return NOTIFY_OK;
7238 }
7239
7240 void __init perf_event_init(void)
7241 {
7242         int ret;
7243
7244         idr_init(&pmu_idr);
7245
7246         perf_event_init_all_cpus();
7247         init_srcu_struct(&pmus_srcu);
7248         perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
7249         perf_pmu_register(&perf_cpu_clock, NULL, -1);
7250         perf_pmu_register(&perf_task_clock, NULL, -1);
7251         perf_tp_register();
7252         perf_cpu_notifier(perf_cpu_notify);
7253         register_reboot_notifier(&perf_reboot_notifier);
7254
7255         ret = init_hw_breakpoint();
7256         WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
7257 }
7258
7259 static int __init perf_event_sysfs_init(void)
7260 {
7261         struct pmu *pmu;
7262         int ret;
7263
7264         mutex_lock(&pmus_lock);
7265
7266         ret = bus_register(&pmu_bus);
7267         if (ret)
7268                 goto unlock;
7269
7270         list_for_each_entry(pmu, &pmus, entry) {
7271                 if (!pmu->name || pmu->type < 0)
7272                         continue;
7273
7274                 ret = pmu_dev_alloc(pmu);
7275                 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
7276         }
7277         pmu_bus_running = 1;
7278         ret = 0;
7279
7280 unlock:
7281         mutex_unlock(&pmus_lock);
7282
7283         return ret;
7284 }
7285 device_initcall(perf_event_sysfs_init);
7286
7287 #ifdef CONFIG_CGROUP_PERF
7288 static struct cgroup_subsys_state *perf_cgroup_create(
7289         struct cgroup_subsys *ss, struct cgroup *cont)
7290 {
7291         struct perf_cgroup *jc;
7292
7293         jc = kzalloc(sizeof(*jc), GFP_KERNEL);
7294         if (!jc)
7295                 return ERR_PTR(-ENOMEM);
7296
7297         jc->info = alloc_percpu(struct perf_cgroup_info);
7298         if (!jc->info) {
7299                 kfree(jc);
7300                 return ERR_PTR(-ENOMEM);
7301         }
7302
7303         return &jc->css;
7304 }
7305
7306 static void perf_cgroup_destroy(struct cgroup_subsys *ss,
7307                                 struct cgroup *cont)
7308 {
7309         struct perf_cgroup *jc;
7310         jc = container_of(cgroup_subsys_state(cont, perf_subsys_id),
7311                           struct perf_cgroup, css);
7312         free_percpu(jc->info);
7313         kfree(jc);
7314 }
7315
7316 static int __perf_cgroup_move(void *info)
7317 {
7318         struct task_struct *task = info;
7319         perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
7320         return 0;
7321 }
7322
7323 static void
7324 perf_cgroup_attach_task(struct cgroup *cgrp, struct task_struct *task)
7325 {
7326         task_function_call(task, __perf_cgroup_move, task);
7327 }
7328
7329 static void perf_cgroup_exit(struct cgroup_subsys *ss, struct cgroup *cgrp,
7330                 struct cgroup *old_cgrp, struct task_struct *task)
7331 {
7332         /*
7333          * cgroup_exit() is called in the copy_process() failure path.
7334          * Ignore this case since the task hasn't ran yet, this avoids
7335          * trying to poke a half freed task state from generic code.
7336          */
7337         if (!(task->flags & PF_EXITING))
7338                 return;
7339
7340         perf_cgroup_attach_task(cgrp, task);
7341 }
7342
7343 struct cgroup_subsys perf_subsys = {
7344         .name           = "perf_event",
7345         .subsys_id      = perf_subsys_id,
7346         .create         = perf_cgroup_create,
7347         .destroy        = perf_cgroup_destroy,
7348         .exit           = perf_cgroup_exit,
7349         .attach_task    = perf_cgroup_attach_task,
7350 };
7351 #endif /* CONFIG_CGROUP_PERF */