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