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