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