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