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